Single module modding

This commit is contained in:
2026-11-14 12:18:41 -03:00
parent 605008f584
commit 313098892e
134 changed files with 919 additions and 924 deletions
+61 -33
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// deno task check-mods
// validates every mod in mods/: manifests, data files, textures, references between them, and typechecks scripts
// validates every mod in mods/: manifests, data files, textures, references between them, and typechecks their scripts
import * as z from "zod";
import {
data_file,
@@ -25,7 +25,7 @@ import {
} from "@/common/mod_data.ts";
import { json_object } from "@/common/schema.ts";
import { check_references, load_order, type LoadedMod, type ModReport } from "@/common/mod_check.ts";
import { png_size, texture_size_problem } from "@/common/mod.ts";
import { data_url, png_size, texture_size_problem } from "@/common/mod.ts";
import { type TextureJson, validate_texture_json } from "@/common/texture_animation.ts";
import { type LootTableJson, validate_loot_table } from "@/common/loot.ts";
import { validate_biome } from "@/common/worldgen/biomes.ts";
@@ -67,23 +67,35 @@ export async function load_and_check(mods_dir = "mods"): Promise<LoadedMod[]> {
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
// runs its script's content phase 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);
const path = main_script(mod);
if (path === undefined || !exists(`${mod.dir}/${path}`)) return;
// only this folder's deno.json is in this realm's import map, so a mod with its own is bundled first
let url = toFileUrl(resolve(mod.dir, path)).href;
if (mod_deno_config(mod.dir)) {
try {
url = data_url(await bundle_script(mod.dir, `${mod.dir}/${path}`));
} catch (e) {
mod.report.errors.push((e as Error).message);
return;
}
}
const { blocks, problems } = await run_content_script({
mod: mod.id,
version: String(mod.manifest?.version),
url: toFileUrl(resolve(mod.dir, path)).href,
engine_access: mod.manifest?.engine_access === true,
url,
});
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;
// the path of the mod's script in its folder, which is also the file the blocks its content phase registers are
// listed under
export function main_script(mod: LoadedMod): string | undefined {
const path = mod.manifest?.main;
return typeof path === "string" ? path : undefined;
}
@@ -97,7 +109,7 @@ export async function check_mods(mods_dir = "mods", options = { typecheck: true
if (options.typecheck) {
for (const mod of mods) {
await typecheck_scripts(mod);
await typecheck_script(mod);
}
}
@@ -144,22 +156,14 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
error(`"cubi" is reserved for the engine itself`);
}
const scripts = (mod.manifest?.scripts ?? {}) as Record<string, string>;
for (const [side, path] of Object.entries(scripts)) {
if (typeof path === "string" && !exists(`${dir}/${path}`)) {
error(`manifest.json: scripts.${side} ${path} doesn't exist`);
}
}
const main = main_script(mod);
if (main !== undefined && !exists(`${dir}/${main}`)) error(`manifest.json: main ${main} doesn't exist`);
// cubi/engine needs engine_access, it's checked again on the bundled code when a .cubi loads
if (mod.manifest?.engine_access !== true) {
const folders = new Set(Object.values(scripts).filter((p) => typeof p === "string").map((p) => dirname(p)));
for (const folder of folders) {
for (const file of [...walk(`${dir}/${folder}`, ".ts"), ...walk(`${dir}/${folder}`, ".js")]) {
if (/["']cubi\/engine["']/.test(Deno.readTextFileSync(`${dir}/${folder}/${file}`))) {
error(
`${folder}/${file} imports cubi/engine, which needs "engine_access": true in manifest.json`,
);
}
if (mod.manifest?.engine_access !== true && main !== undefined) {
const folder = dirname(main);
for (const file of [...walk(`${dir}/${folder}`, ".ts"), ...walk(`${dir}/${folder}`, ".js")]) {
if (/["']cubi\/engine["']/.test(Deno.readTextFileSync(`${dir}/${folder}/${file}`))) {
error(`${folder}/${file} imports cubi/engine, which needs "engine_access": true in manifest.json`);
}
}
}
@@ -308,22 +312,20 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
return mod;
}
async function typecheck_scripts(mod: LoadedMod) {
const scripts = Object.values((mod.manifest?.scripts ?? {}) as Record<string, string>)
.filter((path) => typeof path === "string" && exists(`${mod.dir}/${path}`))
.map((path) => `${mod.dir}/${path}`);
if (scripts.length === 0) return;
async function typecheck_script(mod: LoadedMod) {
const path = main_script(mod);
if (path === undefined || !exists(`${mod.dir}/${path}`)) return;
const config = mod_deno_config(mod.dir) ?? "deno.json";
const output = await new Deno.Command(Deno.execPath(), {
args: ["check", "--config", config, ...scripts],
args: ["check", "--config", config, `${mod.dir}/${path}`],
stdout: "piped",
stderr: "piped",
env: { NO_COLOR: "1" },
}).output();
if (!output.success) {
const text = new TextDecoder().decode(output.stderr).trim();
mod.report.errors.push(`scripts don't typecheck:\n${text}`);
mod.report.errors.push(`its script doesn't typecheck:\n${text}`);
}
}
@@ -366,7 +368,33 @@ function safe_read_dir(dir: string): Deno.DirEntry[] {
}
}
// a mod with its own deno.json is its own deno project, see pack_mod.ts
// a mod is a deno project: with its own deno.json its script is bundled with it (its imports, npm packages and so
// on), otherwise with the deno.json of the folder the build runs in. for browsers, since players run it too, and the
// server's realms have no permissions, so deno's own apis are no use there
export async function bundle_script(mod_dir: string, entry: string): Promise<string> {
const platform = "browser";
const config = mod_deno_config(mod_dir);
if (!config) {
const result = await Deno.bundle({ entrypoints: [entry], platform, write: false, minify: false });
if (!result.success || !result.outputFiles?.length) {
throw new Error(`Couldn't bundle ${entry}:\n${result.errors.map((e) => e.text).join("\n")}`);
}
return result.outputFiles[0].text();
}
const result = await new Deno.Command(Deno.execPath(), {
args: ["bundle", "--config", config, "--platform", platform, entry],
stdout: "piped",
stderr: "piped",
env: { NO_COLOR: "1" },
}).output();
if (!result.success) {
throw new Error(`Couldn't bundle ${entry}:\n${new TextDecoder().decode(result.stderr).trim()}`);
}
return new TextDecoder().decode(result.stdout);
}
// a mod with its own deno.json is its own deno project, see bundle_script
export function mod_deno_config(mod_dir: string): string | undefined {
return ["deno.json", "deno.jsonc"].map((name) => `${mod_dir}/${name}`).find(exists);
}
+7 -50
View File
@@ -2,32 +2,18 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// deno task pack-mod mods/copper_tools [copper_tools.cubi]
// builds a mod folder into a .cubi: its data merged into data.json, each script bundled into one module, and its
// builds a mod folder into a .cubi: its data merged into data.json, its script bundled into one module, and its
// textures and credits. deno task build does this for every mod in mods/, see docs/modding/gettingstarted/modfiles.md
import { basename, dirname, resolve } from "@std/path";
import { type Mod, MOD_EXTENSION, SCRIPT_SIDES, type ScriptSide, write_mod } from "@/common/mod.ts";
import { MOD_EXTENSION, write_mod } from "@/common/mod.ts";
import type { ManifestJson } from "@/common/mod_data.ts";
import { content_script, load_and_check, type LoadedMod, mod_deno_config } from "./check_mods.ts";
import { bundle_script, load_and_check, type LoadedMod, main_script } 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. 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
export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>> {
const manifest = mod.manifest as unknown as ManifestJson;
const scripts: Mod["scripts"] = {};
for (const side of SCRIPT_SIDES) {
const entry = manifest.scripts?.[side];
if (entry) scripts[side] = await bundle_script(mod.dir, `${mod.dir}/${entry}`, PLATFORMS[side]);
}
const script = manifest.main ? await bundle_script(mod.dir, `${mod.dir}/${manifest.main}`) : undefined;
const textures = new Map<string, Uint8Array>();
for (const [id, path] of [...mod.texture_files].sort(([a], [b]) => a.localeCompare(b))) {
@@ -35,48 +21,19 @@ 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
// without what the content phase 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);
data.blocks = mod.blocks.filter(({ file }) => file !== main_script(mod)).map(({ json }) => json);
return write_mod({
manifest,
data,
scripts,
script,
textures,
texture_json,
credits: manifest.credits ? Deno.readTextFileSync(`${mod.dir}/${manifest.credits}`) : undefined,
});
}
// a mod is a deno project: with its own deno.json its scripts are bundled with it (its imports, npm packages and
// so on), otherwise with the deno.json of the folder the build runs in
async function bundle_script(mod_dir: string, entry: string, platform: "deno" | "browser"): Promise<string> {
const config = mod_deno_config(mod_dir);
if (!config) {
const result = await Deno.bundle({ entrypoints: [entry], platform, write: false, minify: false });
if (!result.success || !result.outputFiles?.length) {
throw new Error(`Couldn't bundle ${entry}:\n${result.errors.map((e) => e.text).join("\n")}`);
}
return result.outputFiles[0].text();
}
const output = await Deno.makeTempFile({ suffix: ".js" });
try {
const result = await new Deno.Command(Deno.execPath(), {
args: ["bundle", "--config", config, "--platform", platform, "--output", output, entry],
stdout: "piped",
stderr: "piped",
env: { NO_COLOR: "1" },
}).output();
if (!result.success) {
throw new Error(`Couldn't bundle ${entry}:\n${new TextDecoder().decode(result.stderr).trim()}`);
}
return Deno.readTextFileSync(output);
} finally {
Deno.removeSync(output);
}
}
if (import.meta.main) {
const [dir, out] = Deno.args;
if (!dir) {
+2 -2
View File
@@ -19,7 +19,7 @@ const out = Deno.args[1] ?? ".";
const [center_x, center_z] = [Number(Deno.args[2] ?? 0), Number(Deno.args[3] ?? 0)];
Deno.mkdirSync(out, { recursive: true });
// the base game, from mods/bworld: its data registered like the game does, and its worldgen script for trees and the
// the base game, from mods/bworld: its data registered like the game does, and its worldgen phase for trees and the
// rest of its features
const bworld = (await load_and_check()).find((mod) => mod.id === "bworld")!;
const jsons = <T>(list: { json: T }[]) => list.map((entry) => entry.json);
@@ -50,7 +50,7 @@ const dimension = jsons(bworld.dimensions).find((json) => json.default)!;
const shape = dimension_shape(dimension);
const worldgen = await load_worldgen({
mods: ["bworld"],
scripts: [{ mod: "bworld", url: new URL("../mods/bworld/scripts/worldgen.ts", import.meta.url).href }],
scripts: [{ mod: "bworld", url: new URL("../mods/bworld/scripts/main.ts", import.meta.url).href }],
ores: [jsons(bworld.ores)],
generator: dimension.generator,
shape,