Validators using zod
This commit is contained in:
+108
-159
@@ -6,9 +6,19 @@
|
||||
// decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own
|
||||
// conditions and functions (ctx.loot in server scripts), which are ids in their namespace.
|
||||
// see docs/modding/resources/loot_tables.md
|
||||
import * as z from "zod";
|
||||
import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts";
|
||||
import { list_matches, Tags } from "./tags.ts";
|
||||
import { is_object, TAG_ID_PATTERN } from "./mod_data.ts";
|
||||
import {
|
||||
by_kind,
|
||||
find_problems,
|
||||
id,
|
||||
id_or_tag,
|
||||
json_object,
|
||||
loot_table_id,
|
||||
type Problems,
|
||||
TAG_ID_PATTERN,
|
||||
} from "./schema.ts";
|
||||
|
||||
// a whole number, a random one from min to max, or the number of n tries at chance p that succeed, like minecraft's
|
||||
// constant, uniform and binomial number providers
|
||||
@@ -87,17 +97,6 @@ export interface LootEnvironment<C extends BaseLootContext> {
|
||||
random?: () => number;
|
||||
}
|
||||
|
||||
export const LOOT_CONDITIONS = [
|
||||
"random_chance",
|
||||
"match_tool",
|
||||
"block_state",
|
||||
"killed_by_player",
|
||||
"inverted",
|
||||
"any_of",
|
||||
"all_of",
|
||||
] as const;
|
||||
export const LOOT_FUNCTIONS = ["set_count", "limit_count", "set_data"] as const;
|
||||
const ENTRY_TYPES = ["item", "tag", "loot_table", "empty"];
|
||||
// tables in tables in tables: past this it's taken as a loop and gives nothing more
|
||||
const MAX_DEPTH = 16;
|
||||
|
||||
@@ -263,155 +262,105 @@ function apply<C extends BaseLootContext>(
|
||||
|
||||
// checking a table's json
|
||||
|
||||
type Problems = string[];
|
||||
const whole = z.int().min(0);
|
||||
|
||||
const number_provider: z.ZodType<NumberProvider> = z.union([
|
||||
whole,
|
||||
z.object({ min: whole, max: whole }).refine(({ min, max }) => min <= max, {
|
||||
path: ["max"],
|
||||
message: "can't be below min",
|
||||
}),
|
||||
z.object({ n: whole, p: z.number().min(0).max(1) }),
|
||||
], "must be a whole number, { min, max } or { n, p }");
|
||||
|
||||
const conditions = z.array(z.lazy(() => loot_condition));
|
||||
|
||||
// the engine's conditions, by name
|
||||
const CONDITIONS = new Map<string, z.ZodType>([
|
||||
["random_chance", z.object({ chance: z.number().min(0).max(1) })],
|
||||
[
|
||||
"match_tool",
|
||||
z.object({ items: z.array(id_or_tag).optional(), tool: z.string().optional(), min_tier: z.int().optional() }),
|
||||
],
|
||||
[
|
||||
"block_state",
|
||||
z.object({
|
||||
block: id.optional(),
|
||||
states: z.record(
|
||||
z.string(),
|
||||
z.union(
|
||||
[z.int(), z.object({ min: z.int().optional(), max: z.int().optional() })],
|
||||
'must be a number or { min, max }, like { "age": 7 }',
|
||||
),
|
||||
),
|
||||
}),
|
||||
],
|
||||
["killed_by_player", z.object({})],
|
||||
["inverted", z.object({ term: z.lazy(() => loot_condition) })],
|
||||
["any_of", z.object({ terms: conditions })],
|
||||
["all_of", z.object({ terms: conditions })],
|
||||
]);
|
||||
|
||||
// any other condition is a mod's own, by its id. the server checks a script registered it when it starts
|
||||
const loot_condition: z.ZodType<LootCondition> = by_kind(
|
||||
"condition",
|
||||
(name) => CONDITIONS.get(name) ?? (name.includes(":") ? json_object : undefined),
|
||||
`must be one of ${[...CONDITIONS.keys()].join(", ")}, or a mod's own condition's id`,
|
||||
);
|
||||
|
||||
// every function can have conditions
|
||||
const loot_function_base = z.object({ conditions: conditions.optional() });
|
||||
|
||||
// the engine's functions, by name
|
||||
const FUNCTIONS = new Map<string, z.ZodType>([
|
||||
["set_count", loot_function_base.extend({ count: number_provider, add: z.boolean().optional() })],
|
||||
["limit_count", loot_function_base.extend({ min: z.int().optional(), max: z.int().optional() })],
|
||||
["set_data", loot_function_base.extend({ data: z.unknown() })],
|
||||
]);
|
||||
|
||||
// any other function is a mod's own, like conditions
|
||||
const loot_function: z.ZodType<LootFunction> = by_kind(
|
||||
"function",
|
||||
(name) => FUNCTIONS.get(name) ?? (name.includes(":") ? loot_function_base : undefined),
|
||||
`must be one of ${[...FUNCTIONS.keys()].join(", ")}, or a mod's own function's id`,
|
||||
);
|
||||
|
||||
const functions = z.array(loot_function);
|
||||
|
||||
// every entry can have these
|
||||
const loot_entry_base = z.object({
|
||||
weight: z.number().min(0).optional(),
|
||||
conditions: conditions.optional(),
|
||||
functions: functions.optional(),
|
||||
});
|
||||
|
||||
const loot_entry: z.ZodType<LootEntry> = z.discriminatedUnion("type", [
|
||||
loot_entry_base.extend({ type: z.literal("item").optional(), item: id, count: number_provider.optional() }),
|
||||
loot_entry_base.extend({
|
||||
type: z.literal("tag"),
|
||||
tag: z.string('must be a #tag, like "#bworld:logs"').refine((tag) =>
|
||||
tag.startsWith("#") && TAG_ID_PATTERN.test(tag.slice(1))
|
||||
),
|
||||
count: number_provider.optional(),
|
||||
}),
|
||||
loot_entry_base.extend({ type: z.literal("loot_table"), table: loot_table_id }),
|
||||
loot_entry_base.extend({ type: z.literal("empty") }),
|
||||
]);
|
||||
|
||||
const loot_table_schema: z.ZodType<LootTableJson> = z.object({
|
||||
id: z.string("its file name must be a-z, 0-9 and _, in folders").regex(TAG_ID_PATTERN),
|
||||
pools: z.array(z.object({
|
||||
rolls: number_provider.optional(),
|
||||
conditions: conditions.optional(),
|
||||
entries: z.array(loot_entry).min(1),
|
||||
functions: functions.optional(),
|
||||
})),
|
||||
conditions: conditions.optional(),
|
||||
functions: functions.optional(),
|
||||
});
|
||||
|
||||
export function validate_loot_table(json: unknown): Problems {
|
||||
if (!is_object(json)) return ["loot_table must be an object"];
|
||||
const problems: Problems = [];
|
||||
if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) {
|
||||
problems.push("its file name must be a-z, 0-9 and _, in folders");
|
||||
}
|
||||
problems.push(...validate_conditions(json.conditions, "conditions"));
|
||||
problems.push(...validate_functions(json.functions, "functions"));
|
||||
if (!Array.isArray(json.pools)) return [...problems, "pools must be a list"];
|
||||
json.pools.forEach((pool, i) => {
|
||||
const where = `pools[${i}]`;
|
||||
if (!is_object(pool)) return problems.push(`${where} must be { rolls, entries }`);
|
||||
if (pool.rolls !== undefined) problems.push(...validate_number(pool.rolls, `${where}.rolls`));
|
||||
problems.push(...validate_conditions(pool.conditions, `${where}.conditions`));
|
||||
problems.push(...validate_functions(pool.functions, `${where}.functions`));
|
||||
if (!Array.isArray(pool.entries) || pool.entries.length === 0) {
|
||||
return problems.push(`${where}.entries must be a list of entries`);
|
||||
}
|
||||
pool.entries.forEach((entry, j) => problems.push(...validate_entry(entry, `${where}.entries[${j}]`)));
|
||||
});
|
||||
return problems;
|
||||
}
|
||||
|
||||
function validate_entry(entry: unknown, where: string): Problems {
|
||||
if (!is_object(entry)) return [`${where} must be { type, item, weight }`];
|
||||
const problems: Problems = [];
|
||||
const type = entry.type ?? "item";
|
||||
if (typeof type !== "string" || !ENTRY_TYPES.includes(type)) {
|
||||
problems.push(`${where}.type must be one of ${ENTRY_TYPES.join(", ")}`);
|
||||
}
|
||||
const field = { item: "item", tag: "tag", loot_table: "table" }[type as string];
|
||||
if (field && typeof entry[field] !== "string") problems.push(`${where}.${field} is needed for a "${type}" entry`);
|
||||
if (type === "tag" && typeof entry.tag === "string" && !entry.tag.startsWith("#")) {
|
||||
problems.push(`${where}.tag must be a #tag, like "#bworld:logs"`);
|
||||
}
|
||||
if (entry.count !== undefined) problems.push(...validate_number(entry.count, `${where}.count`));
|
||||
if (entry.weight !== undefined && (typeof entry.weight !== "number" || entry.weight < 0)) {
|
||||
problems.push(`${where}.weight must be a number, 0 or more`);
|
||||
}
|
||||
problems.push(...validate_conditions(entry.conditions, `${where}.conditions`));
|
||||
problems.push(...validate_functions(entry.functions, `${where}.functions`));
|
||||
return problems;
|
||||
}
|
||||
|
||||
export function validate_number(value: unknown, where: string): Problems {
|
||||
const whole = (n: unknown) => Number.isInteger(n) && (n as number) >= 0;
|
||||
if (whole(value)) return [];
|
||||
if (is_object(value) && whole(value.min) && whole(value.max) && (value.max as number) >= (value.min as number)) {
|
||||
return [];
|
||||
}
|
||||
if (
|
||||
is_object(value) && whole(value.n) && typeof value.p === "number" && value.p >= 0 && value.p <= 1
|
||||
) return [];
|
||||
return [`${where} must be a whole number, { min, max } or { n, p }`];
|
||||
}
|
||||
|
||||
function validate_conditions(list: unknown, where: string): Problems {
|
||||
if (list === undefined) return [];
|
||||
if (!Array.isArray(list)) return [`${where} must be a list`];
|
||||
return list.flatMap((condition, i) => validate_condition(condition, `${where}[${i}]`));
|
||||
}
|
||||
|
||||
function validate_condition(condition: unknown, where: string): Problems {
|
||||
if (!is_object(condition) || typeof condition.condition !== "string") {
|
||||
return [`${where} must be { "condition": ... }`];
|
||||
}
|
||||
const name = condition.condition;
|
||||
switch (name) {
|
||||
case "random_chance": {
|
||||
const chance = condition.chance;
|
||||
return typeof chance === "number" && chance >= 0 && chance <= 1
|
||||
? []
|
||||
: [`${where}.chance must be from 0 to 1`];
|
||||
}
|
||||
case "match_tool": {
|
||||
const problems: Problems = [];
|
||||
const items = condition.items;
|
||||
if (items !== undefined && !(Array.isArray(items) && items.every((i) => typeof i === "string"))) {
|
||||
problems.push(`${where}.items must be a list of item ids and #tags`);
|
||||
}
|
||||
if (condition.tool !== undefined && typeof condition.tool !== "string") {
|
||||
problems.push(`${where}.tool must be a tool type, like "axe"`);
|
||||
}
|
||||
if (condition.min_tier !== undefined && !Number.isInteger(condition.min_tier)) {
|
||||
problems.push(`${where}.min_tier must be a whole number`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
case "block_state": {
|
||||
const states = condition.states;
|
||||
const ok = is_object(states) && Object.values(states).every((match) =>
|
||||
Number.isInteger(match) ||
|
||||
(is_object(match) && (match.min === undefined || Number.isInteger(match.min)) &&
|
||||
(match.max === undefined || Number.isInteger(match.max)))
|
||||
);
|
||||
return ok ? [] : [`${where}.states must map states to a number or { min, max }, like { "age": 7 }`];
|
||||
}
|
||||
case "killed_by_player":
|
||||
return [];
|
||||
case "inverted":
|
||||
return validate_condition(condition.term, `${where}.term`);
|
||||
case "any_of":
|
||||
case "all_of":
|
||||
return Array.isArray(condition.terms)
|
||||
? condition.terms.flatMap((term, i) => validate_condition(term, `${where}.terms[${i}]`))
|
||||
: [`${where}.terms must be a list of conditions`];
|
||||
}
|
||||
return name.includes(":") ? [] : [
|
||||
`${where}: ${name} isn't a loot condition. the engine's are ${LOOT_CONDITIONS.join(", ")}, a mod's has its id`,
|
||||
];
|
||||
}
|
||||
|
||||
function validate_functions(list: unknown, where: string): Problems {
|
||||
if (list === undefined) return [];
|
||||
if (!Array.isArray(list)) return [`${where} must be a list`];
|
||||
return list.flatMap((fn, i) => {
|
||||
const at = `${where}[${i}]`;
|
||||
if (!is_object(fn) || typeof fn.function !== "string") return [`${at} must be { "function": ... }`];
|
||||
const problems = validate_conditions(fn.conditions, `${at}.conditions`);
|
||||
switch (fn.function) {
|
||||
case "set_count":
|
||||
problems.push(...validate_number(fn.count, `${at}.count`));
|
||||
if (fn.add !== undefined && typeof fn.add !== "boolean") {
|
||||
problems.push(`${at}.add must be true or false`);
|
||||
}
|
||||
break;
|
||||
case "limit_count":
|
||||
for (const key of ["min", "max"]) {
|
||||
if (fn[key] !== undefined && !Number.isInteger(fn[key])) {
|
||||
problems.push(`${at}.${key} must be a whole number`);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "set_data":
|
||||
if (fn.data === undefined) problems.push(`${at}.data is needed`);
|
||||
break;
|
||||
default:
|
||||
if (!fn.function.includes(":")) {
|
||||
problems.push(
|
||||
`${at}: ${fn.function} isn't a loot function. the engine's are ${
|
||||
LOOT_FUNCTIONS.join(", ")
|
||||
}, a mod's has its id`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
});
|
||||
return find_problems(loot_table_schema, json);
|
||||
}
|
||||
|
||||
// what a table refers to, for check-mods: items, item #tags, other tables, and mods' conditions and functions
|
||||
|
||||
Reference in New Issue
Block a user