Files
bworld/common/content_scripts.ts
T
2026-11-12 20:41:13 -03:00

61 lines
2.1 KiB
TypeScript

// 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;
}
}