Files
WT-Offline/apps/server/src/tuning/tuning-loader.ts
T

69 lines
2.8 KiB
TypeScript

/**
* Load one tuning file with multi-layer overrides:
* shipped defaults (`apps/server/tuning/<name>.jsonc`)
* -> each enabled mod's `<server.tuning>/<name>.jsonc` in load order
* -> player overrides (`<dataFolder>/tuning/<name>.jsonc`).
*
* Objects merge key by key; plain lists replace the base list; `{ "$listOps": [...] }`
* performs additive append/prepend/upsertBy/removeBy operations across layers.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseJsonc } from '@wto/jsonc';
import { mergeTuningLayer, type DiscoveredMod } from '@wto/mods';
import { TuningError, TuningReader } from './tuning-reader.ts';
const DEFAULTS_FOLDER = fileURLToPath(new URL('../../tuning/', import.meta.url));
const DEFAULT_MOD_TUNING_DIR = 'server/tuning';
export interface TuningFiles {
/** The merged content of <name>.jsonc, ready for typed reads. */
read(name: string): TuningReader;
}
export function tuningFiles(
dataFolder: string | null,
report: (line: string) => void,
proposed?: ReadonlyMap<string, Record<string, unknown>>,
mods: readonly DiscoveredMod[] = [],
): TuningFiles {
const overridesFolder = dataFolder === null ? null : join(dataFolder, 'tuning');
return {
read(name: string): TuningReader {
const fileName = `${name}.jsonc`;
let merged = parseFile(join(DEFAULTS_FOLDER, fileName));
for (const mod of mods) {
const modTuningDir = mod.manifest.server?.tuning ?? DEFAULT_MOD_TUNING_DIR;
const modFilePath = join(mod.rootDir, ...modTuningDir.split('/'), fileName);
if (!existsSync(modFilePath)) continue;
report(`tuning ${fileName}: applying mod "${mod.manifest.id}" overrides`);
try {
merged = mergeTuningLayer(merged, parseFile(modFilePath));
} catch (error) {
throw new TuningError(
`mod "${mod.manifest.id}" tuning ${fileName} merge failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
const candidate = proposed?.get(name);
if (candidate) return new TuningReader(fileName, mergeTuningLayer(merged, candidate));
if (overridesFolder === null) return new TuningReader(fileName, merged);
const overridePath = join(overridesFolder, fileName);
if (!existsSync(overridePath)) return new TuningReader(fileName, merged);
report(`tuning ${fileName}: using overrides from ${overridePath}`);
return new TuningReader(fileName, mergeTuningLayer(merged, parseFile(overridePath)));
},
};
}
function parseFile(path: string): unknown {
try {
return parseJsonc(readFileSync(path, 'utf8'));
} catch (error) {
throw new TuningError(`tuning file ${path} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
}
}