// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // the server's mods: every .cubi in server_mods/, checked, with the server's changes to their config, sorted so // dependencies load first, and with the copy players download (the same mod without its server phase) ready to serve import { join } from "@std/path"; import { client_copy, type Mod, MOD_EXTENSION, read_mod, write_mod } from "@/common/mod.ts"; import { check_references, load_order, type LoadedMod } from "@/common/mod_check.ts"; 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; listing: ModListing; // what's served at listing.file client_bytes: Uint8Array; } export class ModsError extends Error { constructor(problems: string[]) { super(`Mods have errors:\n${problems.map((p) => ` ${p}`).join("\n")}`); this.name = "ModsError"; } } // engine_textures are the cubi: texture ids, for checking the textures mods use. config_dir has the server's // .json files that change mods' config. only, when given, is which of dir's files to load, like a // singleplayer world's mods. a mod with problems stops the whole server from starting, the game never runs with some // mods missing export async function load_mods( dir: string, engine_textures: Iterable, config_dir?: string, only?: string[], ): Promise { let files: string[]; try { files = only ?? mod_files(dir); } catch (e) { if (e instanceof Deno.errors.NotFound) return []; throw e; } const problems: string[] = []; const by_id = new Map(); for (const file of files) { try { const mod = read_mod(Deno.readFileSync(join(dir, file)), file); const other = by_id.get(mod.manifest.id); if (other) { problems.push(`${file} and ${other.file} are both the mod "${mod.manifest.id}"`); continue; } by_id.set(mod.manifest.id, { file, mod }); } catch (e) { problems.push((e as Error).message); } } 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)); check_references(loaded, engine_textures); for (const mod of loaded) { const dependencies = (mod.manifest?.dependencies ?? []) as { id: string }[]; for (const { id } of dependencies) { if (!by_id.has(id)) mod.report.errors.push(`depends on "${id}", which isn't in ${dir}`); } problems.push(...mod.report.errors.map((error) => `${mod.dir}: ${error}`)); for (const warning of mod.report.warnings) console.warn(`${mod.dir}: ${warning}`); } let ordered: LoadedMod[] = []; try { ordered = load_order(loaded); } catch (e) { problems.push((e as Error).message); } if (problems.length > 0) throw new ModsError(problems); return await Promise.all(ordered.map(async ({ id }) => { const mod = by_id.get(id)!.mod; const client_bytes = write_mod(client_copy(mod)); const hash = await sha256(client_bytes); return { mod, client_bytes, listing: { id: mod.manifest.id, name: mod.manifest.name, version: mod.manifest.version, sha256: hash, file: `mods/${hash}${MOD_EXTENSION}`, size: client_bytes.length, ...(mod.manifest.engine_access ? { engine_access: true } : {}), }, }; })); } // the .cubi files in a folder, by name export function mod_files(dir: string): string[] { return [...Deno.readDirSync(dir)] .filter((entry) => entry.isFile && entry.name.endsWith(MOD_EXTENSION)) .map((entry) => entry.name) .sort(); } // runs the content phase of the mods' 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.script !== undefined); if (with_scripts.length === 0) return; const scripts: ContentScriptCode[] = with_scripts.map(({ mod }) => ({ mod: mod.manifest.id, version: mod.manifest.version, engine_access: mod.manifest.engine_access, code: mod.script!, })); 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 phases: ${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.main}: ${problem}`)); }); } // applies config_dir/.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`); let text: string; try { text = Deno.readTextFileSync(file); } catch (e) { if (e instanceof Deno.errors.NotFound) return; throw e; } let json: unknown; try { json = JSON.parse(text); } catch (e) { problems.push(`${file}: isn't valid json: ${(e as Error).message}`); return; } const config_file = data_file("config", json_object).safeParse(json); if (!config_file.success) { problems.push(`${file}: must be { "format_version": ${FORMAT_VERSION}, "config": { ... } }`); return; } const changed = apply_config(mod.data.config ?? {}, config_file.data.config as Record); problems.push(...changed.problems.map((problem) => `${file}: ${problem}`)); mod.data.config = changed.config; } // a mod's config with changes made to it, like a server's config/.json makes: objects are changed setting by // setting, anything else is replaced. a change has to be to a setting the mod has, and the same kind of json value, // so a misspelled one doesn't go unnoticed export function apply_config( config: Record, changes: Record, ): { config: Record; problems: string[] } { const problems: string[] = []; const apply = (settings: Record, changes: Record, path: string) => { const result = { ...settings }; for (const [key, value] of Object.entries(changes)) { const name = `${path}${key}`; if (!Object.hasOwn(settings, key)) { problems.push(`${name} isn't one of the mod's settings`); } else if (json_kind(value) !== json_kind(settings[key])) { problems.push(`${name} must be ${json_kind(settings[key])}`); } else { result[key] = is_object(value) ? apply(settings[key] as Record, value, `${name}.`) : value; } } return result; }; return { config: apply(config, changes, ""), problems }; } function json_kind(value: unknown): string { if (value === null) return "null"; if (Array.isArray(value)) return "a list"; return is_object(value) ? "an object" : `a ${typeof value}`; } // in the shape the checks in common/mod_check.ts take function as_loaded_mod(file: string, mod: Mod): LoadedMod { const entries = (list: T[]) => list.map((json) => ({ file: `${file} data.json`, json })); return { id: mod.manifest.id, dir: file, report: { id: mod.manifest.id, errors: [], warnings: [] }, manifest: mod.manifest as unknown as Record, blocks: entries(mod.data.blocks), models: entries(mod.data.models), items: entries(mod.data.items), recipes: entries(mod.data.recipes), ores: entries(mod.data.ores), spawns: entries(mod.data.spawns), entities: entries(mod.data.entities), entity_models: entries(mod.data.entity_models), effects: entries(mod.data.effects), fluids: entries(mod.data.fluids), tags: entries(mod.data.tags), loot_tables: entries(mod.data.loot_tables ?? []), biomes: entries(mod.data.biomes ?? []), noises: entries(mod.data.noises ?? []), density_functions: entries(mod.data.density_functions ?? []), noise_settings: entries(mod.data.noise_settings ?? []), biome_sources: entries(mod.data.biome_sources ?? []), dimensions: entries(mod.data.dimensions ?? []), features: entries(mod.data.features ?? []), schematics: entries(mod.data.schematics ?? []), config: mod.data.config, textures: [...mod.textures.keys()], texture_files: new Map(), texture_json: new Map(mod.texture_json), }; }