// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // fluids with their data (see FluidVariant in mod_api/shared.ts) and the rules shared scripts give them, which name and // color a fluid by its data. each side has its own FluidRules from the same scripts, so the server's tooltips and a // client's drawing agree import type { FluidApi, FluidRules as Rules, FluidVariant } from "./mod_api/shared.ts"; import { EverythingRegistry } from "./everything_registry.ts"; import type { FluidJson } from "./mod_data.ts"; import { color as color_schema } from "./schema.ts"; import { name_from_id, same_data } from "./utils.ts"; export class FluidRules { #rules = new Map(); // run runs a mod's code, reporting what it throws instead of letting it take the game down constructor(readonly run: (mod: string, what: string, fn: () => T) => T | undefined) {} register(mod: string, id: string, rules: Rules) { if (!id.startsWith(`${mod}:`)) throw new Error(`[${mod}] fluid ${id} must be in the namespace "${mod}"`); if (!EverythingRegistry.get("fluids", id)) throw new Error(`[${mod}] unknown fluid ${id}`); if (this.#rules.has(id)) throw new Error(`[${mod}] the rules of fluid ${id} are registered twice`); this.#rules.set(id, { mod, rules }); } name(fluid: FluidVariant): string { const json = known_fluid(fluid.id); const name = this.#ask(fluid, "name", "a name", (value) => typeof value === "string" && value.length > 0); return name ?? json.name ?? name_from_id(fluid.id); } color(fluid: FluidVariant): string { const json = known_fluid(fluid.id); const valid = (value: unknown) => color_schema.safeParse(value).success; return this.#ask(fluid, "color", 'a color like "#c42d39"', valid) ?? json.color; } // ctx.fluids for server and client scripts api(): FluidApi { return { exists: (id) => EverythingRegistry.get("fluids", id) !== undefined, name: (fluid) => this.name(fluid), color: (fluid) => this.color(fluid), same: (a, b) => a.id === b.id && same_data(a.data, b.data), }; } // what the fluid's rule says, or undefined when it has none, says nothing, or says something that isn't one #ask(fluid: FluidVariant, rule: "name" | "color", wanted: string, valid: (value: unknown) => boolean) { const entry = this.#rules.get(fluid.id); const fn = entry?.rules[rule]; if (!entry || !fn) return undefined; return this.run(entry.mod, `the ${rule} rule of ${fluid.id}`, () => { const value = fn.call(entry.rules, fluid.data); if (value !== undefined && !valid(value)) throw new Error(`gave ${JSON.stringify(value)}, not ${wanted}`); return value; }); } } function known_fluid(id: string): FluidJson { const json = EverythingRegistry.get("fluids", id); if (!json) throw new Error(`unknown fluid ${id}`); return json; }