// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // engine access: mods importing cubi/engine and hooking the engine's methods. see docs/modding/misc/engine.md import { assert, assertEquals, assertStringIncludes, assertThrows } from "@std/assert"; import { clear_hooks, expose_engine, hook, loading_mod } from "@/common/hooks.ts"; import { GAME_VERSION } from "@/common/constants.ts"; import { engine_version_problem, validate_manifest } from "@/common/mod_data.ts"; import { ItemStack } from "@/common/inventory.ts"; import { EverythingRegistry } from "@/common/everything_registry.ts"; import { read_mod } from "@/common/mod.ts"; import { load_and_check } from "@/tools/check_mods.ts"; import { pack_mod } from "@/tools/pack_mod.ts"; import { load_client_mods } from "@/client/mods.ts"; import { LocalPlayer } from "@/client/entity/local_player.ts"; import { Options } from "@/client/options.ts"; import type { Client } from "@/client/client.ts"; import type { ModListing } from "@/common/mod_loader.ts"; import { copy_dir, test_game } from "./helpers.ts"; import { game_with_pool } from "./chunk_loading.ts"; const [MAJOR, MINOR] = GAME_VERSION.split("."); const THIS_MINOR = `~${MAJOR}.${MINOR}.0`; // a mod in dir with these scripts, as { side: [file, code] } function write_mod( dir: string, id: string, scripts: Record, manifest: Record = { engine_access: true, game_version: THIS_MINOR }, ) { Deno.mkdirSync(`${dir}/${id}/scripts`, { recursive: true }); const paths: Record = {}; for (const [side, [file, code]] of Object.entries(scripts)) { Deno.writeTextFileSync(`${dir}/${id}/scripts/${file}`, code); paths[side] = `scripts/${file}`; } Deno.writeTextFileSync( `${dir}/${id}/manifest.json`, JSON.stringify({ format_version: 1, id, name: id, version: "1.0.0", scripts: paths, ...manifest }), ); } // mods/bworld and the mods write adds, in a temp folder function mods_dir(write: (dir: string) => void) { const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" }); copy_dir("mods/bworld", `${dir}/bworld`); write(dir); return dir; } // a class to hook in the tests that call hook directly, made again for each so their hooks don't meet function counter_class() { return class Counter { count = 0; add(amount: number) { this.count += amount; return this.count; } }; } // runs fn as a mod with engine access, the way the loaders do function as_mod(mod: string, fn: () => T, engine_access = true): Promise { return loading_mod(mod, engine_access, () => Promise.resolve(fn())); } // what console.error got while fn ran async function errors_during(fn: () => unknown): Promise { const errors: string[] = []; const original = console.error; console.error = (...args: unknown[]) => errors.push(args.map(String).join(" ")); try { await fn(); } finally { console.error = original; } return errors; } Deno.test("a server mod hooks GameServer to drop twice, like the plan's example", async () => { const dir = mods_dir((dir) => write_mod(dir, "double_drops", { server: [ "server.ts", `import { engine, hook } from "cubi/engine"; export function setup() { hook(engine.server.GameServer.prototype, "pop_item", { after(game, [x, y, z, stack], entity) { game.spawn_item(entity.x, entity.y, entity.z, stack.clone()); return entity; }, }); }`, ], }) ); const { game } = await test_game(dir); const items = () => game.entities.entities_near(0.5, 100, 0.5, 4).length; const before = items(); game.pop_item(0, 100, 0, new ItemStack("bworld:stone", 1)); assertEquals(items(), before + 2); Deno.removeSync(dir, { recursive: true }); }); Deno.test("a worldgen mod hooks the terrain in engine.common", async () => { const dir = mods_dir((dir) => write_mod(dir, "flat_sea", { worldgen: [ "worldgen.ts", `import { engine, hook } from "cubi/engine"; // no ground anywhere, so it's all sea export function setup() { hook(engine.common.NoiseTerrain.prototype, "density", { replace: () => -1 }); }`, ], }) ); const { game } = await test_game(dir, undefined, "engine-access-flat-sea"); assertEquals(game.world.get_block_id(8, 10, 8), "bworld:water"); Deno.removeSync(dir, { recursive: true }); // the next game doesn't have it const { game: plain } = await test_game("mods", undefined, "engine-access-flat-sea"); assert(plain.world.get_block_id(8, 10, 8) !== "bworld:water"); }); Deno.test({ name: "a worldgen mod's hook reaches the worldgen workers too, since each loads the worldgen scripts", sanitizeOps: false, sanitizeResources: false, fn: async () => { const dir = mods_dir((dir) => write_mod(dir, "flat_sea", { worldgen: [ "worldgen.ts", `import { engine, hook } from "cubi/engine"; export function setup() { hook(engine.common.NoiseTerrain.prototype, "density", { replace: () => -1 }); }`, ], }) ); // it's all sea, so no spawn search const t = await game_with_pool(1, "engine-access-flat-sea-pool", dir, false); try { const around: [number, number][] = []; for (let x = -1; x <= 1; x++) for (let z = -1; z <= 1; z++) around.push([x, z]); await t.pool!.prefetch(around); const fallbacks = t.game.world.fallbacks; assertEquals(t.game.world.get_block_id(8, 10, 8), "bworld:water"); assertEquals(t.game.world.fallbacks, fallbacks, "the worker made it, not the game"); } finally { t.close(); Deno.removeSync(dir, { recursive: true }); } }, }); Deno.test("a client mod hooks LocalPlayer from its .cubi", async () => { const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" }); write_mod(dir, "floaty", { client: [ "client.ts", `import { engine, hook } from "cubi/engine"; // everyone is a block higher than they think export function setup() { hook(engine.client.LocalPlayer.prototype, "set_position", { before(_player, args) { args[1] += 1; }, }); }`, ], }); const mod = load_and_check(dir)[0]; assertEquals(mod.report.errors, []); const packed = read_mod(await pack_mod(mod), "floaty.cubi"); const listing: ModListing = { id: "floaty", name: "floaty", version: "1.0.0", sha256: "", file: "", size: 0, engine_access: true, }; EverythingRegistry.clear(); await load_client_mods([listing], [packed]); const client = { options: new Options(), level: {}, connection: { send() {} } }; const player = new LocalPlayer(client as unknown as Client, "id", "alice"); player.set_position(0, 10, 0); assertEquals(player.y, 11); clear_hooks(); Deno.removeSync(dir, { recursive: true }); }); Deno.test("hooks on one method run in priority order, then load order", async () => { const Counter = counter_class(); const order: string[] = []; const add = (name: string, priority?: number) => hook(Counter.prototype, "add", { priority, before() { order.push(`${name} before`); }, replace(_self, args, original) { order.push(`${name} replace`); return original(...args); }, after() { order.push(`${name} after`); }, }); await as_mod("late", () => add("late", 2000)); await as_mod("first", () => add("first")); await as_mod("second", () => add("second")); await as_mod("early", () => add("early", 0)); assertEquals(new Counter().add(1), 1); assertEquals(order, [ "early before", "first before", "second before", "late before", // the first is outermost "early replace", "first replace", "second replace", "late replace", "early after", "first after", "second after", "late after", ]); clear_hooks(); }); Deno.test("before can change args or skip the method, after chains the result", async () => { const Counter = counter_class(); await as_mod("a", () => { hook(Counter.prototype, "add", { before(_self, args) { args[0] *= 10; }, }); hook(Counter.prototype, "add", { before: (_self, [amount]) => amount < 0 ? { result: -1 } : undefined, }); hook(Counter.prototype, "add", { after: (_self, _args, result) => result + 1 }); hook(Counter.prototype, "add", { after: (_self, _args, result) => result * 2 }); }); const counter = new Counter(); assertEquals(counter.add(1), 22); assertEquals(counter.count, 10); // skipped: no method, no after hooks assertEquals(counter.add(-5), -1); assertEquals(counter.count, 10); clear_hooks(); }); Deno.test("a throwing hook is logged under its mod and skipped", async () => { const Counter = counter_class(); await as_mod("broken", () => { hook(Counter.prototype, "add", { before() { throw new Error("before"); }, }); hook(Counter.prototype, "add", { replace(_self, args, original) { original(...args); throw new Error("replace"); }, }); hook(Counter.prototype, "add", { after() { throw new Error("after"); }, }); }); const counter = new Counter(); let result = 0; const errors = await errors_during(() => result = counter.add(3)); // the method ran once, with what the throwing replace hook got from it assertEquals(result, 3); assertEquals(counter.count, 3); assertEquals(errors.length, 3); for (const error of errors) assertStringIncludes(error, "[broken]"); assertStringIncludes(errors[0], "a before hook on Counter.add threw"); clear_hooks(); }); Deno.test("unhooking puts the original method back", async () => { const Counter = counter_class(); const original = Counter.prototype.add; const unhook = await as_mod("a", () => hook(Counter.prototype, "add", { after: () => 100 })); assertEquals(new Counter().add(1), 100); unhook(); assertEquals(Counter.prototype.add, original); assert(!Object.hasOwn(Counter.prototype, "add") || Counter.prototype.add === original); assertEquals(new Counter().add(1), 1); // a plain object's function too, like engine.common.physics const object = { double: (n: number) => n * 2 }; const unhook_object = await as_mod("a", () => hook(object, "double", { after: (_self, _args, result) => -result })); assertEquals(object.double(2), -4); unhook_object(); assertEquals(object.double(2), 4); }); Deno.test("hook needs a loading mod with engine access", async () => { const Counter = counter_class(); assertThrows(() => hook(Counter.prototype, "add", {}), Error, "while a mod's script loads"); let error: Error | undefined; try { await as_mod("sneaky", () => hook(Counter.prototype, "add", {}), false); } catch (e) { error = e as Error; } assertStringIncludes(String(error), `sneaky hooks the engine without "engine_access"`); // and not something that isn't a method await as_mod("a", () => { assertThrows(() => hook(new Counter(), "count", {}), Error, "isn't a method"); }); // importing cubi/engine at all expose_engine({}); const shim = new URL("../common/mod_api/engine.ts", import.meta.url).href; let import_error: Error | undefined; try { await loading_mod("sneaky", false, () => import(`${shim}?sneaky`)); } catch (e) { import_error = e as Error; } assertStringIncludes(String(import_error), `sneaky imports cubi/engine without "engine_access"`); }); Deno.test("cubi/engine without engine_access is an error in check-mods and in a .cubi", async () => { const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" }); const script = `import { engine } from "cubi/engine"; export function setup() { console.log(engine.common.physics); }`; write_mod(dir, "sneaky", { server: ["server.ts", script] }, {}); const [mod] = load_and_check(dir); assertEquals(mod.report.errors, [ `scripts/server.ts imports cubi/engine, which needs "engine_access": true in manifest.json`, ]); // packed anyway, the bundle gives it away const bytes = await pack_mod(mod); assertThrows(() => read_mod(bytes, "sneaky.cubi"), Error, "a script uses cubi/engine"); Deno.removeSync(dir, { recursive: true }); }); Deno.test("engine access ties a mod to one minor version of the game", () => { assertEquals(engine_version_problem("~0.4.0", "0.4.2"), undefined); assertEquals(engine_version_problem("~0.4.2", "0.4.2"), undefined); assertEquals(engine_version_problem("0.4.2", "0.4.2"), undefined); assertStringIncludes(engine_version_problem("~0.4.3", "0.4.2")!, "this is the game's 0.4.2"); assertStringIncludes(engine_version_problem("~0.3.0", "0.4.2")!, "this is the game's 0.4.2"); assertStringIncludes(engine_version_problem("0.4.1", "0.4.2")!, "this is the game's 0.4.2"); for (const range of [undefined, ">=0.4.0", "^0.4.0", "*", "0.4"]) { assertStringIncludes(engine_version_problem(range, "0.4.2")!, "needs game_version to be one minor version"); } const manifest = { format_version: 1, id: "a", name: "A", version: "1.0.0", engine_access: true }; assertEquals(validate_manifest({ ...manifest, game_version: THIS_MINOR }, "a"), []); assertEquals(validate_manifest({ ...manifest, game_version: ">=0.1.0" }, "a").length, 1); assertEquals(validate_manifest({ ...manifest, engine_access: "yes" }, "a"), [ "engine_access must be true or false", ]); });