Files
WT-Offline/packages/exepatch/src/definition.ts
T
N0VAN0M4LY 16b5d3cab1 Store patch definitions as commented JSONC with separate script fragments
Patch definitions under exe-patches/ and gui-patches/ move from
patch.json/locate.json to patch.jsonc/locate.jsonc. Each file now holds
only the data needed to apply the patch plus a short English comment
stating what it changes, why the local service cannot provide it, and
what happens without it. Every definition records the game versions it
was verified on (verified_on, required).

GUI patches keep their stock text and replacement in find.nut and
replace.nut next to patch.jsonc instead of escaped JSON strings, so the
script edits are readable, diffable and can carry Quirrel comments.
Matching treats CRLF and LF as the same line break because stock
scripts mix both; only the matched span is rewritten.

Loaders on both sides (packages/build, packages/exepatch, wtotools)
reject unknown keys so analysis text cannot creep back into the data.
JSONC parsing moves into a shared @wto/jsonc package; the build now
parses tuning/store.jsonc instead of scanning it with a regex.

Verified: npm run typecheck; check-patches (10/10 ready on 2.61.0.37);
check-gui (33 patches, 24 scripts compile); the TypeScript and Python
appliers produce identical scripts, byte-identical to the previous
definitions except one stock script with mixed line endings.

The 15 battle patches are migrated mechanically and still carry the
pending-review comment; they are rewritten by the LocalMP review.
2026-11-28 03:24:12 +08:00

156 lines
6.3 KiB
TypeScript

/**
* Patch definitions as stored on disk, one directory per change to the program's behaviour,
* under exe-patches/<domain>/<name>/:
*
* patch.jsonc id, title, features, required patches, the game versions it was verified
* on, and the bytes to write; comments explain the change and why the local
* service cannot provide it
* locate.jsonc how to find the site
*
* Unknown keys are rejected so that explanations stay in comments and in the patch notes
* instead of growing into data fields.
*/
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { parseJsonc } from '@wto/jsonc';
import { DefinitionError } from './errors.ts';
const PATCH_FILE = 'patch.jsonc';
const LOCATE_FILE = 'locate.jsonc';
const PATCH_KEYS = new Set(['id', 'title', 'features', 'requires', 'verified_on', 'edit']);
const EDIT_KEYS = new Set(['offset', 'asm', 'data', 'bytes', 'expect_original']);
const LOCATE_KEYS = new Set(['method', 'section', 'pattern']);
export interface PatchEdit {
/** Distance from the located site to the first byte written. */
readonly offset: number;
readonly payload: Uint8Array;
readonly expectOriginal: Uint8Array;
}
export interface LocateSpec {
readonly method: string;
readonly [key: string]: unknown;
}
export interface PatchDefinition {
readonly id: string;
readonly title: string;
readonly features: readonly string[];
readonly requires: readonly string[];
readonly verifiedOn: readonly string[];
readonly edit: PatchEdit;
readonly locate: LocateSpec;
readonly directory: string;
}
/** Every definition under `root`, sorted by id. */
export function loadPatches(root: string): PatchDefinition[] {
const definitions = findDefinitionDirectories(root).map(readDefinition);
rejectDuplicateIds(definitions);
rejectUnknownRequirements(definitions);
return definitions.sort((left, right) => left.id.localeCompare(right.id));
}
function findDefinitionDirectories(root: string): string[] {
const found: string[] = [];
for (const entry of readdirSync(root, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const directory = join(root, entry.name);
if (isFile(join(directory, PATCH_FILE))) found.push(directory);
else found.push(...findDefinitionDirectories(directory));
}
return found;
}
function readDefinition(directory: string): PatchDefinition {
const where = join(directory, PATCH_FILE);
const locateWhere = join(directory, LOCATE_FILE);
const patch = readJson(where);
const locate = readJson(locateWhere);
rejectUnknownKeys(patch, PATCH_KEYS, where);
rejectUnknownKeys(locate, LOCATE_KEYS, locateWhere);
if (typeof patch.id !== 'string' || typeof patch.title !== 'string') throw new DefinitionError(`${where}: needs string "id" and "title"`);
if (typeof locate.method !== 'string') throw new DefinitionError(`${locateWhere}: needs a string "method"`);
const verifiedOn = stringList(patch.verified_on, where, 'verified_on');
if (verifiedOn.length === 0) throw new DefinitionError(`${where}: "verified_on" must name at least one game version`);
return {
id: patch.id,
title: patch.title,
features: stringList(patch.features, where, 'features'),
requires: stringList(patch.requires, where, 'requires'),
verifiedOn,
edit: readEdit(patch.edit, where),
locate: locate as LocateSpec,
directory,
};
}
function readEdit(raw: unknown, where: string): PatchEdit {
if (!raw || typeof raw !== 'object') throw new DefinitionError(`${where}: "edit" must be an object`);
const edit = raw as Record<string, unknown>;
rejectUnknownKeys(edit, EDIT_KEYS, `${where} edit`);
const payload = hexBytes(edit.bytes, where, 'bytes');
const expectOriginal = hexBytes(edit.expect_original, where, 'expect_original');
if (payload.length !== expectOriginal.length) {
throw new DefinitionError(`${where}: bytes is ${payload.length} bytes but expect_original is ${expectOriginal.length}`);
}
const offset = edit.offset ?? 0;
if (typeof offset !== 'number' || !Number.isInteger(offset)) throw new DefinitionError(`${where}: edit.offset must be an integer`);
return { offset, payload, expectOriginal };
}
function hexBytes(value: unknown, where: string, key: string): Uint8Array {
if (typeof value !== 'string' || !/^([0-9a-fA-F]{2})*$/.test(value)) throw new DefinitionError(`${where}: edit.${key} must be a hex string`);
return Buffer.from(value, 'hex');
}
function stringList(value: unknown, where: string, key: string): string[] {
if (value === undefined) return [];
if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) throw new DefinitionError(`${where}: "${key}" must be a list of strings`);
return value;
}
function readJson(path: string): Record<string, unknown> {
let data: unknown;
try {
data = parseJsonc(readFileSync(path, 'utf-8'));
} catch (error) {
throw new DefinitionError(`${path}: ${(error as Error).message}`);
}
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new DefinitionError(`${path}: expected a JSON object`);
return data as Record<string, unknown>;
}
function rejectUnknownKeys(object: Record<string, unknown>, allowed: ReadonlySet<string>, where: string): void {
const unknown = Object.keys(object).filter((key) => !allowed.has(key));
if (unknown.length) {
throw new DefinitionError(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`);
}
}
function isFile(path: string): boolean {
try {
return statSync(path).isFile();
} catch {
return false;
}
}
function rejectDuplicateIds(definitions: readonly PatchDefinition[]): void {
const seen = new Map<string, string>();
for (const definition of definitions) {
const previous = seen.get(definition.id);
if (previous) throw new DefinitionError(`two definitions use id "${definition.id}": ${previous} and ${definition.directory}`);
seen.set(definition.id, definition.directory);
}
}
function rejectUnknownRequirements(definitions: readonly PatchDefinition[]): void {
const known = new Set(definitions.map((definition) => definition.id));
for (const definition of definitions) {
const unknown = definition.requires.filter((id) => !known.has(id));
if (unknown.length) throw new DefinitionError(`${definition.id} requires unknown patch(es): ${unknown.join(', ')}`);
}
}