Build a module

What a module is

A module is a small JavaScript program that adds a page to the Enzonic Launcher. It appears in the Modules section of the sidebar, it can read and change your Minecraft instances, manage mods, run test launches, keep its own data, talk to web services you name in advance, and use Enzica. It cannot do anything else.

Every module is a zip file with three kinds of content:

  • module.json, the manifest: the module's id, name, version, author, description, which file to run, which launcher version it needs, and the list of permissions it asks for.
  • One JavaScript file, usually main.js, that contains all of the module's code.
  • Optional assets such as an icon and images.

Modules are distributed through the marketplace at launcher.enzonic.com. Each published version is reviewed by the Enzonic team before it is listed, and the launcher verifies the SHA-256 checksum of every package it downloads, so what users install is exactly the reviewed file.

Some things modules are good for:

  • Tools that inspect instances: finding duplicate or disabled mods, summarizing crash logs, comparing configuration files between instances.
  • Workflows that change instances on request: applying a set of recommended settings, installing a curated list of mods, cleaning up old screenshots.
  • Dashboards that pull data from a web service: server status, mod update feeds, community event calendars.
  • Assistants built on Enzica that use your own tools to look at an instance and propose or apply fixes.

Things modules are deliberately not able to do: run arbitrary programs, read files outside instances, open network connections to hosts that were not declared, show web pages, or run code in the background when nobody triggered it. Those limits are what let users install modules from people they do not know.

The first-party Enzica module runs on exactly the same runtime and API described here. Its native chat surface and its local troubleshooting tools come from documented first-party extensions (see "First-party extensions" in the reference) that the launcher grants only to the verified official build of Enzica; your module never needs them and cannot obtain them.

How modules run

Before writing code, it helps to understand five ideas: the sandbox, permissions, the synchronous API, UI trees and the lifecycle. The complete, normative rules are in the API reference included later on this page; this section explains how they fit together.

The sandbox

The launcher runs your main.js in Mozilla Rhino 1.9.1, a JavaScript engine written in Java, configured for its ES6 language level. Your code runs in a scope that contains the standard JavaScript built-ins and one extra global, enzonic. There is no access to Java classes, no require, no import, no fetch, no timers and no console. If you are used to Node.js or the browser, the important differences are:

  • One file. All code lives in the file named by main. You cannot import other files. If you want to organize code, use functions and objects inside that file. If you use a bundler, configure it to output a single ES5-compatible script with no module wrapper that expects require, and keep the output readable, because reviewers must read it.
  • Conservative JavaScript. let, const, arrow functions and template literals work. Destructuring, spread, default parameters, classes, async/await and Promises do not. Write plain functions and objects. The reference lists exactly which features are guaranteed.
  • No timers. Your code runs only when the launcher calls it: once at activation and once per user interaction. There is no way to schedule work for later. If you need to refresh something, give the user a button.
  • Budgets. Each call into your code gets 50 million interpreter instructions and 5 seconds of script time. Time spent waiting inside enzonic.* calls (network requests, confirmation dialogs, test launches) does not count. A typical event handler uses a tiny fraction of this. If you exceed a budget the launcher stops your module and shows an error; three such failures in ten minutes disable it.

Permissions in brief

Every capability on the enzonic object belongs to a permission. Your module.json lists the permissions you need, and users see that list, in plain language, before they install. They must accept all of them or not install at all. If your code calls a method whose permission you did not declare, the call throws an error with code permission_denied.

PermissionWhat it lets your module do
instances.readList instances, read their settings and files, list their mods.
instances.writeWrite and delete files inside instances. Asks the user first.
mods.manageInstall mods from Modrinth, enable, disable and remove mods. Asks the user first.
launchStart the game, including test launches. Asks the user first.
storageSave up to 1 MiB of your own data.
notificationsShow notifications.
aiCall Enzica on the user's account. Gets extra review.
http:<host>Make HTTPS requests to exactly that host.

Three of these, instances.write, mods.manage and launch, are "asks first" permissions. Each call shows a native confirmation dialog that describes the exact action, such as which file will be written or which mods will be installed. The user can allow it, deny it, or tick Always allow for this module for that permission. If they deny, your call throws user_denied. Your code must handle that gracefully.

The UI functions, enzonic.log, enzonic.module and enzonic.launcher need no permission.

A synchronous API

Every enzonic.* function is synchronous. It returns a plain JavaScript value or throws. There are no callbacks and no Promises:

js
const instances = enzonic.instances.list();
const log = enzonic.instances.readFile(instances[0].id, "logs/latest.log");

This works because each module has its own worker thread. While your code waits for a network response or for the user to answer a confirmation dialog, only that worker thread waits. The launcher window stays responsive, and your budgets are paused.

The consequence you need to design around is that your module handles one thing at a time. If you start a three-minute test launch, any buttons the user clicks in your page meanwhile are queued and run afterwards, in order. That is why you should always show a progress state before a long call (you will see how below).

UI trees

A module's interface is a description, not a document. You build a tree of plain objects, each with a type and some properties, and hand it to enzonic.ui.render. The launcher validates the tree and renders it with native Material 3 components that match the rest of the launcher, in light or dark theme.

js
enzonic.ui.render(enzonic.ui.page({
  title: "Hello",
  children: [
    enzonic.ui.text({ text: "This is a module." }),
    enzonic.ui.button({ label: "Say hi", onClick: () => enzonic.log("info", "Hi") })
  ]
}));

There are exactly ten component types: page, card, list, button, text, input, switch, select, progress and image. Event handlers such as onClick are ordinary JavaScript functions. When the user clicks, the launcher calls that function on your module's thread.

To change what is on screen you call render again with a new tree. The launcher compares it to the previous one and keeps local state such as text being typed, focus and scroll position for nodes that match. Matching uses position and, when you provide one, the key property.

The lifecycle

A module has two entry points, both ordinary global functions in main.js:

  • activate(ctx) is required. The launcher evaluates your file and calls activate when the module is enabled, when the launcher starts with the module enabled, or when you press Reload in Developer mode. ctx tells you your module's id, version and permissions, and the launcher's version, operating system, locale and theme. activate should prepare your state and call enzonic.ui.render to show the page.
  • deactivate() is optional. It is called when the module is disabled, uninstalled, updated, or when the launcher exits normally. It has a strict two-second limit and cannot show dialogs or render. Do not rely on it to save data; save data when it changes.

Between those two calls, your code runs only in event handlers. Every activation starts with a fresh global scope, so anything you want to keep across launcher restarts must go into enzonic.storage.

If activate throws, or any call exceeds its budget, the module enters an errored state: its page shows the error and a Restart button. An error thrown inside an event handler is less severe: it is logged, shown as a snackbar, and the module keeps running with its current state.

Quick start

This walkthrough takes about ten minutes. You will build a module that lists your instances and shows details for the one you click.

Step 1: Turn on Developer mode

Open the launcher, go to Settings, and enable Developer mode. This adds the Load unpacked module action, a Reload button for unpacked modules, and the module log pane, where you will see enzonic.log output and errors with file and line numbers.

Step 2: Create a folder

Create an empty folder anywhere, for example my-instances in your documents folder. Everything for the module goes in this folder, and later the contents of this folder become the zip.

Step 3: Write module.json

Create my-instances/module.json:

json
{
  "id": "my-instances",
  "name": "My Instances",
  "version": "0.1.0",
  "description": "Lists your instances and shows their details.",
  "author": "Your Name",
  "main": "main.js",
  "minLauncher": "1.0.0",
  "permissions": ["instances.read"]
}

Some details worth knowing right away:

  • id is lowercase letters, digits and hyphens, 2 to 48 characters, starting with a letter or digit, and it must match the slug you choose when you publish. It never changes.
  • version is a semantic version such as 0.1.0 or 1.0.0-beta.1. Every upload must have a new version.
  • permissions lists only what you use. This module only reads instances.
  • Unknown fields are rejected, so a typo such as "permision" makes the manifest invalid instead of being silently ignored.

Step 4: Write main.js

Create my-instances/main.js:

js
var state = {
  instances: [],
  selectedId: null,
  error: null
};

function load() {
  try {
    state.instances = enzonic.instances.list();
    state.error = null;
  } catch (e) {
    state.instances = [];
    state.error = e.message;
  }
}

function detailCard(instance) {
  return enzonic.ui.card({
    key: "detail",
    title: instance.name,
    subtitle: instance.folder ? "Folder: " + instance.folder : "Not in a folder",
    children: [
      enzonic.ui.text({ text: `Minecraft ${instance.minecraftVersion}` }),
      enzonic.ui.text({
        text: instance.loader === "vanilla"
          ? "Loader: vanilla"
          : `Loader: ${instance.loader} ${instance.loaderVersion}`
      }),
      enzonic.ui.text({ text: `Memory: ${instance.memoryMb} MiB` }),
      enzonic.ui.text({
        text: instance.lastPlayedAt ? "Last played: " + instance.lastPlayedAt : "Never played",
        tone: "muted"
      })
    ]
  });
}

function view() {
  const children = [];
  if (state.error) {
    children.push(enzonic.ui.text({ text: state.error, tone: "error" }));
  }
  children.push(enzonic.ui.list({
    key: "instances",
    emptyText: "You have no instances yet.",
    items: state.instances.map(i => ({
      key: i.id,
      title: i.name,
      subtitle: `${i.minecraftVersion} · ${i.loader}`,
      icon: i.id === state.selectedId ? "check" : "sports_esports",
      onClick: () => { state.selectedId = i.id; render(); }
    }))
  }));
  const selected = state.instances.find(i => i.id === state.selectedId);
  if (selected) {
    children.push(detailCard(selected));
  }
  return enzonic.ui.page({
    title: "My Instances",
    subtitle: `${state.instances.length} instances`,
    actions: [
      enzonic.ui.button({ label: "Refresh", icon: "refresh", onClick: () => { load(); render(); } })
    ],
    children: children
  });
}

function render() {
  enzonic.ui.render(view());
}

function activate(ctx) {
  enzonic.log("info", `Activated ${ctx.module.id} ${ctx.module.version} on ${ctx.launcher.os}`);
  load();
  render();
}

Step 5: Load it

In the launcher, open Settings → Developer mode → Load unpacked module and select the my-instances folder. The launcher validates module.json, shows the permission dialog (you will see "Read your instances, their settings and files"), and after you accept, the module appears under Modules. Open it: you should see your instances. Click one and the detail card appears.

Step 6: Change something and reload

Edit main.js, for example change the page title to "Instances", save the file, and press Reload next to the module. The launcher runs deactivate (you did not define one, so nothing happens), re-reads your files and activates again. Open the module log pane to see the "Activated" line from enzonic.log.

Now break something on purpose: change enzonic.ui.text({ text: ... }) to enzonic.ui.text({ txt: ... }) in detailCard and reload. Clicking an instance now fails, and the log shows an invalid_argument error whose message names the path, such as children[1].children[0].txt, because txt is not a property of text. Validation errors always point at the exact node, which makes UI bugs quick to find. Change it back.

You now have a working module. The rest of this guide covers how to structure larger modules, how to use each part of the API well, and how to package and publish.

Designing your UI

State plus a render function

The pattern used throughout this guide, and recommended for every module, has three parts:

  1. A single state object that holds everything the page depends on.
  2. A pure view() function that turns state into a tree. It does not call APIs that change anything and does not modify state.
  3. Event handlers that change state, possibly call enzonic.* functions, and then call render().
js
var state = { filter: "", items: [] };

function view() { /* build the tree from state */ }
function render() { enzonic.ui.render(view()); }

function onFilterChange(value) {
  state.filter = value;
  render();
}

Because every render describes the whole page, you never need to work out which parts changed. The launcher does that. Rendering is cheap: a tree of a few hundred nodes takes well under a millisecond of your budget to build and is transferred to the UI thread immediately.

Keep view() free of slow calls. If the page needs data from an instance or the network, fetch it in an event handler or in activate, store the result in state, and let view() read from state. That way re-rendering never repeats expensive work.

Keys

When you call render again, the launcher matches new nodes to old ones so that it can keep their local state. Without keys, matching is by position among siblings of the same type. That is fine for static layouts, but it goes wrong when items move. Imagine a list of three inputs where you delete the first: without keys, the old first input's text field is reused for what used to be the second item.

Rules of thumb:

  • Every list item already requires a key. Use a stable identifier from your data, such as an instance id or a file name, never the array index.
  • Give a key to every input, so typing and cursor position survive re-renders even if nodes before it appear or disappear.
  • Give a key to cards that appear conditionally, so the cards after them keep their state.
  • To reset a node on purpose, change its key. For example, an editor input with key: "note-" + instanceId starts fresh whenever the selected instance changes.

Keys must be unique among siblings and at most 64 characters.

Forms

Inputs report their text through onChange, which the launcher calls at most once every 150 milliseconds while the user types, always with the latest full text. Store the text in your state:

js
enzonic.ui.input({
  key: "name",
  label: "Server name",
  value: state.name,
  maxLength: 60,
  onChange: value => { state.name = value; },
  onSubmit: value => { state.name = value; submit(); }
})

You do not have to call render in onChange unless something else on the page depends on the text, such as a character counter or a disabled Save button. When you do re-render, the launcher's value rule protects the user's typing: the field's text is only replaced when the value you render differs both from the value you rendered last time and from the latest text the launcher delivered to your onChange. In practice:

  • Rendering the text you received leaves the field alone, even if the user has typed more since.
  • Rendering a different value, such as "" after a successful submit, replaces the text.

Validation works best as part of state. Keep an error message in state, set it when the user submits invalid data, render it with a text node using tone: "error", and clear it when the input changes.

js
function submit() {
  const name = state.name.trim();
  if (name.length === 0) {
    state.nameError = "Enter a name.";
  } else {
    state.saved.push(name);
    state.name = "";
    state.nameError = null;
  }
  render();
}

switch and select follow the same idea. When the user toggles a switch or picks an option, the launcher shows the new value immediately and calls onChange. Your next render is authoritative: if you render the old value, the control goes back. This lets you reject a change by simply not storing it.

onSubmit fires when the user presses Enter in a single-line input. Multi-line inputs do not support it, because Enter inserts a new line; pair them with a Save button. Secret inputs (secret: true) mask the text; use them for values like tokens that the user pastes in, and remember that anything you store with enzonic.storage is stored as plain JSON on disk.

Lists

list is the right component for anything with more than a handful of similar rows: instances, mods, files, servers. Each item has a title, optional subtitle and icon, an optional trailing element (a text, button or switch node) and an optional onClick.

js
enzonic.ui.list({
  key: "mods",
  emptyText: "No mods in this instance.",
  items: state.mods.map(m => ({
    key: m.filename,
    title: m.name || m.filename,
    subtitle: m.enabled ? m.version || "" : "Disabled",
    icon: m.enabled ? "extension" : "close",
    trailing: enzonic.ui.button({
      label: m.enabled ? "Disable" : "Enable",
      variant: "text",
      onClick: () => toggle(m)
    })
  }))
})

Clicking the trailing button does not also trigger the item's onClick, so you can have both.

A list can hold up to 1,000 items, and a whole tree up to 5,000 nodes and 256 KiB. If your data can be larger, add a filter input and show the first matching 200 or so with a text line such as "Showing 200 of 3,412, refine your search."

Event handlers capture variables like any JavaScript closure. Create them inside map or forEach callbacks, as above, so each handler captures its own item. Do not create handlers inside a for (let i ...) loop and rely on i, because per-iteration bindings are not guaranteed in this runtime.

Progress during long operations

A test launch can take minutes, and a mod install or a series of HTTP requests can take seconds. Because your module's calls are synchronous and the UI keeps running on its own thread, you can render as many times as you like inside one handler. Render a busy state first, do the work, and render the result:

js
function runChecks() {
  state.busy = true;
  state.progress = 0;
  render();
  const total = state.servers.length;
  state.servers.forEach((address, index) => {
    state.results[address] = check(address);
    state.progress = (index + 1) / total;
    render();
  });
  state.busy = false;
  render();
}

In the view, show a progress node while busy, and disable buttons that would start another long operation:

js
if (state.busy) {
  children.push(enzonic.ui.progress({ value: state.progress, label: "Checking servers" }));
}
children.push(enzonic.ui.button({ label: "Check all", disabled: state.busy, onClick: runChecks }));

Omit value for an indeterminate indicator when you cannot measure progress, for example during a single test launch.

Disabling buttons matters because clicks during a long operation are queued, not discarded. Without the disabled state, an impatient user who clicks "Check all" three times would get three full runs, one after another. The queue holds up to 100 events; beyond that, events are dropped and a warning appears in the module log.

Use try/finally so a failure never leaves your page stuck in the busy state:

js
state.busy = true;
render();
try {
  doWork();
} finally {
  state.busy = false;
  render();
}

Layout and style

Pages scroll vertically. Use cards to group related controls, layout: "row" for a few buttons side by side, and the text styles (headline, title, body, label, code) for hierarchy. tone: "muted" is for secondary information, accent uses the launcher's green for positive status, and error for problems. code is monospaced and good for log excerpts; add selectable: true so users can copy them.

The page's actions (up to three buttons) appear in the top app bar. Use them for page-wide actions such as Refresh. A button with an icon becomes an icon button there, with the label as a tooltip.

Do not try to imitate controls the component set does not have. The launcher keeps modules visually consistent with the rest of the app on purpose, in both themes, and reviewers check that pages are clear and usable.

Working with instances and files

With instances.read, enzonic.instances.list() returns every instance with its id, name, folder, Minecraft version, loader and loader version, memory, Java path, and timestamps. get(id) returns one instance or throws not_found.

Paths

Every file function takes an instance id and a path relative to the instance's game directory, the folder that contains mods/, config/, saves/, logs/ and so on. Paths use forward slashes on every operating system, never start with /, and never contain ... Examples:

PathRefers to
""The instance root (only valid for listFiles)
options.txtMinecraft's options file
logs/latest.logThe current or most recent game log
config/sodium-options.jsonA mod's configuration
saves/My World/level.datA world's level file

A path that tries to leave the instance, directly or through a symbolic link, throws path_outside_instance. The file enzonic-instance.json in the instance root holds the launcher's own metadata; you can read it, but writing or deleting it throws forbidden_path. Use the instance fields from list() instead of parsing that file.

Listing and reading

listFiles(id, dir) lists the direct children of a directory, sorted by path, with type, size and modification time. It is not recursive, so walk subdirectories yourself if needed, and keep the walk bounded:

js
function findFiles(instanceId, dir, suffix, out, depth) {
  if (depth > 4 || out.length >= 500) return out;
  enzonic.instances.listFiles(instanceId, dir).forEach(entry => {
    if (entry.type === "dir") {
      findFiles(instanceId, entry.path, suffix, out, depth + 1);
    } else if (entry.path.endsWith(suffix) && out.length < 500) {
      out.push(entry);
    }
  });
  return out;
}

const configs = findFiles(id, "config", ".json", [], 0);

readFile(id, path) returns the file as a UTF-8 string. Pass { encoding: "base64" } for binary files. Files over 5 MiB throw too_large; check size from listFiles first if a file might be big, such as an old log. Game logs can be long, so when you only need the end, take a slice:

js
const log = enzonic.instances.readFile(id, "logs/latest.log");
const tail = log.split("\n").slice(-200).join("\n");

String operations on a 5 MiB log are fine within the instruction budget; nested loops over every character of every line are not. Prefer built-in methods like split, indexOf and regular expressions, which run as single instructions from the budget's point of view.

Writing and deleting

With instances.write, writeFile(id, path, content) creates or replaces a file atomically and returns { path, size }. Missing parent directories are created unless you pass createDirs: false. deleteFile(id, path) deletes a single file.

Both show a confirmation dialog that names the file and the instance, unless the user ticked "Always allow" for your module. Both refuse to touch an instance that is running and throw instance_running, because Minecraft and mods often rewrite their files on exit and would overwrite your change.

A safe edit of a configuration file looks like this:

js
function setRenderDistance(instanceId, chunks) {
  const text = enzonic.instances.readFile(instanceId, "options.txt");
  const lines = text.split("\n").map(line =>
    line.indexOf("renderDistance:") === 0 ? "renderDistance:" + chunks : line
  );
  try {
    enzonic.instances.writeFile(instanceId, "options.txt", lines.join("\n"));
    return "Render distance set to " + chunks + ".";
  } catch (e) {
    if (e.code === "user_denied") return "No changes made.";
    if (e.code === "instance_running") return "Close the game, then try again.";
    throw e;
  }
}

Read, change only what you need, and write back the rest exactly as it was. Never write a file you have not read unless you are creating it. Make one call per logical change, because each call may show a dialog; three dialogs for one button press is a poor experience and a common review comment.

Managing mods

enzonic.mods.list(id) (permission instances.read) returns the jars in the instance's mods/ folder. Each Mod has the current filename, whether it is enabled, the name and version read from the jar's loader metadata when possible, Modrinth project and version ids when the launcher knows where the file came from, and the file's SHA-512.

A disabled mod is the same file with .disabled appended. Always use the filename from the latest list() call when you call enable, disable or remove, because the name changes when a mod is toggled. After any change, call list() again rather than patching your own copy.

With mods.manage:

  • install(id, { project }) installs the newest version of a Modrinth project that matches the instance's Minecraft version and loader, plus its required dependencies. Pass versionId to pin a version, or withDependencies: false to skip dependencies. It returns { installed, skipped }. Projects that are already present at the selected version are reported in skipped with reason already_installed; dependencies without a compatible version are reported with no_compatible_version. If the main project has no compatible version, the call throws no_compatible_version.
  • enable(id, filename) and disable(id, filename) rename the file and return the updated Mod. They are idempotent.
  • remove(id, filename) deletes the file.

The user sees one confirmation dialog per call. For install the dialog lists every file that will be added or replaced, after dependency resolution, so the user knows exactly what will happen.

Quilt instances can use Fabric mods, so install considers both loaders for Quilt. Vanilla instances cannot have mods; install throws invalid_argument for them, and list returns an empty array.

js
function installSodium(instanceId) {
  try {
    const result = enzonic.mods.install(instanceId, { project: "sodium" });
    const names = result.installed.map(m => m.name || m.filename);
    return names.length > 0 ? "Installed " + names.join(", ") : "Already installed.";
  } catch (e) {
    if (e.code === "no_compatible_version") return "Sodium has no version for this instance.";
    if (e.code === "user_denied") return "Cancelled.";
    if (e.code === "network_error") return "Could not reach Modrinth: " + e.message;
    throw e;
  }
}

You do not need any http: permission for mod management; the launcher talks to Modrinth itself and verifies each download's SHA-512.

Test launches

enzonic.launch(id, { test: true }) (permission launch) is how a module can find out whether an instance actually starts. The launcher prepares the instance exactly as the Play button would, starts the game with the user's Microsoft account, watches the log for the title screen, and stops the game as soon as it gets there, or when it crashes, exits, or reaches the timeout (default 180 seconds, configurable from 30 to 600 with timeoutSec).

The call blocks until the outcome is known and returns:

  • ok: true if the title screen was reached.
  • reason: reached_menu, crashed, exited or timeout.
  • durationMs: how long the game ran.
  • exitCode: the exit code if the game exited on its own, otherwise null.
  • logTail: the last 200 lines of output.
  • crashReport: the crash report written during this run, if any.

A normal launch, enzonic.launch(id) without test, starts the game and returns { started: true, pid } immediately. Use it for "Play" buttons, and use test launches for verification.

Both forms show a confirmation dialog unless the user chose "Always allow". Both throw instance_running if the instance is already running, and not_signed_in if no Microsoft account is signed in to the launcher. Preparing an instance can download files, so network_error is possible as well.

A good test-launch flow:

  1. Render an indeterminate progress state with a clear label, for example "Test launch running. The game window will open and close automatically."
  2. Call enzonic.launch in a try block.
  3. Render the result: a clear pass or fail line, the reason, and the log tail in a selectable code text when it failed.
  4. Optionally show a notification, since the user may have switched to another window while waiting.

The Mod Health Check example below implements exactly this.

Storage

With the storage permission, enzonic.storage is a small key-value store that persists across launcher restarts and module updates and is deleted when the user uninstalls your module.

js
enzonic.storage.set("settings", { units: "metric", showOffline: true });
const settings = enzonic.storage.get("settings") || { units: "metric", showOffline: true };
enzonic.storage.remove("settings");
const allKeys = enzonic.storage.keys();

Values are any JSON-compatible data: objects, arrays, strings, numbers, booleans and null. Keys are 1 to 128 characters. The whole store, serialized as JSON, must stay within 1 MiB; a set that would exceed it throws quota_exceeded and changes nothing.

Design tips:

  • Load once, save on change. Read what you need in activate and keep it in state. Write when the user changes something. Do not write on every keystroke; write on Save, on blur-equivalent actions like switching items, or on submit.
  • Use key prefixes for collections. For per-instance data, use keys like note:<instanceId>. keys() returns all keys sorted, so you can filter by prefix. Instance ids are at most 64 characters, so such keys stay within the 128-character limit.
  • Store a schema version. If you expect to change the shape of your data, store { v: 1, ... } and migrate in activate when you find an older version.
  • Handle quota errors. Tell the user what to delete rather than failing silently.
  • Do not store secrets you do not need. Storage is a plain JSON file on the user's computer.

Every write is durable before set returns, so you do not need deactivate to save anything.

Network access

To call a web service, declare its exact host as a permission, for example "http:api.mcsrvstat.us", and call enzonic.http.fetch:

js
const res = enzonic.http.fetch("https://api.mcsrvstat.us/3/play.example.com");
if (res.status === 200 && res.json) {
  enzonic.log("info", "Online: " + res.json.online);
}

The response has status, headers (lowercased names), text, and json, which is the parsed body when the server sends JSON and null otherwise. Non-2xx statuses are returned, not thrown, so always check status. Network failures throw network_error, and slow servers throw timeout after 15 seconds by default (timeoutMs up to 30,000).

For a JSON request body:

js
const res = enzonic.http.fetch("https://api.example.com/v1/items", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Authorization": "Bearer " + state.token },
  body: JSON.stringify({ name: "Test" }),
  timeoutMs: 20000
});

The rules exist to make the permission meaningful:

  • Only https:// URLs on port 443.
  • The host must exactly match a declared http: permission. http:example.com does not cover www.example.com; declare each host you need.
  • Redirects are followed only to declared hosts. If a service redirects to a CDN on another domain, declare that domain too.
  • Hosts that resolve to private or local addresses are refused, so a module cannot probe the user's home network.
  • Cookies are never stored or sent. Authentication must use headers such as Authorization.
  • The launcher sets the User-Agent to identify your module, for example EnzonicLauncher/1.0.0 (module server-status/1.2.0). Many public APIs require a descriptive User-Agent, and this one is always present.
  • Responses are limited to 5 MiB, and each module can make 60 requests per minute.

If a service needs an API key that belongs to the user, ask for it in a secret input, store it with enzonic.storage, and explain in your description where it is stored. Never ship your own private API keys in a module. Anyone can download the package and read them, and reviewers reject modules that contain credentials.

Using Enzica from a module

The ai permission gives your module enzonic.ai.chat, a chat-completion call that runs on Enzica with the user's Enzonic account and daily quota. It accepts OpenAI-style messages and function tool definitions, and returns the assistant's message and token usage. You cannot choose the model or provide keys; the launcher proxies every request through https://launcher-ai.enzonic.com/v1/chat with the user's sign-in.

The model does not run tools itself. If you pass tools, the model can respond with tool_calls, and your code decides what to do with them: run your own function, append the result as a tool message, and call chat again. This loop is how the first-party Enzica module works. Requests are for Minecraft help only: the AI API adds a server-side rule that makes the model decline unrelated requests (essays, general programming, general knowledge) in one sentence, so build modules around Minecraft, the launcher or Enzonic services.

Here is a complete, minimal assistant that can look at instances and their latest log. It needs ["ai", "instances.read"]:

js
var TOOLS = [
  {
    type: "function",
    function: {
      name: "list_instances",
      description: "List the user's Minecraft instances with id, name, version and loader.",
      parameters: { type: "object", properties: {}, required: [] }
    }
  },
  {
    type: "function",
    function: {
      name: "read_latest_log",
      description: "Return the last 300 lines of logs/latest.log for one instance.",
      parameters: {
        type: "object",
        properties: { instance_id: { type: "string", description: "Instance id from list_instances" } },
        required: ["instance_id"]
      }
    }
  }
];

var SYSTEM_PROMPT = "You help players fix problems with their Minecraft instances. " +
  "Use the tools to look at real data before answering. Be concise and concrete.";

function runTool(call) {
  let args;
  try {
    args = JSON.parse(call.function.arguments || "{}");
  } catch (e) {
    return { error: "Arguments were not valid JSON." };
  }
  try {
    if (call.function.name === "list_instances") {
      return enzonic.instances.list().map(i => ({
        id: i.id, name: i.name, minecraftVersion: i.minecraftVersion, loader: i.loader
      }));
    }
    if (call.function.name === "read_latest_log") {
      const text = enzonic.instances.readFile(String(args.instance_id), "logs/latest.log");
      return { log: text.split("\n").slice(-300).join("\n") };
    }
    return { error: "Unknown tool " + call.function.name };
  } catch (e) {
    return { error: e.code + ": " + e.message };
  }
}

function ask(question) {
  const messages = [
    { role: "system", content: SYSTEM_PROMPT },
    { role: "user", content: question }
  ];
  for (let step = 0; step < 8; step++) {
    let response = enzonic.ai.chat({ messages: messages, tools: TOOLS, temperature: 0.2 });
    messages.push(response.message);
    let calls = response.message.tool_calls || [];
    if (calls.length === 0) {
      return response.message.content || "";
    }
    calls.forEach(call => {
      messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(runTool(call)) });
    });
  }
  return "I stopped after 8 steps without a final answer. Try a more specific question.";
}

var state = { question: "", answer: null, busy: false, error: null };

function onAsk() {
  if (state.question.trim() === "" || state.busy) return;
  state.busy = true;
  state.error = null;
  render();
  try {
    state.answer = ask(state.question.trim());
  } catch (e) {
    if (e.code === "not_signed_in") state.error = "Sign in to your Enzonic account in the launcher first.";
    else if (e.code === "quota_exceeded") state.error = "You have used today's Enzica quota.";
    else if (e.code === "rate_limited") state.error = "Too many requests. Wait a minute and try again.";
    else state.error = e.message;
  } finally {
    state.busy = false;
    render();
  }
}

function render() {
  const children = [
    enzonic.ui.input({
      key: "question",
      label: "Question",
      placeholder: "Why does my Fabric instance crash on start?",
      value: state.question,
      onChange: v => { state.question = v; },
      onSubmit: v => { state.question = v; onAsk(); }
    }),
    enzonic.ui.button({ label: "Ask", icon: "auto_awesome", disabled: state.busy, onClick: onAsk })
  ];
  if (state.busy) children.push(enzonic.ui.progress({ label: "Thinking" }));
  if (state.error) children.push(enzonic.ui.text({ text: state.error, tone: "error" }));
  if (state.answer) children.push(enzonic.ui.card({
    key: "answer", title: "Answer",
    children: [enzonic.ui.text({ text: state.answer, selectable: true })]
  }));
  enzonic.ui.render(enzonic.ui.page({ title: "Log Helper", children: children }));
}

function activate(ctx) {
  render();
}

Points to notice:

  • The assistant's message, including its tool_calls, is appended to messages as is, followed by one tool message per call with the matching tool_call_id. The model needs both to continue.
  • Tool results are JSON strings. Keep them small: send the relevant part of a log, not the whole file. Requests are limited to 1 MiB, and large prompts use more of the user's quota.
  • Tool errors are returned to the model as data instead of being thrown, so the model can recover, for example by asking for a different instance.
  • The loop has a hard step limit. Never loop until the model stops asking for tools.
  • Each chat call counts against the user's quota of 30 requests per minute and 200 per day, shared with all other AI features.

Mutating tools need extra care. If your AI module offers tools that change things, such as writing files or installing mods, those tools call enzonic.instances.writeFile or enzonic.mods.*, and the launcher's confirmation dialog appears for each one. Do not try to work around that, and make sure each tool performs one clear action so the dialog is meaningful. When the user declines, return { error: "user_denied" } to the model so it can explain or propose an alternative.

Because the ai permission spends the user's quota and sends instance data to a model, modules that request it receive extra review. Explain in your description what data your module sends.

Permissions and user trust

Users decide whether to install your module mostly from three things: its description, its permission list, and its reviews in the community. Permissions are the part the launcher enforces, so treat them as a promise.

Least privilege

Ask only for what the current version uses.

  • If you only read instances, do not ask for instances.write "for later". You can add it in a future version; users will be asked to accept the new permission when they update.
  • If you need one web service, declare its host, not several. Each host appears in the install dialog.
  • Prefer instances.read plus a clear explanation over instances.write if the user can apply a change by hand.
  • Only request ai if AI is central to your module. It costs the user quota.

Reviewers reject modules that declare permissions they never use.

What users see

At install, the launcher shows your module's name, author and icon, then each permission as a sentence, for example:

  • "Read your instances, their settings and files."
  • "Install, enable, disable and remove mods from Modrinth (asks first)."
  • "Connect to api.mcsrvstat.us over HTTPS."

When you publish an update that adds a permission, existing users see the full list again with the new permission highlighted. If they decline, they stay on the old version. An update that only removes permissions installs without a prompt.

During use, every call that writes files, manages mods or launches the game shows a dialog that names your module and the exact action. Users can choose "Always allow for this module" per permission and revoke that choice later in the module's settings.

Earning trust

  • Write a description that says what the module does and what it does not do. If you send data anywhere, say what and where.
  • Link to your source code in the marketplace listing (source_url). Reviewers and users appreciate being able to read the code they run.
  • Make dialogs predictable. A button labelled "Disable this mod" should result in exactly one dialog about disabling that mod.
  • Handle user_denied as a normal outcome, not an error. Show "No changes made." rather than a red error message.
  • Never try to obscure what your code does. Minified or obfuscated code is rejected.

Overview

This document is the normative reference for Enzonic Launcher Module API version 1. It defines the module package format, the module.json manifest, the JavaScript runtime that executes modules, the permission model, every function on the injected enzonic object, the UI component set, the error model and all limits.

A module is a zip package containing a manifest (module.json), one JavaScript file (main) and optional assets. The desktop launcher runs the script in a sandboxed Mozilla Rhino interpreter. The script has no access to Java, the file system, the network or the operating system except through the enzonic object, and each capability on that object is gated by a permission that the module declares and the user accepts at install time. A module's user interface is a tree of plain JavaScript objects describing native components; the launcher renders the tree with Material 3 Compose. There is no HTML and no webview.

The first-party Enzica module runs on exactly this runtime and this API. In addition, the launcher grants it the first-party extensions, and only after verifying that the installed package is the official build; no other module can obtain them.

Conformance terms

The key words MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT and MAY are used as described in RFC 2119.

  • Module: a package that conforms to this document.
  • Host or launcher: the Enzonic Launcher desktop application that loads and runs modules.
  • Invocation: one host-initiated execution of module code: loading the script and calling activate, calling deactivate, or calling one UI event handler.
  • Host call: a call from module code to a function on the enzonic object.
  • KiB / MiB: 1 KiB = 1,024 bytes, 1 MiB = 1,048,576 bytes. Every size limit in this document is measured in bytes of UTF-8 unless stated otherwise.
  • Integer: a JavaScript number that is finite and has no fractional part.
  • ISO timestamp: a string in the exact format produced by Date.prototype.toISOString() in UTC, for example 2026-10-11T14:03:27.000Z.

Where this document says a value "is" something or a host "does" something, that statement is normative.

Runtime environment

Engine and language level

  • The engine is Mozilla Rhino 1.9.1.
  • The context language version is Context.VERSION_ES6 (200).
  • Scripts run in interpreted mode (Context.setInterpretedMode(true)), so that instruction counting is exact and stack depth is bounded.
  • The maximum interpreter stack depth is 1,000 frames (Context.setMaximumInterpreterStackDepth(1000)). Exceeding it throws a catchable InternalError.
  • The main file is decoded as UTF-8. A leading byte-order mark is ignored. The source name used in stack traces is the main path from module.json, for example main.js, so error locations read main.js:42.

Guaranteed language features

Modules MAY rely on the following. Anything not listed here is not guaranteed, even if it happens to work in a given build, and modules MUST NOT depend on it.

FeatureStatus
All of ECMAScript 5.1 (functions, closures, var, object and array literals, getters/setters in literals, regular expressions, try/catch/finally, JSON, Math, Date, Array.prototype.forEach/map/filter/reduce/some/every/indexOf, Object.keys, Object.create, Object.freeze, Array.isArray, String.prototype.trim, encodeURIComponent, decodeURIComponent)Guaranteed
let and constGuaranteed, with three restrictions: a name MUST NOT be declared with let or const more than once in the same function, even in different blocks; code MUST NOT rely on a fresh binding per loop iteration (for (let i ...) closures), and declarations inside the body of a for, while or do loop MUST use let, not const. Callback functions (for example in forEach) are separate functions, so const inside them is fine.
Arrow functions (x => x + 1, (a, b) => { ... }), including lexical thisGuaranteed
Template literals (`Hello ${name}`), untaggedGuaranteed
Array.prototype.find, Array.prototype.findIndex, Array.prototype.includes, Object.assign, String.prototype.includes, String.prototype.startsWith, String.prototype.endsWith, String.prototype.repeat, String.prototype.padStart, String.prototype.padEnd, Number.isInteger, Number.isFiniteGuaranteed
Map and Set with get/set/has/delete/forEach/sizeGuaranteed
Destructuring (const { a } = obj, const [x, y] = arr)Not guaranteed. Modules MUST NOT use it.
Spread and rest (...args, [...a], {...o})Not supported.
Default parameter values (function f(a = 1))Not supported.
Classes (class X {})Not supported.
for...of, generators, tagged templates, Symbol, Object.values, Object.entries, Array.fromNot guaranteed. Modules MUST NOT use them.
async/await, PromiseNot available. The host removes the Promise global. Every enzonic.* call is synchronous.
ES modules (import, export), CommonJS (require, module.exports)Not available. A module is a single script file.
eval and new Function(...)Available inside the same sandbox. Review rejects modules that evaluate code obtained at runtime (for example from the network or from storage).

Globals that do not exist

The following are not defined in the module scope. Referencing them throws a ReferenceError (or yields undefined through typeof).

  • setTimeout, setInterval, clearTimeout, clearInterval, queueMicrotask, requestAnimationFrame: there are no timers and no event loop inside the script. Code runs only during invocations.
  • fetch, XMLHttpRequest, WebSocket: use enzonic.http.fetch.
  • console, print: use enzonic.log.
  • require, module, exports, process, window, document. (globalThis is not guaranteed either; top-level var and function declarations are globals.)
  • Packages, java, javax, org, com, net, edu, JavaAdapter, JavaImporter, importPackage, importClass, getClass, Promise, Continuation, global.

Java isolation

The host creates the standard library with Context.initSafeStandardObjects() (which omits LiveConnect globals), removes the globals listed above, seals every built-in constructor, prototype and namespace object (Object.prototype, Array.prototype, JSON, Math and so on; assigning to them fails), and installs a ClassShutter that returns false for every class name. The module's global object is a fresh object whose prototype is that sealed library, so top-level declarations work as usual. No Java class is visible or constructible from module code. The enzonic object and everything reachable from it are implemented as native Rhino scriptable objects and functions, never as reflected Java objects, so the shutter is never bypassed. Every value returned by a host call is a native JavaScript value (object, array, string, number, boolean or null) created in the module's scope.

Script structure

The main file is evaluated once per activation. Its top-level code SHOULD only declare functions and initialize state. The host then calls the global function activate. A module MUST define activate as a global function and MAY define deactivate.

js
var state = { count: 0 };

function view() {
  return enzonic.ui.page({
    title: "Counter",
    children: [
      enzonic.ui.text({ text: `Clicked ${state.count} times`, style: "title" }),
      enzonic.ui.button({ label: "Click", onClick: () => { state.count += 1; render(); } })
    ]
  });
}

function render() { enzonic.ui.render(view()); }

function activate(ctx) {
  enzonic.log("info", `Started ${ctx.module.id} ${ctx.module.version}`);
  render();
}

function deactivate() {
  enzonic.log("info", "Stopping");
}

Lifecycle

States

A module that is installed is in exactly one of these states:

StateMeaning
disabledInstalled, not running. No code is executed.
activeThe script has been evaluated, activate returned normally, and the module receives UI events.
erroredLoading, activate, or any invocation exceeded a budget, or loading or activate threw. The module's scope has been discarded. The module page shows the error code, message and (in Developer mode) the stack trace, plus a Restart button that performs a fresh activation.

Where a module appears

Every installed module is listed under Modules → Installed with its state, an enable switch, update checks, its settings ("Always allow" choices and saved data size) and Uninstall. An enabled module's page opens as a sub-page of the Modules section; the page's top bar shows the page title, subtitle and actions. The link enzonic://module/<id> opens the module's marketplace page in the launcher.

Activation

Activation happens when the user enables a module, when the launcher starts with the module enabled, when the user presses Restart on an errored module, and when the user presses Reload in Developer mode. Activation is one invocation that:

  1. Creates a fresh global scope (no state survives from a previous activation).
  2. Evaluates the main file.
  3. Calls activate(ctx).

Budgets (see Budgets) apply to steps 2 and 3 together. If either step throws, or activate is not a function, the module enters errored. If activate returns without calling enzonic.ui.render, the module page shows an empty page titled with the module name.

ctx is a frozen object:

json
{
  "module": {
    "id": "instance-notes",
    "version": "1.0.0",
    "permissions": ["instances.read", "storage"]
  },
  "launcher": {
    "version": "1.0.0",
    "os": "windows",
    "locale": "en-US",
    "theme": "dark"
  }
}
FieldTypeDescription
module.idstringThe module id from module.json.
module.versionstringThe module version from module.json.
module.permissionsstring[]The declared permissions, in manifest order. All of them were accepted by the user.
launcher.versionstringLauncher version, SemVer.
launcher.os"windows" | "macos" | "linux"Operating system.
launcher.localestringBCP 47 language tag of the launcher UI, for example "en-US" or "es-ES".
launcher.theme"light" | "dark"Theme in effect.

The same data is available at any time as enzonic.module and enzonic.launcher. These are frozen objects. The host refreshes enzonic.launcher before each invocation, so enzonic.launcher.theme and enzonic.launcher.locale reflect the values at the start of the current invocation. There is no event for theme or locale changes in API version 1; the launcher renders all components in the current theme automatically.

Deactivation

Deactivation happens when the user disables or uninstalls the module, when the module is updated (before the new version activates), when the module is auto-disabled, and when the launcher exits normally. The host:

  1. Cancels the running invocation, if any: pending host calls are aborted (an open confirmation dialog is closed, an HTTP request is aborted, a test launch terminates the game), and the invocation is terminated without running any further script code.
  2. Discards all queued events.
  3. Calls deactivate() if it is defined as a global function.
  4. Discards the scope.

deactivate has a 2-second wall-clock budget that includes time spent in host calls, plus the normal instruction budget. During deactivate:

  • enzonic.ui.render returns true and has no effect.
  • Calls that would show a confirmation dialog throw user_denied without showing a dialog.
  • Errors thrown by deactivate are logged and otherwise ignored.

deactivate is not called if the module is in errored state, or if the launcher process is killed. Modules MUST NOT rely on deactivate for data integrity; write to storage when data changes.

Events

UI event handlers are functions placed on component props (for example onClick). When the user interacts with a component, the host enqueues an event for the module. Each event becomes one invocation that calls the handler from the most recently rendered tree with the arguments defined for that prop. The handler's return value is ignored. If the component no longer exists in the current tree when the event is dequeued, the event is discarded.

Threading model

  • Each active module has one dedicated worker thread. All of that module's code runs on that thread. Module code never runs on the UI thread.
  • Invocations of one module are serialized: at most one runs at a time, in FIFO order. Activation and deactivation go through the same ordering.
  • The event queue holds at most 100 pending events per module. When it is full, new events are dropped and the host writes a warn entry to the module log naming the dropped event.
  • Every host call is synchronous: it blocks the worker thread until it completes and then returns a plain value or throws. The UI thread is never blocked by module code.
  • enzonic.ui.render hands the tree to the UI thread and returns immediately. A module MAY call render several times within one invocation (for example to show progress before and after a long host call); each tree is displayed as soon as the UI thread processes it.
  • While an invocation is running, the UI stays interactive; user interactions are queued as events and run after the current invocation finishes.
  • Different modules run on different threads and cannot communicate.

Budgets

Every invocation (activation, deactivate, each event handler call) has two budgets:

BudgetLimitHow it is measured
Instructions50,000,000 Rhino instructionsContextFactory.observeInstructionCount, with Context.setInstructionObserverThreshold(10000); the host accumulates counts per invocation.
Script time5 secondsWall-clock time of the invocation minus time spent blocked inside enzonic.* host calls (including confirmation dialogs, network requests and test launches). Checked at every instruction observer callback.

deactivate additionally has a 2-second wall-clock limit that includes host calls.

When a budget is exceeded:

  1. The host throws a termination from the instruction observer that script code cannot catch (try/catch and finally blocks in the script do not run). Implementations MUST use a java.lang.Error subclass, not a RhinoException, so that it is never converted to a JavaScript exception.
  2. The invocation is aborted, the module's scope is discarded and the module enters errored with code budget_exceeded.
  3. If a module has 3 budget failures within any 10-minute window, it is auto-disabled: it moves to disabled, the Restart button is not offered, and the user receives a launcher notification. The user can re-enable it from the Modules screen.

Memory is metered coarsely:

  • Allocation budget. At every instruction observer callback the host checks how many bytes the module's worker thread has allocated since the invocation started (as reported by the JVM). More than 512 MiB ends the invocation with budget_exceeded.
  • Allocation failure. If the JVM cannot satisfy an allocation made by module code (for example flattening a gigantic string), the invocation ends with budget_exceeded.
  • Built-in output caps. String.prototype.repeat, String.prototype.padStart, String.prototype.padEnd and Array.prototype.join throw a catchable RangeError instead of producing a string longer than 16,777,216 characters; Array.prototype.fill throws a RangeError on arrays longer than 16,777,216 elements.

The size limits in Limits bound everything that crosses the host boundary. Reviewers reject modules that build unbounded data structures.

Package format

A module package is a zip file:

text
my-module-1.0.0.zip
├── module.json          (REQUIRED, at the zip root)
├── main.js              (REQUIRED, the file named by "main")
├── icon.png             (optional, named by "icon")
└── assets/
    └── logo.png         (optional, referenced by image components)

Rules (the Modules API enforces them at upload; the launcher enforces them again at install):

RuleLimit
module.json locationAt the zip root, exactly module.json. A package whose manifest is inside a folder (for example my-module/module.json) is rejected.
module.json size≤ 64 KiB
Compressed size≤ 10 MiB
Total uncompressed size≤ 25 MiB
Entries≤ 500 (files and directory entries)
Entry pathsRelative, forward slashes only, no leading /, no drive letter prefix (C:), no .. or . segments, no backslashes, no empty segments, no control characters, each path ≤ 255 characters
CompressionStored or deflate entries only
Entry typesRegular files and directories only. Symbolic links are rejected.
Duplicate pathsRejected. Paths are compared case-insensitively, so Main.js and main.js collide.

The launcher additionally rejects entry paths that contain : anywhere or a reserved Windows device name (CON, NUL, COM1, LPT1.txt, ...) as a segment, on every OS.

The Modules API records the SHA-256 of each uploaded package. After downloading a version, the launcher MUST verify that the SHA-256 of the bytes equals the value recorded by the API and MUST refuse to install on mismatch.

Install locations

  • Installed versions are extracted to <launcher data dir>/modules/<id>/<version>/. After a successful update the previous version directory is deleted.
  • Module storage is kept in <launcher data dir>/modules/<id>/storage.json and survives updates.
  • Uninstalling deletes <launcher data dir>/modules/<id>/ entirely, including storage and the "Always allow" choices.

module.json reference

module.json is a UTF-8 JSON object, at most 64 KiB. Unknown top-level fields are rejected. Leading or trailing whitespace makes id, version, main, icon, minLauncher and permission strings invalid. name and author are trimmed before their length is checked; description is not trimmed, so whitespace counts toward its length.

json
{
  "id": "server-status",
  "name": "Server Status",
  "version": "1.2.0",
  "description": "Checks whether your favorite Minecraft servers are online.",
  "author": "Alex Rivera",
  "main": "main.js",
  "icon": "icon.png",
  "minLauncher": "1.0.0",
  "permissions": ["http:api.mcsrvstat.us", "storage", "notifications"]
}
FieldTypeRequiredConstraintsExample
idstringYesRegex ^[a-z0-9][a-z0-9-]{1,47}$ (2 to 48 characters, lowercase letters, digits and hyphens, starting with a letter or digit). MUST equal the module's marketplace slug. Never changes across versions."server-status"
namestringYes2 to 64 characters after trimming. Display name."Server Status"
versionstringYesSemantic version; MUST match the version regex below the table. Unique per module."1.2.0", "2.0.0-beta.1"
descriptionstringNo0 to 2,000 characters. Plain text. Defaults to ""."Checks whether ..."
authorstringYes1 to 64 characters after trimming. Person or organization name."Alex Rivera"
mainstringYesA file path (package path rules above, ≤ 255 characters, not ending in /) ending in .js that exists in the zip. The convention is main.js."main.js"
permissionsstring[]Yes0 to 32 entries, unique, each a known permission string or http:<host> (see Permissions). MAY be empty.["storage"]
minLauncherstringYesSemantic version (same regex as version). The lowest launcher version that can run the module. Use "1.0.0" for API version 1 features."1.0.0"
iconstringNoA file path (same rules as main) ending in .png, .jpg, .jpeg or .webp that exists in the zip. Square, 256×256 pixels recommended."icon.png"

The .js and image extensions are matched case-insensitively. Version regex used for version and minLauncher (at most 160 characters):

text
^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})(?:[-+][0-9A-Za-z.-]{1,64})?$

That is MAJOR.MINOR.PATCH, each part a number of 1 to 9 digits without leading zeros, optionally followed by one suffix: a pre-release (-beta.1) or build metadata (+build.5), 1 to 64 letters, digits, dots or hyphens after the - or +. Versions are ordered by SemVer 2.0.0 precedence: a pre-release sorts before its release and build metadata is ignored.

A launcher whose version is lower than minLauncher (compared by SemVer precedence) MUST refuse to install or activate the module and show the required version.

Permissions

Permissions are declared in module.json permissions. At install, the launcher shows every declared permission with the description below; the user MUST accept all of them to install. On update, if the new version declares any permission the installed version does not, the launcher shows the full list with the new ones highlighted and the user MUST accept again or the update is not applied. A version that only removes permissions updates without a prompt.

Calling a method whose permission is not declared throws permission_denied, regardless of arguments.

PermissionGrantsUser-facing description
instances.readenzonic.instances.list, enzonic.instances.get, enzonic.instances.listFiles, enzonic.instances.readFile, enzonic.mods.listRead your instances, their settings and files.
instances.writeenzonic.instances.writeFile, enzonic.instances.deleteFileCreate, change and delete files inside your instances (asks first).
mods.manageenzonic.mods.install, enzonic.mods.enable, enzonic.mods.disable, enzonic.mods.removeInstall, enable, disable and remove mods from Modrinth (asks first).
launchenzonic.launchStart Minecraft with your signed-in account, including test launches (asks first).
storageenzonic.storage.get, enzonic.storage.set, enzonic.storage.remove, enzonic.storage.keysSave its own data on this computer (up to 1 MiB).
notificationsenzonic.notifyShow notifications.
aienzonic.ai.chatUse Enzica with your Enzonic account and daily quota. Privileged: modules requesting it receive additional review.
http:<host>enzonic.http.fetch to exactly <host>, and https://<host>/... image sourcesConnect to <host> over HTTPS.

The following need no permission: enzonic.ui.*, enzonic.log, enzonic.module, enzonic.launcher, enzonic.apiVersion.

mods.manage does not require an http: permission; the host contacts Modrinth itself. instances.write does not imply instances.read; declare both if you need both.

http host rules

<host> in http:<host> MUST:

  • be a public lowercase DNS hostname with at least two labels, matching ^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$;
  • contain no scheme, port, path, query, user info or wildcard;
  • not be an IP literal (the final label, at least 2 characters, must start with a letter);
  • not be localhost and not end in .localhost, .local or .internal.

Each http: entry grants exactly one host. http:example.com does not grant www.example.com or api.example.com. Requests are HTTPS on port 443 only.

User confirmation

Calls granted by instances.write, mods.manage and launch show a native confirmation dialog that names the module and describes the exact action (for example "Instance Notes wants to write config/sodium-options.json (2.1 KiB) in instance Survival 1.21"). The dialog has Allow, Deny and a checkbox Always allow for this module, which applies to that permission only.

  • If the user denies, the call throws user_denied and nothing is changed.
  • If "Always allow" is enabled for that permission, calls proceed without a dialog. Users can revoke "Always allow" in the module's settings. The choice survives updates and is deleted on uninstall.
  • Time spent waiting for the user does not count against the script-time budget.

The enzonic object

enzonic is a frozen global object. Its members:

MemberKindPermission
enzonic.apiVersionnumber, always 1 in this versionNone
enzonic.modulefrozen object { id, version, permissions }None
enzonic.launcherfrozen object { version, os, locale, theme }None
enzonic.log(level, message)functionNone
enzonic.instances.*functionsinstances.read / instances.write
enzonic.mods.*functionsinstances.read / mods.manage
enzonic.launch(instanceId, options)functionlaunch
enzonic.storage.*functionsstorage
enzonic.notify(options)functionnotifications
enzonic.http.fetch(url, options)functionhttp:<host>
enzonic.ai.chat(request)functionai
enzonic.ui.*functionsNone

Calling conventions

These rules apply to every host function:

  1. Synchronous. Every call returns a value or throws. Nothing returns a Promise.
  2. JSON-compatible values. Every argument and return value is a JSON-compatible value (object, array, string, finite number, boolean, null), except UI event handler props, which are functions. undefined for an optional argument or option means "not provided".
  3. Strict validation. A missing required argument, a value of the wrong type, a value out of range, or an unknown key in an options object throws invalid_argument. The error message names the offending path, for example options.timeoutSec or children[2].label, and details.path contains the same path.
  4. Permission first. The permission check happens before argument validation. An undeclared permission always yields permission_denied.
  5. String size. Every string argument is limited to 5 MiB (5,242,880 bytes of UTF-8), except content in enzonic.instances.writeFile with encoding: "base64", which is limited to 6,990,508 characters (the base64 length of 5 MiB). Larger strings throw too_large.
  6. Fresh values. Returned objects and arrays are new, mutable copies. Mutating them has no effect on the host.
  7. Error objects. Host errors are thrown as described in Error model.

enzonic.log

text
enzonic.log(level: "debug" | "info" | "warn" | "error", message: string) -> true

Writes an entry to the module log, visible in the module log pane in Developer mode and included in the launcher's diagnostic logs at info level and above.

ArgumentTypeRules
levelstringOne of "debug", "info", "warn", "error".
messagestring≤ 4 KiB. Longer messages throw too_large. Non-string values throw invalid_argument (convert with String(x) or JSON.stringify(x)).

Permission: none. Errors: invalid_argument, too_large. Logging is not rate limited, but the log pane retains only the most recent 5,000 entries per module.

enzonic.instances

Instance object

json
{
  "id": "k3v9x2m1",
  "name": "Survival 1.21",
  "folder": "Friends",
  "minecraftVersion": "1.21.1",
  "loader": "fabric",
  "loaderVersion": "0.16.5",
  "memoryMb": 4096,
  "javaPath": null,
  "lastPlayedAt": "2026-10-10T19:22:04.000Z",
  "createdAt": "2026-08-01T09:00:00.000Z"
}
FieldTypeDescription
idstringStable instance identifier, 1 to 64 characters from [A-Za-z0-9_-].
namestringDisplay name.
folderstring | nullName of the Library folder the instance belongs to, or null if it is not in a folder.
minecraftVersionstringMinecraft version id, for example "1.21.1".
loader"vanilla" | "fabric" | "quilt" | "forge" | "neoforge"Mod loader.
loaderVersionstring | nullLoader version; null for vanilla.
memoryMbintegerMaximum heap in MiB.
javaPathstring | nullAbsolute path of a user-selected Java executable, or null when the launcher's managed Java is used.
lastPlayedAtstring | nullISO timestamp of the last launch, or null if never launched.
createdAtstringISO timestamp of creation.

Instance paths

Every path argument in enzonic.instances is relative to the instance's game directory and MUST:

  • use forward slashes;
  • not start with /;
  • not contain a drive letter (C:), a : anywhere (on every OS), a backslash, a control character, an empty segment, a . segment, a .. segment or a reserved Windows device name (CON, NUL, COM1, LPT1.txt, ...);
  • be at most 512 characters.

A path that violates these rules throws invalid_argument. A syntactically valid path that resolves (after following symbolic links) to a location outside the instance directory throws path_outside_instance. Returned paths use the same form.

The file enzonic-instance.json in the instance root holds launcher metadata. It can be read but MUST NOT be written or deleted by modules (forbidden_path). On Windows and macOS this comparison is case-insensitive.

An instance is running while the launcher supervises a game process for it, including a test launch.

enzonic.instances.list

text
enzonic.instances.list() -> Instance[]

Returns all instances, sorted by name (case-insensitive), then by id. Returns [] if there are none.

Permission: instances.read. Errors: permission_denied, io_error.

enzonic.instances.get

text
enzonic.instances.get(instanceId: string) -> Instance

Permission: instances.read. Errors: permission_denied, invalid_argument, not_found (no instance with that id), io_error.

enzonic.instances.listFiles

text
enzonic.instances.listFiles(instanceId: string, dir?: string) -> FileEntry[]

Lists the direct children of dir (default "", the instance root). Not recursive. Sorted by path using ordinal (code unit) comparison.

FileEntry:

json
{ "path": "config/sodium-options.json", "type": "file", "size": 2150, "modifiedAt": "2026-10-09T08:15:00.000Z" }
FieldTypeDescription
pathstringInstance-relative path of the entry (including dir).
type"file" | "dir"Entry type. Symbolic links are reported as the type of their target; links that point outside the instance are omitted.
sizeintegerSize in bytes; 0 for directories.
modifiedAtstringISO timestamp of last modification.

At most 10,000 entries are returned; a directory with more throws too_large.

Permission: instances.read. Errors: permission_denied, invalid_argument (bad path, or dir is a file), not_found (instance or directory does not exist), path_outside_instance, too_large, io_error.

enzonic.instances.readFile

text
enzonic.instances.readFile(instanceId: string, path: string, options?: { encoding?: "utf8" | "base64" }) -> string
OptionTypeDefaultDescription
encoding"utf8" | "base64""utf8"utf8 decodes the file as UTF-8, replacing malformed sequences with U+FFFD. base64 returns standard RFC 4648 base64 with padding and no line breaks.

Files larger than 5 MiB throw too_large (the file is not read).

Permission: instances.read. Errors: permission_denied, invalid_argument (bad path or options, or path is a directory), not_found (instance or file), path_outside_instance, too_large, io_error.

enzonic.instances.writeFile

text
enzonic.instances.writeFile(instanceId: string, path: string, content: string,
  options?: { encoding?: "utf8" | "base64", createDirs?: boolean }) -> { path: string, size: number }
OptionTypeDefaultDescription
encoding"utf8" | "base64""utf8"How content is encoded. utf8 writes the string as UTF-8 without a byte-order mark. base64 decodes standard base64 (padding optional, no whitespace).
createDirsbooleantrueCreate missing parent directories. When false and the parent does not exist, throws not_found.

Creates or replaces the file. The write is atomic: the host writes to a temporary file in the same directory and renames it over the target. The decoded content MUST be ≤ 5 MiB. Returns the normalized path and the number of bytes written.

Shows a confirmation dialog unless "Always allow" is set for instances.write.

Permission: instances.write. Errors: permission_denied, invalid_argument (bad path, options or base64, or path is an existing directory), not_found (instance, or parent with createDirs: false), path_outside_instance, forbidden_path, instance_running, too_large, user_denied, io_error.

enzonic.instances.deleteFile

text
enzonic.instances.deleteFile(instanceId: string, path: string) -> true

Deletes one file. Directories cannot be deleted (invalid_argument). Shows a confirmation dialog unless "Always allow" is set for instances.write.

Permission: instances.write. Errors: permission_denied, invalid_argument, not_found, path_outside_instance, forbidden_path, instance_running, user_denied, io_error.

enzonic.mods

Mods are the .jar files in the instance's mods/ directory. A disabled mod is the same file renamed with a .disabled suffix (sodium.jar becomes sodium.jar.disabled). Subdirectories of mods/ are ignored.

Mod object

json
{
  "filename": "sodium-fabric-0.6.0+mc1.21.1.jar",
  "enabled": true,
  "name": "Sodium",
  "version": "0.6.0+mc1.21.1",
  "modrinthProjectId": "AANobbMI",
  "modrinthVersionId": "u1OEbNKx",
  "sha512": "1c9f5a..."
}
FieldTypeDescription
filenamestringCurrent file name in mods/, including the .disabled suffix when disabled. This is the identifier passed to enable, disable and remove.
enabledbooleanfalse when the file name ends in .disabled.
namestring | nullDisplay name read from the jar's loader metadata (fabric.mod.json, quilt.mod.json, META-INF/mods.toml or META-INF/neoforge.mods.toml), or null if it cannot be read.
versionstring | nullVersion from the same metadata, or null.
modrinthProjectIdstring | nullModrinth project id if the launcher knows the file's origin (installed through the launcher or previously identified by hash), else null.
modrinthVersionIdstring | nullModrinth version id under the same rule.
sha512stringLowercase hex SHA-512 of the file.

Loader compatibility used by install: fabric instances accept Modrinth files for fabric; quilt instances accept quilt and fabric; forge accepts forge; neoforge accepts neoforge. vanilla instances cannot have mods.

enzonic.mods.list

text
enzonic.mods.list(instanceId: string) -> Mod[]

Sorted by filename (case-insensitive). Returns [] when mods/ does not exist.

Permission: instances.read. Errors: permission_denied, invalid_argument, not_found, io_error.

enzonic.mods.install

text
enzonic.mods.install(instanceId: string, request: {
  project: string, versionId?: string, withDependencies?: boolean
}) -> { installed: Mod[], skipped: { project: string, reason: string }[] }
FieldTypeDefaultDescription
projectstring(required)Modrinth project id or slug.
versionIdstringnewest compatibleA specific Modrinth version id of that project.
withDependenciesbooleantrueAlso install the project's required dependencies, recursively. Optional dependencies are never installed.

Behavior:

  1. If versionId is omitted, the host picks the newest release (by publication date; if there is none, the newest beta, then the newest alpha) whose game versions include the instance's minecraftVersion and whose loaders are compatible with the instance's loader. If none exists, throws no_compatible_version. If versionId is given and that version is not compatible, throws no_compatible_version; if it belongs to a different project, throws invalid_argument.
  2. Dependencies are resolved the same way (a dependency pinned to a specific version uses that version when it is compatible). A dependency project that is already installed (any version) is kept and reported in skipped with reason "already_installed". A dependency with no compatible version is reported in skipped with reason "no_compatible_version"; it does not fail the call. If a selected version declares a project incompatible that is installed or part of the same install, the call throws no_compatible_version with details.conflictsWith (the other project) before anything is downloaded.
  3. A project whose selected version is already present (same Modrinth version id) is reported in skipped with reason "already_installed". If a different version of the same project is present, its file is replaced (the old file is deleted after the new file is verified) and the new file is reported in installed.
  4. The confirmation dialog, unless "Always allow" is set for mods.manage, lists every file that will be added or replaced, after resolution and before any download.
  5. Each file is downloaded from Modrinth's CDN and its SHA-512 is verified against Modrinth's metadata before it is moved into mods/. On mismatch nothing from that call is kept and the call throws network_error with details.reason = "hash_mismatch".

skipped[].reason is one of "already_installed", "no_compatible_version".

Permission: mods.manage. Errors: permission_denied, invalid_argument (bad request, version of another project, or the instance uses vanilla), not_found (instance, project or version), no_compatible_version, instance_running, user_denied, network_error, timeout, io_error.

enzonic.mods.enable

text
enzonic.mods.enable(instanceId: string, filename: string) -> Mod

Renames <name>.jar.disabled to <name>.jar and returns the updated Mod. If the mod is already enabled, returns it unchanged without a dialog. If a file with the target name already exists, throws io_error. Shows a confirmation dialog unless "Always allow" is set for mods.manage.

Permission: mods.manage. Errors: permission_denied, invalid_argument, not_found (instance or file), instance_running, user_denied, io_error.

enzonic.mods.disable

text
enzonic.mods.disable(instanceId: string, filename: string) -> Mod

Renames <name>.jar to <name>.jar.disabled. Idempotent like enable. Same dialog, permission and errors as enable.

enzonic.mods.remove

text
enzonic.mods.remove(instanceId: string, filename: string) -> true

Removes the mod file (enabled or disabled) from mods/ by moving it to the launcher trash, where the user can restore it. Shows a confirmation dialog unless "Always allow" is set for mods.manage.

Permission: mods.manage. Errors: permission_denied, invalid_argument, not_found, instance_running, user_denied, io_error.

enzonic.launch

text
enzonic.launch(instanceId: string, options?: { test?: boolean, timeoutSec?: number }) -> LaunchResult | TestResult
OptionTypeDefaultDescription
testbooleanfalseRun a test launch.
timeoutSecinteger180Test launches only: 30 to 600. Passing timeoutSec without test: true throws invalid_argument.

The launcher prepares the instance exactly as the Play button does (downloads missing game files, loader and Java), using the Minecraft account currently selected in the launcher. Shows a confirmation dialog unless "Always allow" is set for launch.

Normal launch returns as soon as the game process has been spawned:

json
{ "started": true, "pid": 18324 }

Test launch spawns the game, then waits for the first of:

  • the launcher's title-screen detection marker in the game log (reached_menu);
  • a crash: the process exits with a non-zero code, a new file appears in crash-reports/, or the launcher's crash detection triggers (crashed);
  • the process exiting with code 0 before reaching the menu (exited);
  • timeoutSec seconds elapsing since the process was spawned (timeout). Preparation time is not counted.

It then terminates the game (graceful termination, then forced after 5 seconds) if it is still running, and returns:

json
{
  "ok": true,
  "reason": "reached_menu",
  "durationMs": 41250,
  "exitCode": null,
  "logTail": "[12:01:07] [Render thread/INFO]: ...",
  "crashReport": null
}
FieldTypeDescription
okbooleantrue exactly when reason is "reached_menu".
reason"reached_menu" | "crashed" | "exited" | "timeout"Outcome.
durationMsintegerMilliseconds from process spawn to the outcome.
exitCodeinteger | nullThe process exit code if it exited by itself; null if the launcher terminated it.
logTailstringThe last 200 lines of game output, further truncated to the last 64 KiB.
crashReportstring | nullContents of the crash report created during this run (truncated to the first 256 KiB), or null.

Time spent inside enzonic.launch does not count against the script-time budget. Because invocations are serialized, other events for the module wait until the test launch returns; render a progress state before calling it.

Permission: launch. Errors: permission_denied, invalid_argument, not_found, instance_running (the instance is already running), not_signed_in (no Microsoft account is signed in to the launcher; the message says "Sign in with a Microsoft account in the launcher to launch Minecraft."), user_denied, network_error (game files could not be downloaded), io_error.

enzonic.storage

A per-module persistent key-value store holding JSON values. It is stored in <launcher data dir>/modules/<id>/storage.json and deleted on uninstall. Writes are durable (atomic file replace) before the call returns.

RuleValue
Keystring, 1 to 128 characters
Valueany JSON-compatible value (object, array, string, finite number, boolean, null). Functions, undefined, NaN and Infinity (anywhere inside the value) throw invalid_argument.
QuotaThe UTF-8 length of JSON.stringify of the whole store (an object mapping keys to values) MUST stay ≤ 1 MiB. A set that would exceed it throws quota_exceeded and changes nothing.
text
enzonic.storage.get(key: string) -> any | null       (null when the key does not exist)
enzonic.storage.set(key: string, value: any) -> true
enzonic.storage.remove(key: string) -> true          (true also when the key did not exist)
enzonic.storage.keys() -> string[]                   (sorted, ordinal comparison)

get returns a fresh copy; storing null is allowed and is indistinguishable from a missing key through get (use keys() to tell them apart).

Permission: storage. Errors: permission_denied, invalid_argument, too_large (a single value larger than 1 MiB), quota_exceeded, io_error.

enzonic.notify

text
enzonic.notify(options: { title: string, body?: string, level?: "info" | "success" | "warning" | "error" }) -> true
FieldTypeDefaultRules
titlestring(required)1 to 80 characters
bodystringnone≤ 300 characters
levelstring"info""info", "success", "warning", "error"

Shows a snackbar in the launcher window, labeled with the module name. If the launcher window is not focused, the launcher also shows an operating-system notification where available. Limit: 10 calls per rolling 60 seconds per module; the 11th throws rate_limited with details.retryAfterMs.

Permission: notifications. Errors: permission_denied, invalid_argument, rate_limited.

enzonic.http

enzonic.http.fetch

text
enzonic.http.fetch(url: string, options?: {
  method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD",
  headers?: { [name: string]: string },
  body?: string,
  timeoutMs?: number
}) -> { status: number, headers: { [name: string]: string }, text: string, json: any | null }
OptionTypeDefaultRules
methodstring"GET"One of the listed methods.
headersobject{}≤ 50 entries. Names are valid RFC 9110 field names (token characters only), ≤ 256 characters; values are strings ≤ 8 KiB without CR or LF.
bodystringnoneSent as UTF-8. Not allowed with GET or HEAD (invalid_argument). If no Content-Type header is given, text/plain; charset=utf-8 is used.
timeoutMsinteger150001,000 to 30,000. Covers the whole request including redirects and reading the body.

Rules:

  1. url MUST be an absolute https:// URL without user info, with no port or port 443. A malformed URL throws invalid_argument. Any other scheme or port throws host_not_allowed.
  2. The URL host (lowercased) MUST exactly equal a declared http:<host>; otherwise host_not_allowed.
  3. If the host resolves to a loopback, private (RFC 1918, RFC 4193), link-local, carrier-grade NAT or multicast address, the request is refused with host_not_allowed and details.reason = "private_address".
  4. Redirects (301, 302, 303, 307, 308) are followed up to 5 times. Each target MUST satisfy rules 1 to 3, otherwise the call throws host_not_allowed and the redirect is not followed. 303 switches to GET without a body; 301 and 302 switch POST to GET without a body; 307 and 308 keep the method and body. More than 5 redirects throw network_error.
  5. Request headers Cookie, Host, Content-Length, Connection, Transfer-Encoding, User-Agent and any header starting with Proxy- are removed (case-insensitive). The host sets User-Agent: EnzonicLauncher/<launcher version> (module <id>/<version>).
  6. No cookies are stored or sent. set-cookie is removed from the returned headers.
  7. The response body is limited to 5 MiB; larger bodies throw too_large.
  8. Non-2xx statuses are returned normally, not thrown.
  9. Limit: 60 requests per rolling 60 seconds per module (redirect hops do not count separately); excess throws rate_limited with details.retryAfterMs.

Response:

FieldTypeDescription
statusintegerHTTP status of the final response.
headersobjectResponse headers with lowercased names. Repeated headers are joined with ", ".
textstringBody decoded with the charset from Content-Type, defaulting to UTF-8. "" for HEAD and empty bodies.
jsonany | nullThe parsed body when Content-Type is application/json or ends in +json and the body parses; otherwise null. A parse failure never throws.

Permission: http:<host> for the request host. Errors: permission_denied (the module declares no http: permission at all), invalid_argument, host_not_allowed, too_large, rate_limited, timeout, network_error (DNS, TLS, connection failure, too many redirects).

enzonic.ai

enzonic.ai.chat

text
enzonic.ai.chat(request: {
  messages: Message[],
  tools?: Tool[],
  temperature?: number
}) -> { message: AssistantMessage, usage: { input_tokens: number, output_tokens: number } }

Message:

FieldTypeRules
role"system" | "user" | "assistant" | "tool"Required.
contentstring | nullRequired. null is allowed only for assistant messages that have tool_calls.
tool_call_idstringRequired for tool messages, forbidden otherwise. Must match an id from a preceding assistant tool_calls entry.
tool_callsToolCall[]Allowed only on assistant messages; copy them from a previous response.

ToolCall: { id: string, type: "function", function: { name: string, arguments: string } }. arguments is a JSON-encoded string produced by the model; parse it with JSON.parse inside try/catch.

Tool (OpenAI function tool definition):

json
{
  "type": "function",
  "function": {
    "name": "list_instances",
    "description": "List the user's Minecraft instances.",
    "parameters": { "type": "object", "properties": {}, "required": [] }
  }
}

function.name matches ^[a-zA-Z0-9_-]{1,64}$; parameters is a JSON Schema object.

FieldRules
messages1 to 200 messages
tools0 to 64 tools, unique names
temperaturenumber, 0 to 2; the server default applies when omitted
Serialized request≤ 1 MiB (too_large)

Return value:

json
{
  "message": {
    "role": "assistant",
    "content": null,
    "tool_calls": [
      { "id": "call_1", "type": "function", "function": { "name": "list_instances", "arguments": "{}" } }
    ]
  },
  "usage": { "input_tokens": 412, "output_tokens": 18 }
}

message.tool_calls is present only when the model requested tool calls. content is null or a string.

The host sends the request to POST https://launcher-ai.enzonic.com/v1/chat with the user's Enzonic (Clerk) OAuth access token, without streaming, and maps the first choice of the OpenAI-compatible response to message and usage.prompt_tokens / usage.completion_tokens to input_tokens / output_tokens. The module cannot choose the model or supply keys. The model executes no tools; the module runs its own tool loop: call chat, execute any requested tools with its own code, append the assistant message and one tool message per call, and call chat again. Each chat call counts against the user's AI quota (30 requests per minute and 200 requests per day per user, shared by all AI features). The request times out after 120 seconds.

Permission: ai. Errors: permission_denied, invalid_argument, too_large, not_signed_in (no Enzonic account signed in; the message says "Sign in to your Enzonic account in the launcher to use Enzica."), rate_limited (per-minute limit), quota_exceeded (daily quota), timeout, network_error (connection failures and 5xx responses, with details.status when there was a response), internal_error.

UI reference

enzonic.ui.render

text
enzonic.ui.render(tree: PageNode) -> true

Replaces the module's page with tree. The root MUST be a page node. The tree is validated completely before anything is displayed; an invalid tree throws invalid_argument and the previous tree stays on screen. The message and details.path name the first invalid location, relative to the root, for example children[2].label or children[0].items[3].trailing.onClick.

Nodes

A node is a plain object { type: string, key?: string, ...props }. Container nodes have children: Node[]. Props not listed for a type throw invalid_argument, as do props with the wrong type. An unknown prop is reported before a missing required prop of the same node, so a typo names the misspelled prop. Optional props MAY be omitted or set to undefined; null is accepted only where the type lists null.

Common propTypeRules
typestringOne of the 10 component types.
keystringOptional. 1 to 64 characters. Unique among siblings (invalid_argument on duplicates).

Builder helpers

For each type there is a helper on enzonic.ui that returns a shallow copy of props with type set: enzonic.ui.page, enzonic.ui.card, enzonic.ui.list, enzonic.ui.button, enzonic.ui.text, enzonic.ui.input, enzonic.ui.select, enzonic.ui.progress, enzonic.ui.image and enzonic.ui["switch"]. Because switch is a reserved word, use the bracket form enzonic.ui["switch"](props) or write the object literal { type: "switch", ... }. Helpers do not validate; validation happens in render. Helpers need no permission and never throw.

Keys and state preservation

Between renders, the host matches each node to a node of the previous tree at the same position in the parent: siblings with a key are matched by key, and siblings without a key are matched by index among unkeyed siblings of the same type. A matched node keeps its local UI state: text being edited, cursor and focus in an input, scroll position of a page or list, and pressed or hover state. An unmatched node is created fresh. Give a key to every node whose identity matters, especially inputs and items in lists that can be reordered, inserted or removed. Changing a node's key deliberately resets its state.

Event handlers

Props whose names start with on take functions. A handler runs as an invocation on the module thread, in the order events occurred, with the arguments listed per component. Handlers count against budgets like any invocation. An uncaught error in a handler is written to the module log with its stack trace and shown as an error snackbar; the module stays active.

Size limits

LimitValue
Serialized tree size (JSON of the tree with functions omitted)≤ 256 KiB (too_large)
Nodes per tree (list items count as nodes)≤ 5,000 (too_large)
Nesting depth≤ 32 (invalid_argument)

Components

page

The root of every tree. Displays a top app bar and a scrollable column of children with 16 dp spacing.

PropTypeDefaultRules
titlestring(required)1 to 120 characters
subtitlestringnone≤ 200 characters
actionsbutton node[][]≤ 3. Rendered in the top app bar. A button with icon renders as an icon button with label as its tooltip; otherwise as a text button. variant is ignored.
childrenNode[](required)Any nodes except page. MAY be empty.

card

A Material 3 card that groups content.

PropTypeDefaultRules
titlestringnone≤ 120 characters
subtitlestringnone≤ 200 characters
layout"column" | "row""column"column stacks children vertically with 8 dp spacing. row places them horizontally with 8 dp spacing and wraps to new lines when space runs out.
childrenNode[][]Any nodes except page.
onClickfunction()noneMakes the whole card clickable. Clicks on interactive children do not trigger it.

list

A vertical list of uniform items.

PropTypeDefaultRules
itemsItem[](required)≤ 1,000
emptyTextstringnoneShown when items is empty. ≤ 200 characters.

Item:

FieldTypeRules
keystringRequired. 1 to 64 characters, unique within the list.
titlestringRequired. ≤ 200 characters.
subtitlestringOptional. ≤ 500 characters.
iconIconNameOptional. Leading icon.
trailingtext, button or switch nodeOptional. Interacting with a trailing button or switch does not trigger the item's onClick.
onClickfunction()Optional. Makes the item clickable.

Items are not nodes and take no type.

button

PropTypeDefaultRules
labelstring(required)1 to 60 characters
variant"filled" | "tonal" | "outlined" | "text""filled"Material 3 button style.
iconIconNamenoneLeading icon.
disabledbooleanfalseDisabled buttons ignore clicks.
onClickfunction()(required)Called with no arguments.

text

PropTypeDefaultRules
textstring(required)≤ 64 KiB. Newlines are preserved. Plain text, no markup.
style"headline" | "title" | "body" | "label" | "code""body"code uses a monospace font and does not wrap long lines (horizontal scroll).
tone"default" | "muted" | "accent" | "error""default"accent uses the launcher's green accent; error the error color.
selectablebooleanfalseAllows the user to select and copy the text.

input

A text field.

PropTypeDefaultRules
labelstring(required)1 to 80 characters
valuestring"" on creationSee value rule below.
placeholderstringnone≤ 200 characters
multilinebooleanfalseMulti-line text area (grows to 10 lines, then scrolls).
secretbooleanfalseMasks the text. Cannot be combined with multiline (invalid_argument).
maxLengthinteger65,5361 to 65,536. The field refuses input beyond it.
disabledbooleanfalse
onChangefunction(value: string)noneCalled with the full current text. The host coalesces changes to at most one call per 150 ms per field, always delivering the latest text.
onSubmitfunction(value: string)noneCalled when the user presses Enter. Not allowed with multiline (invalid_argument).

Value rule: the host replaces the field's text with value only when value differs from both the value of the previous render of this node and the most recent text delivered to this node's onChange. This lets a module re-render while the user types without losing keystrokes, and still lets it clear or set the field deliberately (for example render value: "" after submitting).

switch

PropTypeDefaultRules
labelstring(required)1 to 120 characters
checkedboolean(required)
disabledbooleanfalse
onChangefunction(checked: boolean)(required)Called with the new state.

When the user toggles, the host shows the new state immediately and calls onChange. The next render's checked value is authoritative.

select

A dropdown.

PropTypeDefaultRules
labelstring(required)1 to 80 characters
valuestring(required)MUST equal one of the option values.
options{ value: string, label: string }[](required)1 to 100 options, unique values, labels ≤ 120 characters.
disabledbooleanfalse
onChangefunction(value: string)(required)Called with the chosen option's value.

Like switch, the selection updates immediately and the next render's value is authoritative.

progress

PropTypeDefaultRules
valuenumber | nullindeterminate0 to 1 inclusive. Omitted or null shows an indeterminate indicator.
labelstringnone≤ 200 characters, shown above the bar.

image

PropTypeDefaultRules
srcstring(required)Either a package path inside the module zip (for example "assets/logo.png") or an https:// URL whose host is declared with http:<host>.
altstring(required)1 to 200 characters. Used for accessibility and shown if the image cannot be loaded.
widthnumberintrinsicWidth in dp, 1 to 2,000.
heightnumberintrinsicHeight in dp, 1 to 2,000.
fit"contain" | "cover""contain"How the image fills the box when both width and height are given.

Images MUST be PNG, JPEG or WebP (detected by content), at most 2 MiB. At render time the host validates that a package path exists in the module (else invalid_argument) and that a URL's host is declared (else invalid_argument). Remote images are fetched by the host following the enzonic.http.fetch host rules, cached for the session, and do not count toward the fetch rate limit. An image that fails to load or decode shows its alt text in a placeholder.

IconName

icon props accept exactly these Material Symbols names. Any other value throws invalid_argument.

addcheckclosedeletedownloadupload
editfolderfilesettingsplay_arrowstop
refreshsearchinfowarningerrorstar
persongroupclouddnsmemoryspeed
extensionsports_esportsterminalboltlinkopen_in_new
content_copyvisibilitylockscheduleauto_awesomeinventory_2

file is rendered with the Material Symbols description glyph.

Error model

Error objects

Every error raised by a host call is thrown as a JavaScript Error object created in the module scope, with these properties:

PropertyTypeDescription
namestringAlways "EnzonicError".
codestringOne of the codes below.
messagestringHuman-readable English description.
detailsobjectOptional. Code-specific data, for example { "path": "options.timeoutSec" } (the offending argument of invalid_argument and too_large), { "file": "config/a.json" } (the instance file of not_found, path_outside_instance and forbidden_path) or { "retryAfterMs": 4200 }.

e instanceof Error is true. Errors are catchable with try/catch, except budget_exceeded.

js
try {
  enzonic.instances.writeFile(id, "options.txt", text);
} catch (e) {
  if (e.code === "user_denied") {
    status = "You declined the change.";
  } else if (e.code === "instance_running") {
    status = "Close the game first.";
  } else {
    throw e;
  }
}

Error codes

CodeMeaningThrown by
permission_deniedThe module did not declare the permission the call requires.Every permissioned call
invalid_argumentMissing, wrong-typed, out-of-range or unknown argument or option; malformed path; invalid UI tree; unknown icon; operation not applicable (deleting a directory, installing mods into a vanilla instance). details.path names the location.Every call
not_foundThe instance, file, directory, mod file, Modrinth project or version does not exist.instances.get/listFiles/readFile/writeFile/deleteFile, mods.*, launch
path_outside_instanceThe path resolves (through symbolic links) outside the instance directory.instances.listFiles/readFile/writeFile/deleteFile
forbidden_pathThe path is enzonic-instance.json.instances.writeFile/deleteFile
too_largeA size limit was exceeded (file, string argument, response body, UI tree, directory listing, AI request, log message, storage value).instances.listFiles/readFile/writeFile, storage.set, http.fetch, ai.chat, ui.render, log, any call with an oversized string
io_errorA local file system operation failed. details.reason carries the operating system message.instances.*, mods.*, launch, storage.*
instance_runningThe instance is running, so it cannot be modified or launched again.instances.writeFile/deleteFile, mods.install/enable/disable/remove, launch
no_compatible_versionNo Modrinth version matches the instance's Minecraft version and loader.mods.install
network_errorDNS, TLS or connection failure, too many redirects, a corrupted download (details.reason = "hash_mismatch"), or an upstream 5xx (details.status).mods.install, launch, http.fetch, ai.chat
host_not_allowedThe URL's scheme, port or host is not permitted, a redirect left the declared hosts, or the host resolves to a private address.http.fetch
timeoutThe operation exceeded its time limit.http.fetch, ai.chat, mods.install
rate_limitedA rate limit was hit. details.retryAfterMs says when to retry.notify, http.fetch, ai.chat
quota_exceededStorage quota (1 MiB) or the daily Enzica quota is used up.storage.set, ai.chat
not_signed_inThe required account is not signed in: Microsoft account for launch, Enzonic account for ai.chat.launch, ai.chat
user_deniedThe user declined the confirmation dialog, or a confirmation was needed during deactivate.instances.writeFile/deleteFile, mods.install/enable/disable/remove, launch
budget_exceededThe invocation exceeded its instruction, time or memory budget. Not catchable; reported as the module's error state.Any invocation
cancelledThe user pressed Stop in the Enzica chat. First-party extensions only.enzonic.official.agent.*
internal_errorAn unexpected launcher failure. The launcher log has the details.Any call

Uncaught errors

WhereEffect
Top-level script code or activateModule enters errored; the page shows the error and a Restart button.
Event handlerLogged with stack trace and shown as an error snackbar. The module stays active and keeps its state.
deactivateLogged. Deactivation completes.
Budget exceeded anywhereModule enters errored with budget_exceeded; 3 times in 10 minutes auto-disables it.

Developer mode

Developer mode is enabled in Settings → Developer mode. Turning it off unloads every unpacked module. It adds:

  • Load unpacked module: choose a folder that contains module.json. The folder is validated with the same rules as a package (except that it is not zipped), the permission dialog is shown, and the module is activated in the same sandbox with the same budgets and limits. If an installed module has the same id, the installed one is deactivated while the unpacked one is loaded. Unpacked modules use a separate store, <launcher data dir>/modules/<id>/storage.dev.json, and their "Always allow" choices last until the module is unloaded or the launcher exits. Unpacked modules never receive the first-party extensions.
  • Reload: runs deactivate, re-reads module.json and the main file from disk, and activates again. If the new manifest adds permissions, the permission dialog is shown again.
  • Module log pane: shows enzonic.log entries, dropped-event warnings, budget failures and uncaught errors with stack traces in file:line form.
  • Unload: removes the unpacked module and reactivates the installed module with the same id, if any.

Limits

ItemLimit
Instruction budget per invocation50,000,000 (checked every 10,000)
Script time per invocation (host calls excluded)5 s
deactivate wall-clock time (host calls included)2 s
Budget failures before auto-disable3 within 10 minutes
Interpreter stack depth1,000 frames
Queued events per module100
String argument5 MiB (base64 writeFile content: 6,990,508 characters)
enzonic.log message4 KiB
Module log retention5,000 entries
File read / write5 MiB
Directory listing10,000 entries
Instance path length512 characters
Storage per module1 MiB serialized JSON
Storage key length1 to 128 characters
Notifications10 per 60 s
notify title / body80 / 300 characters
HTTP requests60 per 60 s
HTTP timeout1,000 to 30,000 ms (default 15,000)
HTTP redirects5
HTTP response body5 MiB
HTTP request headers50
AI request size1 MiB serialized
AI messages / tools200 / 64
AI timeout120 s
AI quota (per user, all AI features)30 requests per minute, 200 per day
Test launch timeout30 to 600 s (default 180)
Test launch logTail200 lines, 64 KiB
Test launch crashReport256 KiB
UI tree size256 KiB serialized
UI nodes per tree5,000
UI nesting depth32
Page actions3
List items1,000
Select options100
Image file2 MiB, PNG/JPEG/WebP
Memory allocated per invocation512 MiB
repeat / padStart / padEnd / join result16,777,216 characters
Array.prototype.fill array length16,777,216
input change coalescing1 call per 150 ms
module.json64 KiB
Permissions per module32
Package compressed / uncompressed10 MiB / 25 MiB
Package entries500
Package path length255 characters
Module id2 to 48 characters
Manifest name / author / description2 to 64 / 1 to 64 / 0 to 2,000 characters
IconPNG, JPEG or WebP (.png, .jpg, .jpeg, .webp)

First-party extensions

The launcher grants the members below only to the official Enzica module (id enzonic-ai), and only when all of these hold:

  1. The Modules API reports the module with official: true when it is installed.
  2. The SHA-256 of the downloaded package equals a hash pinned inside the launcher build (the launcher's own release of Enzica).
  3. At every activation, the SHA-256 of each installed file still equals the pinned file hash.

Unpacked Developer-mode copies, modified installs and every other module never receive them: enzonic.official and enzonic.ui.chat are undefined, and a chat node is an unknown component type. Module review does not grant these members.

enzonic.official.agent

FunctionDescription
tools() -> Tool[]The OpenAI function definitions of the launcher's local troubleshooting tools: list_instances, get_instance, read_latest_log, read_crash_report, list_files, read_file, list_worlds, read_world_info, search_modrinth, get_mod_versions, install_mod, update_mod, disable_mod, enable_mod, delete_mod, test_launch.
complete(request) -> { message, usage, finish_reason }Requires ai. Same request rules as enzonic.ai.chat, but the host sends it with stream: true and shows the tokens live in the chat surface. message and usage have the enzonic.ai.chat shapes.
runTool(call, context?) -> { content, ok, denied }Executes one ToolCall returned by complete and returns the string to send back as the tool message. context is { instanceId?: string or null }; tools that take an instance argument default to it. Read-only tools run immediately. Tools that change files or start the game (install_mod, update_mod, disable_mod, enable_mod, delete_mod, test_launch) show an approval card with Approve, Deny and Always allow this session unless the user turned on YOLO mode; a denial returns denied: true and an error content instead of throwing. Tools only touch files inside the launcher data directory (instance folders through the same path rules as enzonic.instances; removed mods go to the launcher trash and can be restored). Results are truncated to 24,000 characters.
notice(level, text) -> trueAdds a notice line ("info", "warning" or "error", text up to 2,000 characters) to the chat.

When the user presses Stop, the running complete or runTool call and every later call in the same invocation throw cancelled.

chat node

{ type: "chat", key?, instances?, instanceId?, placeholder?, onSend, onInstanceChange?, onReset? } renders the native chat surface: the transcript (user messages, streamed answers, tool cards), an instance picker built from instances ({ value, label }[], at most 100; instanceId is one of the values or null), the YOLO mode switch, the daily quota and the composer with Send and Stop. onSend(text, instanceId) runs when the user sends a message, onInstanceChange(instanceId) when the picker changes and onReset() when the user starts a new chat. The transcript, YOLO mode (stored per Enzonic user) and the session's "Always allow" choices are kept by the host.

API versioning and compatibility

  • This document defines API version 1. enzonic.apiVersion is 1 in every launcher that implements it.
  • Within API version 1, launcher releases only make additive changes: new functions, new optional options, new optional props, new components, new icon names, new error codes for new functions. Existing signatures, defaults, limits and error codes for existing situations do not change in ways that break conforming modules, except that limits MAY be raised.
  • A module that uses a feature added after launcher 1.0.0 MUST set minLauncher to the first launcher version that provides it. Because unknown option keys and props are rejected, a module that uses a newer option on an older launcher fails loudly with invalid_argument instead of silently misbehaving.
  • A future incompatible API would be version 2 with a new manifest format. Launchers that support version 2 continue to run version 1 modules unchanged.
  • The module package format and module.json schema in this document are version 1. Unknown manifest fields are rejected so that future fields cannot be silently ignored by older launchers.

Packaging

A package is a zip whose root contains module.json. The most common packaging mistake is zipping the folder itself, which puts everything one level down (my-module/module.json). The Modules API rejects such packages.

A correct package looks like this:

text
server-status-1.0.0.zip
├── module.json
├── main.js
├── icon.png
└── assets/
    └── offline.png

The rules in brief: at most 10 MiB compressed, 25 MiB uncompressed, 500 entries; relative paths of at most 255 characters with forward slashes only; no .., no absolute paths, no symbolic links, no two paths that differ only in letter case. Leave out anything the module does not need at runtime: source maps, tests, node_modules, .git, editor folders and .DS_Store files.

Zipping on macOS and Linux

Run zip from inside the module folder, so paths in the archive are relative to it:

bash
cd my-module
zip -r ../my-module-1.0.0.zip . -x ".*" -x "*/.*" -x "node_modules/*"
cd ..
unzip -l my-module-1.0.0.zip

The listing should show module.json with no folder in front of it. The -x patterns exclude hidden files such as .git and .DS_Store.

Do not use Finder's Compress command on the folder: it puts the files inside a folder in the archive and adds a __MACOSX folder.

Zipping on Windows

In PowerShell, compress the folder's contents (note the \*), not the folder:

text
Compress-Archive -Path .\my-module\* -DestinationPath .\my-module-1.0.0.zip

This is reliable for modules without subfolders. Some versions of Compress-Archive, including the one in Windows PowerShell 5.1, write backslashes into the paths of files inside subfolders (assets\logo.png), which the Modules API rejects. If your module has subfolders such as assets/, use the tar command built into Windows 10 and 11 instead, listing the top-level entries of the folder explicitly:

text
tar -a -c -f my-module-1.0.0.zip -C my-module module.json main.js icon.png assets

The -a flag picks the zip format from the .zip extension, and -C my-module makes the paths relative to the module folder. Whichever tool you use, check the result in PowerShell:

text
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::OpenRead("$PWD\my-module-1.0.0.zip").Entries.FullName

Every name should be relative, use forward slashes, and module.json should appear without a folder prefix.

Naming

The file name of the zip does not matter to the launcher or the API. Naming it <id>-<version>.zip keeps your releases easy to tell apart.

Testing locally

Developer mode is your test environment. An unpacked module runs in the same sandbox, with the same budgets, limits and permission checks, as an installed one. The only differences are that it is loaded from a folder, it can be reloaded instantly, and it uses a separate storage file, so testing never touches the data of an installed copy of the same module.

The workflow

  1. Load the folder with Load unpacked module.
  2. Keep the module log pane open. It shows enzonic.log output, uncaught errors with main.js:line locations, budget failures and dropped events.
  3. Edit, save, press Reload. Reload runs deactivate, re-reads module.json and main.js, and activates again with a fresh scope. If you added a permission, you are asked to accept it.
  4. Use enzonic.log("debug", ...) generously while developing. Logging is cheap. Remove noisy debug logging before publishing.
  5. When it works, build the zip exactly as you will publish it, unload the unpacked module, and test the package too. Validating the zip catches packaging mistakes such as a missing assets folder.

Test checklist

Before you publish, go through this list:

  • Fresh start. Clear the module's storage (unload and delete storage.dev.json, or remove your keys) and activate. The module should work with no saved data.
  • No instances. If your module works with instances, check how it looks when the user has none, and when an instance is vanilla.
  • Denied dialogs. Click every button that triggers a confirmation and choose Deny. The module should say "No changes made." or similar and keep working.
  • Running game. Start an instance, then use your write or mod features on it. You should see a friendly message for instance_running.
  • Signed out. If you use launch or ai, sign out of the relevant account and check the not_signed_in message.
  • Offline. Disconnect from the network and use your network features. network_error and timeout should be handled.
  • Large data. Test with an instance that has many mods, a long log, or many saved entries. The page should stay within the UI limits and well within the budgets.
  • Rapid clicking. Click a long-running button several times. Buttons should be disabled while busy.
  • Both themes and both languages. Switch the launcher between light and dark. If your module shows text that depends on ctx.launcher.locale, check English and Spanish.
  • Permissions. Remove each permission from module.json one at a time and reload. If nothing breaks, you do not need that permission.
  • Manifest. version is new, description is accurate, minLauncher is right, and the icon exists.

Publishing

Publishing has two steps: creating the module listing, then uploading versions. Each uploaded version is reviewed before it becomes available. You can do both steps on the website or through the API.

You need an Enzonic account. By publishing you agree to the Module Developer Agreement and the Acceptable Use Policy, both linked from the publish page.

Publishing on the website

  1. Go to https://launcher.enzonic.com/publish and sign in with your Enzonic account.
  2. Create the module: choose the slug (2 to 48 lowercase letters, digits and hyphens; it must equal the id in your module.json and cannot be changed later), the name, a one-line summary, a longer description, and optionally an icon URL, a source code URL and a homepage URL. The module starts as a draft, visible only to you.
  3. Open the module and upload a version: select the zip and write a changelog. The server validates the package immediately. If anything is wrong, such as a missing module.json at the root, a duplicate version, or an invalid permission, you get a specific error and can fix and re-upload.
  4. The version is now pending, and so is the module if it has never been approved. Wait for review. The publish page shows the status of each version and, after review, the reviewer's note.
  5. When the version is approved, the module becomes approved, appears in the marketplace and in the launcher, and the version becomes its latest version.

Publishing with the API

For automation, create a publisher key. On https://launcher.enzonic.com/publish, open the keys section, create a key with a descriptive name such as "GitHub Actions", and copy it. It looks like enzm_ followed by 32 letters and digits, and it is shown only once. Publisher keys can create, update, delete and publish your modules; they cannot do anything else on your account. Store the key in a secret manager, never in your repository. If a key leaks, delete it on the same page and create a new one.

In the commands below, the key is in the environment variable ENZONIC_PUBLISHER_KEY.

Create the module once:

bash
curl --fail-with-body -X POST https://launcher-api.enzonic.com/v1/modules \
  -H "Authorization: Bearer $ENZONIC_PUBLISHER_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "slug": "server-status",
    "name": "Server Status",
    "summary": "Check whether your favorite Minecraft servers are online.",
    "description": "Keeps a list of server addresses and shows whether each one is online, its player count, version and message of the day. Uses the public mcsrvstat.us API.",
    "source_url": "https://github.com/your-name/server-status"
  }'

The response is the module object with "status": "draft".

Upload a version:

bash
curl --fail-with-body -X POST https://launcher-api.enzonic.com/v1/modules/server-status/versions \
  -H "Authorization: Bearer $ENZONIC_PUBLISHER_KEY" \
  -F "file=@server-status-1.0.0.zip;type=application/zip" \
  -F "changelog=First release."

The response is the version object with "status": "pending". If validation fails, the response is an error object whose message names the problem, for example { "error": { "code": "invalid_manifest", "message": "module.json is missing from the archive root" } }.

Check the status of all your modules and versions:

bash
curl --fail-with-body https://launcher-api.enzonic.com/v1/me/modules \
  -H "Authorization: Bearer $ENZONIC_PUBLISHER_KEY"

The full HTTP API, including updating listing details with PATCH /v1/modules/<slug>, is documented on the API page of these docs.

Publishing from GitHub Actions

This workflow publishes a new version whenever you push a tag such as v1.2.0. It assumes your repository keeps the module files in a module/ folder, and that you have added your publisher key as a repository secret named ENZONIC_PUBLISHER_KEY (Settings → Secrets and variables → Actions → New repository secret). Save it as .github/workflows/publish.yml:

text
name: Publish module

on:
  push:
    tags: ["v*"]

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Read id and version from module.json
        run: |
          ID=$(jq -r .id module/module.json)
          VERSION=$(jq -r .version module/module.json)
          if [ "v$VERSION" != "$GITHUB_REF_NAME" ]; then
            echo "Tag $GITHUB_REF_NAME does not match module.json version $VERSION" >&2
            exit 1
          fi
          echo "ID=$ID" >> "$GITHUB_ENV"
          echo "VERSION=$VERSION" >> "$GITHUB_ENV"

      - name: Build package
        run: |
          cd module
          zip -r "../$ID-$VERSION.zip" . -x ".*" -x "*/.*"
          cd ..
          unzip -l "$ID-$VERSION.zip"

      - name: Upload version
        env:
          ENZONIC_PUBLISHER_KEY: ${{ secrets.ENZONIC_PUBLISHER_KEY }}
        run: |
          curl --fail-with-body -X POST "https://launcher-api.enzonic.com/v1/modules/$ID/versions" \
            -H "Authorization: Bearer $ENZONIC_PUBLISHER_KEY" \
            -F "file=@$ID-$VERSION.zip;type=application/zip" \
            --form-string "changelog=Release $VERSION. Details: https://github.com/$GITHUB_REPOSITORY/releases/tag/$GITHUB_REF_NAME"

The workflow fails if the tag and module.json disagree, so you cannot accidentally publish the wrong version. curl --fail-with-body makes the step fail and print the API's error message if the upload is rejected. Create the module listing once by hand (on the website or with the POST /v1/modules command above) before the first tagged release.

Uploads are rate limited to 10 per hour per account, which is plenty for releases but worth knowing if you are debugging a rejected upload in a loop.

Review process and guidelines

Every uploaded version is reviewed by the Enzonic team before it is listed. Reviews are done by people reading your manifest and code, usually within a few days. There is no guaranteed timeline. Versions are reviewed oldest first.

What reviewers check

  • The manifest matches the listing. The name, description and author are accurate, and the description explains what the module does with each permission.
  • Permissions are necessary. Each declared permission is used, and its use matches the description. ai and mods.manage get extra scrutiny.
  • The code is readable. Reviewers read main.js in a review tool that displays text files up to 512 KiB. Keep main.js under that size, and do not minify or obfuscate it. Bundled code is acceptable if the output is readable.
  • No dynamic code from outside. Code must not eval or new Function anything downloaded or stored at runtime. Everything that runs must be in the reviewed package.
  • Network use is honest. Requests go only to services related to the module's stated purpose. Instance data, file contents or user input are sent to a third party only if the description says so and the user triggers it.
  • No credentials in the package. API keys, tokens and passwords for your own services must not be embedded.
  • Confirmations are respected. Each write, mod change or launch corresponds to a clear user action, and the module does not try to pressure the user into "Always allow".
  • It works. Reviewers install the package, open the page, and try the main features, including denying a confirmation. A module that throws on activation or shows an empty page is rejected.
  • UI quality. The page is understandable, labels are clear, errors are explained in plain language, and long operations show progress.
  • Content. Nothing that violates the Acceptable Use Policy, no impersonation of Enzonic or other developers, and no ads presented as launcher features.

Common rejection reasons

  • module.json declares permissions the code never uses.
  • The description does not mention that data is sent to an external service.
  • Minified or obfuscated main.js.
  • Errors when the user has no instances, or when a dialog is denied.
  • Buttons that start long operations are not disabled while busy, leading to queued duplicate operations.
  • Writing files the module did not need to touch, or writing several files per click with a dialog for each.
  • An http: permission for a host that is never contacted, or a module that fetches and evaluates remote scripts.
  • Placeholder text, broken images, or test code left in the UI.

If a version is rejected, the reviewer's note explains why. Fix the issue, bump the version (rejected version numbers cannot be reused), and upload again.

After approval

Approved versions are immutable. If you find a bug, publish a new version. Users get the update through the launcher's module update check. The Enzonic team can unlist a module that turns out to violate the guidelines, which removes it from the marketplace.

Versioning

Module versions follow Semantic Versioning 2.0.0 (MAJOR.MINOR.PATCH, each part at most 9 digits, plus one optional -prerelease or +build suffix; the exact regex is in the module.json reference of the API reference):

  • Patch (1.0.0 to 1.0.1): bug fixes with no visible change in behavior or permissions.
  • Minor (1.0.1 to 1.1.0): new features that keep existing data working.
  • Major (1.1.0 to 2.0.0): changes that users notice in a disruptive way, such as a different storage format that loses old data, or removal of features.
  • Pre-releases such as 2.0.0-beta.1 are allowed. They sort before the corresponding release.
  • Build metadata such as 1.2.0+build.5 is allowed but ignored when versions are ordered, so prefer a new patch version.

Rules enforced by the platform:

  • Versions are unique and immutable. Every upload must use a version number that has never been uploaded for that module, including rejected ones.
  • The id never changes. id in module.json must equal the module's slug for every version.
  • Permission changes trigger re-consent. Adding a permission means existing users must accept the new list to update. Removing one does not. Plan permission additions carefully, because some users will stay on the old version.
  • minLauncher gates installation. Set minLauncher to the lowest launcher version that supports every API feature you use. API version 1 features are available from launcher 1.0.0. Launchers older than minLauncher refuse to install or run the module and tell the user which version they need.

Storage survives updates. If a new version changes the shape of stored data, migrate it in activate, and keep the migration code for at least a few versions so users who skip updates are covered.

Example modules

The three modules below are complete. Each one can be copied into a folder as module.json and main.js, loaded with Load unpacked module, and published as is. They use only the API described on this page, and only the language features the runtime guarantees.

Example: Instance Notes

Per-instance notes for things like seeds, coordinates and settings you changed. It shows how to load state on activation, edit text with a keyed multi-line input, save to storage with prefixed keys, and handle the storage quota.

module.json:

json
{
  "id": "instance-notes",
  "name": "Instance Notes",
  "version": "1.0.0",
  "description": "Keep private notes for each of your Minecraft instances: seeds, coordinates, to-do lists and settings you changed. Notes are stored only on this computer.",
  "author": "Enzonic",
  "main": "main.js",
  "minLauncher": "1.0.0",
  "permissions": ["instances.read", "storage"]
}

main.js:

js
// Instance Notes: per-instance notes stored with enzonic.storage.
// Storage layout: one key per instance, "note:<instanceId>" -> { text, updatedAt }.

var NOTE_PREFIX = "note:";
var MAX_SELECT_OPTIONS = 100;

var state = {
  instances: [],
  selectedId: null,
  draft: "",
  savedText: "",
  savedAt: null,
  message: null,
  messageTone: "muted"
};

function noteKey(instanceId) {
  return NOTE_PREFIX + instanceId;
}

function setMessage(text, tone) {
  state.message = text;
  state.messageTone = tone;
}

function isDirty() {
  return state.draft !== state.savedText;
}

function loadNote() {
  if (state.selectedId === null) {
    state.draft = "";
    state.savedText = "";
    state.savedAt = null;
    return;
  }
  const saved = enzonic.storage.get(noteKey(state.selectedId));
  state.savedText = saved ? saved.text : "";
  state.savedAt = saved ? saved.updatedAt : null;
  state.draft = state.savedText;
}

function loadInstances() {
  state.instances = enzonic.instances.list();
  const stillExists = state.instances.some(i => i.id === state.selectedId);
  if (!stillExists) {
    state.selectedId = state.instances.length > 0 ? state.instances[0].id : null;
    loadNote();
  }
}

// Writes the current draft. Returns true on success.
function persist() {
  const key = noteKey(state.selectedId);
  try {
    if (state.draft.trim() === "") {
      enzonic.storage.remove(key);
      state.savedAt = null;
      setMessage("Note cleared.", "muted");
    } else {
      const now = new Date().toISOString();
      enzonic.storage.set(key, { text: state.draft, updatedAt: now });
      state.savedAt = now;
      setMessage("Saved.", "accent");
    }
    state.savedText = state.draft;
    return true;
  } catch (e) {
    if (e.code === "quota_exceeded") {
      setMessage("Storage is full (1 MiB). Shorten this note or delete notes for other instances.", "error");
    } else {
      setMessage("Could not save: " + e.message, "error");
    }
    return false;
  }
}

function selectInstance(instanceId) {
  if (instanceId === state.selectedId) return;
  if (isDirty() && !persist()) {
    render();
    return;
  }
  state.selectedId = instanceId;
  state.message = null;
  loadNote();
  render();
}

function selectedInstance() {
  return state.instances.find(i => i.id === state.selectedId) || null;
}

function formatTime(iso) {
  return iso.replace("T", " ").substring(0, 16) + " UTC";
}

function firstLine(text) {
  const line = text.split("\n")[0].trim();
  return line.length > 80 ? line.substring(0, 77) + "..." : line;
}

function notesList() {
  const noteIds = enzonic.storage.keys()
    .filter(k => k.indexOf(NOTE_PREFIX) === 0)
    .map(k => k.substring(NOTE_PREFIX.length));
  const items = state.instances
    .filter(i => noteIds.indexOf(i.id) !== -1)
    .map(i => {
      const saved = enzonic.storage.get(noteKey(i.id));
      return {
        key: i.id,
        title: i.name,
        subtitle: saved ? firstLine(saved.text) : "",
        icon: i.id === state.selectedId ? "edit" : "file",
        onClick: () => selectInstance(i.id)
      };
    });
  return enzonic.ui.card({
    key: "all-notes",
    title: "Instances with notes",
    children: [
      enzonic.ui.list({ key: "notes", items: items, emptyText: "No notes yet." })
    ]
  });
}

function editorCard(instance) {
  let status;
  if (isDirty()) {
    status = "Unsaved changes";
  } else if (state.savedAt) {
    status = "Last saved " + formatTime(state.savedAt);
  } else {
    status = "No note for this instance yet";
  }
  const children = [
    enzonic.ui.input({
      key: "note-" + instance.id,
      label: "Notes",
      value: state.draft,
      placeholder: "Seeds, coordinates, things to remember...",
      multiline: true,
      maxLength: 20000,
      onChange: value => {
        const wasDirty = isDirty();
        state.draft = value;
        // Re-render only when the "Unsaved changes" status flips.
        if (wasDirty !== isDirty()) render();
      }
    }),
    enzonic.ui.text({ key: "status", text: status, style: "label", tone: "muted" }),
    enzonic.ui.card({
      key: "buttons",
      layout: "row",
      children: [
        enzonic.ui.button({
          label: "Save",
          icon: "check",
          disabled: !isDirty(),
          onClick: () => { persist(); render(); }
        }),
        enzonic.ui.button({
          label: "Revert",
          variant: "outlined",
          disabled: !isDirty(),
          onClick: () => { state.draft = state.savedText; state.message = null; render(); }
        })
      ]
    })
  ];
  if (state.message) {
    children.push(enzonic.ui.text({ key: "message", text: state.message, tone: state.messageTone }));
  }
  return enzonic.ui.card({
    key: "editor",
    title: instance.name,
    subtitle: instance.minecraftVersion + " · " + instance.loader,
    children: children
  });
}

function view() {
  const actions = [
    enzonic.ui.button({
      label: "Refresh instances",
      icon: "refresh",
      onClick: () => { loadInstances(); render(); }
    })
  ];
  if (state.instances.length === 0) {
    return enzonic.ui.page({
      title: "Instance Notes",
      actions: actions,
      children: [
        enzonic.ui.text({ text: "Create an instance in the Library, then press Refresh.", tone: "muted" })
      ]
    });
  }
  const instance = selectedInstance();
  const options = state.instances.slice(0, MAX_SELECT_OPTIONS).map(i => ({ value: i.id, label: i.name }));
  if (options.every(o => o.value !== instance.id)) {
    options[options.length - 1] = { value: instance.id, label: instance.name };
  }
  return enzonic.ui.page({
    title: "Instance Notes",
    subtitle: "Private notes for each instance",
    actions: actions,
    children: [
      enzonic.ui.select({
        key: "instance",
        label: "Instance",
        value: instance.id,
        options: options,
        onChange: value => selectInstance(value)
      }),
      editorCard(instance),
      notesList()
    ]
  });
}

function render() {
  enzonic.ui.render(view());
}

function activate(ctx) {
  loadInstances();
  render();
}

How it works:

  • activate loads the instance list and the first instance's note, then renders.
  • The input's key includes the instance id, so switching instances creates a fresh text field instead of reusing the old one's cursor and scroll position.
  • onChange stores every change in state.draft but only re-renders when the "Unsaved changes" status flips, which keeps typing smooth.
  • Switching to another instance saves unsaved changes first. If saving fails, for example because storage is full, the switch is cancelled and the error is shown.
  • The select shows at most 100 instances (the component's limit) and always includes the selected one; the list of instances with notes offers another way to navigate.

Example: Mod Health Check

Lists the mods of a chosen instance, flags disabled, duplicate and unidentified mods, lets the user disable or enable a mod, and runs a test launch to confirm the instance starts. It shows confirmation handling, refreshing data after changes, and a long-running operation with progress, a result card and a notification.

module.json:

json
{
  "id": "mod-health-check",
  "name": "Mod Health Check",
  "version": "1.0.0",
  "description": "Checks the mods in an instance for duplicates, disabled files and unidentified jars, lets you enable or disable mods, and runs a test launch to confirm the game reaches the main menu.",
  "author": "Enzonic",
  "main": "main.js",
  "minLauncher": "1.0.0",
  "permissions": ["instances.read", "mods.manage", "launch", "notifications"]
}

main.js:

js
// Mod Health Check: inspect mods, toggle them, and test-launch an instance.

var MAX_SELECT_OPTIONS = 100;
var TEST_TIMEOUT_SEC = 180;

var state = {
  instances: [],
  selectedId: null,
  mods: [],
  issues: {},
  busy: null,
  message: null,
  messageTone: "muted",
  testResult: null
};

function setMessage(text, tone) {
  state.message = text;
  state.messageTone = tone;
}

function safeNotify(title, body, level) {
  try {
    enzonic.notify({ title: title, body: body, level: level });
  } catch (e) {
    enzonic.log("warn", "Notification not shown: " + e.code);
  }
}

// Returns { [filename]: string[] } with human-readable issues per mod.
function analyze(mods) {
  const issues = {};
  const groups = {};
  mods.forEach(m => {
    issues[m.filename] = [];
    if (!m.enabled) issues[m.filename].push("disabled");
    if (m.name === null && m.modrinthProjectId === null) issues[m.filename].push("unidentified jar");
    let groupKey = null;
    if (m.modrinthProjectId !== null) groupKey = "modrinth:" + m.modrinthProjectId;
    else if (m.name !== null) groupKey = "name:" + m.name.toLowerCase();
    if (groupKey !== null && m.enabled) {
      if (!Object.prototype.hasOwnProperty.call(groups, groupKey)) groups[groupKey] = [];
      groups[groupKey].push(m.filename);
    }
  });
  Object.keys(groups).forEach(groupKey => {
    const files = groups[groupKey];
    if (files.length > 1) {
      files.forEach(f => {
        issues[f].push("duplicate (" + (files.length - 1) + " other " + (files.length > 2 ? "copies" : "copy") + ")");
      });
    }
  });
  return issues;
}

function loadMods() {
  if (state.selectedId === null) {
    state.mods = [];
    state.issues = {};
    return;
  }
  try {
    state.mods = enzonic.mods.list(state.selectedId);
    state.issues = analyze(state.mods);
  } catch (e) {
    state.mods = [];
    state.issues = {};
    setMessage("Could not read mods: " + e.message, "error");
  }
}

function loadInstances() {
  state.instances = enzonic.instances.list().filter(i => i.loader !== "vanilla");
  const stillExists = state.instances.some(i => i.id === state.selectedId);
  if (!stillExists) {
    state.selectedId = state.instances.length > 0 ? state.instances[0].id : null;
    state.testResult = null;
  }
  loadMods();
}

function selectedInstance() {
  return state.instances.find(i => i.id === state.selectedId) || null;
}

function describeError(e) {
  if (e.code === "user_denied") return "No changes made.";
  if (e.code === "instance_running") return "This instance is running. Close the game and try again.";
  if (e.code === "not_signed_in") return "Sign in with a Microsoft account in the launcher to launch Minecraft.";
  if (e.code === "network_error") return "Network problem: " + e.message;
  return e.message;
}

function toggleMod(mod) {
  if (state.busy) return;
  try {
    const updated = mod.enabled
      ? enzonic.mods.disable(state.selectedId, mod.filename)
      : enzonic.mods.enable(state.selectedId, mod.filename);
    setMessage((updated.enabled ? "Enabled " : "Disabled ") + (updated.name || updated.filename) + ".", "accent");
  } catch (e) {
    setMessage(describeError(e), e.code === "user_denied" ? "muted" : "error");
  }
  loadMods();
  render();
}

function runTestLaunch() {
  if (state.busy || state.selectedId === null) return;
  const instance = selectedInstance();
  state.busy = "Test launch running. The game window opens and closes automatically.";
  state.testResult = null;
  state.message = null;
  render();
  try {
    const result = enzonic.launch(state.selectedId, { test: true, timeoutSec: TEST_TIMEOUT_SEC });
    state.testResult = result;
    if (result.ok) {
      safeNotify("Test launch passed", instance.name + " reached the main menu.", "success");
    } else {
      safeNotify("Test launch failed", instance.name + ": " + result.reason, "error");
    }
  } catch (e) {
    setMessage(describeError(e), e.code === "user_denied" ? "muted" : "error");
  } finally {
    state.busy = null;
    render();
  }
}

function summaryText() {
  const flagged = state.mods.filter(m => state.issues[m.filename].length > 0).length;
  const enabled = state.mods.filter(m => m.enabled).length;
  return state.mods.length + " mods, " + enabled + " enabled, " + flagged + " with issues";
}

function modItems() {
  return state.mods.map(m => {
    const problems = state.issues[m.filename];
    const parts = [m.filename];
    if (m.version) parts.push(m.version);
    if (problems.length > 0) parts.push("Issues: " + problems.join(", "));
    return {
      key: m.filename,
      title: m.name || m.filename,
      subtitle: parts.join(" · "),
      icon: problems.length > 0 ? "warning" : "extension",
      trailing: enzonic.ui.button({
        label: m.enabled ? "Disable" : "Enable",
        variant: "text",
        disabled: state.busy !== null,
        onClick: () => toggleMod(m)
      })
    };
  });
}

function lastLines(text, count) {
  return text.split("\n").slice(-count).join("\n");
}

function resultCard(result) {
  const seconds = Math.round(result.durationMs / 1000);
  const reasons = {
    reached_menu: "The game reached the main menu.",
    crashed: "The game crashed.",
    exited: "The game exited before reaching the main menu.",
    timeout: "The game did not reach the main menu within " + TEST_TIMEOUT_SEC + " seconds."
  };
  const children = [
    enzonic.ui.text({
      text: reasons[result.reason] + " (" + seconds + " s)",
      tone: result.ok ? "accent" : "error",
      style: "title"
    })
  ];
  if (result.exitCode !== null) {
    children.push(enzonic.ui.text({ text: "Exit code " + result.exitCode, tone: "muted" }));
  }
  if (!result.ok) {
    if (result.crashReport) {
      children.push(enzonic.ui.text({ text: "Crash report (beginning)", style: "label" }));
      children.push(enzonic.ui.text({ text: result.crashReport.substring(0, 4000), style: "code", selectable: true }));
    }
    children.push(enzonic.ui.text({ text: "Last log lines", style: "label" }));
    children.push(enzonic.ui.text({ text: lastLines(result.logTail, 60), style: "code", selectable: true }));
  }
  return enzonic.ui.card({ key: "result", title: "Test launch result", children: children });
}

function view() {
  const actions = [
    enzonic.ui.button({
      label: "Refresh",
      icon: "refresh",
      disabled: state.busy !== null,
      onClick: () => { state.message = null; loadInstances(); render(); }
    })
  ];
  if (state.instances.length === 0) {
    return enzonic.ui.page({
      title: "Mod Health Check",
      actions: actions,
      children: [
        enzonic.ui.text({ text: "You have no modded instances. Create a Fabric, Quilt, Forge or NeoForge instance first.", tone: "muted" })
      ]
    });
  }
  const instance = selectedInstance();
  const options = state.instances.slice(0, MAX_SELECT_OPTIONS).map(i => ({
    value: i.id,
    label: i.name + " (" + i.minecraftVersion + ", " + i.loader + ")"
  }));
  if (options.every(o => o.value !== instance.id)) {
    options[options.length - 1] = { value: instance.id, label: instance.name };
  }
  const children = [
    enzonic.ui.select({
      key: "instance",
      label: "Instance",
      value: instance.id,
      options: options,
      disabled: state.busy !== null,
      onChange: value => {
        state.selectedId = value;
        state.testResult = null;
        state.message = null;
        loadMods();
        render();
      }
    }),
    enzonic.ui.card({
      key: "summary",
      title: "Summary",
      subtitle: summaryText(),
      layout: "row",
      children: [
        enzonic.ui.button({
          label: "Run test launch",
          icon: "play_arrow",
          disabled: state.busy !== null,
          onClick: runTestLaunch
        })
      ]
    })
  ];
  if (state.busy) {
    children.push(enzonic.ui.progress({ key: "busy", label: state.busy }));
  }
  if (state.message) {
    children.push(enzonic.ui.text({ key: "message", text: state.message, tone: state.messageTone }));
  }
  if (state.testResult) {
    children.push(resultCard(state.testResult));
  }
  children.push(enzonic.ui.list({ key: "mods", items: modItems(), emptyText: "This instance has no mods." }));
  return enzonic.ui.page({
    title: "Mod Health Check",
    subtitle: instance.name,
    actions: actions,
    children: children
  });
}

function render() {
  enzonic.ui.render(view());
}

function activate(ctx) {
  loadInstances();
  render();
}

How it works:

  • analyze computes issues once per load and stores them in state, so view stays cheap. Duplicates are detected among enabled mods by Modrinth project id when known, otherwise by mod name.
  • Toggling calls disable or enable, which shows the launcher's confirmation dialog. Whatever happens, the module reloads the mod list from the launcher rather than guessing the new file name.
  • The test launch renders a busy state with an indeterminate progress bar and disables every control, then blocks in enzonic.launch. Time spent waiting does not count against the script budget. The result card shows the reason and, on failure, the crash report and the last 60 log lines.
  • safeNotify catches notification errors such as rate_limited so that a notification problem never hides the actual result.
  • Vanilla instances are filtered out because they cannot have mods.

Example: Server Status

Keeps a saved list of Minecraft server addresses and checks them through the public mcsrvstat.us API. It shows network access with a declared host, storage of a list, input validation, per-item and batch operations with a determinate progress bar, and notifications when a server changes state.

module.json:

json
{
  "id": "server-status",
  "name": "Server Status",
  "version": "1.0.0",
  "description": "Save a list of Minecraft server addresses and check whether each one is online, with player count, version and message of the day. Server addresses are sent to the public api.mcsrvstat.us service when you press Check.",
  "author": "Enzonic",
  "main": "main.js",
  "minLauncher": "1.0.0",
  "permissions": ["http:api.mcsrvstat.us", "storage", "notifications"]
}

main.js:

js
// Server Status: check Minecraft servers with https://api.mcsrvstat.us/3/<address>.
// Storage: "servers" -> string[] of addresses, "lastOnline" -> { [address]: boolean }.

var API_BASE = "https://api.mcsrvstat.us/3/";
var MAX_SERVERS = 20;
var ADDRESS_PATTERN = /^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[0-9]{1,5})?$/;

var state = {
  servers: [],
  results: {},
  lastOnline: {},
  newAddress: "",
  inputError: null,
  busy: false,
  progress: 0,
  message: null
};

function loadSaved() {
  state.servers = enzonic.storage.get("servers") || [];
  state.lastOnline = enzonic.storage.get("lastOnline") || {};
}

function saveServers() {
  enzonic.storage.set("servers", state.servers);
}

function saveLastOnline() {
  enzonic.storage.set("lastOnline", state.lastOnline);
}

function normalizeAddress(text) {
  return text.trim().toLowerCase();
}

function validateAddress(address) {
  if (address.length === 0) return "Enter a server address, for example play.example.com or play.example.com:25565.";
  if (!ADDRESS_PATTERN.test(address)) return "That does not look like a server address.";
  const colon = address.indexOf(":");
  if (colon !== -1) {
    const port = Number(address.substring(colon + 1));
    if (port < 1 || port > 65535) return "The port must be between 1 and 65535.";
  }
  if (state.servers.indexOf(address) !== -1) return "That server is already in the list.";
  if (state.servers.length >= MAX_SERVERS) return "You can save up to " + MAX_SERVERS + " servers.";
  return null;
}

function addServer() {
  const address = normalizeAddress(state.newAddress);
  const problem = validateAddress(address);
  if (problem) {
    state.inputError = problem;
    render();
    return;
  }
  state.servers.push(address);
  try {
    saveServers();
    state.newAddress = "";
    state.inputError = null;
    checkOne(address);
  } catch (e) {
    state.servers.pop();
    state.inputError = "Could not save: " + e.message;
  }
  render();
}

function removeServer(address) {
  state.servers = state.servers.filter(s => s !== address);
  delete state.results[address];
  delete state.lastOnline[address];
  saveServers();
  saveLastOnline();
  render();
}

// Returns a result object; never throws for network problems.
function fetchStatus(address) {
  const checkedAt = new Date().toISOString();
  try {
    const res = enzonic.http.fetch(API_BASE + address, { timeoutMs: 10000 });
    if (res.status !== 200 || res.json === null) {
      return { error: "Status service answered HTTP " + res.status + ".", checkedAt: checkedAt };
    }
    const data = res.json;
    if (data.online !== true) {
      return { online: false, checkedAt: checkedAt };
    }
    let motd = "";
    if (data.motd && data.motd.clean) {
      motd = data.motd.clean.join(" ").replace(/\s+/g, " ").trim();
    }
    return {
      online: true,
      players: data.players ? data.players.online : null,
      maxPlayers: data.players ? data.players.max : null,
      version: data.version || null,
      motd: motd,
      checkedAt: checkedAt
    };
  } catch (e) {
    if (e.code === "rate_limited") return { error: "Too many checks. Wait a minute.", checkedAt: checkedAt };
    if (e.code === "timeout") return { error: "The status service did not answer in time.", checkedAt: checkedAt };
    if (e.code === "network_error") return { error: "No connection to the status service.", checkedAt: checkedAt };
    return { error: e.message, checkedAt: checkedAt };
  }
}

// Records a result and returns "online", "offline" or null if the state did not change.
function record(address, result) {
  state.results[address] = result;
  if (result.error) return null;
  const known = Object.prototype.hasOwnProperty.call(state.lastOnline, address);
  const previous = state.lastOnline[address];
  state.lastOnline[address] = result.online;
  if (known && previous !== result.online) return result.online ? "online" : "offline";
  return null;
}

function checkOne(address) {
  record(address, fetchStatus(address));
  saveLastOnline();
}

function safeNotify(title, body, level) {
  try {
    enzonic.notify({ title: title, body: body, level: level });
  } catch (e) {
    enzonic.log("warn", "Notification not shown: " + e.code);
  }
}

function checkAll() {
  if (state.busy || state.servers.length === 0) return;
  state.busy = true;
  state.progress = 0;
  state.message = null;
  render();
  const changes = [];
  try {
    const total = state.servers.length;
    state.servers.forEach((address, index) => {
      const change = record(address, fetchStatus(address));
      if (change) changes.push(address + " is now " + change);
      state.progress = (index + 1) / total;
      render();
    });
    saveLastOnline();
    const online = state.servers.filter(a => state.results[a] && state.results[a].online === true).length;
    state.message = online + " of " + total + " servers online.";
    if (changes.length > 0) {
      const body = changes.join(", ");
      safeNotify("Server status changed", body.length > 300 ? body.substring(0, 297) + "..." : body, "info");
    }
  } finally {
    state.busy = false;
    render();
  }
}

function subtitleFor(address) {
  const r = state.results[address];
  if (!r) return "Not checked yet";
  const time = r.checkedAt.substring(11, 16) + " UTC";
  if (r.error) return r.error + " · " + time;
  if (!r.online) return "Offline · " + time;
  const parts = ["Online"];
  if (r.players !== null && r.maxPlayers !== null) parts.push(r.players + "/" + r.maxPlayers + " players");
  if (r.version) parts.push(r.version);
  if (r.motd) parts.push(r.motd.length > 120 ? r.motd.substring(0, 117) + "..." : r.motd);
  parts.push(time);
  return parts.join(" · ");
}

function iconFor(address) {
  const r = state.results[address];
  if (!r) return "dns";
  if (r.error) return "warning";
  return r.online ? "check" : "close";
}

function view() {
  const children = [
    enzonic.ui.card({
      key: "add",
      title: "Add a server",
      children: [
        enzonic.ui.input({
          key: "new-address",
          label: "Server address",
          placeholder: "play.example.com:25565",
          value: state.newAddress,
          maxLength: 260,
          disabled: state.busy,
          onChange: value => {
            state.newAddress = value;
            if (state.inputError) {
              state.inputError = null;
              render();
            }
          },
          onSubmit: value => { state.newAddress = value; addServer(); }
        }),
        enzonic.ui.button({ label: "Add", icon: "add", disabled: state.busy, onClick: addServer })
      ]
    })
  ];
  if (state.inputError) {
    children.push(enzonic.ui.text({ key: "input-error", text: state.inputError, tone: "error" }));
  }
  if (state.busy) {
    children.push(enzonic.ui.progress({ key: "progress", value: state.progress, label: "Checking servers" }));
  }
  if (state.message) {
    children.push(enzonic.ui.text({ key: "message", text: state.message, tone: "muted" }));
  }
  children.push(enzonic.ui.list({
    key: "servers",
    emptyText: "No servers saved yet. Add one above.",
    items: state.servers.map(address => ({
      key: address,
      title: address,
      subtitle: subtitleFor(address),
      icon: iconFor(address),
      onClick: () => {
        if (state.busy) return;
        checkOne(address);
        render();
      },
      trailing: enzonic.ui.button({
        label: "Remove",
        icon: "delete",
        variant: "text",
        disabled: state.busy,
        onClick: () => removeServer(address)
      })
    }))
  }));
  return enzonic.ui.page({
    title: "Server Status",
    subtitle: state.servers.length + " of " + MAX_SERVERS + " servers",
    actions: [
      enzonic.ui.button({
        label: "Check all",
        icon: "refresh",
        disabled: state.busy || state.servers.length === 0,
        onClick: checkAll
      })
    ],
    children: children
  });
}

function render() {
  enzonic.ui.render(view());
}

function activate(ctx) {
  loadSaved();
  render();
}

How it works:

  • The address list and the last known online state live in storage, so the list survives restarts and the module can tell when a server changes state between checks.
  • Addresses are validated before they are saved: hostname characters, an optional port in range, no duplicates, and at most 20 servers. Twenty servers fit comfortably inside the 60-requests-per-minute limit even when the user checks twice in a row.
  • fetchStatus turns every outcome, including HTTP errors, timeouts and rate limits, into a result object, so one unreachable server never stops a batch check.
  • "Check all" renders after each server so the progress bar advances, and notifies only when something changed since the previous check.
  • Clicking a server re-checks just that one. The trailing Remove button does not trigger the item's click.

Troubleshooting and FAQ

My module shows "errored" right after loading

The script threw during evaluation or in activate, or activate is not defined as a global function. Open the module log pane: it shows the error and the main.js:line location. Common causes are using unsupported syntax (destructuring, spread, default parameters, classes, async), a typo in an enzonic method name, or calling a method without its permission (permission_denied).

I get SyntaxError for code that works in my browser

The runtime is Rhino 1.9.1 at its ES6 level, which does not implement every modern feature. Replace destructuring with property access (const name = obj.name;), spread with Object.assign or concat, default parameters with if (x === undefined) x = 1;, classes with constructor functions or plain objects, and for...of with forEach. If you use a bundler, configure it to target ES5.

Why can I not use setTimeout to refresh every minute?

Modules only run in response to activation and user actions; there are no timers and no background work. This keeps modules from using resources while the user is not looking at them. Add a Refresh button, and check on activation if appropriate.

A call throws invalid_argument, but my arguments look right

Read the error message: it includes the path of the offending value, for example options.timeoutSec or children[3].items[0].trailing.label. Typical causes: an unknown option or prop (options and props are validated strictly, so typos are errors), a number where a string is expected (instance ids are strings), null where a prop does not accept it, an icon name that is not in the IconName list, or a select whose value is not one of its options.

My module stopped with budget_exceeded

An invocation used more than 50 million instructions or 5 seconds of script time. Look for loops over large data, such as character-by-character processing of a big file, nested loops over lists, or recursion over deep directory trees. Use built-in string methods and regular expressions, limit how much data you process, and do heavy work only on demand. Time spent inside enzonic.* calls does not count, so slow network requests or test launches are never the cause.

My clicks do nothing for a while, then all happen at once

Your module was busy with a long call, such as a test launch or a series of HTTP requests, and events were queued. Disable buttons while busy and show a progress indicator, as in the examples.

Text in my input jumps back or loses characters

Make sure the input has a stable key, and that you render value from the text you received in onChange. Do not transform the value on every keystroke (for example by trimming it), because a different value replaces the user's text. Validate on submit instead.

http.fetch throws host_not_allowed

The URL's host does not exactly match an http: permission, the URL is not HTTPS on port 443, the server redirected to a host you did not declare, or the host resolves to a private network address. Declare every host you use, including redirect targets, and reload.

enzonic.launch throws not_signed_in

Launching requires a Microsoft account signed in to the launcher, because the game is started with the user's real account. The user must sign in from the account menu. Test launches are no exception.

enzonic.ai.chat throws not_signed_in or quota_exceeded

Enzica uses the user's Enzonic account, not the Microsoft account. The user must sign in to Enzonic in the launcher. Each user has a daily quota shared by all AI features, including the first-party Enzica module; when it is used up, calls fail with quota_exceeded until the next day (UTC).

Can my module talk to other modules?

No. Each module has its own scope, thread and storage, and there is no messaging between modules.

Can my module show a web page or custom graphics?

No. Modules use the ten native components only. You can show images from your package or from a declared HTTPS host with the image component.

Can I read files outside an instance, like screenshots in the user's Pictures folder?

No. File access is limited to instance directories. Screenshots taken in-game are in each instance's screenshots/ folder, which you can read.

My upload was rejected with a validation error

The error message names the problem. The most common ones: module.json is inside a folder in the zip, the version already exists, id does not match the slug, a permission string is malformed (http: entries must be bare lowercase hostnames such as http:api.example.com), the main file is missing, or the zip contains backslash paths from an older Compress-Archive.

How do users get my updates?

When a new version is approved, the launcher's module update check offers it to users. If the new version adds permissions, users must accept them before updating.

Where is my module's data stored?

In <launcher data dir>/modules/<id>/storage.json, next to the extracted package in <launcher data dir>/modules/<id>/<version>/. Unpacked modules in Developer mode use storage.dev.json. Uninstalling a module deletes the whole folder.

Questions about the docs: admin@enzonic.com

Theme

Language

Sign-in only works on launcher.enzonic.com because Enzonic accounts are tied to the enzonic.com domain.