// SPDX-FileCopyrightText: 2026 Paula Wisnievski // 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 their scripts import * as z from "zod"; import { data_file, entity_model_from_geo, FORMAT_VERSION, type OreJson, type SpawnJson, type TagJson, validate_block, validate_effect, validate_entity, validate_fluid, validate_item, validate_manifest, validate_model, validate_ore, validate_recipe, validate_spawn, validate_tag, } 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 { 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 { decode_schematic, type Schematic, SCHEMATIC_EXTENSION, validate_schematic } from "@/common/schematic.ts"; import { validate_biome } from "@/common/worldgen/biomes.ts"; import { validate_biome_source, validate_density_function, validate_dimension, validate_noise, validate_noise_settings, } from "@/common/worldgen/data.ts"; import { validate_feature } from "@/common/worldgen/features.ts"; import { dirname, resolve, toFileUrl } from "@std/path"; import { run_content_script } from "@/common/content_scripts.ts"; export { load_order, type LoadedMod, type ModReport }; // the engine's own textures, named cubi: export const ENGINE_TEXTURE_DIR = "assets/sprites/textures"; // cubi:missing is drawn by code, the rest are files export function engine_texture_ids(): string[] { return [ "cubi:missing", ...walk(ENGINE_TEXTURE_DIR, ".png").map((file) => `cubi:${file.replace(/\.png$/, "")}`), ]; } // loads and checks every mod without typechecking, which is slow. the build uses this export async function load_and_check(mods_dir = "mods"): Promise { const mods: LoadedMod[] = []; for (const entry of safe_read_dir(mods_dir)) { if (entry.isDirectory && !entry.name.startsWith(".") && !entry.name.startsWith("_")) { 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 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 = 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), 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 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; } export async function check_mods(mods_dir = "mods", options = { typecheck: true }): Promise { const mods = await load_and_check(mods_dir); try { load_order(mods); } catch (e) { for (const mod of mods) mod.report.errors.push((e as Error).message); } if (options.typecheck) { for (const mod of mods) { await typecheck_script(mod); } } return mods.map((mod) => mod.report); } function load_mod(mods_dir: string, id: string): LoadedMod { const dir = `${mods_dir}/${id}`; const mod: LoadedMod = { id, dir, report: { id, errors: [], warnings: [] }, blocks: [], models: [], items: [], recipes: [], ores: [], spawns: [], entities: [], entity_models: [], effects: [], fluids: [], tags: [], loot_tables: [], biomes: [], noises: [], density_functions: [], noise_settings: [], biome_sources: [], dimensions: [], features: [], schematics: [], textures: [], texture_files: new Map(), texture_json: new Map(), }; const error = (message: string) => mod.report.errors.push(message); const manifest = read_json(`${dir}/manifest.json`, error); if (manifest !== undefined) { for (const problem of validate_manifest(manifest, id)) error(`manifest.json: ${problem}`); mod.manifest = manifest as Record; } if (id === "cubi") { error(`"cubi" is reserved for the engine itself`); } 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 && 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`); } } } const credits = mod.manifest?.credits; if (typeof credits === "string" && !exists(`${dir}/${credits}`)) { error(`manifest.json: credits ${credits} doesn't exist`); } // what a data file holds, under key next to its format_version. example is what that looks like, for the error const read_data = (path: string, key: string, contents: T, example: string) => { const json = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); if (json === undefined) return undefined; const file = data_file(key, contents).safeParse(json); if (!file.success) { error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "${key}": ${example} }`); return undefined; } return file.data[key] as z.infer; }; const load_data = ( folder: string, key: string, validate: (json: unknown) => string[], into: { file: string; json: T }[], ) => { // models/.geo.json are entity models, not block ones for (const file of walk(`${dir}/${folder}`, ".json").filter((file) => !file.endsWith(".geo.json"))) { const path = `${folder}/${file}`; const json = read_data(path, key, json_object, "{ ... }"); if (json === undefined) continue; const problems = validate(json); for (const problem of problems) error(`${path}: ${problem}`); if (problems.length === 0) into.push({ file: path, json: json as T }); } }; load_data("blocks", "block", validate_block, mod.blocks); load_data("models", "model", validate_model, mod.models); load_data("items", "item", validate_item, mod.items); load_data("recipes", "recipe", validate_recipe, mod.recipes); load_data("entities", "entity", validate_entity, mod.entities); load_data("effects", "effect", validate_effect, mod.effects); load_data("fluids", "fluid", validate_fluid, mod.fluids); load_data("worldgen/biomes", "biome", validate_biome, mod.biomes); load_data("worldgen/noise", "noise", validate_noise, mod.noises); load_data("worldgen/density_function", "density_function", validate_density_function, mod.density_functions); load_data("worldgen/noise_settings", "noise_settings", validate_noise_settings, mod.noise_settings); load_data("worldgen/biome_source", "biome_source", validate_biome_source, mod.biome_sources); load_data("worldgen/dimension", "dimension", validate_dimension, mod.dimensions); load_data("worldgen/features", "feature", validate_feature, mod.features); for (const file of walk(`${dir}/models`, ".geo.json")) { const path = `models/${file}`; const json = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`)); if (json === undefined) continue; const { model, problems } = entity_model_from_geo( json, `${id}:${file.replace(/\.geo\.json$/, "").replaceAll("/", "_")}`, ); for (const problem of problems) error(`${path}: ${problem}`); if (model) mod.entity_models.push({ file: path, json: model }); } // tags///.json is the tag :, in any namespace: tags are shared for (const file of walk(`${dir}/tags`, ".json")) { const path = `tags/${file}`; const [registry, namespace, ...rest] = file.replace(/\.json$/, "").split("/"); if (rest.length === 0) { error(`${path}: tag files go in tags///, like tags/items/${id}/things.json`); continue; } const tag = read_data(path, "tag", json_object, '{ "values": [ ... ] }'); if (tag === undefined) continue; const json = { ...tag, registry, id: `${namespace}:${rest.join("/")}` }; const problems = validate_tag(json); for (const problem of problems) error(`${path}: ${problem}`); if (problems.length === 0) mod.tags.push({ file: path, json: json as TagJson }); } // loot_tables/.json is the loot table :, like minecraft's for (const file of walk(`${dir}/loot_tables`, ".json")) { const path = `loot_tables/${file}`; const loot_table = read_data(path, "loot_table", json_object, '{ "pools": [ ... ] }'); if (loot_table === undefined) continue; const json = { ...loot_table, id: `${id}:${file.replace(/\.json$/, "")}` }; const problems = validate_loot_table(json); for (const problem of problems) error(`${path}: ${problem}`); if (problems.length === 0) mod.loot_tables.push({ file: path, json: json as LootTableJson }); } if (exists(`${dir}/worldgen/ores.json`)) { const ores = read_data("worldgen/ores.json", "ores", z.array(z.unknown()), "[ ... ]") ?? []; ores.forEach((ore, i) => { const problems = validate_ore(ore); for (const problem of problems) error(`worldgen/ores.json: ore ${i}: ${problem}`); if (problems.length === 0) mod.ores.push({ file: "worldgen/ores.json", json: ore as OreJson }); }); } if (exists(`${dir}/worldgen/spawns.json`)) { const spawns = read_data("worldgen/spawns.json", "spawns", z.array(z.unknown()), "[ ... ]") ?? []; spawns.forEach((spawn, i) => { const problems = validate_spawn(spawn); for (const problem of problems) error(`worldgen/spawns.json: spawn ${i}: ${problem}`); if (problems.length === 0) mod.spawns.push({ file: "worldgen/spawns.json", json: spawn as SpawnJson }); }); } // schematics/.cbsm is the schematic : for (const file of walk(`${dir}/schematics`, SCHEMATIC_EXTENSION)) { const path = `schematics/${file}`; let schematic: Schematic; try { schematic = decode_schematic(Deno.readFileSync(`${dir}/${path}`)); } catch (e) { error(`${path}: ${(e as Error).message}`); continue; } const json = { ...schematic, id: `${id}:${file.slice(0, -SCHEMATIC_EXTENSION.length)}` }; const problems = validate_schematic(json); for (const problem of problems) error(`${path}: ${problem}`); if (problems.length === 0) mod.schematics.push({ file: path, json }); } if (exists(`${dir}/config.json`)) { mod.config = read_data("config.json", "config", json_object, "{ ... }"); } // a mod only registers ids in its own namespace for (const { file, json } of [...mod.blocks, ...mod.models, ...mod.items, ...mod.entities]) { if (json.id.split(":")[0] !== id) error(`${file}: ${json.id} isn't in this mod's namespace "${id}"`); } for (const file of walk(`${dir}/textures`, ".png")) { const texture_id = `${id}:${file.replace(/\.png$/, "").replaceAll("/", "_")}`; mod.textures.push(texture_id); mod.texture_files.set(texture_id, `${dir}/textures/${file}`); const size = png_size(Deno.readFileSync(`${dir}/textures/${file}`)); if (!size) error(`textures/${file}: isn't a png`); } for (const file of walk(`${dir}/textures`, ".json")) { const texture_id = `${id}:${file.replace(/\.json$/, "").replaceAll("/", "_")}`; const png = mod.texture_files.get(texture_id); if (!png) { error(`textures/${file}: there's no ${file.replace(/\.json$/, ".png")} for it to go with`); continue; } const json = read_json(`${dir}/textures/${file}`, (message) => error(`textures/${file}: ${message}`)); const size = png_size(Deno.readFileSync(png)); if (json === undefined || !size) continue; const problems = validate_texture_json(json, size); for (const problem of problems) error(`textures/${file}: ${problem}`); if (problems.length === 0) mod.texture_json.set(texture_id, json as TextureJson); } // once it's known which are animated, their frames are what has to fit for (const [texture_id, path] of mod.texture_files) { const size = png_size(Deno.readFileSync(path)); const problem = size && texture_size_problem(size, mod.texture_json.get(texture_id)); if (problem) error(`${path.slice(dir.length + 1)}: ${problem}`); } return mod; } 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, `${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(`its script doesn't typecheck:\n${text}`); } } // helpers function read_json(path: string, error: (message: string) => void): unknown { let text: string; try { text = Deno.readTextFileSync(path); } catch { error(`${path.split("/").pop()} is missing`); return undefined; } try { return JSON.parse(text); } catch (e) { error(`isn't valid json: ${(e as Error).message}`); return undefined; } } // relative paths of files ending in `extension`, in subfolders too function walk(dir: string, extension: string, prefix = ""): string[] { const files: string[] = []; for (const entry of safe_read_dir(dir)) { if (entry.isDirectory) { files.push(...walk(`${dir}/${entry.name}`, extension, `${prefix}${entry.name}/`)); } else if (entry.name.endsWith(extension)) { files.push(`${prefix}${entry.name}`); } } return files.sort(); } function safe_read_dir(dir: string): Deno.DirEntry[] { try { return [...Deno.readDirSync(dir)].sort((a, b) => a.name.localeCompare(b.name)); } catch { return []; } } // 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 { 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); } function exists(path: string) { try { Deno.statSync(path); return true; } catch { return false; } } if (import.meta.main) { const reports = await check_mods(); let errors = 0; for (const report of reports) { const status = report.errors.length ? "✗" : "✓"; console.log(`${status} ${report.id}`); for (const error of report.errors) console.log(` error: ${error.replaceAll("\n", "\n ")}`); for (const warning of report.warnings) console.log(` warning: ${warning}`); errors += report.errors.length; } if (reports.length === 0) console.log("No mods in mods/"); Deno.exit(errors ? 1 : 0); }