diff --git a/eaglercraft-saveeditor/PROVENANCE.json b/eaglercraft-saveeditor/PROVENANCE.json new file mode 100644 index 0000000..c33c24a --- /dev/null +++ b/eaglercraft-saveeditor/PROVENANCE.json @@ -0,0 +1,46 @@ +{ + "slug": "eaglercraft-saveeditor", + "name": "Eaglercraft Save Editor (RePack)", + "category": "tool", + "mc_version": "any", + "author": "ayqshi", + "license": "MIT", + "upstream_ref": "main", + "sha256": "67c8f1baeb3404a271999c9cdbe0e2989343f4c279f2220f64dc8fc0482b0206", + "size": 5553951, + "storage": { + "git_path": null, + "fs_url": null + }, + "play": { + "sandbox_url": "https://play-archive.eaglercraft.tech/eaglercraft-saveeditor/", + "sandbox_attr": "allow-scripts allow-downloads", + "network_notes": "Browser-runnable world and profile editor" + }, + "sources": [ + { + "url": "https://github.com/ayqshi/Eaglercraft-SaveEditor", + "retrieved_at": "2026-11-28T03:10:30Z", + "type": "upstream", + "notes": "Source repository on GitHub" + }, + { + "url": "https://ayqshi.github.io/Eaglercraft-SaveEditor/", + "retrieved_at": "2026-11-28T03:10:30Z", + "type": "other", + "notes": "Live web application on GitHub Pages" + } + ], + "vetting": { + "verdict": "clean", + "tools": [ + "vet-static.mjs", + "virustotal-hash", + "static-code-review" + ], + "date": "2026-11-28", + "notes": "Uses navigator.clipboard.writeText for copy buttons in index.html:173,188; main.js:1 is a benign scanner hit on MINECRAFT_ITEMS_DB.", + "reviewer": "vet-gemini" + }, + "large_files_omitted_from_git": [] +} diff --git a/eaglercraft-saveeditor/README.md b/eaglercraft-saveeditor/README.md new file mode 100644 index 0000000..70e0c7d --- /dev/null +++ b/eaglercraft-saveeditor/README.md @@ -0,0 +1,11 @@ +# Eaglercraft Save Editor (RePack) + +Web-based EPK file extractor, viewer, editor, and repacker for Eaglercraft singleplayer world saves and player data. Inspects file hierarchies and parses NBT structures. + +- **Archive page:** https://archive.eaglercraft.tech/entries/eaglercraft-saveeditor.html +- **Play:** https://play-archive.eaglercraft.tech/eaglercraft-saveeditor/ +- **MC Version:** any +- **Author:** ayqshi +- **License:** MIT +- **SHA-256:** `67c8f1baeb3404a271999c9cdbe0e2989343f4c279f2220f64dc8fc0482b0206` +- **Vetting:** clean (2026-11-28) diff --git a/eaglercraft-saveeditor/files/.github/ISSUE_TEMPLATE/feature_request.md b/eaglercraft-saveeditor/files/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..bbcbbe7 --- /dev/null +++ b/eaglercraft-saveeditor/files/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/eaglercraft-saveeditor/files/CODE_OF_CONDUCT.md b/eaglercraft-saveeditor/files/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..11dc862 --- /dev/null +++ b/eaglercraft-saveeditor/files/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +THE ISSUES PAGE. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/eaglercraft-saveeditor/files/CONTRIBUTING.md b/eaglercraft-saveeditor/files/CONTRIBUTING.md new file mode 100644 index 0000000..d6f54b9 --- /dev/null +++ b/eaglercraft-saveeditor/files/CONTRIBUTING.md @@ -0,0 +1,37 @@ +# Contributing to RePack + +Thank you for considering contributing to RePack! We appreciate your help in making this project better. Please follow the guidelines below to ensure a smooth contribution process. + +## How to Contribute + +1. **Fork the Repository**: Click the "Fork" button at the top right of the repository page to create your own copy of the project. + +2. **Clone Your Fork**: Clone your forked repository to your local machine using the following command: + git clone https://github.com/ayqshi/RePack.git +Create a Branch: Create a new branch for your feature or bug fix: + +git checkout -b my-feature-branch +Make Changes: Make your changes in the codebase. Be sure to follow the project's coding style and conventions. + +Test Your Changes: Run any tests to ensure your changes work as expected. If applicable, add new tests for your changes. + +Commit Your Changes: Commit your changes with a clear and descriptive commit message: + +git commit -m "Add a brief description of your changes" +Push to Your Fork: Push your changes to your forked repository: + +git push origin my-feature-branch +Create a Pull Request: Go to the original repository and click on the "Pull Requests" tab. Click the "New Pull Request" button and select your branch. Provide a clear description of your changes and submit the pull request. + +# Guidelines +Code Style: Please adhere to the coding style used in the project. Consistency is key to maintaining readability. +Documentation: If you add new features or make changes, please update the documentation accordingly. +Issue Tracking: If you are fixing a bug or implementing a feature, please reference the relevant issue in your pull request description. +Reporting Issues +If you encounter any issues or have suggestions for improvements, please open an issue in the repository. Be sure to provide as much detail as possible to help us understand the problem. + +## Code of Conduct +By participating in this project, you agree to abide by our Code of Conduct. + +## Thank You! +Thank you for your interest in contributing to RePack! We look forward to your contributions and appreciate your help in making this project better. diff --git a/eaglercraft-saveeditor/files/LICENSE b/eaglercraft-saveeditor/files/LICENSE new file mode 100644 index 0000000..1c376cf --- /dev/null +++ b/eaglercraft-saveeditor/files/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Ayashi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/eaglercraft-saveeditor/files/README.md b/eaglercraft-saveeditor/files/README.md new file mode 100644 index 0000000..1846144 --- /dev/null +++ b/eaglercraft-saveeditor/files/README.md @@ -0,0 +1,178 @@ +# RePack — Eaglercraft Save Editor +> **Status: Official Launch** +> +> This project is still under active development but is near completion. Expect bugs, rough edges, and incomplete features. If you are not comfortable troubleshooting issues on your own, you may want to wait for a more stable version. +> +> If you are interested in helping improve the project—especially usability and simplicity—contributions are welcome. +> Reach out (discord): **@ayqshi** + +--- + +## What This Project Is + +**RePack** is a browser-based tool for inspecting, editing, and rebuilding `.epk` save files used in Eaglercraft. + +It is designed for users who want more control over their world data—whether that means exploring file contents, modifying NBT data, or understanding how `.epk` archives are structured internally. + +--- +# ROADMAP +- Fixing non functional feats +- Making functional bookmarklets (EPK scraper, In-Game Mod Menu) +- .ZIP support +## Features + +### EPK Extraction + +Decompile `.epk` archives and access their internal files. + +* View the full contents of a save +* Understand file structure and layout +* No external tools required + +--- + +### NBT Parsing (Readable JSON) + +Automatically converts `.dat` (NBT) files into structured JSON. + +* Makes complex binary data readable +* Easier inspection of player and world data +* Simplifies editing workflows + +--- + +### File Editing + +Edit supported file types directly in the browser: + +* JSON (NBT data) +* Plain text files + +Changes are applied in real time and reflected in the repacked archive. + +--- + +### EPK Repacking + +Rebuild a valid `.epk` archive after making edits. + +* Preserves original structure +* Automatically re-compresses files when required (GZIP) +* Designed to minimize manual intervention + +--- + +### Integrity Checks + +Basic validation is included to reduce the chance of corruption: + +* Header and footer verification +* CRC32 checks for file data consistency + +--- + +### Binary File Handling + +Files that cannot be displayed are still preserved: + +* Shown as placeholders in the UI +* Included unchanged during repacking + +--- + +## Usage + +1. In Eaglercraft: + + * Select your world + * Click **Backup** and export as `.epk` + +2. In RePack: + + * Open the tool (beta) + * Upload your `.epk` file + +3. Browse and edit: + + * Select a file from the extracted list + * Its contents will appear in the editor panel + +4. Repack: + + * Save your changes + * Download the rebuilt `.epk` file + +--- + +## How It Works + +RePack runs entirely in your browser using JavaScript. Files are processed locally and are not uploaded to any server. + +### EPK Format Overview + +An `.epk` archive contains: + +* A header +* Version information +* File count (stored as Big-Endian) +* A metadata table for each file: + + * Name + * Size + * Offset + * Compression type + * CRC32 checksum +* File data blocks +* A footer + +Most numeric values are stored as Little-Endian, except for the file count, which uses Big-Endian encoding. + +--- + +### Internal Processing + +When loading a file: + +* The archive structure is parsed +* Metadata and offsets are read +* Files are decompressed if necessary +* NBT data is converted into JSON + +When repacking: + +* Metadata is rebuilt +* Files are recompressed where required +* CRC32 values are recalculated +* A valid `.epk` archive is generated + +--- + +## Dependencies + +* **Pako.js** — GZIP compression and decompression +* **NBT.js** — Parsing and handling NBT data + +--- + +## Limitations + +* Some edge cases may fail during extraction or repacking +* User interface is minimal and still evolving +* Binary files cannot be edited +* Error handling is not yet comprehensive + +--- + +## Contributing + +Feedback and contributions are encouraged, especially in areas like: + +* Simplifying the user experience +* Improving error handling +* Expanding file support + +--- + +## Notes + +This tool is intended for users who want direct access to and control over their save data. It prioritizes transparency and functionality over polish at this stage of development. diff --git a/eaglercraft-saveeditor/files/SECURITY.md b/eaglercraft-saveeditor/files/SECURITY.md new file mode 100644 index 0000000..d1cbddc --- /dev/null +++ b/eaglercraft-saveeditor/files/SECURITY.md @@ -0,0 +1,23 @@ +# Security Policy + +## Reporting a Vulnerability + +If you discover a security vulnerability within this project, please report it by sending me a message on snapchat: @ayqshi. + +Please include the following information in your report: + +- A description of the vulnerability +- Steps to reproduce the issue +- Any relevant screenshots or logs + +## Supported Versions + +We only support the latest version of the project. Older versions may not receive security updates. + +## Security Updates + +We will make every effort to respond to security vulnerabilities in a timely manner. Security updates will be released as soon as possible. + +## Acknowledgements + +We appreciate the efforts of the community in helping us improve the security of this project. If you report a vulnerability, we will acknowledge your contribution in the release notes if you wish. diff --git a/eaglercraft-saveeditor/files/epk.png b/eaglercraft-saveeditor/files/epk.png new file mode 100644 index 0000000..8159a68 Binary files /dev/null and b/eaglercraft-saveeditor/files/epk.png differ diff --git a/eaglercraft-saveeditor/files/example_world.epk b/eaglercraft-saveeditor/files/example_world.epk new file mode 100644 index 0000000..39f5b3a Binary files /dev/null and b/eaglercraft-saveeditor/files/example_world.epk differ diff --git a/eaglercraft-saveeditor/files/index.html b/eaglercraft-saveeditor/files/index.html new file mode 100644 index 0000000..19cbd90 --- /dev/null +++ b/eaglercraft-saveeditor/files/index.html @@ -0,0 +1,234 @@ + + + + + + + RePack — Eaglercraft Save Editor + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+
Starting up... +
+
+
+
RePack +

RePack

+
+ no cache +
+
+
+
Eaglercraft Save Editor +

RePack

+

Open any Eaglercraft world, tweak what you want, and export it back. Runs entirely + in your browser — nothing leaves your device.

+
GitHub
+
+
+
+
EPK Support
+
Unpack and repack 1.5.2 and 1.8.8 Eaglercraft world saves. Version is + detected automatically.
+
+
+
+
Full Inventory
+
Edit all 36 slots plus all 4 armor slots. Add, remove, enchant, and + set durability on any item.
+
+
+
+
World Settings
+
Change game mode, difficulty, time, weather, spawn point, seed, and + every gamerule.
+
+
+
+
+
+
+ +
+
+
+

Editor

+
File:None
+
+
+
+
+
+
+
+
+
+

Export

+
+

Pack all changes back into an EPK file and download it.

+ +
+
+
+
+
+
+
+

Bookmarklet

+

These browser bookmarks let you grab + EPK files straight from an Eaglercraft page and open them here automatically — no manual + download needed.

+
+
+
+

EPK Scraper

+
+

Drag this to your bookmarks bar. Click it on any Eaglercraft 1.12.2 + client page to extract the world EPK and open it here.

+
+
coming soon. +
+
+
+
+

Live In-Game Edit (Experimental)

+
+

The idea: inject a bookmarklet on an active + Eaglercraft tab that reads the cached/IndexedDB world data while you're in-game, sends it to + RePack, and writes edits back.

+
+
coming soon. +
+
+
+
+ +
+ + + + + + + + + + + + diff --git a/eaglercraft-saveeditor/files/inveditor.png b/eaglercraft-saveeditor/files/inveditor.png new file mode 100644 index 0000000..6cafffa Binary files /dev/null and b/eaglercraft-saveeditor/files/inveditor.png differ diff --git a/eaglercraft-saveeditor/files/main.js b/eaglercraft-saveeditor/files/main.js new file mode 100644 index 0000000..fafce2e --- /dev/null +++ b/eaglercraft-saveeditor/files/main.js @@ -0,0 +1 @@ +if("undefined"==typeof nbt)throw new Error("nbt.js not loaded.");if("undefined"==typeof pako)throw new Error("pako.min.js not loaded.");const MINECRAFT_ITEMS_DB=["minecraft:air","minecraft:stone","minecraft:granite","minecraft:polished_granite","minecraft:diorite","minecraft:polished_diorite","minecraft:andesite","minecraft:polished_andesite","minecraft:grass","minecraft:dirt","minecraft:coarse_dirt","minecraft:podzol","minecraft:cobblestone","minecraft:planks","minecraft:sapling","minecraft:bedrock","minecraft:flowing_water","minecraft:water","minecraft:flowing_lava","minecraft:lava","minecraft:sand","minecraft:red_sand","minecraft:gravel","minecraft:gold_ore","minecraft:iron_ore","minecraft:coal_ore","minecraft:log","minecraft:log2","minecraft:leaves","minecraft:leaves2","minecraft:sponge","minecraft:wet_sponge","minecraft:glass","minecraft:lapis_ore","minecraft:lapis_block","minecraft:dispenser","minecraft:sandstone","minecraft:chiseled_sandstone","minecraft:smooth_sandstone","minecraft:noteblock","minecraft:bed","minecraft:golden_rail","minecraft:detector_rail","minecraft:sticky_piston","minecraft:web","minecraft:tallgrass","minecraft:deadbush","minecraft:piston","minecraft:piston_head","minecraft:wool","minecraft:yellow_flower","minecraft:red_flower","minecraft:brown_mushroom","minecraft:red_mushroom","minecraft:gold_block","minecraft:iron_block","minecraft:double_stone_slab","minecraft:stone_slab","minecraft:brick_block","minecraft:tnt","minecraft:bookshelf","minecraft:mossy_cobblestone","minecraft:obsidian","minecraft:torch","minecraft:fire","minecraft:mob_spawner","minecraft:oak_stairs","minecraft:chest","minecraft:redstone_wire","minecraft:diamond_ore","minecraft:diamond_block","minecraft:crafting_table","minecraft:wheat","minecraft:farmland","minecraft:furnace","minecraft:lit_furnace","minecraft:standing_sign","minecraft:wooden_door","minecraft:ladder","minecraft:rail","minecraft:stone_stairs","minecraft:wall_sign","minecraft:lever","minecraft:stone_pressure_plate","minecraft:iron_door","minecraft:wooden_pressure_plate","minecraft:redstone_ore","minecraft:lit_redstone_ore","minecraft:unlit_redstone_torch","minecraft:redstone_torch","minecraft:stone_button","minecraft:snow_layer","minecraft:ice","minecraft:snow","minecraft:cactus","minecraft:clay","minecraft:reeds","minecraft:jukebox","minecraft:fence","minecraft:pumpkin","minecraft:netherrack","minecraft:soul_sand","minecraft:glowstone","minecraft:portal","minecraft:lit_pumpkin","minecraft:cake","minecraft:unpowered_repeater","minecraft:powered_repeater","minecraft:stained_glass","minecraft:trapdoor","minecraft:monster_egg","minecraft:stonebrick","minecraft:brown_mushroom_block","minecraft:red_mushroom_block","minecraft:iron_bars","minecraft:glass_pane","minecraft:melon_block","minecraft:pumpkin_stem","minecraft:melon_stem","minecraft:vine","minecraft:fence_gate","minecraft:brick_stairs","minecraft:stone_brick_stairs","minecraft:mycelium","minecraft:waterlily","minecraft:nether_brick","minecraft:nether_brick_fence","minecraft:nether_brick_stairs","minecraft:nether_wart","minecraft:enchanting_table","minecraft:brewing_stand","minecraft:cauldron","minecraft:end_portal","minecraft:end_portal_frame","minecraft:end_stone","minecraft:dragon_egg","minecraft:redstone_lamp","minecraft:lit_redstone_lamp","minecraft:double_wooden_slab","minecraft:wooden_slab","minecraft:cocoa","minecraft:sandstone_stairs","minecraft:emerald_ore","minecraft:ender_chest","minecraft:tripwire_hook","minecraft:tripwire","minecraft:emerald_block","minecraft:spruce_stairs","minecraft:birch_stairs","minecraft:jungle_stairs","minecraft:command_block","minecraft:beacon","minecraft:cobblestone_wall","minecraft:flower_pot","minecraft:carrots","minecraft:potatoes","minecraft:wooden_button","minecraft:skull","minecraft:anvil","minecraft:trapped_chest","minecraft:light_weighted_pressure_plate","minecraft:heavy_weighted_pressure_plate","minecraft:unpowered_comparator","minecraft:powered_comparator","minecraft:daylight_detector","minecraft:redstone_block","minecraft:quartz_ore","minecraft:hopper","minecraft:quartz_block","minecraft:quartz_stairs","minecraft:activator_rail","minecraft:dropper","minecraft:stained_hardened_clay","minecraft:stained_glass_pane","minecraft:leaves2","minecraft:log2","minecraft:acacia_stairs","minecraft:dark_oak_stairs","minecraft:slime","minecraft:barrier","minecraft:iron_trapdoor","minecraft:prismarine","minecraft:sea_lantern","minecraft:hay_block","minecraft:carpet","minecraft:hardened_clay","minecraft:coal_block","minecraft:packed_ice","minecraft:double_plant","minecraft:standing_banner","minecraft:wall_banner","minecraft:daylight_detector_inverted","minecraft:red_sandstone","minecraft:red_sandstone_stairs","minecraft:double_stone_slab2","minecraft:stone_slab2","minecraft:spruce_fence_gate","minecraft:birch_fence_gate","minecraft:jungle_fence_gate","minecraft:dark_oak_fence_gate","minecraft:acacia_fence_gate","minecraft:spruce_fence","minecraft:birch_fence","minecraft:jungle_fence","minecraft:dark_oak_fence","minecraft:acacia_fence","minecraft:spruce_door","minecraft:birch_door","minecraft:jungle_door","minecraft:acacia_door","minecraft:dark_oak_door","minecraft:end_rod","minecraft:chorus_plant","minecraft:chorus_flower","minecraft:purpur_block","minecraft:purpur_pillar","minecraft:purpur_stairs","minecraft:purpur_double_slab","minecraft:purpur_slab","minecraft:end_bricks","minecraft:beetroots","minecraft:grass_path","minecraft:end_gateway","minecraft:repeating_command_block","minecraft:chain_command_block","minecraft:frosted_ice","minecraft:magma","minecraft:nether_wart_block","minecraft:red_nether_brick","minecraft:bone_block","minecraft:structure_void","minecraft:observer","minecraft:white_shulker_box","minecraft:orange_shulker_box","minecraft:magenta_shulker_box","minecraft:light_blue_shulker_box","minecraft:yellow_shulker_box","minecraft:lime_shulker_box","minecraft:pink_shulker_box","minecraft:gray_shulker_box","minecraft:silver_shulker_box","minecraft:cyan_shulker_box","minecraft:purple_shulker_box","minecraft:blue_shulker_box","minecraft:brown_shulker_box","minecraft:green_shulker_box","minecraft:red_shulker_box","minecraft:black_shulker_box","minecraft:white_glazed_terracotta","minecraft:orange_glazed_terracotta","minecraft:magenta_glazed_terracotta","minecraft:light_blue_glazed_terracotta","minecraft:yellow_glazed_terracotta","minecraft:lime_glazed_terracotta","minecraft:pink_glazed_terracotta","minecraft:gray_glazed_terracotta","minecraft:silver_glazed_terracotta","minecraft:cyan_glazed_terracotta","minecraft:purple_glazed_terracotta","minecraft:blue_glazed_terracotta","minecraft:brown_glazed_terracotta","minecraft:green_glazed_terracotta","minecraft:red_glazed_terracotta","minecraft:black_glazed_terracotta","minecraft:concrete","minecraft:concrete_powder","minecraft:structure_block","minecraft:iron_shovel","minecraft:iron_pickaxe","minecraft:iron_axe","minecraft:flint_and_steel","minecraft:apple","minecraft:bow","minecraft:arrow","minecraft:coal","minecraft:diamond","minecraft:iron_ingot","minecraft:gold_ingot","minecraft:iron_sword","minecraft:wooden_sword","minecraft:wooden_shovel","minecraft:wooden_pickaxe","minecraft:wooden_axe","minecraft:stone_sword","minecraft:stone_shovel","minecraft:stone_pickaxe","minecraft:stone_axe","minecraft:diamond_sword","minecraft:diamond_shovel","minecraft:diamond_pickaxe","minecraft:diamond_axe","minecraft:golden_sword","minecraft:golden_shovel","minecraft:golden_pickaxe","minecraft:golden_axe","minecraft:stick","minecraft:bowl","minecraft:mushroom_stew","minecraft:string","minecraft:feather","minecraft:gunpowder","minecraft:wooden_hoe","minecraft:stone_hoe","minecraft:iron_hoe","minecraft:diamond_hoe","minecraft:golden_hoe","minecraft:wheat_seeds","minecraft:wheat","minecraft:bread","minecraft:leather_helmet","minecraft:leather_chestplate","minecraft:leather_leggings","minecraft:leather_boots","minecraft:chainmail_helmet","minecraft:chainmail_chestplate","minecraft:chainmail_leggings","minecraft:chainmail_boots","minecraft:iron_helmet","minecraft:iron_chestplate","minecraft:iron_leggings","minecraft:iron_boots","minecraft:diamond_helmet","minecraft:diamond_chestplate","minecraft:diamond_leggings","minecraft:diamond_boots","minecraft:golden_helmet","minecraft:golden_chestplate","minecraft:golden_leggings","minecraft:golden_boots","minecraft:flint","minecraft:porkchop","minecraft:cooked_porkchop","minecraft:painting","minecraft:golden_apple","minecraft:sign","minecraft:bucket","minecraft:water_bucket","minecraft:lava_bucket","minecraft:minecart","minecraft:saddle","minecraft:iron_door","minecraft:redstone","minecraft:snowball","minecraft:boat","minecraft:leather","minecraft:milk_bucket","minecraft:brick","minecraft:clay_ball","minecraft:reeds","minecraft:paper","minecraft:book","minecraft:slime_ball","minecraft:chest_minecart","minecraft:furnace_minecart","minecraft:egg","minecraft:compass","minecraft:fishing_rod","minecraft:clock","minecraft:glowstone_dust","minecraft:fish","minecraft:cooked_fish","minecraft:dye","minecraft:bone","minecraft:sugar","minecraft:cake","minecraft:bed","minecraft:repeater","minecraft:cookie","minecraft:filled_map","minecraft:shears","minecraft:melon","minecraft:pumpkin_seeds","minecraft:melon_seeds","minecraft:beef","minecraft:cooked_beef","minecraft:chicken","minecraft:cooked_chicken","minecraft:rotten_flesh","minecraft:ender_pearl","minecraft:blaze_rod","minecraft:ghast_tear","minecraft:gold_nugget","minecraft:nether_wart","minecraft:potion","minecraft:glass_bottle","minecraft:spider_eye","minecraft:fermented_spider_eye","minecraft:blaze_powder","minecraft:magma_cream","minecraft:brewing_stand","minecraft:cauldron","minecraft:ender_eye","minecraft:speckled_melon","minecraft:spawn_egg","minecraft:experience_bottle","minecraft:fire_charge","minecraft:writable_book","minecraft:written_book","minecraft:emerald","minecraft:item_frame","minecraft:flower_pot","minecraft:carrot","minecraft:potato","minecraft:baked_potato","minecraft:poisonous_potato","minecraft:map","minecraft:golden_carrot","minecraft:skull","minecraft:carrot_on_a_stick","minecraft:nether_star","minecraft:pumpkin_pie","minecraft:fireworks","minecraft:firework_charge","minecraft:enchanted_book","minecraft:comparator","minecraft:netherbrick","minecraft:quartz","minecraft:tnt_minecart","minecraft:hopper_minecart","minecraft:prismarine_shard","minecraft:prismarine_crystals","minecraft:rabbit","minecraft:cooked_rabbit","minecraft:rabbit_stew","minecraft:rabbit_foot","minecraft:rabbit_hide","minecraft:armor_stand","minecraft:iron_horse_armor","minecraft:golden_horse_armor","minecraft:diamond_horse_armor","minecraft:lead","minecraft:name_tag","minecraft:command_block_minecart","minecraft:mutton","minecraft:cooked_mutton","minecraft:banner","minecraft:end_crystal","minecraft:spruce_door","minecraft:birch_door","minecraft:jungle_door","minecraft:acacia_door","minecraft:dark_oak_door","minecraft:chorus_fruit","minecraft:chorus_fruit_popped","minecraft:beetroot","minecraft:beetroot_seeds","minecraft:beetroot_soup","minecraft:dragon_breath","minecraft:splash_potion","minecraft:spectral_arrow","minecraft:tipped_arrow","minecraft:lingering_potion","minecraft:shield","minecraft:elytra","minecraft:spruce_boat","minecraft:birch_boat","minecraft:jungle_boat","minecraft:acacia_boat","minecraft:dark_oak_boat","minecraft:totem_of_undying","minecraft:shulker_shell","minecraft:iron_nugget","minecraft:knowledge_book","minecraft:record_13","minecraft:record_cat","minecraft:record_blocks","minecraft:record_chirp","minecraft:record_far","minecraft:record_mall","minecraft:record_mellohi","minecraft:record_stal","minecraft:record_strad","minecraft:record_ward","minecraft:record_11","minecraft:record_wait"],ENCHANTMENTS_DB=[{id:0,name:"Protection"},{id:1,name:"Fire Protection"},{id:2,name:"Feather Falling"},{id:3,name:"Blast Protection"},{id:4,name:"Projectile Protection"},{id:5,name:"Respiration"},{id:6,name:"Aqua Affinity"},{id:7,name:"Thorns"},{id:16,name:"Sharpness"},{id:17,name:"Smite"},{id:18,name:"Bane of Arthropods"},{id:19,name:"Knockback"},{id:20,name:"Fire Aspect"},{id:21,name:"Looting"},{id:32,name:"Efficiency"},{id:33,name:"Silk Touch"},{id:34,name:"Unbreaking"},{id:35,name:"Fortune"},{id:48,name:"Power"},{id:49,name:"Punch"},{id:50,name:"Flame"},{id:51,name:"Infinity"},{id:61,name:"Luck of the Sea"},{id:62,name:"Lure"}],POTION_EFFECTS_DB=[{id:1,name:"Speed"},{id:2,name:"Slowness"},{id:3,name:"Haste"},{id:4,name:"Mining Fatigue"},{id:5,name:"Strength"},{id:6,name:"Instant Health"},{id:7,name:"Instant Damage"},{id:8,name:"Jump Boost"},{id:9,name:"Nausea"},{id:10,name:"Regeneration"},{id:11,name:"Resistance"},{id:12,name:"Fire Resistance"},{id:13,name:"Water Breathing"},{id:14,name:"Invisibility"},{id:15,name:"Blindness"},{id:16,name:"Night Vision"},{id:17,name:"Hunger"},{id:18,name:"Weakness"},{id:19,name:"Poison"},{id:20,name:"Wither"},{id:21,name:"Health Boost"},{id:22,name:"Absorption"},{id:23,name:"Saturation"}],ORE_RANGES={Coal:{min:5,max:128,best:68},Iron:{min:5,max:64,best:32},Gold:{min:5,max:32,best:12},Diamond:{min:5,max:16,best:11},Lapis:{min:13,max:37,best:17},Redstone:{min:5,max:16,best:10},Emerald:{min:5,max:32,best:10},Quartz:{min:10,max:117,best:63}},ARMOR_SLOTS=[{slot:103,label:"Helmet"},{slot:102,label:"Chest"},{slot:101,label:"Legs"},{slot:100,label:"Boots"}],DEFAULT_GAMERULES=["doFireTick","doMobLoot","doMobSpawning","doTileDrops","keepInventory","mobGriefing","naturalRegeneration","doDaylightCycle","commandBlockOutput","logAdminCommands","randomTickSpeed","sendCommandFeedback","showDeathMessages"];let epkFileInput,decompileButton,repackButton,statusMessageDiv,fileListContainer,fileContentEditor,saveChangesButton,messageBox,messageTitle,messageContent,messageCloseBtn,epkNameDisplay,activeFileNameDisplay,addFileButton,removeFileButton,moddingMenuContainer,epkFile=null,extractedFiles=new Map,activeFile={name:null,buffer:null,nbtParsed:null,wasGzipped:!1},parsedSaveData={},selectedInventoryIndex=null,detectedVersion=null;const DB_NAME="repack_cache",DB_VER=1;let db=null;function openDB(){return new Promise((res,rej)=>{const req=indexedDB.open(DB_NAME,1);req.onupgradeneeded=e=>{const d=e.target.result;d.objectStoreNames.contains("saves")||d.createObjectStore("saves",{keyPath:"name"})},req.onsuccess=e=>{db=e.target.result,res(db)},req.onerror=e=>rej(e)})}async function cacheEPK(name,filesMap){if(!db)return;const serialized={};filesMap.forEach((buf,k)=>{serialized[k]=Array.from(new Uint8Array(buf))}),db.transaction("saves","readwrite").objectStore("saves").put({name:name,files:serialized,ts:Date.now()}),localStorage.setItem("repack_last",name),updateCacheBadge()}async function loadCachedEPK(name){return db?new Promise((res,rej)=>{const req=db.transaction("saves","readonly").objectStore("saves").get(name);req.onsuccess=e=>{if(!e.target.result)return void res(null);const map=new Map,{files:files}=e.target.result;for(const k in files)map.set(k,new Uint8Array(files[k]).buffer);res(map)},req.onerror=rej}):null}async function listCachedEPKs(){return db?new Promise((res,rej)=>{const req=db.transaction("saves","readonly").objectStore("saves").getAll();req.onsuccess=e=>res(e.target.result.map(r=>({name:r.name,ts:r.ts}))),req.onerror=rej}):[]}async function deleteCachedEPK(name){db&&(db.transaction("saves","readwrite").objectStore("saves").delete(name),localStorage.getItem("repack_last")===name&&localStorage.removeItem("repack_last"),updateCacheBadge())}function updateCacheBadge(){const badge=document.getElementById("cacheBadge");badge&&listCachedEPKs().then(list=>{list.length>0?(badge.textContent=`${list.length} saved`,badge.classList.add("has-cache")):(badge.textContent="no cache",badge.classList.remove("has-cache"))})}function showMessageBox(title,body){const box=document.getElementById("messageBox"),t=document.getElementById("messageTitle"),b=document.getElementById("messageContent");box?(t.textContent=title,b.textContent=body,box.classList.add("show")):console.warn(title,body)}function closeMessageBox(){const box=document.getElementById("messageBox");box&&box.classList.remove("show")}function showPromptBox(title,body,defaultVal=""){return new Promise(res=>{const box=document.getElementById("promptBox"),t=document.getElementById("promptTitle"),b=document.getElementById("promptBody"),inp=document.getElementById("promptInput"),okBtn=document.getElementById("promptOk"),canBtn=document.getElementById("promptCancel");if(!box)return void res(window.prompt(`${title}\n${body}`,defaultVal));t.textContent=title,b.textContent=body,inp.value=defaultVal,box.classList.add("show"),inp.focus();const cleanup=()=>{box.classList.remove("show"),okBtn.onclick=null,canBtn.onclick=null};okBtn.onclick=()=>{cleanup(),res(inp.value)},canBtn.onclick=()=>{cleanup(),res(null)},inp.onkeydown=e=>{"Enter"===e.key&&okBtn.click(),"Escape"===e.key&&canBtn.click()}})}function showConfirmBox(title,body){return new Promise(res=>{const box=document.getElementById("confirmBox"),t=document.getElementById("confirmTitle"),b=document.getElementById("confirmBody"),okBtn=document.getElementById("confirmOk"),canBtn=document.getElementById("confirmCancel");if(!box)return void res(window.confirm(`${title}\n\n${body}`));t.textContent=title,b.textContent=body,box.classList.add("show");const cleanup=()=>{box.classList.remove("show"),okBtn.onclick=null,canBtn.onclick=null};okBtn.onclick=()=>{cleanup(),res(!0)},canBtn.onclick=()=>{cleanup(),res(!1)}})}let _statusTimer=null;function showStatusMessage(msg,type="info"){statusMessageDiv&&(statusMessageDiv.textContent=msg,statusMessageDiv.className=`status-message show status-${type}`,clearTimeout(_statusTimer),_statusTimer=setTimeout(()=>statusMessageDiv.classList.remove("show"),4500))}function showPage(id){document.querySelectorAll(".page").forEach(p=>p.classList.remove("active")),document.querySelectorAll(".header-nav-btn").forEach(b=>b.classList.remove("active"));const page=document.getElementById(`page-${id}`),btn=document.getElementById(`nav-${id}`);page&&page.classList.add("active"),btn&&btn.classList.add("active"),sessionStorage.setItem("repack_page",id)}function renderHexView(buffer){const bytes=new Uint8Array(buffer),display=bytes.slice(0,4096),rows=[];for(let i=0;ib.toString(16).padStart(2,"0")).join(" "),ascii=Array.from(chunk).map(b=>b>=32&&b<127?String.fromCharCode(b):".").join(""),offset=i.toString(16).padStart(6,"0").toUpperCase();rows.push(`
${offset}${hex.padEnd(47," ")}${ascii}
`)}const truncNote=bytes.length>4096?`
... ${bytes.length-4096} more bytes (showing first 4 KB)
`:"";return`
${rows.join("")}${truncNote}
`}function arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer);for(let i=0;iNo files found in package.'));const pinned=[],player=[],stats=[],data=[],chunks=[],other=[];filesMap.forEach((buffer,filename)=>{const lc=filename.toLowerCase();["level.dat","level.dat_old","file-type","world-name","world-owner"].includes(filename)||"level.dat"===lc||"level.dat_old"===lc?pinned.push(filename):lc.startsWith("player/")?player.push(filename):lc.startsWith("stats/")?stats.push(filename):lc.startsWith("data/")?data.push(filename):lc.startsWith("level0/")?chunks.push(filename):other.push(filename)}),fileListContainer.innerHTML="";const makeItem=filename=>{const buf=filesMap.get(filename),item=document.createElement("div");item.className="file-list-item",item.dataset.filename=filename;let ext=filename.split(".").pop().toUpperCase();filename.startsWith("level0/")&&(ext="CHUNK"),(filename.includes("file-type")||filename.includes("world-"))&&(ext="META"),filename.endsWith(".dat_old")&&(ext="BAK");const short=(filename.includes("/"),filename);return item.innerHTML=`${short}${ext}`,item.addEventListener("click",()=>selectFileForEditing(filename,buf)),item},makeSection=(label,files,collapsed=!1)=>{if(0===files.length)return;const section=document.createElement("div"),header=document.createElement("div");header.className="file-section-header"+(collapsed?" collapsed":""),header.innerHTML=`${label} (${files.length})▾`;const body=document.createElement("div");body.className="file-section-body"+(collapsed?" collapsed":""),files.forEach(f=>body.appendChild(makeItem(f))),header.addEventListener("click",()=>{header.classList.toggle("collapsed"),body.classList.toggle("collapsed")}),section.appendChild(header),section.appendChild(body),fileListContainer.appendChild(section)},pinnedSection=document.createElement("div");pinned.forEach(f=>pinnedSection.appendChild(makeItem(f))),fileListContainer.appendChild(pinnedSection),makeSection("Player Data",player),makeSection("Stats",stats),makeSection("World Data",data),makeSection("Chunk Files",chunks,!0),makeSection("Other",other,!0)}async function viewNBTData(fileName,buffer){showStatusMessage(`Reading ${fileName}...`,"info");let data=new Uint8Array(buffer);activeFile.wasGzipped=!1;try{if(data.length>2&&31===data[0]&&139===data[1]&&(data=pako.ungzip(data),activeFile.wasGzipped=!0),!data||0===data.length)throw new Error("Empty or invalid NBT data");const parsed=await new Promise((resolve,reject)=>{try{nbt.parse(data.buffer,(err,result)=>{err?reject(err):result&&result.value?resolve(result):reject(new Error("NBT parse returned invalid data"))})}catch(e){reject(e)}});activeFile.nbtParsed=parsed,fileContentEditor&&(fileContentEditor.value=JSON.stringify(parsed.value,null,2)),saveChangesButton&&(saveChangesButton.disabled=!1),showStatusMessage(`Parsed ${fileName}.`,"success")}catch(err){console.warn(`NBT parse failed for ${fileName}:`,err),fileContentEditor&&(fileContentEditor.value="",fileContentEditor.disabled=!0);const container=fileContentEditor?fileContentEditor.parentElement:null;if(container){const existing=container.querySelector(".hex-viewer");existing&&existing.remove();const hexEl=document.createElement("div");hexEl.innerHTML=renderHexView(buffer),container.insertBefore(hexEl.firstChild,fileContentEditor)}showStatusMessage(`Showing hex view for ${fileName}.`,"info")}}async function decryptEpk(buffer){showStatusMessage("Unpacking...","info");const bytes=new Uint8Array(buffer),filesMap=new Map;try{const header=bytes.subarray(0,8),ver2=new Uint8Array([69,65,71,80,75,71,36,36]),ver1=new Uint8Array([69,65,71,80,75,71,33,33]);if(!arraysEqual(header,ver2)){if(arraysEqual(header,ver1))throw new Error("Legacy EPK v1 not supported.");throw new Error("Not a valid EPK file.")}if(!arraysEqual(bytes.subarray(bytes.byteLength-8),new Uint8Array([58,58,58,89,69,69,58,62])))throw new Error("File is truncated or corrupted.");const body=bytes.subarray(8,bytes.byteLength-8),view=new DataView(body.buffer,body.byteOffset,body.byteLength);let ptr=0;const verLen=view.getUint8(ptr++),versionString=new TextDecoder("ascii").decode(body.subarray(ptr,ptr+verLen));if(ptr+=verLen,!versionString.startsWith("ver2."))throw new Error(`Unsupported version: ${versionString}`);const buildLen=view.getUint8(ptr++);ptr+=buildLen;const paddingLen=view.getUint16(ptr,!1);ptr+=2,ptr+=paddingLen,ptr+=8;let filesCount=view.getInt32(ptr,!1);ptr+=4;const compChar=String.fromCharCode(view.getUint8(ptr++)),compressedData=body.subarray(ptr);let decompressed;switch(compChar){case"G":decompressed=pako.ungzip(compressedData);break;case"Z":decompressed=pako.inflate(compressedData);break;case"0":decompressed=compressedData;break;default:throw new Error(`Unknown compression: ${compChar}`)}const decView=new DataView(decompressed.buffer,decompressed.byteOffset,decompressed.byteLength);let decPtr=0;for(;filesCount>0&&!(decPtr+4>decompressed.byteLength);){const entryType=new TextDecoder("ascii").decode(decompressed.subarray(decPtr,decPtr+4));if(decPtr+=4,"END$"===entryType){filesCount=0;break}const nameLen=decView.getUint8(decPtr++),fileName=new TextDecoder("ascii").decode(decompressed.subarray(decPtr,decPtr+nameLen));decPtr+=nameLen;const entrySize=decView.getInt32(decPtr,!1);let fileContent;if(decPtr+=4,"FILE"===entryType){if(entrySize<5)throw new Error(`Truncated entry: ${fileName}`);if(decView.getInt32(decPtr,!1),decPtr+=4,fileContent=decompressed.slice(decPtr,decPtr+entrySize-5),decPtr+=entrySize-5,":"!==String.fromCharCode(decView.getUint8(decPtr++)))throw new Error(`Misaligned entry: ${fileName}`)}else fileContent=decompressed.slice(decPtr,decPtr+entrySize),decPtr+=entrySize;if(">"!==String.fromCharCode(decView.getUint8(decPtr++)))throw new Error(`Missing terminator: ${fileName}`);filesMap.set(fileName,fileContent.buffer),filesCount--}return detectedVersion=detectVersionFromFiles(filesMap),showStatusMessage(`Unpacked ${filesMap.size} files.`,"success"),filesMap}catch(err){throw showStatusMessage(`Failed: ${err.message}`,"error"),err}}async function updateLevelDatLevelName(worldName){if(extractedFiles.has("level.dat")){const buf=extractedFiles.get("level.dat");let bytes=new Uint8Array(buf),gz=!1;try{bytes.length>2&&31===bytes[0]&&139===bytes[1]&&(bytes=pako.ungzip(bytes),gz=!0);const parsed=await new Promise((res,rej)=>nbt.parse(bytes.buffer,(e,r)=>e?rej(e):res(r))),v=parsed.value;v.Data&&v.Data.value&&(v.Data.value.LevelName||(v.Data.value.LevelName={type:"string",value:""}),v.Data.value.LevelName.value=worldName);let out=new Uint8Array(nbt.writeUncompressed(parsed));gz&&(out=pako.gzip(out)),extractedFiles.set("level.dat",out.buffer)}catch(e){console.warn("level.dat name update failed:",e)}}extractedFiles.has("world-name")&&extractedFiles.set("world-name",(new TextEncoder).encode(worldName).buffer)}async function encryptEpk(filesMap,outputName,gameVersion){showStatusMessage("Packing...","info");try{const stream=new ByteArrayOutputStream;stream.writeString("EAGPKG$$","ascii");const fmt="ver2.0";stream.writeUint8(fmt.length),stream.writeString(fmt,"ascii");const baseName=`${outputName}.epk`;stream.writeUint8(baseName.length),stream.writeString(baseName,"ascii");const now=new Date,header2=`\n\n # RePack\n # ${now.getFullYear()+"-"+String(now.getMonth()+1).padStart(2,"0")+"-"+String(now.getDate()).padStart(2,"0")+" "+String(now.getHours()).padStart(2,"0")+":"+String(now.getMinutes()).padStart(2,"0")}\n\n`;if(stream.writeUint16(header2.length),stream.writeString(header2,"ascii"),"undefined"==typeof Long)throw new Error("long.js not loaded.");stream.writeLong(now.getTime());const contentMap=new Map;filesMap.forEach((buf,key)=>{if("file-type"===key||"_metadata"===key)return;let p=key.replace(/\\/g,"/").replace(/^\//,"");outputName&&p.startsWith(`${outputName}/`)&&(p=p.substring(outputName.length+1)),contentMap.set(p,buf)}),stream.writeInt(contentMap.size+1),stream.writeUint8("0".charCodeAt(0));const dec=new ByteArrayOutputStream;dec.writeString("HEAD","ascii");const g="file-type";dec.writeUint8(g.length),dec.writeString(g,"ascii");const f="1.8.8"===gameVersion?"epk/world188":"epk/world152";dec.writeInt(f.length),dec.writeString(f,"ascii"),dec.writeUint8(">".charCodeAt(0));const crc=new CRC32;return contentMap.forEach((buf,key)=>{const bytes=new Uint8Array(buf);crc.reset(),crc.update(bytes),dec.writeString("FILE","ascii"),dec.writeUint8(key.length),dec.writeString(key,"ascii"),dec.writeInt(bytes.length+5),dec.writeInt(crc.getValue()),dec.writeBytes(bytes),dec.writeUint8(":".charCodeAt(0)),dec.writeUint8(">".charCodeAt(0))}),dec.writeString("END$","ascii"),stream.writeBytes(dec.toByteArray()),stream.writeString(":::YEE:>","ascii"),showStatusMessage("Packed.","success"),stream.toByteArray().buffer}catch(err){throw showStatusMessage(`Pack failed: ${err.message}`,"error"),err}}async function saveChanges(){if(activeFile.name){showStatusMessage(`Saving ${activeFile.name}...`,"info");try{let buffer;if(activeFile.name.endsWith(".dat")&&!activeFile.name.endsWith(".dat_old")&&activeFile.nbtParsed){let out=new Uint8Array(nbt.writeUncompressed(activeFile.nbtParsed));activeFile.wasGzipped&&(out=pako.gzip(out)),buffer=out.buffer,fileContentEditor&&(fileContentEditor.value=JSON.stringify(activeFile.nbtParsed.value,null,2))}else{if(!fileContentEditor||void 0===fileContentEditor.value)return;{const val=fileContentEditor.value;buffer=activeFile.name.match(/\.(txt|json|yml|xml|html|css|js|glsl)$/i)?(new TextEncoder).encode(val).buffer:base64ToArrayBuffer(val.split("\n").filter(l=>!l.trim().startsWith("//")).join("").trim())}}extractedFiles.set(activeFile.name,buffer),activeFile.buffer=buffer,showStatusMessage("Saved.","success"),repackButton&&(repackButton.disabled=!1)}catch(err){throw showStatusMessage(`Save failed: ${err.message}`,"error"),err}}}async function selectFileForEditing(fileName,buffer){if(activeFile.name)try{await saveChanges()}catch(_){}if(fileContentEditor){const parent=fileContentEditor.parentElement;parent&&parent.querySelectorAll(".hex-viewer").forEach(el=>el.remove()),fileContentEditor.style.display="",fileContentEditor.disabled=!1}fileListContainer&&fileListContainer.querySelectorAll(".file-list-item").forEach(i=>i.classList.remove("selected"));const sel=fileListContainer&&fileListContainer.querySelector(`[data-filename="${CSS.escape(fileName)}"]`);if(sel&&sel.classList.add("selected"),showStatusMessage(`Opening ${fileName}...`,"info"),saveChangesButton&&(saveChangesButton.disabled=!1),removeFileButton&&(removeFileButton.disabled=!1),activeFileNameDisplay&&(activeFileNameDisplay.textContent=fileName),activeFile={name:fileName,buffer:buffer,nbtParsed:null,wasGzipped:!1},selectedInventoryIndex=null,fileName.endsWith(".dat")&&!fileName.endsWith(".dat_old")&&"session.lock"!==fileName)try{if(await viewNBTData(fileName,buffer),activeFile.nbtParsed&&activeFile.nbtParsed.value&&activeFile.nbtParsed.value.Data){const worldData=activeFile.nbtParsed.value.Data.value;if(worldData&&worldData.Player)return parsedSaveData=activeFile.nbtParsed.value,moddingMenuContainer&&(moddingMenuContainer.classList.remove("hidden-by-default"),fileContentEditor&&fileContentEditor.classList.add("hidden-by-default")),activeFileNameDisplay&&(activeFileNameDisplay.textContent=fileName),void renderModdingMenu(worldData)}}catch(_){}if(moddingMenuContainer&&moddingMenuContainer.classList.add("hidden-by-default"),fileContentEditor&&fileContentEditor.classList.remove("hidden-by-default"),clearModdingMenu(),fileName.match(/\.(txt|json|yml|xml|html|css|js|glsl)$/i))try{const text=new TextDecoder("utf-8",{fatal:!0}).decode(buffer);fileContentEditor&&(fileContentEditor.value=text)}catch(_){fileContentEditor&&(fileContentEditor.value=`// UTF-8 decode failed. Raw base64:\n${arrayBufferToBase64(buffer)}`)}else if("file-type"===fileName||"world-name"===fileName||"world-owner"===fileName)try{fileContentEditor&&(fileContentEditor.value=(new TextDecoder).decode(buffer))}catch(_){fileContentEditor&&(fileContentEditor.value=arrayBufferToBase64(buffer))}else{fileContentEditor&&(fileContentEditor.style.display="none");const parent=fileContentEditor?fileContentEditor.parentElement:null;if(parent){const hexDiv=document.createElement("div");hexDiv.innerHTML=renderHexView(buffer),parent.insertBefore(hexDiv.firstChild,fileContentEditor)}fileContentEditor&&(fileContentEditor.value=`// Binary file (hex view above). Edit as base64 below:\n${arrayBufferToBase64(buffer)}`),showStatusMessage(`Hex view loaded for ${fileName}.`,"info")}}function resetFileEditor(){if(fileContentEditor){fileContentEditor.value="",fileContentEditor.disabled=!0,fileContentEditor.style.display="",fileContentEditor.classList.remove("hidden-by-default");const parent=fileContentEditor.parentElement;parent&&parent.querySelectorAll(".hex-viewer").forEach(e=>e.remove())}saveChangesButton&&(saveChangesButton.disabled=!0),activeFileNameDisplay&&(activeFileNameDisplay.textContent="None"),removeFileButton&&(removeFileButton.disabled=!0),moddingMenuContainer&&moddingMenuContainer.classList.add("hidden-by-default"),activeFile={name:null,buffer:null,nbtParsed:null,wasGzipped:!1};const sel=fileListContainer&&fileListContainer.querySelector(".file-list-item.selected");sel&&sel.classList.remove("selected")}function renderModdingMenu(worldNbtData){if(moddingMenuContainer=document.getElementById("moddingMenuContainer"),!moddingMenuContainer)return;const player=worldNbtData.Player?worldNbtData.Player.value:{},inv=player.Inventory||{value:{value:[]}},pos=player.Pos?player.Pos.value.value:[0,64,0],spawn=[worldNbtData.SpawnX?worldNbtData.SpawnX.value:0,worldNbtData.SpawnY?worldNbtData.SpawnY.value:64,worldNbtData.SpawnZ?worldNbtData.SpawnZ.value:0],abilities=player.abilities?player.abilities.value:{},activeEffects=player.ActiveEffects?player.ActiveEffects.value.value:[],gamerules=worldNbtData.GameRules?worldNbtData.GameRules.value:{},thundering=(worldNbtData.weatherTime&&worldNbtData.weatherTime.value,worldNbtData.thundering?worldNbtData.thundering.value:0),raining=worldNbtData.raining?worldNbtData.raining.value:0;moddingMenuContainer.innerHTML=`\n
\n
\n \n \n \n \n \n \n
\n\n \x3c!-- World Tab --\x3e\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n \n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n
\n \n
\n
\n
\n
\n
\n
\n
\n
\n\n \x3c!-- Player Tab --\x3e\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n \n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n
\n \n
\n ${["flying","mayfly","instabuild","invulnerable"].map(k=>`\n
\n \n \n
`).join("")}\n
\n
\n
\n\n \x3c!-- Inventory Tab --\x3e\n
\n
\n
\n \x3c!-- Armor Slots --\x3e\n \n
\n \x3c!-- Main grid --\x3e\n \n
\n
\n
\n
\n
\n
\n \x3c!-- Item creator --\x3e\n
\n \n
\n \n
\n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n \n \n
\n \n
\n
\n\n \x3c!-- Deep inspection --\x3e\n
\n
\n Select a slot\n \n
\n
\n
\n
Durability
\n

0 = pristine

\n
\n \n \n
\n
\n
\n
Enchantments
\n
\n
\n \n \n \n
\n
\n
\n
\n
\n\n \x3c!-- Effects Tab --\x3e\n
\n \n
\n
\n \n
\n \n
\n \n \n
\n
\n \n \n
\n \n
\n
\n
\n\n \x3c!-- Gamerules Tab --\x3e\n
\n \n
\n
\n\n \x3c!-- Tools Tab --\x3e\n
\n \x3c!-- Ore Finder --\x3e\n
\n \n

Generates optimal Y-level ranges near your position.

\n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n \n
\n
\n
\n\n \x3c!-- Quick Presets --\x3e\n
\n \n
\n \n \n \n \n \n \n
\n
\n\n \x3c!-- Achievement Unlock --\x3e\n
\n \n

Clears all achievement progress — they'll be re-granted next login, or add all at once.

\n
\n \n \n
\n
\n
\n\n
\n \n
\n
`;const tabs=moddingMenuContainer.querySelectorAll(".tab-button");tabs.forEach(btn=>{btn.addEventListener("click",()=>{tabs.forEach(b=>b.classList.remove("active")),btn.classList.add("active");const tid=btn.dataset.tab;moddingMenuContainer.querySelectorAll(".tab-content").forEach(tc=>{tc.classList.toggle("hidden-by-default",tc.id!==`${tid}Tab`)})})}),renderArmorGrid(inv),renderMinecraftGrid(inv),renderEffects(activeEffects),renderGamerules(gamerules),setupSuggestions(),addModdingMenuListeners(worldNbtData)}function esc(s){return String(s).replace(/"/g,""").replace(//g,">")}function renderArmorGrid(inventoryNbt){const container=document.getElementById("armorGrid");if(!container)return;container.innerHTML="";const itemsBySlot={};inventoryNbt&&inventoryNbt.value&&inventoryNbt.value.value&&inventoryNbt.value.value.forEach((item,idx)=>{item.Slot&&(itemsBySlot[item.Slot.value]={node:item,index:idx})}),ARMOR_SLOTS.forEach(({slot:slot,label:label})=>{const row=document.createElement("div");row.className="armor-strip";const lbl=document.createElement("span");lbl.className="armor-strip-label",lbl.textContent=label;const slotEl=createSlotElement(slot,itemsBySlot[slot],!0);row.appendChild(lbl),row.appendChild(slotEl),container.appendChild(row)})}function renderMinecraftGrid(inventoryNbt){const mainGrid=document.getElementById("mcMainGrid"),hotbarGrid=document.getElementById("mcHotbarGrid");if(!mainGrid||!hotbarGrid)return;mainGrid.innerHTML="",hotbarGrid.innerHTML="";const slotsMap={};inventoryNbt&&inventoryNbt.value&&inventoryNbt.value.value&&inventoryNbt.value.value.forEach((item,idx)=>{item.Slot&&(slotsMap[item.Slot.value]={node:item,index:idx})});for(let s=9;s<=35;s++)mainGrid.appendChild(createSlotElement(s,slotsMap[s]));for(let s=0;s<=8;s++)hotbarGrid.appendChild(createSlotElement(s,slotsMap[s]))}function createSlotElement(slotNum,itemData,isArmor=!1){const el=document.createElement("div");if(el.className=`mc-slot${isArmor?" armor-slot":""}${selectedInventoryIndex===(itemData?itemData.index:null)&&itemData?" selected":""}`,el.dataset.slot=slotNum,itemData){const n=itemData.node,rawId=n.id&&("string"===n.id.type?n.id.value:String(n.id.value)),shortId=rawId?rawId.split(":")[1]||rawId:"?",count=n.Count?n.Count.value:1;el.innerHTML=`
\n ${shortId.substring(0,5)}\n ${count}\n
`,el.addEventListener("click",()=>selectSlotForInspection(itemData.index,n))}else el.innerHTML=`${slotNum}`,el.addEventListener("click",()=>{const dst=document.getElementById("newItemSlot");if(dst&&(dst.value=slotNum),isArmor){const tgt=document.getElementById("newItemTarget");tgt&&(tgt.value="armor")}hideDeepInspectionPanel()});return el}function selectSlotForInspection(idx,itemNode){if(selectedInventoryIndex=idx,parsedSaveData.Data&&parsedSaveData.Data.value.Player){const inv=parsedSaveData.Data.value.Player.value.Inventory;renderArmorGrid(inv),renderMinecraftGrid(inv)}const panel=document.getElementById("deepModdingPanel"),header=document.getElementById("selectedItemHeader"),damInp=document.getElementById("itemDamageInput");if(!panel)return;panel.classList.remove("hidden-by-default");const rawId=itemNode.id?itemNode.id.value:"unknown";header&&(header.textContent=`${rawId.split(":")[1]||rawId} (idx ${idx})`),damInp&&(damInp.value=itemNode.Damage?itemNode.Damage.value:0),renderEnchantments(itemNode)}function hideDeepInspectionPanel(){selectedInventoryIndex=null;const p=document.getElementById("deepModdingPanel");if(p&&p.classList.add("hidden-by-default"),parsedSaveData.Data&&parsedSaveData.Data.value.Player){const inv=parsedSaveData.Data.value.Player.value.Inventory;renderArmorGrid(inv),renderMinecraftGrid(inv)}}function renderEnchantments(itemNode){const list=document.getElementById("enchantmentsList");if(!list)return;list.innerHTML="";let enchs=[];if(itemNode.tag&&itemNode.tag.value){const t=itemNode.tag.value;enchs=t.ench&&t.ench.value&&t.ench.value.value||t.Enchantments&&t.Enchantments.value&&t.Enchantments.value.value||[]}0!==enchs.length?enchs.forEach((e,i)=>{const match=ENCHANTMENTS_DB.find(d=>d.id===e.id.value),name=match?match.name:`ID ${e.id.value}`,row=document.createElement("div");row.className="potion-effect-row",row.innerHTML=`${name}Lvl ${e.lvl.value}`,row.querySelector("button").addEventListener("click",()=>{enchs.splice(i,1),renderEnchantments(itemNode)}),list.appendChild(row)}):list.innerHTML='

None

'}function renderEffects(effectList){const container=document.getElementById("effectsList");container&&(container.innerHTML="",effectList&&0!==effectList.length?effectList.forEach((e,i)=>{const match=POTION_EFFECTS_DB.find(d=>d.id===e.Id.value),name=match?match.name:`Effect ${e.Id.value}`,dur=e.Duration?Math.round(e.Duration.value/20):0,amp=e.Amplifier?e.Amplifier.value+1:1,row=document.createElement("div");row.className="potion-effect-row",row.innerHTML=`${name}Lvl ${amp} · ${dur}s`,row.querySelector("button").addEventListener("click",()=>{effectList.splice(i,1),renderEffects(effectList)}),container.appendChild(row)}):container.innerHTML='

No active effects.

')}function renderGamerules(gamerules){const grid=document.getElementById("gameruleGrid");grid&&(grid.innerHTML="",(Object.keys(gamerules).length>0?Object.keys(gamerules):DEFAULT_GAMERULES).forEach(key=>{const val=gamerules[key]?gamerules[key].value:"true",row=document.createElement("div");row.className="gamerule-row";const isBool="true"===val||"false"===val;row.innerHTML=isBool?`${key}\n `:`${key}\n `,grid.appendChild(row)}))}function setupSuggestions(){const input=document.getElementById("newItemId"),box=document.getElementById("itemSuggestions");input&&box&&(input.addEventListener("input",()=>{const q=input.value.trim().toLowerCase();if(box.innerHTML="",!q)return void box.classList.add("hidden");const matches=MINECRAFT_ITEMS_DB.filter(i=>i.includes(q)).slice(0,6);0!==matches.length?(box.classList.remove("hidden"),matches.forEach(item=>{const row=document.createElement("div");row.className="suggestion-item",row.textContent=item,row.addEventListener("mousedown",e=>{e.preventDefault(),input.value=item,box.innerHTML="",box.classList.add("hidden")}),box.appendChild(row)})):box.classList.add("hidden")}),input.addEventListener("blur",()=>setTimeout(()=>{box.innerHTML="",box.classList.add("hidden")},150)))}function addModdingMenuListeners(worldNbtData){const playerNode=worldNbtData.Player?worldNbtData.Player.value:{},inventory=playerNode.Inventory||{value:{value:[]}},invArray=inventory.value.value,activeEffects=playerNode.ActiveEffects?playerNode.ActiveEffects.value.value:[],addItemBtn=document.getElementById("addItemButton");addItemBtn&&(addItemBtn.onclick=()=>{const idVal=(document.getElementById("newItemId")||{}).value||"",countVal=parseInt((document.getElementById("newItemCount")||{}).value)||1,slotVal=(document.getElementById("newItemSlot")||{}).value,target=(document.getElementById("newItemTarget")||{}).value||"inventory";if(idVal.trim())if(countVal<1||countVal>64)showStatusMessage("Count must be 1–64.","error");else{if("armor"===target){let slotNum=parseInt(slotVal);if(isNaN(slotNum)||!ARMOR_SLOTS.some(a=>a.slot===slotNum)){const usedSlots=new Set(invArray.map(i=>i.Slot.value)),pick=ARMOR_SLOTS.find(a=>!usedSlots.has(a.slot));if(!pick)return void showStatusMessage("All armor slots occupied.","error");slotNum=pick.slot}const existing=invArray.findIndex(i=>i.Slot.value===slotNum),item={id:{type:"string",value:idVal.trim()},Count:{type:"byte",value:countVal},Slot:{type:"byte",value:slotNum},Damage:{type:"short",value:0},tag:{type:"compound",value:{}}};-1!==existing?invArray[existing]=item:invArray.push(item)}else{const existingSlots=new Set(invArray.filter(i=>i.Slot.value<36).map(i=>i.Slot.value));let targetSlot=parseInt(slotVal);if(isNaN(targetSlot)||targetSlot<0||targetSlot>35)for(targetSlot=0;existingSlots.has(targetSlot)&&targetSlot<36;)targetSlot++;if(targetSlot>=36)return void showStatusMessage("Inventory full.","error");if(existingSlots.has(targetSlot))return void showStatusMessage(`Slot ${targetSlot} occupied.`,"error");invArray.push({id:{type:"string",value:idVal.trim()},Count:{type:"byte",value:countVal},Slot:{type:"byte",value:targetSlot},Damage:{type:"short",value:0},tag:{type:"compound",value:{}}})}renderArmorGrid(inventory),renderMinecraftGrid(inventory),document.getElementById("newItemId").value="",document.getElementById("newItemCount").value="1",document.getElementById("newItemSlot").value="",showStatusMessage(`Added ${countVal}x ${idVal}.`,"success")}else showStatusMessage("Enter an item ID.","error")});const delBtn=document.getElementById("deleteItemButton");delBtn&&(delBtn.onclick=()=>{null!==selectedInventoryIndex&&(invArray.splice(selectedInventoryIndex,1),hideDeepInspectionPanel(),renderArmorGrid(inventory),renderMinecraftGrid(inventory),showStatusMessage("Item removed.","success"))});const damInp=document.getElementById("itemDamageInput");damInp&&damInp.addEventListener("input",()=>{if(null!==selectedInventoryIndex){const item=invArray[selectedInventoryIndex];if(item){const v=parseInt(damInp.value)||0;item.Damage?item.Damage.value=v:item.Damage={type:"short",value:v}}}});const enchBtn=document.getElementById("addEnchantmentButton");enchBtn&&(enchBtn.onclick=()=>{if(null===selectedInventoryIndex)return;const item=invArray[selectedInventoryIndex];if(!item)return;const eid=parseInt(document.getElementById("enchantmentSelect").value),elv=parseInt(document.getElementById("enchantmentLevel").value)||1;item.tag||(item.tag={type:"compound",value:{}}),item.tag.value.ench||(item.tag.value.ench={type:"list",value:{type:"compound",value:[]}});const list=item.tag.value.ench.value.value,ei=list.findIndex(e=>e.id.value===eid);-1!==ei?list[ei].lvl.value=elv:list.push({id:{type:"short",value:eid},lvl:{type:"short",value:elv}}),renderEnchantments(item),showStatusMessage("Enchantment added.","success")});const effBtn=document.getElementById("addEffectButton");effBtn&&(effBtn.onclick=()=>{const eid=parseInt(document.getElementById("effectSelect").value),amp=parseInt(document.getElementById("effectAmp").value)||0,dur=parseInt(document.getElementById("effectDur").value)||60,existing=activeEffects.findIndex(e=>e.Id.value===eid),obj={Id:{type:"byte",value:eid},Amplifier:{type:"byte",value:amp},Duration:{type:"int",value:20*dur},ShowParticles:{type:"byte",value:1}};-1!==existing?activeEffects[existing]=obj:activeEffects.push(obj),playerNode.ActiveEffects||(playerNode.ActiveEffects={type:"list",value:{type:"compound",value:activeEffects}}),renderEffects(activeEffects),showStatusMessage("Effect applied.","success")});const oreBtn=document.getElementById("generateOreBtn");oreBtn&&(oreBtn.onclick=()=>{const oreName=document.getElementById("oreSelect").value,ox=parseInt(document.getElementById("oreX").value)||0,oz=parseInt(document.getElementById("oreZ").value)||0,range=ORE_RANGES[oreName],results=document.getElementById("oreResults");if(!results||!range)return;results.innerHTML="";const coords=[];for(let i=0;i<15;i++){const y=range.min+Math.floor(Math.random()*(range.max-range.min)),xOff=Math.floor(32*(Math.random()-.5)),zOff=Math.floor(32*(Math.random()-.5));coords.push({x:ox+xOff,y:y,z:oz+zOff})}coords.sort((a,b)=>Math.abs(a.y-range.best)-Math.abs(b.y-range.best)),coords.forEach(c=>{const row=document.createElement("div");row.className="ore-result-row",row.innerHTML=`${oreName}X ${c.x} Y ${c.y} Z ${c.z}`,results.appendChild(row)}),showStatusMessage(`Generated ${coords.length} ${oreName} coordinates.`,"success")});const presets={presetGodMode:()=>{if(playerNode.Health&&(playerNode.Health.value=20),playerNode.foodLevel&&(playerNode.foodLevel.value=20),playerNode.abilities){const a=playerNode.abilities.value;a.invulnerable?a.invulnerable.value=1:playerNode.abilities.value.invulnerable={type:"byte",value:1}}showStatusMessage("God mode on.","success")},presetFullInv:()=>{for(let s=0;s<36;s++)invArray.find(i=>i.Slot.value===s)||invArray.push({id:{type:"string",value:"minecraft:diamond"},Count:{type:"byte",value:64},Slot:{type:"byte",value:s},Damage:{type:"short",value:0},tag:{type:"compound",value:{}}});renderArmorGrid(inventory),renderMinecraftGrid(inventory),showStatusMessage("Inventory filled with diamonds.","success")},presetDiamond:()=>{[{id:"minecraft:diamond_helmet",slot:103},{id:"minecraft:diamond_chestplate",slot:102},{id:"minecraft:diamond_leggings",slot:101},{id:"minecraft:diamond_boots",slot:100},{id:"minecraft:diamond_sword",slot:0},{id:"minecraft:diamond_pickaxe",slot:1}].forEach(({id:id,slot:slot})=>{const idx=invArray.findIndex(i=>i.Slot.value===slot),item={id:{type:"string",value:id},Count:{type:"byte",value:1},Slot:{type:"byte",value:slot},Damage:{type:"short",value:0},tag:{type:"compound",value:{}}};-1!==idx?invArray[idx]=item:invArray.push(item)}),renderArmorGrid(inventory),renderMinecraftGrid(inventory),showStatusMessage("Diamond gear equipped.","success")},presetClear:()=>{invArray.length=0,hideDeepInspectionPanel(),renderArmorGrid(inventory),renderMinecraftGrid(inventory),showStatusMessage("Inventory cleared.","success")},presetDayTime:()=>{worldNbtData.Time&&(worldNbtData.Time.value=1e3);const inp=document.getElementById("worldTimeInput");inp&&(inp.value=1e3),showStatusMessage("Time set to day.","success")},presetMaxXP:()=>{playerNode.XpLevel&&(playerNode.XpLevel.value=100);const inp=document.getElementById("playerXpInput");inp&&(inp.value=100),showStatusMessage("XP set to level 100.","success")}};Object.entries(presets).forEach(([id,fn])=>{const btn=document.getElementById(id);btn&&(btn.onclick=fn)});const achieveAll=document.getElementById("achieveUnlockAll");achieveAll&&(achieveAll.onclick=()=>{playerNode.achievements||(playerNode.achievements={type:"compound",value:{}}),["openInventory","mineWood","buildWorkBench","buildPickaxe","buildFurnace","acquireIron","buildHoe","makeBread","bakeCake","buildBetterPickaxe","cookFish","onARail","buildSword","killEnemy","killCow","flyPig","snipeSkeleton","diamonds","diamondsToYou","portal","ghast","blazeRod","potion","theEnd","theEnd2","enchantments","overkill","bookcase","exploreAllBiomes","spawnWither","witherKiller","fullBeacon","breed","full_beacon_tier1","full_beacon_tier2","full_beacon_tier3"].forEach(k=>{playerNode.achievements.value[k]={type:"byte",value:1}}),showStatusMessage("All achievements unlocked.","success")});const achieveClear=document.getElementById("achieveClearAll");achieveClear&&(achieveClear.onclick=()=>{playerNode.achievements&&(playerNode.achievements.value={}),showStatusMessage("Achievement data cleared.","success")});const applyBtn=document.getElementById("applyModificationsButton");applyBtn&&(applyBtn.onclick=async()=>{try{const wni=document.getElementById("worldNameInput"),gms=document.getElementById("gameModeSelect"),dif=document.getElementById("difficultyInput"),wti=document.getElementById("worldTimeInput"),cht=document.getElementById("cheatsToggle"),wsd=document.getElementById("worldSeedInput"),spx=document.getElementById("spawnX"),spy=document.getElementById("spawnY"),spz=document.getElementById("spawnZ"),wr=document.getElementById("weatherRaining"),wth=document.getElementById("weatherThunder");wni&&worldNbtData.LevelName&&(worldNbtData.LevelName.value=wni.value),gms&&worldNbtData.GameType&&(worldNbtData.GameType.value=parseInt(gms.value)),dif&&worldNbtData.Difficulty&&(worldNbtData.Difficulty.value=parseInt(dif.value)),wti&&worldNbtData.Time&&(worldNbtData.Time.value=parseInt(wti.value)),cht&&worldNbtData.allowCommands&&(worldNbtData.allowCommands.value=cht.checked?1:0),wsd&&worldNbtData.RandomSeed&&(worldNbtData.RandomSeed.value=parseInt(wsd.value)),spx&&worldNbtData.SpawnX&&(worldNbtData.SpawnX.value=parseInt(spx.value)),spy&&worldNbtData.SpawnY&&(worldNbtData.SpawnY.value=parseInt(spy.value)),spz&&worldNbtData.SpawnZ&&(worldNbtData.SpawnZ.value=parseInt(spz.value)),wr&&worldNbtData.raining&&(worldNbtData.raining.value=wr.checked?1:0),wth&&worldNbtData.thundering&&(worldNbtData.thundering.value=wth.checked?1:0);const h=document.getElementById("playerHealth"),fud=document.getElementById("playerFood"),sat=document.getElementById("playerSaturation"),xp=document.getElementById("playerXpInput"),sc=document.getElementById("playerScore"),fir=document.getElementById("playerFire"),air=document.getElementById("playerAir"),px=document.getElementById("playerPosX"),py=document.getElementById("playerPosY"),pz=document.getElementById("playerPosZ");h&&playerNode.Health&&(playerNode.Health.value=parseFloat(h.value)),fud&&playerNode.foodLevel&&(playerNode.foodLevel.value=parseInt(fud.value)),sat&&playerNode.foodSaturationLevel&&(playerNode.foodSaturationLevel.value=parseFloat(sat.value)),xp&&playerNode.XpLevel&&(playerNode.XpLevel.value=parseInt(xp.value)),sc&&playerNode.Score&&(playerNode.Score.value=parseInt(sc.value)),fir&&playerNode.Fire&&(playerNode.Fire.value=parseInt(fir.value)),air&&playerNode.Air&&(playerNode.Air.value=parseInt(air.value)),px&&playerNode.Pos&&playerNode.Pos.value&&playerNode.Pos.value.value&&(playerNode.Pos.value.value[0]=parseFloat(px.value)||0,playerNode.Pos.value.value[1]=parseFloat(py.value)||0,playerNode.Pos.value.value[2]=parseFloat(pz.value)||0),["flying","mayfly","instabuild","invulnerable"].forEach(k=>{const el=document.getElementById(`ability_${k}`);el&&playerNode.abilities&&void 0!==playerNode.abilities.value[k]&&(playerNode.abilities.value[k].value=el.checked?1:0)});const gr=worldNbtData.GameRules?worldNbtData.GameRules.value:{};Object.keys(gr).forEach(key=>{const el=document.getElementById(`gr_${key}`);if(!el)return;const val="checkbox"===el.type?el.checked?"true":"false":el.value;gr[key]&&(gr[key].value=val)}),await saveChanges(),epkFile&&await cacheEPK(epkFile.name,extractedFiles),showStatusMessage("Changes applied.","success")}catch(err){showStatusMessage(`Error: ${err.message}`,"error")}})}function clearModdingMenu(){parsedSaveData={},selectedInventoryIndex=null,moddingMenuContainer&&(moddingMenuContainer.innerHTML="")}window.showStatus=showStatusMessage;class ByteArrayOutputStream{constructor(){this.buffer=[]}writeUint8(v){const b=new Uint8Array(1);new DataView(b.buffer).setUint8(0,v),this.buffer.push(b.buffer)}writeUint16(v){const b=new Uint8Array(2);new DataView(b.buffer).setUint16(0,v,!1),this.buffer.push(b.buffer)}writeInt(v){const b=new Uint8Array(4);new DataView(b.buffer).setInt32(0,v,!1),this.buffer.push(b.buffer)}writeLong(v){if("undefined"==typeof Long)throw new Error("long.js required.");const l=Long.fromValue(v),b=new Uint8Array(8),dv=new DataView(b.buffer);dv.setInt32(0,l.high,!1),dv.setInt32(4,l.low,!1),this.buffer.push(b.buffer)}writeString(s){const b=(new TextEncoder).encode(s);this.buffer.push(b.buffer)}writeBytes(b){const a=new Uint8Array(b);this.buffer.push(a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength))}toByteArray(){if(0===this.buffer.length)return new Uint8Array(0);const len=this.buffer.reduce((s,b)=>s+b.byteLength,0),out=new Uint8Array(len);let off=0;return this.buffer.forEach(b=>{out.set(new Uint8Array(b),off),off+=b.byteLength}),out}}function arraysEqual(a,b){if(a.length!==b.length)return!1;for(let i=0;i>>1:t>>>1;this.table[i]=t}}update(b){let c=this.crc;for(let i=0;i>>8^this.table[255&(c^b[i])];this.crc=c}getValue(){return~this.crc}reset(){this.crc=-1}}function runLoadingScreen(){const screen=document.getElementById("loadingScreen"),bar=document.getElementById("loadingBar"),label=document.getElementById("loadingLabel");if(!screen)return;const steps=[[10,"Loading dependencies..."],[30,"Initialising NBT parser..."],[55,"Setting up workspace..."],[75,"Restoring session..."],[90,"Almost ready..."],[100,"Done."]];let i=0;const tick=()=>{if(i>=steps.length)return void setTimeout(()=>{screen.classList.add("hidden")},300);const[pct,msg]=steps[i++];bar&&(bar.style.width=`${pct}%`),label&&(label.textContent=msg),setTimeout(tick,200+150*Math.random())};setTimeout(tick,100)}document.addEventListener("DOMContentLoaded",async()=>{runLoadingScreen();try{await openDB()}catch(e){console.warn("IndexedDB unavailable:",e)}updateCacheBadge();const savedTheme=localStorage.getItem("repack_theme")||"dark";document.documentElement.dataset.theme=savedTheme;const lastPage=sessionStorage.getItem("repack_page")||"home";epkFileInput=document.getElementById("epkFileInput"),decompileButton=document.getElementById("decompileButton"),repackButton=document.getElementById("repackButton"),statusMessageDiv=document.getElementById("statusMessage"),fileListContainer=document.getElementById("fileList"),fileContentEditor=document.getElementById("fileContentEditor"),saveChangesButton=document.getElementById("saveChangesButton"),messageBox=document.getElementById("messageBox"),messageTitle=document.getElementById("messageTitle"),messageContent=document.getElementById("messageContent"),messageCloseBtn=document.getElementById("messageCloseBtn"),epkNameDisplay=document.getElementById("epkName"),activeFileNameDisplay=document.getElementById("activeFileNameDisplay"),addFileButton=document.getElementById("addFileButton"),removeFileButton=document.getElementById("removeFileButton"),moddingMenuContainer=document.getElementById("moddingMenuContainer"),decompileButton&&(decompileButton.disabled=!0),repackButton&&(repackButton.disabled=!0),saveChangesButton&&(saveChangesButton.disabled=!0),fileContentEditor&&(fileContentEditor.disabled=!0),removeFileButton&&(removeFileButton.disabled=!0),showStatusMessage("Load an EPK to begin.","info"),clearFileListDisplay(),document.querySelectorAll(".header-nav-btn").forEach(btn=>{btn.addEventListener("click",()=>showPage(btn.dataset.page))}),showPage(lastPage),epkFileInput&&epkFileInput.addEventListener("change",e=>{epkFile=e.target.files[0]||null,epkFile?(showStatusMessage(`Loaded: ${epkFile.name}`,"info"),decompileButton&&(decompileButton.disabled=!1),epkNameDisplay&&(epkNameDisplay.textContent=epkFile.name)):(decompileButton&&(decompileButton.disabled=!0),epkNameDisplay&&(epkNameDisplay.textContent="None"))}),decompileButton&&decompileButton.addEventListener("click",()=>{if(!epkFile)return void showMessageBox("No file","Choose an EPK file first.");showStatusMessage("Unpacking...","info"),decompileButton.disabled=!0,resetFileEditor();const reader=new FileReader;reader.onload=async ev=>{try{extractedFiles=await decryptEpk(ev.target.result),displayExtractedFiles(extractedFiles),repackButton&&(repackButton.disabled=!1),decompileButton.disabled=!1,showStatusMessage(`${extractedFiles.size} files loaded. Version: ${detectedVersion||"unknown"}.`,"success"),await cacheEPK(epkFile.name,extractedFiles),showPage("editor")}catch(err){showStatusMessage(`Failed: ${err.message}`,"error"),decompileButton.disabled=!1}},reader.onerror=()=>{showStatusMessage("File read error.","error"),decompileButton.disabled=!1},reader.readAsArrayBuffer(epkFile)}),saveChangesButton&&saveChangesButton.addEventListener("click",async()=>{try{await saveChanges(),epkFile&&await cacheEPK(epkFile.name,extractedFiles)}catch(_){}}),repackButton&&repackButton.addEventListener("click",async()=>{if(0===extractedFiles.size)return void showMessageBox("Nothing to pack","Load and unpack an EPK first.");if(activeFile.name)try{await saveChanges()}catch(e){return}const worldName=epkFile&&epkFile.name.replace(/\.epk$/i,"").trim().replace(/[^\w\s\-.]/g,"")||"EaglerWorld",gameVersion=detectedVersion||detectVersionFromFiles(extractedFiles);showStatusMessage(`Packing as ${gameVersion}...`,"info"),decompileButton&&(decompileButton.disabled=!0),repackButton.disabled=!0;try{await updateLevelDatLevelName(worldName);const packed=await encryptEpk(extractedFiles,worldName,gameVersion),blob=new Blob([packed],{type:"application/octet-stream"}),url=URL.createObjectURL(blob),a=document.createElement("a");a.href=url,a.download=`${worldName}.epk`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(url),showStatusMessage(`Downloaded ${worldName}.epk (${gameVersion}).`,"success")}catch(err){showStatusMessage(`Pack failed: ${err.message}`,"error")}finally{decompileButton&&(decompileButton.disabled=!1),repackButton.disabled=!1}}),addFileButton&&addFileButton.addEventListener("click",()=>{const inp=document.createElement("input");inp.type="file",inp.onchange=e=>{const f=e.target.files[0];if(!f)return;const r=new FileReader;r.onload=ev=>{extractedFiles.set(f.name,ev.target.result),displayExtractedFiles(extractedFiles),repackButton&&(repackButton.disabled=!1),showStatusMessage(`Added ${f.name}.`,"success")},r.readAsArrayBuffer(f)},inp.click()}),removeFileButton&&removeFileButton.addEventListener("click",async()=>{activeFile.name?await showConfirmBox("Remove file",`Remove "${activeFile.name}" from the package?`)&&(extractedFiles.delete(activeFile.name),resetFileEditor(),displayExtractedFiles(extractedFiles),showStatusMessage("File removed.","success")):showMessageBox("Nothing selected","Click a file first.")}),messageCloseBtn&&messageCloseBtn.addEventListener("click",closeMessageBox);const badge=document.getElementById("cacheBadge");badge&&badge.addEventListener("click",async()=>{const list=await listCachedEPKs();0!==list.length?showMessageBox("Cached Saves",list.map(r=>`${r.name} (${new Date(r.ts).toLocaleDateString()})`).join("\n")):showMessageBox("No cached saves","Import an EPK to cache it automatically.")}),document.querySelectorAll("[data-tab]").forEach(btn=>{btn.closest("#moddingMenuContainer")||btn.addEventListener("click",()=>{btn.dataset.tab,btn.closest(".app-card, section")&&btn.closest(".app-card, section").querySelectorAll(".tab-button").forEach(b=>b.classList.remove("active")),btn.classList.add("active")})}),window.showModdingMenu=(show,name)=>{moddingMenuContainer&&fileContentEditor&&(show?(moddingMenuContainer.classList.remove("hidden-by-default"),fileContentEditor.classList.add("hidden-by-default")):(moddingMenuContainer.classList.add("hidden-by-default"),fileContentEditor.classList.remove("hidden-by-default")),activeFileNameDisplay&&(activeFileNameDisplay.textContent=name||"None"))},window.showMessageBox=showMessageBox}); diff --git a/eaglercraft-saveeditor/files/nbt.js b/eaglercraft-saveeditor/files/nbt.js new file mode 100644 index 0000000..b55794a --- /dev/null +++ b/eaglercraft-saveeditor/files/nbt.js @@ -0,0 +1,674 @@ +/* + NBT.js - a JavaScript parser for NBT archives + by Sijmen Mulder + + I, the copyright holder of this work, hereby release it into the public + domain. This applies worldwide. + + In case this is not legally possible: I grant anyone the right to use this + work for any purpose, without any conditions, unless such conditions are + required by law. +*/ + +(function() { + 'use strict'; + + if (typeof ArrayBuffer === 'undefined') { + throw new Error('Missing required type ArrayBuffer'); + } + if (typeof DataView === 'undefined') { + throw new Error('Missing required type DataView'); + } + if (typeof Uint8Array === 'undefined') { + throw new Error('Missing required type Uint8Array'); + } + + /** @exports nbt */ + + var nbt = this; + var zlib = typeof require !== 'undefined' ? require('zlib') : window.zlib; + + /** + * A mapping from type names to NBT type numbers. + * {@link module:nbt.Writer} and {@link module:nbt.Reader} + * have correspoding methods (e.g. {@link module:nbt.Writer#int}) + * for every type. + * + * @type Object + * @see module:nbt.tagTypeNames */ + nbt.tagTypes = { + 'end': 0, + 'byte': 1, + 'short': 2, + 'int': 3, + 'long': 4, + 'float': 5, + 'double': 6, + 'byteArray': 7, + 'string': 8, + 'list': 9, + 'compound': 10, + 'intArray': 11, + 'longArray': 12 + }; + + /** + * A mapping from NBT type numbers to type names. + * + * @type Object + * @see module:nbt.tagTypes */ + nbt.tagTypeNames = {}; + (function() { + for (var typeName in nbt.tagTypes) { + if (nbt.tagTypes.hasOwnProperty(typeName)) { + nbt.tagTypeNames[nbt.tagTypes[typeName]] = typeName; + } + } + })(); + + function hasGzipHeader(data) { + var head = new Uint8Array(data.slice(0, 2)); + return head.length === 2 && head[0] === 0x1f && head[1] === 0x8b; + } + + function encodeUTF8(str) { + var array = [], i, c; + for (i = 0; i < str.length; i++) { + c = str.charCodeAt(i); + if (c < 0x80) { + array.push(c); + } else if (c < 0x800) { + array.push(0xC0 | c >> 6); + array.push(0x80 | c & 0x3F); + } else if (c < 0x10000) { + array.push(0xE0 | c >> 12); + array.push(0x80 | (c >> 6) & 0x3F); + array.push(0x80 | c & 0x3F); + } else { + array.push(0xF0 | (c >> 18) & 0x07); + array.push(0x80 | (c >> 12) & 0x3F); + array.push(0x80 | (c >> 6) & 0x3F); + array.push(0x80 | c & 0x3F); + } + } + return array; + } + + function decodeUTF8(array) { + var codepoints = [], i; + for (i = 0; i < array.length; i++) { + if ((array[i] & 0x80) === 0) { + codepoints.push(array[i] & 0x7F); + } else if (i+1 < array.length && + (array[i] & 0xE0) === 0xC0 && + (array[i+1] & 0xC0) === 0x80) { + codepoints.push( + ((array[i] & 0x1F) << 6) | + ( array[i+1] & 0x3F)); + } else if (i+2 < array.length && + (array[i] & 0xF0) === 0xE0 && + (array[i+1] & 0xC0) === 0x80 && + (array[i+2] & 0xC0) === 0x80) { + codepoints.push( + ((array[i] & 0x0F) << 12) | + ((array[i+1] & 0x3F) << 6) | + ( array[i+2] & 0x3F)); + } else if (i+3 < array.length && + (array[i] & 0xF8) === 0xF0 && + (array[i+1] & 0xC0) === 0x80 && + (array[i+2] & 0xC0) === 0x80 && + (array[i+3] & 0xC0) === 0x80) { + codepoints.push( + ((array[i] & 0x07) << 18) | + ((array[i+1] & 0x3F) << 12) | + ((array[i+2] & 0x3F) << 6) | + ( array[i+3] & 0x3F)); + } + } + return String.fromCharCode.apply(null, codepoints); + } + + /* Not all environments, in particular PhantomJS, supply + Uint8Array.slice() */ + function sliceUint8Array(array, begin, end) { + if ('slice' in array) { + return array.slice(begin, end); + } else { + return new Uint8Array([].slice.call(array, begin, end)); + } + } + + /** + * In addition to the named writing methods documented below, + * the same methods are indexed by the NBT type number as well, + * as shown in the example below. + * + * @constructor + * @see module:nbt.Reader + * + * @example + * var writer = new nbt.Writer(); + * + * // all equivalent + * writer.int(42); + * writer[3](42); + * writer(nbt.tagTypes.int)(42); + * + * // overwrite the second int + * writer.offset = 0; + * writer.int(999); + * + * return writer.buffer; */ + nbt.Writer = function() { + var self = this; + + /* Will be resized (x2) on write if necessary. */ + var buffer = new ArrayBuffer(1024); + + /* These are recreated when the buffer is */ + var dataView = new DataView(buffer); + var arrayView = new Uint8Array(buffer); + + /** + * The location in the buffer where bytes are written or read. + * This increases after every write, but can be freely changed. + * The buffer will be resized when necessary. + * + * @type number */ + this.offset = 0; + + // Ensures that the buffer is large enough to write `size` bytes + // at the current `self.offset`. + function accommodate(size) { + var requiredLength = self.offset + size; + if (buffer.byteLength >= requiredLength) { + return; + } + + var newLength = buffer.byteLength; + while (newLength < requiredLength) { + newLength *= 2; + } + + var newBuffer = new ArrayBuffer(newLength); + var newArrayView = new Uint8Array(newBuffer); + newArrayView.set(arrayView); + + // If there's a gap between the end of the old buffer + // and the start of the new one, we need to zero it out + if (self.offset > buffer.byteLength) { + newArrayView.fill(0, buffer.byteLength, self.offset); + } + + buffer = newBuffer; + dataView = new DataView(newBuffer); + arrayView = newArrayView; + } + + function write(dataType, size, value) { + accommodate(size); + dataView['set' + dataType](self.offset, value); + self.offset += size; + return self; + } + + /** + * Returns the writen data as a slice from the internal buffer, + * cutting off any padding at the end. + * + * @returns {ArrayBuffer} a [0, offset] slice of the interal buffer */ + this.getData = function() { + accommodate(0); /* make sure the offset is inside the buffer */ + return buffer.slice(0, self.offset); + }; + + /** + * @method module:nbt.Writer#byte + * @param {number} value - a signed byte + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.byte] = write.bind(this, 'Int8', 1); + + /** + * @method module:nbt.Writer#ubyte + * @param {number} value - an unsigned byte + * @returns {module:nbt.Writer} itself */ + this.ubyte = write.bind(this, 'Uint8', 1); + + /** + * @method module:nbt.Writer#short + * @param {number} value - a signed 16-bit integer + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.short] = write.bind(this, 'Int16', 2); + + /** + * @method module:nbt.Writer#int + * @param {number} value - a signed 32-bit integer + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.int] = write.bind(this, 'Int32', 4); + + /** + * @method module:nbt.Writer#float + * @param {number} value - a signed 32-bit float + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.float] = write.bind(this, 'Float32', 4); + + /** + * @method module:nbt.Writer#float + * @param {number} value - a signed 64-bit float + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.double] = write.bind(this, 'Float64', 8); + + /** + * As JavaScript does not support 64-bit integers natively, this + * method takes an array of two 32-bit integers that make up the + * upper and lower halves of the long. + * + * @method module:nbt.Writer#long + * @param {Array.} value - [upper, lower] + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.long] = function(value) { + self.int(value[0]); + self.int(value[1]); + return self; + }; + + /** + * @method module:nbt.Writer#byteArray + * @param {Array.|Uint8Array|Buffer} value + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.byteArray] = function(value) { + this.int(value.length); + accommodate(value.length); + arrayView.set(value, this.offset); + this.offset += value.length; + return this; + }; + + /** + * @method module:nbt.Writer#intArray + * @param {Array.} value + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.intArray] = function(value) { + this.int(value.length); + var i; + for (i = 0; i < value.length; i++) { + this.int(value[i]); + } + return this; + }; + + /** + * @method module:nbt.Writer#longArray + * @param {Array.} value + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.longArray] = function(value) { + this.int(value.length); + var i; + for (i = 0; i < value.length; i++) { + this.long(value[i]); + } + return this; + }; + + /** + * @method module:nbt.Writer#string + * @param {string} value + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.string] = function(value) { + var bytes = encodeUTF8(value); + this.short(bytes.length); + accommodate(bytes.length); + arrayView.set(bytes, this.offset); + this.offset += bytes.length; + return this; + }; + + /** + * @method module:nbt.Writer#list + * @param {Object} value + * @param {number} value.type - the NBT type number + * @param {Array} value.value - an array of values + * @returns {module:nbt.Writer} itself */ + this[nbt.tagTypes.list] = function(value) { + this.byte(nbt.tagTypes[value.type]); + this.int(value.value.length); + var i; + for (i = 0; i < value.value.length; i++) { + this[value.type](value.value[i]); + } + return this; + }; + + /** + * @method module:nbt.Writer#compound + * @param {Object} value - a key/value map + * @param {Object} value.KEY + * @param {string} value.KEY.type - the NBT type number + * @param {Object} value.KEY.value - a value matching the type + * @returns {module:nbt.Writer} itself + * + * @example + * writer.compound({ + * foo: { type: 'int', value: 12 }, + * bar: { type: 'string', value: 'Hello, World!' } + * }); */ + this[nbt.tagTypes.compound] = function(value) { + var self = this; + Object.keys(value).map(function (key) { + self.byte(nbt.tagTypes[value[key].type]); + self.string(key); + self[value[key].type](value[key].value); + }); + this.byte(nbt.tagTypes.end); + return this; + }; + + var typeName; + for (typeName in nbt.tagTypes) { + if (nbt.tagTypes.hasOwnProperty(typeName)) { + this[typeName] = this[nbt.tagTypes[typeName]]; + } + } + }; + + /** + * In addition to the named writing methods documented below, + * the same methods are indexed by the NBT type number as well, + * as shown in the example below. + * + * @constructor + * @see module:nbt.Writer + * + * @example + * var reader = new nbt.Reader(buf); + * int x = reader.int(); + * int y = reader[3](); + * int z = reader[nbt.tagTypes.int](); */ + nbt.Reader = function(buffer) { + if (!buffer) { throw new Error('Argument "buffer" is falsy'); } + + var self = this; + + /** + * The current location in the buffer. Can be freely changed + * within the bounds of the buffer. + * + * @type number */ + this.offset = 0; + + var arrayView = new Uint8Array(buffer); + var dataView = new DataView(arrayView.buffer); + + function read(dataType, size) { + var val = dataView['get' + dataType](self.offset); + self.offset += size; + return val; + } + + /** + * @method module:nbt.Reader#byte + * @returns {number} the read byte */ + this[nbt.tagTypes.byte] = read.bind(this, 'Int8', 1); + + /** + * @method module:nbt.Reader#byte + * @returns {number} the read unsigned byte */ + this.ubyte = read.bind(this, 'Uint8', 1); + + /** + * @method module:nbt.Reader#short + * @returns {number} the read signed 16-bit short */ + this[nbt.tagTypes.short] = read.bind(this, 'Int16', 2); + + /** + * @method module:nbt.Reader#int + * @returns {number} the read signed 32-bit integer */ + this[nbt.tagTypes.int] = read.bind(this, 'Int32', 4); + + /** + * @method module:nbt.Reader#float + * @returns {number} the read signed 32-bit float */ + this[nbt.tagTypes.float] = read.bind(this, 'Float32', 4); + + /** + * @method module:nbt.Reader#double + * @returns {number} the read signed 64-bit float */ + this[nbt.tagTypes.double] = read.bind(this, 'Float64', 8); + + /** + * As JavaScript does not not natively support 64-bit + * integers, the value is returned as an array of two + * 32-bit integers, the upper and the lower. + * + * @method module:nbt.Reader#long + * @returns {Array.} [upper, lower] */ + this[nbt.tagTypes.long] = function() { + return [this.int(), this.int()]; + }; + + /** + * @method module:nbt.Reader#byteArray + * @returns {Array.} the read array */ + this[nbt.tagTypes.byteArray] = function() { + var length = this.int(); + var bytes = []; + var i; + for (i = 0; i < length; i++) { + bytes.push(this.byte()); + } + return bytes; + }; + + /** + * @method module:nbt.Reader#intArray + * @returns {Array.} the read array of 32-bit ints */ + this[nbt.tagTypes.intArray] = function() { + var length = this.int(); + var ints = []; + var i; + for (i = 0; i < length; i++) { + ints.push(this.int()); + } + return ints; + }; + + /** + * As JavaScript does not not natively support 64-bit + * integers, the value is returned as an array of arrays of two + * 32-bit integers, the upper and the lower. + * + * @method module:nbt.Reader#longArray + * @returns {Array.} the read array of 64-bit ints + * split into [upper, lower] */ + this[nbt.tagTypes.longArray] = function() { + var length = this.int(); + var longs = []; + var i; + for (i = 0; i < length; i++) { + longs.push(this.long()); + } + return longs; + }; + + /** + * @method module:nbt.Reader#string + * @returns {string} the read string */ + this[nbt.tagTypes.string] = function() { + var length = this.short(); + var slice = sliceUint8Array(arrayView, this.offset, + this.offset + length); + this.offset += length; + return decodeUTF8(slice); + }; + + /** + * @method module:nbt.Reader#list + * @returns {{type: string, value: Array}} + * + * @example + * reader.list(); + * // -> { type: 'string', values: ['foo', 'bar'] } */ + this[nbt.tagTypes.list] = function() { + var type = this.byte(); + var length = this.int(); + var values = []; + var i; + for (i = 0; i < length; i++) { + values.push(this[type]()); + } + return { type: nbt.tagTypeNames[type], value: values }; + }; + + /** + * @method module:nbt.Reader#compound + * @returns {Object.} + * + * @example + * reader.compound(); + * // -> { foo: { type: int, value: 42 }, + * // bar: { type: string, value: 'Hello! }} */ + this[nbt.tagTypes.compound] = function() { + var values = {}; + while (true) { + var type = this.byte(); + if (type === nbt.tagTypes.end) { + break; + } + var name = this.string(); + var value = this[type](); + values[name] = { type: nbt.tagTypeNames[type], value: value }; + } + return values; + }; + + var typeName; + for (typeName in nbt.tagTypes) { + if (nbt.tagTypes.hasOwnProperty(typeName)) { + this[typeName] = this[nbt.tagTypes[typeName]]; + } + } + }; + + /** + * @param {Object} value - a named compound + * @param {string} value.name - the top-level name + * @param {Object} value.value - a compound + * @returns {ArrayBuffer} + * + * @see module:nbt.parseUncompressed + * @see module:nbt.Writer#compound + * + * @example + * nbt.writeUncompressed({ + * name: 'My Level', + * value: { + * foo: { type: int, value: 42 }, + * bar: { type: string, value: 'Hi!' } + * } + * }); */ + nbt.writeUncompressed = function(value) { + if (!value) { throw new Error('Argument "value" is falsy'); } + + var writer = new nbt.Writer(); + + writer.byte(nbt.tagTypes.compound); + writer.string(value.name); + writer.compound(value.value); + + return writer.getData(); + }; + + /** + * @param {ArrayBuffer|Buffer} data - an uncompressed NBT archive + * @returns {{name: string, value: Object.}} + * a named compound + * + * @see module:nbt.parse + * @see module:nbt.writeUncompressed + * + * @example + * nbt.readUncompressed(buf); + * // -> { name: 'My Level', + * // value: { foo: { type: int, value: 42 }, + * // bar: { type: string, value: 'Hi!' }}} */ + nbt.parseUncompressed = function(data) { + if (!data) { throw new Error('Argument "data" is falsy'); } + + var reader = new nbt.Reader(data); + + var type = reader.byte(); + if (type !== nbt.tagTypes.compound) { + throw new Error('Top tag should be a compound'); + } + + return { + name: reader.string(), + value: reader.compound() + }; + }; + + /** + * @callback parseCallback + * @param {Object} error + * @param {Object} result - a named compound + * @param {string} result.name - the top-level name + * @param {Object} result.value - the top-level compound */ + + /** + * This accepts both gzipped and uncompressd NBT archives. + * If the archive is uncompressed, the callback will be + * called directly from this method. For gzipped files, the + * callback is async. + * + * For use in the browser, window.zlib must be defined to decode + * compressed archives. It will be passed a Buffer if the type is + * available, or an Uint8Array otherwise. + * + * @param {ArrayBuffer|Buffer} data - gzipped or uncompressed data + * @param {parseCallback} callback + * + * @see module:nbt.parseUncompressed + * @see module:nbt.Reader#compound + * + * @example + * nbt.parse(buf, function(error, results) { + * if (error) { + * throw error; + * } + * console.log(result.name); + * console.log(result.value.foo); + * }); */ + nbt.parse = function(data, callback) { + if (!data) { throw new Error('Argument "data" is falsy'); } + + var self = this; + + if (!hasGzipHeader(data)) { + callback(null, self.parseUncompressed(data)); + } else if (!zlib) { + callback(new Error('NBT archive is compressed but zlib is not ' + + 'available'), null); + } else { + /* zlib.gunzip take a Buffer, at least in Node, so try to convert + if possible. */ + var buffer; + if (data.length) { + buffer = data; + } else if (typeof Buffer !== 'undefined') { + buffer = new Buffer(data); + } else { + /* In the browser? Unknown zlib library. Let's settle for + Uint8Array and see what happens. */ + buffer = new Uint8Array(data); + } + + zlib.gunzip(buffer, function(error, uncompressed) { + if (error) { + callback(error, null); + } else { + callback(null, self.parseUncompressed(uncompressed)); + } + }); + } + }; +}).apply(typeof exports !== 'undefined' ? exports : (window.nbt = {})); diff --git a/eaglercraft-saveeditor/files/powernbt.js b/eaglercraft-saveeditor/files/powernbt.js new file mode 100644 index 0000000..2096679 --- /dev/null +++ b/eaglercraft-saveeditor/files/powernbt.js @@ -0,0 +1,7 @@ +/** + * powernbt-js + * @version v1.2.0 - 2015-01-07T22:34:37.748Z + * @author DPOH-VAR (dpohvar@gmail.com) + * @license MIT License, http://www.opensource.org/licenses/MIT + */ +!function(t,e){"use strict";function r(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);t.prototype=Object.create(e.prototype,{constructor:{value:t}})}function n(t){this._buffer=t.buffer||t,this._offset=0}function a(){this._buffer=[]}var o;o=window.Long;var i={};i.readTag=function(t,r){var a;a=t instanceof n?t:new n(t);var o="";if(r==e){if(r=a.readInt8(),r==i.Type.TAG_END)return new i.NBTTagEnd;var T=a.readInt16(),s=a.read(T),p=new Int8Array(s);o=u.decode(p)}switch(r){case i.Type.TAG_BYTE:return new i.NBTTagByte(a.read(1),o);case i.Type.TAG_SHORT:return new i.NBTTagShort(a.read(2),o);case i.Type.TAG_INT:return new i.NBTTagInt(a.read(4),o);case i.Type.TAG_LONG:return new i.NBTTagLong(a.read(8),o);case i.Type.TAG_FLOAT:return new i.NBTTagFloat(a.read(4),o);case i.Type.TAG_DOUBLE:return new i.NBTTagDouble(a.read(8),o);case i.Type.TAG_BYTE_ARRAY:var f=a.readInt32();return new i.NBTTagByteArray(a.read(f),o);case i.Type.TAG_STRING:var y=a.readInt16();return new i.NBTTagString(a.read(y),o);case i.Type.TAG_LIST:for(var g=a.readInt8(),h=a.readInt32(),B=[],l=0;h>l;l++){var N=i.readTag(a,g);B.push(N)}return new i.NBTTagList(g,B,o);case i.Type.TAG_COMPOUND:for(var c={};;){var _=i.readTag(a);if(_.type==i.Type.TAG_END)break;c[_._name]=_}return new i.NBTTagCompound(c,o);case i.Type.TAG_INT_ARRAY:var w=a.readInt32();return new i.NBTTagIntArray(a.read(4*w),o);default:throw new Error("NBT parsing error: tag type: "+r)}},"function"==typeof require&&"object"==typeof module&&module&&"object"==typeof exports&&exports?module.exports=i:t.NBT=i;var u={encode:function(t){t=t.replace(/\r\n/g,"\n");for(var e=[],r=0;rn?e[e.length]=n:n>127&&2048>n?(e[e.length]=n>>6|192,e[e.length]=63&n|128):(e[e.length]=n>>12|224,e[e.length]=n>>6&63|128,e[e.length]=63&n|128)}return e},decode:function(t){for(var e=t.length||t.byteLength,r="",n=0,a=0,o=0,i=0;e>n;)a=255&t[n],128>a?(r+=String.fromCharCode(a),n++):a>191&&224>a?(o=255&t[n+1],r+=String.fromCharCode((31&a)<<6|63&o),n+=2):(o=255&t[n+1],i=255&t[n+2],r+=String.fromCharCode((15&a)<<12|(63&o)<<6|63&i),n+=3);return r}};i.Type={TAG_END:0,TAG_BYTE:1,TAG_SHORT:2,TAG_INT:3,TAG_LONG:4,TAG_FLOAT:5,TAG_DOUBLE:6,TAG_BYTE_ARRAY:7,TAG_STRING:8,TAG_LIST:9,TAG_COMPOUND:10,TAG_INT_ARRAY:11},i.NBTBase=function(t){if(this.constructor==i.NBTBase)throw new Error("NBTBase is abstract");this._name=(t||"")+""},Object.defineProperty(i.NBTBase.prototype,"name",{enumerable:!0,get:function(){return this._name}}),i.NBTBase.prototype.type=null,i.NBTBase.prototype.clone=function(){},i.NBTBase.prototype.toString=function(){},i.NBTBase.prototype.save=function(t,e){return null==t&&(t=new a),t.writeInt8(this.type),this.type==i.Type.TAG_END?t:(t.writeUtf8String(null==e?this.name:e),this._write(t),t)},Object.defineProperty(i.NBTBase.prototype,"typeName",{enumerable:!0,get:function(){return i.TypeName[this.type]}}),i.NBTBase.prototype._write=function(){},i.NBTNumber=function(t,e){if(this.constructor==i.NBTNumber)throw new Error("NBTNumber is abstract");i.NBTBase.call(this,e),this._value=new ArrayBuffer(t)},r(i.NBTNumber,i.NBTBase),i.NBTNumber.prototype.valueOf=function(){},i.NBTNumber.prototype._write=function(t){t.write(this._value)},i.NBTArray=function(t){if(this.constructor==i.NBTArray)throw new Error("NBTArray is abstract");i.NBTBase.call(this,t)},r(i.NBTArray,i.NBTBase),i.NBTArray.prototype.toArray=function(){for(var t=[],e=0;en;n++)r.setInt8(n,t[n])},i.NBTTagByteArray.prototype.get=function(t){var e=new DataView(this._value);return e.getInt8(t)},i.NBTTagByteArray.prototype.set=function(t,e){var r=new DataView(this._value);r.setInt8(t,e)},i.NBTTagByteArray.prototype._write=function(t){t.writeInt32(this._value.byteLength),t.write(this._value)},Object.defineProperty(i.NBTTagByteArray.prototype,"size",{enumerable:!0,get:function(){return this._value.byteLength}}),i.NBTTagCompound=function(t,e){i.NBTBase.call(this,e),this._value=t||{}},r(i.NBTTagCompound,i.NBTBase),i.NBTTagCompound.prototype.type=i.Type.TAG_COMPOUND,i.NBTTagCompound.prototype.get=function(t){return this._value[t]},i.NBTTagCompound.prototype.put=function(t,e){e?(e._name=t,this._value[t]=e):this.remove(t)},i.NBTTagCompound.prototype.putClone=function(t,e){this.put(t,e&&e.clone())},i.NBTTagCompound.prototype.remove=function(t){var e=this._value[t];return delete this._value[t],e},i.NBTTagCompound.prototype.containsKey=function(t){return this._value[t]!=e},i.NBTTagCompound.prototype.clear=function(){this._value={}},i.NBTTagCompound.prototype.clone=function(){var t=new i.NBTTagCompound,e=this._value,r=t._value;for(var n in e)e.hasOwnProperty(n)&&(r[n]=e[n].clone());return t},i.NBTTagCompound.prototype.toString=function(){return"NBTTagCompound["+this.keys.length+"]"},Object.defineProperty(i.NBTTagCompound.prototype,"size",{enumerable:!0,get:function(){var t=0,e=this._value;for(var r in e)e.hasOwnProperty(r)&&t++;return t}}),Object.defineProperty(i.NBTTagCompound.prototype,"keys",{enumerable:!0,get:function(){var t=[],e=this._value;for(var r in e)e.hasOwnProperty(r)&&t.push(r);return t}}),Object.defineProperty(i.NBTTagCompound.prototype,"entries",{enumerable:!0,get:function(){var t=[],e=this._value;for(var r in e)e.hasOwnProperty(r)&&t.push({key:r,value:e[r]});return t}}),i.NBTTagCompound.prototype._write=function(t){var e=this._value;for(var r in e)if(e.hasOwnProperty(r)){var n=this._value[r];n.save(t,r)}t.writeInt8(0)},i.NBTTagDouble=function(t,e){i.NBTNumber.call(this,8,e),t&&this.setValue(t)},r(i.NBTTagDouble,i.NBTNumber),i.NBTTagDouble.prototype.type=i.Type.TAG_DOUBLE,i.NBTTagDouble.prototype.toString=function(){return new DataView(this._value).getFloat64(0).toString()},i.NBTTagDouble.prototype.valueOf=function(){return new DataView(this._value).getFloat64(0)},i.NBTTagDouble.prototype.clone=function(){return new i.NBTTagDouble(this._value.slice(0),this._name)},i.NBTTagDouble.prototype.setValue=function(t){if(t instanceof ArrayBuffer){if(8!=t.byteLength)throw new Error("NBTTagDouble: byteLength must be 8");return void(this._value=t)}"string"==typeof t&&(t=parseFloat(t));var e=new DataView(this._value);e.setFloat64(0,t)},i.NBTTagEnd=function(){i.NBTBase.call(this,"")},r(i.NBTTagEnd,i.NBTBase),i.NBTTagEnd.prototype.type=i.Type.TAG_END,i.NBTTagEnd.prototype.clone=function(){return new i.NBTTagEnd},i.NBTTagEnd.prototype.toString=function(){return""},i.NBTTagFloat=function(t,e){i.NBTNumber.call(this,4,e),t&&this.setValue(t)},r(i.NBTTagFloat,i.NBTNumber),i.NBTTagFloat.prototype.type=i.Type.TAG_FLOAT,i.NBTTagFloat.prototype.toString=function(){return new DataView(this._value).getFloat32(0).toString()},i.NBTTagFloat.prototype.valueOf=function(){return new DataView(this._value).getFloat32(0)},i.NBTTagFloat.prototype.clone=function(){return new i.NBTTagFloat(this._value.slice(0),this._name)},i.NBTTagFloat.prototype.setValue=function(t){if(t instanceof ArrayBuffer){if(4!=t.byteLength)throw new Error("NBTTagFloat: byteLength must be 4");return void(this._value=t)}"string"==typeof t&&(t=parseFloat(t));var e=new DataView(this._value);e.setFloat32(0,t)},i.NBTTagInt=function(t,e){i.NBTNumber.call(this,4,e),t&&this.setValue(t)},r(i.NBTTagInt,i.NBTNumber),i.NBTTagInt.MAX_VALUE=2147483647,i.NBTTagInt.MIN_VALUE=-2147483648,i.NBTTagInt.prototype.type=i.Type.TAG_INT,i.NBTTagInt.prototype.toString=function(t){return new DataView(this._value).getInt32(0).toString(t)},i.NBTTagInt.prototype.valueOf=function(){return new DataView(this._value).getInt32(0)},i.NBTTagInt.prototype.clone=function(){return new i.NBTTagInt(this._value.slice(0),this._name)},i.NBTTagInt.prototype.setValue=function(t,e){if(t instanceof ArrayBuffer){if(4!=t.byteLength)throw new Error("NBTTagInt: byteLength must be 4");return void(this._value=t)}t instanceof i.NBTNumber&&(t=t.valueOf()),"string"==typeof t&&(t=parseInt(t,e));var r=new DataView(this._value);r.setInt32(0,t)},i.NBTTagIntArray=function(t,e){i.NBTArray.call(this,e),this.setValue(t)},r(i.NBTTagIntArray,i.NBTArray),i.NBTTagIntArray.prototype.type=i.Type.TAG_INT_ARRAY,i.NBTTagIntArray.prototype.toString=function(){return"NBTTagIntArray["+Math.round(this._value.byteLength/4)+"]"},i.NBTTagIntArray.prototype.clone=function(){return new i.NBTTagIntArray(this._value.slice(0),this._name)},i.NBTTagIntArray.prototype.setValue=function(t){if(null==t)return void(this._value=new ArrayBuffer(0));if(t instanceof ArrayBuffer)return void(this._value=t);"string"==typeof t&&(t=u.encode(t));var e=t.length||t.byteLength;this._value=new ArrayBuffer(4*e);for(var r=new DataView(this._value),n=0;e>n;n++)r.setInt32(4*n,t[n])},i.NBTTagIntArray.prototype.get=function(t){var e=new DataView(this._value);return e.getInt32(4*t)},i.NBTTagIntArray.prototype.set=function(t,e){var r=new DataView(this._value);r.setInt32(4*t,e)},i.NBTTagIntArray.prototype._write=function(t){t.writeInt32(this._value.byteLength/4),t.write(this._value)},Object.defineProperty(i.NBTTagIntArray.prototype,"size",{enumerable:!0,get:function(){return this._value.byteLength/4}}),i.NBTTagList=function(t,e,r){this._listType=t||i.Type.TAG_END,i.NBTBase.call(this,r),this._value=e||[]},r(i.NBTTagList,i.NBTBase),i.NBTTagList.prototype.type=i.Type.TAG_LIST,i.NBTTagList.prototype.get=function(t){return this._value[t]},i.NBTTagList.prototype.set=function(t,e){if(this._listType==i.Type.TAG_END)this._listType=e.type;else if(this._listType!=e.type)throw new Error("NBT tag has wrong type: "+e.type+"; expected: "+this._listType);e._name="",this._value[t]=e},i.NBTTagList.prototype.add=function(){for(var t=0;t