Block registry api

This commit is contained in:
2026-11-12 20:41:13 -03:00
parent e7fe663746
commit 76802ed430
39 changed files with 499 additions and 100 deletions
+2 -2
View File
@@ -84,8 +84,8 @@ deno task build && deno task server # packs the mods and starts a se
## API Types
The API types are the reference for everything scripts can call. Scripts import them as `cubi/server`, `cubi/client` and
`cubi/worldgen`, and they live in [`common/mod_api/`](common/mod_api/).
The API types are the reference for everything scripts can call. Scripts import them as `cubi/server`, `cubi/client`,
`cubi/shared`, `cubi/worldgen` and `cubi/content`, and they live in [`common/mod_api/`](common/mod_api/).
A few parts of those types aren't built yet and throw when used: forms, custom screens, HUD elements and keybinds.
[`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the mod API.
+3 -3
View File
@@ -95,8 +95,8 @@ async function build_assets() {
// every mod in mods/, checked and sorted so dependencies load first. a broken mod fails the whole build,
// the game never runs with some mods missing
function load_mods(): LoadedMod[] {
const mods = load_and_check(MODS_FOLDER);
async function load_mods(): Promise<LoadedMod[]> {
const mods = await load_and_check(MODS_FOLDER);
const problems = mods.flatMap((mod) => mod.report.errors.map((error) => ` ${mod.id}: ${error}`));
if (problems.length > 0) {
throw new Error(`Mods have errors (deno task check-mods for details):\n${problems.join("\n")}`);
@@ -154,7 +154,7 @@ async function build() {
const now = performance.now();
clear_folder(BUILD_FOLDER);
// checked first: a mod with errors stops the build before any .cubi is written
const mods = load_mods();
const mods = await load_mods();
await build_assets();
await build_client();
await write_client_manifest(BUILD_FOLDER);
+60
View File
@@ -0,0 +1,60 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// runs a mod's content script, see common/mod_api/content.ts. check-mods runs it on the mod's folder, the server on
// its .cubi in a worker without permissions (server/content_worker.ts), and both add what it registers to the mod's
// data before anything else reads it
import { type BlockJson, validate_block } from "./mod_data.ts";
import type { ContentContext } from "./mod_api/content.ts";
export interface ContentScript {
mod: string;
version: string;
// importable url of the script
url: string;
}
// a .cubi's bundled content script, what server/content_worker.ts is sent
export interface ContentScriptCode {
mod: string;
version: string;
code: string;
}
// what a content script registered, in order, and what was wrong. with problems the mod doesn't load
export interface RegisteredContent {
blocks: BlockJson[];
problems: string[];
}
export async function run_content_script({ mod, version, url }: ContentScript): Promise<RegisteredContent> {
const blocks: BlockJson[] = [];
let setting_up = true;
const ctx: ContentContext = {
mod: { id: mod, version },
blocks: {
register(block) {
if (!setting_up) throw new Error("blocks can only be registered during setup");
// what a file could hold, so the server, its players and its worldgen workers all get the same thing
const json = JSON.parse(JSON.stringify(block ?? null));
const id = typeof json?.id === "string" ? json.id : "without an id";
const problems = validate_block(json);
if (problems.length > 0) throw new Error(`block ${id}: ${problems.join("; ")}`);
if (json.id.split(":")[0] !== mod) {
throw new Error(`block ${json.id} isn't in this mod's namespace "${mod}"`);
}
blocks.push(json);
},
},
};
try {
const module = await import(url);
if (typeof module.setup !== "function") throw new Error("the content script doesn't export a setup function");
await module.setup(ctx);
return { blocks, problems: [] };
} catch (e) {
return { blocks, problems: [e instanceof Error ? e.message : String(e)] };
} finally {
setting_up = false;
}
}
+14 -2
View File
@@ -59,8 +59,8 @@ const MAX_UNZIPPED_BYTES = 64 * 1024 * 1024;
// written into every entry, so packing the same mod twice gives the same bytes and the same hash
const FIXED_TIME = new Date(Date.UTC(2020, 0, 1));
export type ScriptSide = "server" | "client" | "worldgen" | "shared";
export const SCRIPT_SIDES: ScriptSide[] = ["server", "client", "worldgen", "shared"];
export type ScriptSide = "server" | "client" | "worldgen" | "shared" | "content";
export const SCRIPT_SIDES: ScriptSide[] = ["server", "client", "worldgen", "shared", "content"];
export interface Mod {
manifest: ManifestJson;
@@ -302,6 +302,8 @@ export function client_copy(mod: Mod): Mod {
const scripts = { ...mod.scripts };
delete scripts.server;
delete scripts.worldgen;
// players get what it registered in data, see common/mod_api/content.ts
delete scripts.content;
const {
noises: _n,
density_functions: _d,
@@ -354,3 +356,13 @@ export function png_size(bytes: Uint8Array): { width: number; height: number } |
const view = new DataView(bytes.buffer, bytes.byteOffset);
return { width: view.getUint32(16), height: view.getUint32(20) };
}
// a mod's bundled script as a url import() takes, for realms without file access
export function data_url(code: string) {
const bytes = new TextEncoder().encode(code);
let binary = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
return `data:application/javascript;base64,${btoa(binary)}`;
}
+20
View File
@@ -0,0 +1,20 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// content scripts: blocks made in code, for content that's easier to generate than to write out file by file, like
// every block of every kind of rock. the server runs them while it loads mods, before anything else reads their data,
// and what they register becomes part of the mod's data just like its files: checked the same way, sent to players
// with the rest, and generated by worldgen workers. see docs/modding/gettingstarted/modfiles.md
import type { BlockJson } from "../mod_data.ts";
import type { ModInfo } from "./shared.ts";
export type { BlockJson };
export interface ContentContext {
readonly mod: ModInfo;
readonly blocks: {
// adds a block, what a blocks/ file holds under "block", checked the same way. only during setup, and only in
// the mod's own namespace. it's registered right after the mod's blocks/ files, in the order of the calls
register(block: BlockJson): void;
};
}
+1
View File
@@ -87,6 +87,7 @@ const manifest_schema = (folder_name: string) =>
client: z.string().optional(),
worldgen: z.string().optional(),
shared: z.string().optional(),
content: z.string().optional(),
}).optional(),
credits: z.string().optional(),
}).superRefine((manifest, ctx) => {
+2 -1
View File
@@ -9,7 +9,7 @@
"pack-mod": "deno run --allow-read --allow-write --allow-run --allow-env tools/pack_mod.ts",
"test": "deno test --allow-read --allow-write --allow-run --allow-net tests/",
"bench": "deno bench --allow-read --allow-write --allow-run tests/",
"desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-ffi --allow-env=CUBI_SERVER,CUBI_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME,DEBUG --include build --include server_mods --include server/game/worker.ts --include server/game/worldgen_worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld",
"desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-ffi --allow-env=CUBI_SERVER,CUBI_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME,DEBUG --include build --include server_mods --include server/game/worker.ts --include server/game/worldgen_worker.ts --include server/content_worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld",
"desktop-all": "deno run -A tools/desktop_all.ts"
},
"compilerOptions": {
@@ -29,6 +29,7 @@
"cubi/client": "./common/mod_api/client.ts",
"cubi/worldgen": "./common/mod_api/worldgen.ts",
"cubi/shared": "./common/mod_api/shared.ts",
"cubi/content": "./common/mod_api/content.ts",
"cubi/engine": "./common/mod_api/engine.ts",
"@gfx/canvas-wasm": "jsr:@gfx/canvas-wasm@^0.4.2",
"@paulaboks/rng": "jsr:@paulaboks/rng@^0.0.3",
+3
View File
@@ -26,6 +26,9 @@ This registers the block and an item with the same id that places it. It's a ful
side, takes 5 seconds to break by hand, breaks faster with a pickaxe, and only drops itself when broken with a pickaxe
of tier 1 (stone or copper) or better.
A mod with many similar blocks, like every block of every kind of rock, can register them in code from a
[content script](../concepts/sides.md#content-scripts) instead, with the same object a file holds under `"block"`.
## Properties
### Looks
+8 -5
View File
@@ -31,17 +31,20 @@ The server and every client load mods the same way, in the same order:
1. **Order.** Dependencies come before the mods that need them, and otherwise mods load alphabetically. Mods that depend
on each other in a circle are an error. The server sends its order to clients, and they follow it.
2. **Data**, one mod at a time: its block models, blocks (and their items), items, entity models, entities, effects and
fluids. Then every mod's [tags](../resources/tags.md), merged in load order, then each mod's recipes and ores, which
can use tags.
2. **Data**, one mod at a time: its block models, blocks (and their items), including the ones its
[content script](sides.md#content-scripts) registers, after its `blocks/` files, items, entity models, entities,
effects and fluids. Then every mod's [tags](../resources/tags.md), merged in load order, then each mod's recipes and
ores, which can use tags.
3. **Scripts.** Server scripts' `setup` runs on the server, and client scripts' on each client. Worldgen scripts'
`setup` runs on the server before it makes chunks.
Scripts read the registries but can't add to them. Content comes from data files.
Scripts read the registries but can't add to them. Content comes from data files, and from content scripts, which the
server runs when it loads mods, before anything else, and whose blocks go to players as data.
> [!IMPORTANT]
> The server and the client must end up with exactly the same blocks, items and recipes. They do as long as content is
> only data, since both load the same files in the same order.
> only data, since both load the same files in the same order. Content scripts only run on the server, and players get
> what they made as data.
## Numeric Ids
+44 -8
View File
@@ -31,17 +31,18 @@ clicking them does something else.
└───────────────────────────────────────┘
```
## The Four Scripts
## The Five Scripts
| Script | Runs on | Sent to players | For |
| ---------- | -------------------------------- | --------------- | ------------------------------------------------------------------- |
| `server` | the server, in the game worker | **never** | game logic: block and item components, events, commands, containers |
| `client` | every player's browser | yes | presentation: inventory overlays, and later custom screens and HUD |
| `shared` | the server and every browser | yes | block rules: the states blocks are placed with, joining neighbors |
| `worldgen` | the server, when it makes chunks | no | features that decorate terrain, deterministic |
| Script | Runs on | Sent to players | For |
| ---------- | -------------------------------- | ---------------------- | ------------------------------------------------------------------- |
| `server` | the server, in the game worker | **never** | game logic: block and item components, events, commands, containers |
| `client` | every player's browser | yes | presentation: inventory overlays, and later custom screens and HUD |
| `shared` | the server and every browser | yes | block rules: the states blocks are placed with, joining neighbors |
| `worldgen` | the server, when it makes chunks | no | features that decorate terrain, deterministic |
| `content` | the server, while it loads mods | no, only what it makes | blocks made in code, like one for every kind of rock |
Data (blocks, items, models, recipes, entities, textures) isn't a script: it's registered the same way on the server and
on every client, before any script runs. See [Registries](registries.md).
on every client, before any script runs. See [Registries](registries.md). Content scripts make more of it.
### Server Scripts
@@ -110,6 +111,40 @@ mod's rules being there. Rules can only be registered during `setup`, and `ctx.w
Shared code is sent to players like client code, so it's for rules anyone may read, never anti-cheat or secrets.
### Content Scripts
```ts
import type { ContentContext } from "cubi/content";
const ROCKS = ["granite", "basalt", "slate"];
export function setup(ctx: ContentContext) {
for (const rock of ROCKS) {
ctx.blocks.register({
id: `rocks:${rock}`,
textures: `rocks:${rock}`,
mining: { toughness: 3, tool: "pickaxe", requires_tool: true },
drops: `rocks:${rock}`,
});
}
}
```
Content scripts make data in code, for content that's easier to generate than to write out file by file.
`ctx.blocks.register` takes the same object a `blocks/` file holds under `"block"`. The blocks a content script
registers become part of the mod's data, the same as its files:
- They're registered right after the mod's `blocks/` files, in the order of the calls.
- They're checked the same way, so a mistake stops the mod loading and names the script. They have to be in the mod's
own namespace.
- The mod's files can name them: tags, recipes, drops, ores and the rest of worldgen.
- Players get them with the rest of the mod's data and never run the script, so the server and its players always agree.
The server runs content scripts when it loads mods, before anything else reads their data, in a worker with **no Deno
permissions**, like the game's. `check-mods`, the build and tests run them from the mod's folder. Blocks can only be
registered during `setup`. Content scripts don't see other mods' content or the server's [config](../misc/config.md),
and can't import [`cubi/engine`](../misc/engine.md).
### Worldgen Scripts
Worldgen scripts register features that run on every chunk the server generates. They must be deterministic: the same
@@ -129,6 +164,7 @@ seed and chunk always give the same blocks. See [World Generation](../worldgen/i
| [Config](../misc/config.md) | yes | no |
| Server script code | yes | **never** |
| Shared script code | yes | yes, and runs it |
| Content script code | yes | **never**, only the blocks it registers |
When a client needs to see something only the server has, the server has to send it: open a
[menu](../inventories/menus.md), put it in an item's `data`, or set a block state the block's model shows.
+11 -7
View File
@@ -1,6 +1,6 @@
# Mod Files
A mod is a folder with a `manifest.json`, some data files, textures, and up to four scripts. The build packs it into a
A mod is a folder with a `manifest.json`, some data files, textures, and up to five scripts. The build packs it into a
single `.cubi` file, which is what servers load.
## Layout
@@ -36,6 +36,7 @@ mods/
client.ts # sent to players
shared.ts # block rules, run on the server and sent to players
worldgen.ts # terrain features, never sent to players
content.ts # blocks made in code, run by the server while it loads mods, never sent to players
```
Data folders can have subfolders. Every data file holds one definition, wrapped with the format version:
@@ -66,7 +67,8 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
"server": "scripts/server.ts",
"client": "scripts/client.ts",
"worldgen": "scripts/worldgen.ts",
"shared": "scripts/shared.ts"
"shared": "scripts/shared.ts",
"content": "scripts/content.ts"
},
"credits": "CREDITS.md"
}
@@ -83,7 +85,7 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
| `game_version` | no | The bworld versions the mod works with, as a semver range. Only checked for mods with `engine_access`. |
| `engine_access` | no | `true` lets the scripts import `cubi/engine` and hook the engine. See [Engine Access](../misc/engine.md). |
| `dependencies` | no | Other mods, `{ "id", "version" }`. A missing dependency is an error, and dependencies load first. The version range isn't checked yet. |
| `scripts` | no | Paths to the `server`, `client`, `shared` and `worldgen` scripts. See [Sides](../concepts/sides.md). |
| `scripts` | no | Paths to the `server`, `client`, `shared`, `worldgen` and `content` scripts. See [Sides](../concepts/sides.md). |
| `credits` | no | A markdown file for licenses and thanks, shown on the Credits screen. Raw HTML in it is shown as text. |
List every mod whose ids you use in `dependencies`, including `bworld` for the base game's blocks and items. It
@@ -102,8 +104,8 @@ so they can import other files and packages, but code imported by several script
When a mod's folder has a `deno.json`, its scripts are bundled and typechecked with it, so the mod can have its own
imports and npm or JSR packages. Mods without one use the `deno.json` of the folder the build runs in, like the mods in
this repository. That config maps the API types, which scripts import as `cubi/server`, `cubi/client`, `cubi/shared` and
`cubi/worldgen`, and [`cubi/engine`](../misc/engine.md):
this repository. That config maps the API types, which scripts import as `cubi/server`, `cubi/client`, `cubi/shared`,
`cubi/worldgen` and `cubi/content`, and [`cubi/engine`](../misc/engine.md):
```ts
import type { ServerContext } from "cubi/server";
@@ -127,6 +129,7 @@ copper_tools.cubi
scripts/client.js
scripts/worldgen.js
scripts/shared.js
scripts/content.js
textures/<name>.png
textures/<name>.json # for animated textures
credits.md
@@ -136,5 +139,6 @@ copper_tools.cubi
- Packing the same mod twice gives the same bytes, so the file only changes when the mod does.
- `deno task build` leaves other `.cubi` files in `server_mods/` alone, so mods from elsewhere can sit next to the ones
it builds.
- Players get a copy **without** `scripts/server.js`, `scripts/worldgen.js` and the config. See
[Networking](../networking/index.md).
- `data.json` doesn't hold the blocks `scripts/content.js` registers. The server runs it when it loads the `.cubi`.
- Players get a copy **without** `scripts/server.js`, `scripts/worldgen.js`, `scripts/content.js` and the config, but
with the blocks the content script registered in its `data.json`. See [Networking](../networking/index.md).
+29 -5
View File
@@ -41,7 +41,12 @@ The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.t
**In the API types but throwing:** forms, HUD elements, keybinds, `g.slider`, `register_terrain`.
**Not built at all:** common scripts, the registry freeze and hash, overrides.
**Content scripts** are built, the first part of common scripts: `scripts.content` with `ctx.blocks.register`, see
[Content Scripts](#content-scripts-as-built). The code is in `common/content_scripts.ts`, `common/mod_api/content.ts`,
`server/content_worker.ts`, `server/load_mods.ts` and `tools/check_mods.ts`.
**Not built at all:** the rest of common scripts (items and models from code, reading other mods' content), the registry
freeze and hash, overrides.
**Engine access** is built (phase 3): `cubi/engine`, `hook`, `engine_access` and its checks, and `physics` as the first
plain object mods can hook. See [Engine Access](modding/misc/engine.md). The code is in `common/hooks.ts`,
@@ -68,6 +73,24 @@ JSON is registered. Data would then be shorthand for code: loading `blocks/coppe
`ctx.blocks.register(...)` with the same object does, so content that's easier to generate (every color of wool) or
depends on other mods can be written as code.
#### Content Scripts, as Built
The first part is built differently from the rest of this section: `scripts.content` with only `ctx.blocks.register`,
run **once, on the server**, while it loads mods, instead of on both sides. What it registers is added to the mod's data
as if it were files, so everything downstream needs no change:
- `check-mods` runs it from the mod's folder before checking references, so tags, recipes and worldgen files can name
its blocks. Packing leaves its blocks out of `data.json`.
- The server runs it on each `.cubi` before its reference check, in a worker without permissions, since the host that
loads mods has file access.
- Players get the blocks in the copy of `data.json` they download and never run the script, like Luanti's clients get
node definitions from the server. The server and its players can't disagree, so this part needs no freeze or hash.
- Worldgen workers get the blocks in the worldgen bundle, which is built from the mods' data, and number them the same
way, like Luanti's mapgen threads get a copy of the finished registrations instead of running mods' code again.
Since it runs per mod, before any registry exists, it can't read other mods' content or the server's config yet. Reading
other mods' content would mean running content scripts in load order with a view of what came before.
```ts
import type { CommonContext } from "bworld/common";
@@ -331,10 +354,11 @@ How the server sends the world, like Minecraft Java since 1.20.2. The code is in
Each phase ends with every test passing and the game playable.
**Phase 1: loading and common scripts.** `scripts.common` bundled like the client script and run on both sides between
each mod's data and the next mod. `CommonContext`, with the JSON loader going through the same functions. The freeze and
the registry hash. Recipe types as ids with `register_type`. Check: a test mod registers content from code, and the
server and a client end up with equal registries and hashes.
**Phase 1: loading and common scripts.** Partly done: content scripts register blocks, see
[Content Scripts](#content-scripts-as-built). `scripts.common` bundled like the client script and run on both sides
between each mod's data and the next mod. `CommonContext`, with the JSON loader going through the same functions. The
freeze and the registry hash. Recipe types as ids with `register_type`. Check: a test mod registers content from code,
and the server and a client end up with equal registries and hashes.
**Phase 2: overrides.** `override` and `extend` in common scripts, `overrides/*.json`, `recipes.remove`, and the
`check-mods` rules. Check: a test mod adds a component to `bworld:grass_block`, changes `bworld:glass`'s toughness and
+17
View File
@@ -0,0 +1,17 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference lib="deno.worker" />
// runs the mods' content scripts for server/load_mods.ts, without permissions like the game's worker, since the host
// that loads mods can read and write files. gets each one's script and answers with what each registered, in order
import { type ContentScriptCode, run_content_script } from "@/common/content_scripts.ts";
import { data_url } from "@/common/mod.ts";
self.onmessage = async (event: MessageEvent<ContentScriptCode[]>) => {
const results = [];
for (const { mod, version, code } of event.data) {
results.push(await run_content_script({ mod, version, url: data_url(code) }));
}
self.postMessage(results);
};
-9
View File
@@ -125,12 +125,3 @@ function script_of(mod: ServerModSource) {
config: mod.data.config ?? {},
};
}
export function data_url(code: string) {
const bytes = new TextEncoder().encode(code);
let binary = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
return `data:application/javascript;base64,${btoa(binary)}`;
}
+2 -1
View File
@@ -7,7 +7,8 @@
import type { GameServer } from "./game_server.ts";
import { GameLoop } from "./game_loop.ts";
import { GameToHost, HostToGame, READ_DONE, READ_HEADER, READ_TOO_SMALL, READ_WAITING } from "./host_protocol.ts";
import { data_url, start_game } from "./load_mods.ts";
import { start_game } from "./load_mods.ts";
import { data_url } from "@/common/mod.ts";
import { type WorkerPort, WorldgenPool } from "./worldgen_pool.ts";
const SAVE_INTERVAL_MS = 30_000;
+36
View File
@@ -10,6 +10,7 @@ import type { ModListing } from "@/common/mod_loader.ts";
import { data_file, FORMAT_VERSION } from "@/common/mod_data.ts";
import { is_object, json_object } from "@/common/schema.ts";
import { sha256 } from "@/common/utils.ts";
import type { ContentScriptCode, RegisteredContent } from "@/common/content_scripts.ts";
export interface ServerMod {
mod: Mod;
@@ -62,6 +63,7 @@ export async function load_mods(
if (config_dir) {
for (const { mod } of by_id.values()) change_config(mod, config_dir, problems);
}
await add_registered_content([...by_id.values()], problems);
// the same checks check-mods runs on mod folders
const loaded = [...by_id.values()].map(({ file, mod }) => as_loaded_mod(file, mod));
@@ -102,6 +104,40 @@ export async function load_mods(
}));
}
// runs the mods' content scripts in a worker without permissions and adds the blocks they register to their data,
// after their files' ones. from then on they're the mod's data like the rest: checked, in the copy players download,
// and in the worldgen bundle
async function add_registered_content(mods: { file: string; mod: Mod }[], problems: string[]) {
const with_scripts = mods.filter(({ mod }) => mod.scripts.content !== undefined);
if (with_scripts.length === 0) return;
const scripts: ContentScriptCode[] = with_scripts.map(({ mod }) => ({
mod: mod.manifest.id,
version: mod.manifest.version,
code: mod.scripts.content!,
}));
const worker = new Worker(new URL("./content_worker.ts", import.meta.url), {
type: "module",
deno: { permissions: "none" },
} as WorkerOptions);
let results: RegisteredContent[];
try {
results = await new Promise((resolve, reject) => {
worker.onmessage = (event) => resolve(event.data);
worker.onerror = (event) => {
event.preventDefault();
reject(new Error(`content scripts: ${event.message}`));
};
worker.postMessage(scripts);
});
} finally {
worker.terminate();
}
with_scripts.forEach(({ file, mod }, i) => {
mod.data.blocks.push(...results[i].blocks);
problems.push(...results[i].problems.map((problem) => `${file}: ${mod.manifest.scripts!.content}: ${problem}`));
});
}
// applies config_dir/<mod id>.json to the mod's config, when the server has one
function change_config(mod: Mod, config_dir: string, problems: string[]) {
const file = join(config_dir, `${mod.manifest.id}.json`);
+160
View File
@@ -0,0 +1,160 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// blocks a content script registers in code are the mod's data like its files': checked, registered on the server,
// sent to players and generated by worldgen workers. see common/mod_api/content.ts
import { assert, assertEquals, assertRejects, assertStringIncludes, assertThrows } from "@std/assert";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import { ID_MASK } from "@/common/constants.ts";
import { client_copy, read_mod } from "@/common/mod.ts";
import { to_flat } from "@/common/section.ts";
import { load_bundle } from "@/common/worldgen_bundle.ts";
import type { ContentContext } from "@/common/mod_api/content.ts";
import { load_client_mods } from "@/client/mods.ts";
import { load_mods } from "@/server/load_mods.ts";
import { load_and_check } from "@/tools/check_mods.ts";
import { pack_mod } from "@/tools/pack_mod.ts";
import { copy_dir, test_game } from "./helpers.ts";
// a block for every rock and its bricks, and one more where the script can't read files, like the server's worker
const CONTENT = `
import type { ContentContext } from "cubi/content";
export function setup(ctx: ContentContext) {
for (const rock of ["granite", "basalt"]) {
ctx.blocks.register({ id: \`rocks:\${rock}\`, textures: "cubi:missing", drops: \`rocks:\${rock}\` });
ctx.blocks.register({ id: \`rocks:\${rock}_bricks\`, textures: "cubi:missing" });
}
try {
Deno.readTextFileSync("deno.json");
} catch {
ctx.blocks.register({ id: "rocks:sandboxed", textures: "cubi:missing" });
}
(globalThis as any).rocks_ctx = ctx;
EXTRA
}
`;
const CODE_BLOCKS = ["rocks:granite", "rocks:granite_bricks", "rocks:basalt", "rocks:basalt_bricks"];
// the base game, and rocks: a block file, the content script above, and a tag and an ore that name its blocks
function rocks_mod(extra = "") {
const dir = Deno.makeTempDirSync({ prefix: "bworld_content_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const write = (path: string, content: unknown) => {
Deno.mkdirSync(`${dir}/rocks/${path.split("/").slice(0, -1).join("/")}`, { recursive: true });
Deno.writeTextFileSync(`${dir}/rocks/${path}`, typeof content === "string" ? content : JSON.stringify(content));
};
write("manifest.json", {
format_version: 1,
id: "rocks",
name: "Rocks",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { content: "scripts/content.ts" },
});
write("blocks/lamp.json", { format_version: 1, block: { id: "rocks:lamp", textures: "cubi:missing" } });
write("scripts/content.ts", CONTENT.replace("EXTRA", extra));
write("tags/blocks/rocks/rocks.json", { format_version: 1, tag: { values: ["rocks:granite", "rocks:basalt"] } });
write("worldgen/ores.json", {
format_version: 1,
ores: [{ id: "rocks:basalt", replaces: "bworld:stone", min_y: 5, max_y: 200, scale: 0.07, threshold: 0.3 }],
});
return dir;
}
Deno.test("check-mods runs a mod's content script, and its files can name the blocks it registers", async () => {
const dir = rocks_mod();
const rocks = (await load_and_check(dir)).find((mod) => mod.id === "rocks")!;
Deno.removeSync(dir, { recursive: true });
assertEquals(rocks.report.errors, []);
// after the files' blocks, in the order they were registered, listed under the script
assertEquals(rocks.blocks.map(({ json }) => json.id), ["rocks:lamp", ...CODE_BLOCKS]);
assertEquals(rocks.blocks.slice(1).map(({ file }) => file), CODE_BLOCKS.map(() => "scripts/content.ts"));
// only during setup
const ctx = (globalThis as unknown as { rocks_ctx: ContentContext }).rocks_ctx;
assertThrows(
() => ctx.blocks.register({ id: "rocks:late", textures: "cubi:missing" }),
Error,
"only be registered during setup",
);
});
Deno.test("the server registers a content script's blocks, and a worldgen worker numbers and generates them alike", async () => {
const dir = rocks_mod();
const { game } = await test_game(dir);
Deno.removeSync(dir, { recursive: true });
for (const id of CODE_BLOCKS) {
assert(EverythingRegistry.get("blocks", id), `${id} is a block`);
assert(EverythingRegistry.get("items", id), `${id} has an item`);
}
const bundle = structuredClone(game.worldgen_bundle!);
const game_ids = { ...game.world.block_ids };
EverythingRegistry.clear();
const loaded = await load_bundle(bundle);
assertEquals(loaded.block_ids, game_ids, "blocks are numbered like the game numbers them");
const basalt = loaded.block_ids["rocks:basalt"];
const generated = to_flat(loaded.generate(0, 0).column.sections);
assert(generated.some((value) => (value & ID_MASK) === basalt), "the ore of a block made in code is generated");
});
Deno.test("a packed mod leaves its content script's blocks out, the server registers them without permissions, and players get them as data", async () => {
const sources = rocks_mod();
const folder = Deno.makeTempDirSync({ prefix: "bworld_content_mods_" });
for (const mod of await load_and_check(sources)) {
Deno.writeFileSync(`${folder}/${mod.id}.cubi`, await pack_mod(mod));
}
Deno.removeSync(sources, { recursive: true });
const packed = read_mod(Deno.readFileSync(`${folder}/rocks.cubi`), "rocks.cubi");
assertEquals(packed.data.blocks.map((block) => block.id), ["rocks:lamp"]);
assert(packed.scripts.content);
const rocks = (await load_mods(folder, ["cubi:missing"])).find((mod) => mod.listing.id === "rocks")!;
Deno.removeSync(folder, { recursive: true });
// its worker can't read files, unlike check-mods
const ids = ["rocks:lamp", ...CODE_BLOCKS, "rocks:sandboxed"];
assertEquals(rocks.mod.data.blocks.map((block) => block.id), ids);
const copy = read_mod(rocks.client_bytes, rocks.listing.file);
assertEquals(copy.scripts.content, undefined, "players don't run it, they get what it registered");
assertEquals(copy.data.blocks, client_copy(rocks.mod).data.blocks);
EverythingRegistry.clear();
await load_client_mods([rocks.listing], [copy]);
for (const id of ids) assert(EverythingRegistry.get("blocks", id), `${id} is a block on the client`);
});
Deno.test("a content script's mistakes stop its mod loading, naming the script", async () => {
const cases: [string, string][] = [
[
`ctx.blocks.register({ id: "bworld:granite", textures: "cubi:missing" });`,
`scripts/content.ts: block bworld:granite isn't in this mod's namespace "rocks"`,
],
[`ctx.blocks.register({ id: "rocks:broken" } as any);`, "scripts/content.ts: block rocks:broken: "],
[
`ctx.blocks.register({ id: "rocks:lamp", textures: "cubi:missing" });`,
"scripts/content.ts: block rocks:lamp is also defined by rocks",
],
[`throw new Error("no rocks today");`, "scripts/content.ts: no rocks today"],
];
for (const [extra, error] of cases) {
const dir = rocks_mod(extra);
const rocks = (await load_and_check(dir)).find((mod) => mod.id === "rocks")!;
Deno.removeSync(dir, { recursive: true });
assert(rocks.report.errors.some((e) => e.includes(error)), `${error} in ${rocks.report.errors.join("\n")}`);
}
// on the server too, from the .cubi
const sources = rocks_mod(`ctx.blocks.register({ id: "bworld:granite", textures: "cubi:missing" });`);
const folder = Deno.makeTempDirSync({ prefix: "bworld_content_mods_" });
for (const mod of await load_and_check(sources)) {
Deno.writeFileSync(`${folder}/${mod.id}.cubi`, await pack_mod(mod));
}
Deno.removeSync(sources, { recursive: true });
const rejected = await assertRejects(() => load_mods(folder, ["cubi:missing"]));
Deno.removeSync(folder, { recursive: true });
assertStringIncludes(
(rejected as Error).message,
`rocks.cubi: scripts/content.js: block bworld:granite isn't in this mod's namespace "rocks"`,
);
});
+5 -5
View File
@@ -205,19 +205,19 @@ Deno.test("in a dimension without sky light only blocks give light", async () =>
});
Deno.test("a dimension's min_y and max_y have to be whole sections, and fit its generator's cells", async () => {
const errors = (options: Parameters<typeof mods>[0]) => {
const errors = async (options: Parameters<typeof mods>[0]) => {
const dir = mods(options);
const report = load_and_check(dir).find((mod) => mod.id === "flat")!.report;
const report = (await load_and_check(dir)).find((mod) => mod.id === "flat")!.report;
Deno.removeSync(dir, { recursive: true });
return report.errors.filter((error) => error.includes("worldgen/dimension/flat.json"));
};
assertEquals(errors({ flat: true, bworld_default: false, shape: TALL }), []);
assertEquals(await errors({ flat: true, bworld_default: false, shape: TALL }), []);
for (const shape of [{ min_y: -8 }, { max_y: 0 }, { min_y: -4096 }, { max_y: 4096 }]) {
assertEquals(errors({ flat: true, bworld_default: false, shape }).length, 1, JSON.stringify(shape));
assertEquals((await errors({ flat: true, bworld_default: false, shape })).length, 1, JSON.stringify(shape));
}
// sections of 16, but the generator samples every 32 blocks
const shape = { min_y: -48, max_y: 320 };
assert(errors({ flat: true, bworld_default: false, shape, cell_height: 32 })[0].includes("cell_height 32"));
assert((await errors({ flat: true, bworld_default: false, shape, cell_height: 32 }))[0].includes("cell_height 32"));
const dir = mods({ flat: true, bworld_default: false, shape, cell_height: 32 });
await assertRejects(() => test_game(dir), Error, "flat.json: can't be generated by flat:flat");
+2 -2
View File
@@ -173,7 +173,7 @@ Deno.test("a client mod hooks LocalPlayer from its .cubi", async () => {
}`,
],
});
const mod = load_and_check(dir)[0];
const mod = (await load_and_check(dir))[0];
assertEquals(mod.report.errors, []);
const packed = read_mod(await pack_mod(mod), "floaty.cubi");
const listing: ModListing = {
@@ -344,7 +344,7 @@ Deno.test("cubi/engine without engine_access is an error in check-mods and in a
console.log(engine.common.physics);
}`;
write_mod(dir, "sneaky", { server: ["server.ts", script] }, {});
const [mod] = load_and_check(dir);
const [mod] = await load_and_check(dir);
assertEquals(mod.report.errors, [
`scripts/server.ts imports cubi/engine, which needs "engine_access": true in manifest.json`,
]);
+4 -4
View File
@@ -42,7 +42,7 @@ Deno.test("a mod's fluids/ file registers a fluid, packed into its .cubi", async
const dir = Deno.makeTempDirSync({ prefix: "bworld_fluids_" });
const syrup = { id: "testfluids:syrup", name: "Maple Syrup", color: "#a0522d", texture: "testfluids:syrup_still" };
fluid_mod(dir, { "syrup.json": syrup });
const mods = load_and_check(dir);
const mods = await load_and_check(dir);
assertEquals(mods[0].report.errors, []);
// it has no textures
assertEquals(mods[0].report.warnings, [
@@ -55,10 +55,10 @@ Deno.test("a mod's fluids/ file registers a fluid, packed into its .cubi", async
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a fluid with a bad color fails loading", () => {
Deno.test("a fluid with a bad color fails loading", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_fluids_" });
fluid_mod(dir, { "syrup.json": { id: "testfluids:syrup", color: "brown" } });
const errors = load_and_check(dir)[0].report.errors;
const errors = (await load_and_check(dir))[0].report.errors;
assert(errors.some((e) => e.startsWith("fluids/syrup.json:") && e.includes("color")), errors.join("\n"));
Deno.removeSync(dir, { recursive: true });
});
@@ -86,7 +86,7 @@ async function both_sides(ask: (fluids: FluidApi) => unknown) {
const { game } = await test_game(dir);
const server = ask(game.mods.fluid_rules.api());
const mod = load_and_check(dir).find((m) => m.id === "testfluids")!;
const mod = (await load_and_check(dir)).find((m) => m.id === "testfluids")!;
const packed = read_mod(await pack_mod(mod), "testfluids.cubi");
Deno.removeSync(dir, { recursive: true });
const listing: ModListing = { id: "testfluids", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 };
+6 -6
View File
@@ -36,14 +36,14 @@ let repo_mods: ServerModSource[] | undefined;
// mods straight from their source folders, skipping the build: scripts are imported as typescript. each call gets its
// own copy, so a test that changes what it got can't change another test's
export function mod_sources(mods_dir: string): ServerModSource[] {
if (resolve(mods_dir) !== resolve("mods")) return read_mod_sources(mods_dir);
repo_mods ??= read_mod_sources(mods_dir);
export async function mod_sources(mods_dir: string): Promise<ServerModSource[]> {
if (resolve(mods_dir) !== resolve("mods")) return await read_mod_sources(mods_dir);
repo_mods ??= await read_mod_sources(mods_dir);
return structuredClone(repo_mods);
}
function read_mod_sources(mods_dir: string): ServerModSource[] {
const mods = load_and_check(mods_dir);
async function read_mod_sources(mods_dir: string): Promise<ServerModSource[]> {
const mods = await load_and_check(mods_dir);
const errors = mods.flatMap((mod) => mod.report.errors.map((e) => `${mod.id}: ${e}`));
if (errors.length) throw new Error(errors.join("\n"));
return load_order(mods).map((mod) => {
@@ -94,7 +94,7 @@ export async function test_game(
config: Record<string, Record<string, unknown>> = {},
) {
EverythingRegistry.clear();
const mods = mod_sources(mods_dir);
const mods = await mod_sources(mods_dir);
for (const mod of mods) {
if (!config[mod.listing.id]) continue;
const changed = apply_config(mod.data.config ?? {}, config[mod.listing.id]);
+6 -6
View File
@@ -487,9 +487,9 @@ function gears_mod(): string {
return mod;
}
Deno.test("tags keep their entries, renamed, and ones that don't exist here become optional", () => {
Deno.test("tags keep their entries, renamed, and ones that don't exist here become optional", async () => {
const mod = gears_mod();
const report = import_tags(
const report = await import_tags(
data({
"gears/tags/items/spinning": {
values: ["gears:gear", "minecraft:stone", "#forge:ingots/brass", { id: "other:cog", required: false }],
@@ -517,9 +517,9 @@ Deno.test("tags keep their entries, renamed, and ones that don't exist here beco
assertStringIncludes(report.warnings[0].warning, "bworld:stone");
});
Deno.test("create's pressing recipes keep their shape, with bworld's item choices, from 0.5's and 6.0's json", () => {
Deno.test("create's pressing recipes keep their shape, with bworld's item choices, from 0.5's and 6.0's json", async () => {
const mod = gears_mod();
const report = import_recipes(
const report = await import_recipes(
data({
// 0.5 named results' items "item", and an ingredient that's a list is one any of whose items fit
"gears/recipes/pressing/teeth": {
@@ -558,7 +558,7 @@ Deno.test("create's pressing recipes keep their shape, with bworld's item choice
assertEquals(report.skipped.map(({ location }) => location), ["gears:pressing/granite"]);
});
Deno.test("stonecutting recipes become bworld's, and ones it can't use are reported", () => {
Deno.test("stonecutting recipes become bworld's, and ones it can't use are reported", async () => {
const mod = gears_mod();
const cut = (ingredient: unknown, result: unknown, extra = {}) => ({
type: "minecraft:stonecutting",
@@ -566,7 +566,7 @@ Deno.test("stonecutting recipes become bworld's, and ones it can't use are repor
result,
...extra,
});
const report = import_recipes(
const report = await import_recipes(
data({
// before 1.20.5 the count is the recipe's, after it the result's. 1.21 renamed the folder
"gears/recipes/gear_from_teeth": cut({ tag: "gears:teeth" }, "gears:gear", { count: 2 }),
+2 -2
View File
@@ -49,10 +49,10 @@ Deno.test("an item with a model is drawn with it, in the model's own textures, p
Deno.removeSync(dir, { recursive: true });
});
Deno.test("check-mods reports an item's model that doesn't exist", () => {
Deno.test("check-mods reports an item's model that doesn't exist", async () => {
const dir = mods_with({ textures: { "0": "bworld:oak_planks" }, elements: [HANDLE] });
Deno.removeSync(`${dir}/copper_tools/models/wrench.json`);
const errors = load_and_check(dir).find((mod) => mod.id === "copper_tools")!.report.errors.join("\n");
const errors = (await load_and_check(dir)).find((mod) => mod.id === "copper_tools")!.report.errors.join("\n");
assert(errors.includes("model copper_tools:wrench doesn't exist"), errors);
Deno.removeSync(dir, { recursive: true });
});
+3 -3
View File
@@ -259,11 +259,11 @@ async function setup() {
return { ...t, dir };
}
Deno.test("check-mods catches loot tables that point at nothing", () => {
Deno.test("check-mods catches loot tables that point at nothing", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_loot_check_" });
copy_dir("mods/bworld", `${dir}/bworld`);
loot_mod(dir);
const ok = load_and_check(dir).find((mod) => mod.id === "testloot")!;
const ok = (await load_and_check(dir)).find((mod) => mod.id === "testloot")!;
assertEquals(ok.report.errors, []);
assertEquals(ok.loot_tables.map((t) => t.json.id).sort(), [
"testloot:blocks/ore",
@@ -280,7 +280,7 @@ Deno.test("check-mods catches loot tables that point at nothing", () => {
},
}),
);
const errors = load_and_check(dir).find((mod) => mod.id === "testloot")!.report.errors;
const errors = (await load_and_check(dir)).find((mod) => mod.id === "testloot")!.report.errors;
assert(errors.some((e) => e.includes("item testloot:nothing doesn't exist")), errors.join("\n"));
assert(errors.some((e) => e.includes("loot table testloot:nowhere doesn't exist")), errors.join("\n"));
Deno.removeSync(dir, { recursive: true });
+1 -1
View File
@@ -65,7 +65,7 @@ export function setup(ctx: ServerContext) {
await assertRejects(() => config_of({ copper_tools: { sped: 1 } }), Error, "sped");
Deno.writeTextFileSync(`${dir}/copper_tools/config.json`, config_file([16]));
const errors = load_and_check(dir).find((mod) => mod.id === "copper_tools")!.report.errors;
const errors = (await load_and_check(dir)).find((mod) => mod.id === "copper_tools")!.report.errors;
assert(errors.some((error) => error.startsWith("config.json")), errors.join("\n"));
Deno.removeSync(dir, { recursive: true });
+2 -2
View File
@@ -26,7 +26,7 @@ async function packed_mods() {
const sources = Deno.makeTempDirSync({ prefix: "bworld_mod_src_" });
copy_dir("mods/bworld", `${sources}/bworld`);
create_mod("copper_tools", "Copper Tools", sources);
const mods = load_and_check(sources);
const mods = await load_and_check(sources);
for (const mod of mods) assertEquals(mod.report.errors, [], mod.id);
const folder = Deno.makeTempDirSync({ prefix: "bworld_mod_" });
@@ -206,7 +206,7 @@ Deno.test("a mod with its own deno.json is bundled with it", async () => {
`import { GREETING } from "lib/greeting.ts";\n// deno-lint-ignore no-explicit-any\nexport function setup(ctx: any) {\n\tctx.log(GREETING);\n}\n`,
);
const project = load_and_check(sources).find((m) => m.id === "project")!;
const project = (await load_and_check(sources)).find((m) => m.id === "project")!;
assertEquals(project.report.errors, []);
const packed = read_mod(await pack_mod(project), "project.cubi");
assertStringIncludes(packed.scripts.server!, "hello from a deno project");
+2 -2
View File
@@ -88,13 +88,13 @@ Deno.test("a mod's model can use the base game's templates as its parent", async
Deno.removeSync(dir, { recursive: true });
});
Deno.test("check-mods reports a parent that doesn't exist and parents that loop", () => {
Deno.test("check-mods reports a parent that doesn't exist and parents that loop", async () => {
const dir = mods_with({
orphan: { id: "copper_tools:orphan", parent: "copper_tools:nowhere" },
one: { id: "copper_tools:one", parent: "copper_tools:two" },
two: { id: "copper_tools:two", parent: "copper_tools:one" },
});
const errors = load_and_check(dir).find((mod) => mod.id === "copper_tools")!.report.errors.join("\n");
const errors = (await load_and_check(dir)).find((mod) => mod.id === "copper_tools")!.report.errors.join("\n");
assert(errors.includes("model copper_tools:nowhere doesn't exist"), errors);
assert(errors.includes("copper_tools:one's parents loop"), errors);
Deno.removeSync(dir, { recursive: true });
+2 -2
View File
@@ -87,7 +87,7 @@ const seen = globalThis as unknown as Record<string, unknown>;
// packs testrecipes from dir, which it then removes, and loads it on a client like one joining would
async function load_client(dir: string) {
const mod = load_and_check(dir).find((m) => m.id === "testrecipes")!;
const mod = (await load_and_check(dir)).find((m) => m.id === "testrecipes")!;
assertEquals(mod.report.errors, []);
const packed = read_mod(await pack_mod(mod), "testrecipes.cubi");
Deno.removeSync(dir, { recursive: true });
@@ -222,7 +222,7 @@ Deno.test("recipes can only be registered while shared scripts set up", async ()
});
Deno.test("every mod's recipe types are registered on a client too, so it loads them", async () => {
const mods = load_order(load_and_check("mods"));
const mods = load_order(await load_and_check("mods"));
const packed = await Promise.all(mods.map(async (mod) => read_mod(await pack_mod(mod), `${mod.id}.cubi`)));
const listings = mods.map((mod): ModListing => ({
id: mod.id,
+3 -3
View File
@@ -80,8 +80,8 @@ Deno.test("a texture's .json is checked, packed into the .cubi and read back", a
const json = { animation: { frametime: 3, interpolate: true } };
Deno.writeTextFileSync(`${textures}/lamps/goo.json`, JSON.stringify(json));
const lamps = () => load_and_check(sources).find((m) => m.id === "lava_lamps")!;
const mod = lamps();
const lamps = async () => (await load_and_check(sources)).find((m) => m.id === "lava_lamps")!;
const mod = await lamps();
assertEquals(mod.report.errors, []);
const packed = read_mod(await pack_mod(mod), "lava_lamps.cubi");
assertEquals([...packed.texture_json!], [["lava_lamps:lamps_goo", json]]);
@@ -92,7 +92,7 @@ Deno.test("a texture's .json is checked, packed into the .cubi and read back", a
`${textures}/lamps/goo.json`,
JSON.stringify({ animation: { width: 5 } }),
);
const broken = lamps();
const broken = await lamps();
assertEquals(broken.report.errors, [
"textures/lamps/goo.json: the png is 16×64, which doesn't split into 5×16 frames",
"textures/stray.json: there's no stray.png for it to go with",
+1 -1
View File
@@ -47,7 +47,7 @@ async function load(client_script: string) {
}),
);
write("scripts/client.ts", client_script);
const mods = load_order(load_and_check(dir));
const mods = load_order(await load_and_check(dir));
const packed = await Promise.all(mods.map(async (mod) => read_mod(await pack_mod(mod), `${mod.id}.cubi`)));
Deno.removeSync(dir, { recursive: true });
const listings: ModListing[] = mods.map((mod) => ({
+1 -1
View File
@@ -477,7 +477,7 @@ Deno.test("client scripts register visuals during setup, for blocks that exist",
const load = async (script: string) => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" });
write_testmod(dir, script);
const mod = load_and_check(dir)[0];
const mod = (await load_and_check(dir))[0];
const packed = read_mod(await pack_mod(mod), "testmod.cubi");
Deno.removeSync(dir, { recursive: true });
const listing: ModListing = { id: "testmod", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 };
+27 -4
View File
@@ -37,7 +37,8 @@ import {
validate_noise_settings,
} from "@/common/worldgen/data.ts";
import { validate_feature } from "@/common/worldgen/features.ts";
import { dirname } from "@std/path";
import { dirname, resolve, toFileUrl } from "@std/path";
import { run_content_script } from "@/common/content_scripts.ts";
export { load_order, type LoadedMod, type ModReport };
@@ -53,19 +54,41 @@ export function engine_texture_ids(): string[] {
}
// loads and checks every mod without typechecking, which is slow. the build uses this
export function load_and_check(mods_dir = "mods"): LoadedMod[] {
export async function load_and_check(mods_dir = "mods"): Promise<LoadedMod[]> {
const mods: LoadedMod[] = [];
for (const entry of safe_read_dir(mods_dir)) {
if (entry.isDirectory && !entry.name.startsWith(".") && !entry.name.startsWith("_")) {
mods.push(load_mod(mods_dir, entry.name));
const mod = load_mod(mods_dir, entry.name);
await add_registered_content(mod);
mods.push(mod);
}
}
check_references(mods, engine_texture_ids());
return mods;
}
// runs the mod's content script and adds the blocks it registers after its files' ones, named after the script, like
// the server does with a .cubi's. packing leaves them out, the server registers them again
async function add_registered_content(mod: LoadedMod) {
const path = content_script(mod);
if (path === undefined || !exists(`${mod.dir}/${path}`)) return;
const { blocks, problems } = await run_content_script({
mod: mod.id,
version: String(mod.manifest?.version),
url: toFileUrl(resolve(mod.dir, path)).href,
});
for (const json of blocks) mod.blocks.push({ file: path, json });
for (const problem of problems) mod.report.errors.push(`${path}: ${problem}`);
}
// the path of the mod's content script in its folder, which is also the file its blocks are listed under
export function content_script(mod: LoadedMod): string | undefined {
const path = (mod.manifest?.scripts as Record<string, unknown> | undefined)?.content;
return typeof path === "string" ? path : undefined;
}
export async function check_mods(mods_dir = "mods", options = { typecheck: true }): Promise<ModReport[]> {
const mods = load_and_check(mods_dir);
const mods = await load_and_check(mods_dir);
try {
load_order(mods);
} catch (e) {
+2
View File
@@ -28,6 +28,8 @@ const DESKTOP_ARGS = [
"--include",
"server/game/worker.ts",
"--include",
"server/content_worker.ts",
"--include",
"desktop/config.json",
"desktop/main.ts",
];
+2 -2
View File
@@ -14,7 +14,7 @@ import { DEFAULT_REMAPS, type ImportOptions, type ImportReport } from "./importe
import { import_tags } from "./importer/tags.ts";
import { import_textures } from "./importer/textures.ts";
const KINDS: Record<string, (input: string, options: ImportOptions) => ImportReport> = {
const KINDS: Record<string, (input: string, options: ImportOptions) => ImportReport | Promise<ImportReport>> = {
model: import_models,
texture: import_textures,
blockstate: import_blocks,
@@ -113,7 +113,7 @@ if (import.meta.main) {
}
const run = KINDS[kind];
if (!run) throw new Error(`"${kind}" isn't a kind that can be imported yet: ${Object.keys(KINDS).join(", ")}`);
const report = run(input, options);
const report = await run(input, options);
print_report(report);
if (report.errors.length > 0) Deno.exit(1);
} catch (e) {
+2 -2
View File
@@ -81,9 +81,9 @@ function processing(json: Json, context: Context): Converted {
};
}
export function import_recipes(input: string, options: ImportOptions = {}): ImportReport {
export async function import_recipes(input: string, options: ImportOptions = {}): Promise<ImportReport> {
if (options.output === undefined) throw new Error("--output is needed for recipes");
const context = { remaps: options.remaps ?? DEFAULT_REMAPS, known: known_in(options.output) };
const context = { remaps: options.remaps ?? DEFAULT_REMAPS, known: await known_in(options.output) };
const report = empty_report();
if (context.known === undefined) {
report.warnings.push({
+2 -2
View File
@@ -221,10 +221,10 @@ export interface Known {
tags: Record<TagRegistry, Set<string>>;
}
export function known_in(output: string): Known | undefined {
export async function known_in(output: string): Promise<Known | undefined> {
const mod = mod_of(`${output}/x`);
if (!mod) return undefined;
const mods = load_and_check(dirname(mod.dir));
const mods = await load_and_check(dirname(mod.dir));
const tags: Known["tags"] = { blocks: new Set(), items: new Set(), entities: new Set(), biomes: new Set() };
for (const { json } of mods.flatMap((mod) => mod.tags)) tags[json.registry].add(json.id);
return { ids: registered_ids(mods), tags };
+2 -2
View File
@@ -47,7 +47,7 @@ export function tag_id(location: string, remaps: Remaps): string {
return `${namespace}:${path}`;
}
export function import_tags(input: string, options: ImportOptions = {}): ImportReport {
export async function import_tags(input: string, options: ImportOptions = {}): Promise<ImportReport> {
if (options.output === undefined) throw new Error("--output is needed for tags");
const remaps = options.remaps ?? DEFAULT_REMAPS;
const report = empty_report();
@@ -68,7 +68,7 @@ export function import_tags(input: string, options: ImportOptions = {}): ImportR
return [{ location, registry, id, json: JSON.parse(Deno.readTextFileSync(file)) }];
});
const known = known_in(options.output);
const known = await known_in(options.output);
const own = new Set(tags.map(({ registry, id }) => `${registry} ${id}`));
for (const { location, registry, id, json } of tags) {
if (!TAG_ID_PATTERN.test(id)) {
+9 -4
View File
@@ -7,15 +7,17 @@
import { basename, dirname, resolve } from "@std/path";
import { type Mod, MOD_EXTENSION, SCRIPT_SIDES, type ScriptSide, write_mod } from "@/common/mod.ts";
import type { ManifestJson } from "@/common/mod_data.ts";
import { load_and_check, type LoadedMod, mod_deno_config } from "./check_mods.ts";
import { content_script, load_and_check, type LoadedMod, mod_deno_config } from "./check_mods.ts";
import { mod_data } from "@/common/mod_check.ts";
// what each script is bundled for: the server runs in deno, clients in browsers, worldgen and shared in both
// what each script is bundled for: the server runs in deno, clients in browsers, worldgen and shared in both. content
// scripts only run on the server
const PLATFORMS: Record<ScriptSide, "deno" | "browser"> = {
server: "deno",
client: "browser",
worldgen: "browser",
shared: "browser",
content: "deno",
};
// a mod that passed check-mods, as .cubi bytes
@@ -33,9 +35,12 @@ export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>>
}
const texture_json = new Map([...mod.texture_json].sort(([a], [b]) => a.localeCompare(b)));
// without what the content script registered, which the server registers again when it loads the .cubi
const data = mod_data(mod);
data.blocks = mod.blocks.filter(({ file }) => file !== content_script(mod)).map(({ json }) => json);
return write_mod({
manifest,
data: mod_data(mod),
data,
scripts,
textures,
texture_json,
@@ -80,7 +85,7 @@ if (import.meta.main) {
}
// its siblings are checked too, so references to mods it depends on can be checked
const folder = resolve(dir);
const mod = load_and_check(dirname(folder)).find((m) => resolve(m.dir) === folder);
const mod = (await load_and_check(dirname(folder))).find((m) => resolve(m.dir) === folder);
if (!mod) {
console.error(`${dir} isn't a mod folder`);
Deno.exit(1);
+1 -1
View File
@@ -20,7 +20,7 @@ const [center_x, center_z] = [Number(Deno.args[2] ?? 0), Number(Deno.args[3] ??
// the base game, from mods/bworld: its data registered like the game does, and its worldgen script for trees and the
// rest of its features
const bworld = load_and_check().find((mod) => mod.id === "bworld")!;
const bworld = (await load_and_check()).find((mod) => mod.id === "bworld")!;
const jsons = <T>(list: { json: T }[]) => list.map((entry) => entry.json);
register_mod_data([{
id: "bworld",