feat(mods): merge additive mod system, official map selector, and mod-dev-docs
# Conflicts: # apps/launcher/src/main/workers/build-worker.ts # apps/launcher/src/renderer/src/i18n/locales/en.json # apps/launcher/src/renderer/src/i18n/locales/zh-CN.json
This commit is contained in:
commit
d94c8fe687
103 files changed
+10829
-1621
No files matched your search
@@ -10,6 +10,7 @@ export { emptyBlock } from './model.ts';
|
||||
export { BlkFormatError } from './errors.ts';
|
||||
export { BlkLabel, decodeBlk, encodeBlk, type SharedNameContext } from './binary/format.ts';
|
||||
export { parseSharedNameMap, type SharedNameMap } from './shared-name-map.ts';
|
||||
export { appendParam, ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts';
|
||||
export { appendParam, cloneBlock, ensureBlock, findBlock, findParam, setParam, visitParams } from './tree.ts';
|
||||
export { formatBlkText } from './text/format-text.ts';
|
||||
export { isBinaryBlk, parseBlkText } from './text/parse-text.ts';
|
||||
export { singleVehiclePackId, stableGuid } from './stable-guid.ts';
|
||||
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* Parse a BLK document in Dagor's text syntax back into the typed in-memory model.
|
||||
*
|
||||
* Syntax source: DagorEngine prog/engine/ioSys/dataBlock/blk_read.cpp (BSD-3).
|
||||
* Supports C/C++ comments, quoted and bare identifiers, `~` string escapes, nested blocks,
|
||||
* optional semicolons, and every typed parameter suffix emitted by `format-text.ts`.
|
||||
*/
|
||||
import { BlkFormatError } from '../errors.ts';
|
||||
import { emptyBlock, type BlkBlock, type BlkValue } from '../model.ts';
|
||||
|
||||
export function isBinaryBlk(bytes: Uint8Array): boolean {
|
||||
if (bytes.length === 0) return false;
|
||||
const first = bytes[0]!;
|
||||
// Binary BLK labels used by DagorEngine (see binary/format.ts BlkLabel: 0x00..0x06, zstd 0x28).
|
||||
return first <= 0x06 || first === 0x28;
|
||||
}
|
||||
|
||||
export function parseBlkText(source: string): BlkBlock {
|
||||
const parser = new BlkTextParser(source);
|
||||
const root = emptyBlock('');
|
||||
parser.readBlockBody(root, false);
|
||||
return root;
|
||||
}
|
||||
|
||||
class BlkTextParser {
|
||||
readonly #text: string;
|
||||
#pos = 0;
|
||||
|
||||
constructor(text: string) {
|
||||
// Strip UTF-8 BOM if present.
|
||||
this.#text = text.startsWith('\uFEFF') ? text.slice(1) : text;
|
||||
}
|
||||
|
||||
readBlockBody(target: BlkBlock, expectClosingBrace: boolean): void {
|
||||
while (true) {
|
||||
this.#skipIgnored();
|
||||
if (this.#eof()) {
|
||||
if (expectClosingBrace) this.#fail('unexpected end of BLK text inside block');
|
||||
return;
|
||||
}
|
||||
if (this.#peek() === '}') {
|
||||
if (!expectClosingBrace) this.#fail('unexpected closing brace "}" at root');
|
||||
this.#pos += 1;
|
||||
return;
|
||||
}
|
||||
const key = this.#readIdentifierOrString();
|
||||
this.#skipIgnored();
|
||||
const ch = this.#peek();
|
||||
if (ch === '{') {
|
||||
this.#pos += 1;
|
||||
const child = emptyBlock(key);
|
||||
this.readBlockBody(child, true);
|
||||
target.blocks.push(child);
|
||||
continue;
|
||||
}
|
||||
if (ch === ':') {
|
||||
this.#pos += 1;
|
||||
const suffix = this.#readTypeSuffix();
|
||||
this.#skipHorizontalAndComments();
|
||||
if (this.#peek() !== '=') this.#fail(`expected "=" after type suffix ":${suffix}"`);
|
||||
this.#pos += 1;
|
||||
const value = this.#readValue(suffix);
|
||||
target.params.push({ name: key, value });
|
||||
continue;
|
||||
}
|
||||
// Untyped `include "..."` directive or unknown syntax.
|
||||
if (key === 'include' && (ch === '"' || ch === "'")) {
|
||||
const included = this.#readQuotedString();
|
||||
target.params.push({ name: 'include', value: { type: 'string', value: included } });
|
||||
continue;
|
||||
}
|
||||
this.#fail(`expected "{" or ":" after "${key}"`);
|
||||
}
|
||||
}
|
||||
|
||||
#readIdentifierOrString(): string {
|
||||
const ch = this.#peek();
|
||||
if (ch === '"' || ch === "'") return this.#readQuotedString();
|
||||
const start = this.#pos;
|
||||
while (!this.#eof()) {
|
||||
const c = this.#text[this.#pos]!;
|
||||
if (c === ':' || c === '{' || c === '}' || c === '=' || c === ';' || /\s/.test(c)) break;
|
||||
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
|
||||
this.#pos += 1;
|
||||
}
|
||||
if (this.#pos === start) this.#fail(`unexpected character "${ch ?? ''}"`);
|
||||
return this.#text.slice(start, this.#pos);
|
||||
}
|
||||
|
||||
#readTypeSuffix(): string {
|
||||
const start = this.#pos;
|
||||
while (!this.#eof() && /[A-Za-z0-9]/.test(this.#text[this.#pos]!)) this.#pos += 1;
|
||||
const suffix = this.#text.slice(start, this.#pos);
|
||||
if (!suffix) this.#fail('missing BLK type suffix after ":"');
|
||||
return suffix;
|
||||
}
|
||||
|
||||
#readValue(suffix: string): BlkValue {
|
||||
this.#skipHorizontalAndComments();
|
||||
switch (suffix) {
|
||||
case 't': return { type: 'string', value: this.#readStringValue() };
|
||||
case 'i': return { type: 'int', value: this.#readInt() };
|
||||
case 'i64': return { type: 'int64', value: this.#readBigInt() };
|
||||
case 'r': return { type: 'real', value: this.#readReal() };
|
||||
case 'b': return { type: 'bool', value: this.#readBool() };
|
||||
case 'p2': return { type: 'point2', value: this.#readReals(2) as [number, number] };
|
||||
case 'p3': return { type: 'point3', value: this.#readReals(3) as [number, number, number] };
|
||||
case 'p4': return { type: 'point4', value: this.#readReals(4) as [number, number, number, number] };
|
||||
case 'ip2': return { type: 'ipoint2', value: this.#readInts(2) as [number, number] };
|
||||
case 'ip3': return { type: 'ipoint3', value: this.#readInts(3) as [number, number, number] };
|
||||
case 'ip4': return { type: 'ipoint4', value: this.#readInts(4) as [number, number, number, number] };
|
||||
case 'c': return { type: 'color', value: this.#readColor() };
|
||||
case 'm': return { type: 'matrix', value: this.#readMatrix() };
|
||||
default: this.#fail(`unsupported BLK type suffix ":${suffix}"`);
|
||||
}
|
||||
}
|
||||
|
||||
#readStringValue(): string {
|
||||
const ch = this.#peek();
|
||||
if (ch === '"' || ch === "'") return this.#readQuotedString();
|
||||
// Unquoted single-line string terminated by newline, semicolon, brace, or comment.
|
||||
const start = this.#pos;
|
||||
while (!this.#eof()) {
|
||||
const c = this.#text[this.#pos]!;
|
||||
if (c === '\r' || c === '\n' || c === ';' || c === '}') break;
|
||||
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
|
||||
this.#pos += 1;
|
||||
}
|
||||
return this.#text.slice(start, this.#pos).trim();
|
||||
}
|
||||
|
||||
#readQuotedString(): string {
|
||||
const quote = this.#text[this.#pos]!;
|
||||
this.#pos += 1;
|
||||
let out = '';
|
||||
while (!this.#eof()) {
|
||||
const c = this.#text[this.#pos]!;
|
||||
this.#pos += 1;
|
||||
if (c === quote) return out;
|
||||
if (c === '~' && !this.#eof()) {
|
||||
const next = this.#text[this.#pos]!;
|
||||
this.#pos += 1;
|
||||
switch (next) {
|
||||
case 'n': out += '\n'; break;
|
||||
case 'r': out += '\r'; break;
|
||||
case 't': out += '\t'; break;
|
||||
case '~': out += '~'; break;
|
||||
case '"': out += '"'; break;
|
||||
case "'": out += "'"; break;
|
||||
default: out += next; break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out += c;
|
||||
}
|
||||
this.#fail('unterminated string literal');
|
||||
}
|
||||
|
||||
#readToken(): string {
|
||||
this.#skipHorizontalAndComments();
|
||||
const start = this.#pos;
|
||||
while (!this.#eof()) {
|
||||
const c = this.#text[this.#pos]!;
|
||||
if (c === ',' || c === ';' || c === '}' || c === ']' || /\s/.test(c)) break;
|
||||
if (c === '/' && (this.#text[this.#pos + 1] === '/' || this.#text[this.#pos + 1] === '*')) break;
|
||||
this.#pos += 1;
|
||||
}
|
||||
if (this.#pos === start) this.#fail('expected value token');
|
||||
return this.#text.slice(start, this.#pos);
|
||||
}
|
||||
|
||||
#readInt(): number {
|
||||
const raw = this.#readToken();
|
||||
const parsed = raw.startsWith('0x') || raw.startsWith('0X') ? Number.parseInt(raw, 16) : Number(raw);
|
||||
if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) this.#fail(`invalid integer "${raw}"`);
|
||||
return parsed | 0;
|
||||
}
|
||||
|
||||
#readBigInt(): bigint {
|
||||
const raw = this.#readToken();
|
||||
try {
|
||||
return BigInt(raw);
|
||||
} catch {
|
||||
this.#fail(`invalid int64 "${raw}"`);
|
||||
}
|
||||
}
|
||||
|
||||
#readReal(): number {
|
||||
const raw = this.#readToken();
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isFinite(parsed)) this.#fail(`invalid real "${raw}"`);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
#readBool(): boolean {
|
||||
const raw = this.#readToken().toLowerCase();
|
||||
if (raw === 'yes' || raw === 'true' || raw === '1') return true;
|
||||
if (raw === 'no' || raw === 'false' || raw === '0') return false;
|
||||
this.#fail(`invalid bool "${raw}"`);
|
||||
}
|
||||
|
||||
#readReals(count: number): number[] {
|
||||
const values: number[] = [];
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
if (i > 0) this.#expectComma();
|
||||
values.push(this.#readReal());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
#readInts(count: number): number[] {
|
||||
const values: number[] = [];
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
if (i > 0) this.#expectComma();
|
||||
values.push(this.#readInt());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
#readColor(): number {
|
||||
const channels = this.#readInts(4);
|
||||
const [r, g, b, a] = channels as [number, number, number, number];
|
||||
return (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) >>> 0;
|
||||
}
|
||||
|
||||
#readMatrix(): number[] {
|
||||
this.#expectChar('[');
|
||||
const values: number[] = [];
|
||||
for (let row = 0; row < 4; row += 1) {
|
||||
this.#skipIgnored();
|
||||
this.#expectChar('[');
|
||||
for (let col = 0; col < 3; col += 1) {
|
||||
if (col > 0) this.#expectComma();
|
||||
values.push(this.#readReal());
|
||||
}
|
||||
this.#skipHorizontalAndComments();
|
||||
this.#expectChar(']');
|
||||
this.#skipHorizontalAndComments();
|
||||
if (this.#peek() === ',') this.#pos += 1;
|
||||
}
|
||||
this.#skipIgnored();
|
||||
this.#expectChar(']');
|
||||
return values;
|
||||
}
|
||||
|
||||
#expectComma(): void {
|
||||
this.#skipHorizontalAndComments();
|
||||
if (this.#peek() !== ',') this.#fail('expected "," between tuple components');
|
||||
this.#pos += 1;
|
||||
}
|
||||
|
||||
#expectChar(expected: string): void {
|
||||
this.#skipHorizontalAndComments();
|
||||
if (this.#peek() !== expected) this.#fail(`expected "${expected}"`);
|
||||
this.#pos += 1;
|
||||
}
|
||||
|
||||
#skipIgnored(): void {
|
||||
while (!this.#eof()) {
|
||||
const c = this.#text[this.#pos]!;
|
||||
if (c === ';' || /\s/.test(c)) {
|
||||
this.#pos += 1;
|
||||
continue;
|
||||
}
|
||||
if (this.#skipComment()) continue;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#skipHorizontalAndComments(): void {
|
||||
while (!this.#eof()) {
|
||||
const c = this.#text[this.#pos]!;
|
||||
if (c === ' ' || c === '\t') {
|
||||
this.#pos += 1;
|
||||
continue;
|
||||
}
|
||||
if (this.#skipComment()) continue;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#skipComment(): boolean {
|
||||
if (this.#text[this.#pos] !== '/') return false;
|
||||
const next = this.#text[this.#pos + 1];
|
||||
if (next === '/') {
|
||||
this.#pos += 2;
|
||||
while (!this.#eof() && this.#text[this.#pos] !== '\n') this.#pos += 1;
|
||||
return true;
|
||||
}
|
||||
if (next === '*') {
|
||||
this.#pos += 2;
|
||||
while (!this.#eof()) {
|
||||
if (this.#text[this.#pos] === '*' && this.#text[this.#pos + 1] === '/') {
|
||||
this.#pos += 2;
|
||||
return true;
|
||||
}
|
||||
this.#pos += 1;
|
||||
}
|
||||
this.#fail('unterminated block comment');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#peek(): string | undefined {
|
||||
return this.#text[this.#pos];
|
||||
}
|
||||
|
||||
#eof(): boolean {
|
||||
return this.#pos >= this.#text.length;
|
||||
}
|
||||
|
||||
#fail(message: string): never {
|
||||
const prefix = this.#text.slice(0, this.#pos);
|
||||
const line = prefix.split('\n').length;
|
||||
throw new BlkFormatError(`BLK text parse error on line ${line}: ${message}`);
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,31 @@ export function appendParam(block: BlkBlock, name: string, value: BlkValue): voi
|
||||
block.params.push({ name, value });
|
||||
}
|
||||
|
||||
/** Deep-clone a BLK block tree, optionally under a new block name. */
|
||||
export function cloneBlock(block: BlkBlock, newName = block.name): BlkBlock {
|
||||
return {
|
||||
name: newName,
|
||||
params: block.params.map((param) => ({
|
||||
name: param.name,
|
||||
value: cloneValue(param.value),
|
||||
})),
|
||||
blocks: block.blocks.map((child) => cloneBlock(child)),
|
||||
};
|
||||
}
|
||||
|
||||
function cloneValue(value: BlkValue): BlkValue {
|
||||
switch (value.type) {
|
||||
case 'point2': return { type: 'point2', value: [...value.value] as [number, number] };
|
||||
case 'point3': return { type: 'point3', value: [...value.value] as [number, number, number] };
|
||||
case 'point4': return { type: 'point4', value: [...value.value] as [number, number, number, number] };
|
||||
case 'ipoint2': return { type: 'ipoint2', value: [...value.value] as [number, number] };
|
||||
case 'ipoint3': return { type: 'ipoint3', value: [...value.value] as [number, number, number] };
|
||||
case 'ipoint4': return { type: 'ipoint4', value: [...value.value] as [number, number, number, number] };
|
||||
case 'matrix': return { type: 'matrix', value: [...value.value] };
|
||||
default: return { ...value };
|
||||
}
|
||||
}
|
||||
|
||||
/** Visit every parameter of the tree, depth first, with the path of block names leading to it. */
|
||||
export function visitParams(block: BlkBlock, visit: (param: BlkParam, path: readonly string[]) => void,
|
||||
path: readonly string[] = []): void {
|
||||
|
||||
@@ -13,6 +13,6 @@ export { DefinitionError, LocateError, PatchError, PeFormatError, VerifyError }
|
||||
export { asObject, readJsonObject, rejectUnknownKeys, requiredString, stringList, variantObjects } from './json-fields.ts';
|
||||
export { NO_CONTEXT, type LocateContext } from './locate/index.ts';
|
||||
export { PeImage, type FunctionRange, type Section } from './pe-image.ts';
|
||||
export { describePlan, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts';
|
||||
export { describePlan, planAdditionalPatches, planPatches, type PatchFailure, type PatchPlan, type PlannedWrite } from './plan.ts';
|
||||
export { findSite, readSiteSpec, type FoundSite, type SiteSpec } from './site.ts';
|
||||
export { chooseVariant, type Chosen, type Variant } from './variants.ts';
|
||||
@@ -58,6 +58,67 @@ export function planPatches(image: PeImage, definitions: readonly PatchDefinitio
|
||||
return { writes, failures };
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan additive patches (such as declarative mod exe patches) on top of locked core writes.
|
||||
* Any patch that fails to locate/verify, depends on a failed patch, overlaps a protected core
|
||||
* write, or overlaps an earlier accepted additive write is recorded in `failures` rather than
|
||||
* throwing, so core offline isolation patches are never overwritten or broken.
|
||||
*/
|
||||
export function planAdditionalPatches(
|
||||
image: PeImage,
|
||||
definitions: readonly PatchDefinition[],
|
||||
protectedWrites: readonly PlannedWrite[],
|
||||
): PatchPlan {
|
||||
const planned = new Map<string, PlannedWrite>();
|
||||
const failed = new Map<string, string>();
|
||||
for (const definition of definitions) {
|
||||
try {
|
||||
const chosen = chooseVariant(definition.variants, (variant) => planVariant(image, variant));
|
||||
planned.set(definition.id, { patchId: definition.id, variant: chosen.variant.writtenFor, ...chosen.value });
|
||||
} catch (error) {
|
||||
if (!(error instanceof PatchError)) throw error;
|
||||
failed.set(definition.id, error.message);
|
||||
}
|
||||
}
|
||||
propagateFailures(definitions, failed);
|
||||
|
||||
const accepted: PlannedWrite[] = [];
|
||||
for (const definition of definitions) {
|
||||
if (failed.has(definition.id)) continue;
|
||||
const candidate = planned.get(definition.id)!;
|
||||
const coreConflict = findOverlappingWrite(candidate, protectedWrites);
|
||||
if (coreConflict) {
|
||||
failed.set(definition.id, `overlaps protected core patch "${coreConflict.patchId}" at ${hex(candidate.rva)}`);
|
||||
continue;
|
||||
}
|
||||
const earlierConflict = findOverlappingWrite(candidate, accepted);
|
||||
if (earlierConflict) {
|
||||
failed.set(definition.id, `overlaps earlier patch "${earlierConflict.patchId}" at ${hex(candidate.rva)}`);
|
||||
continue;
|
||||
}
|
||||
accepted.push(candidate);
|
||||
}
|
||||
// Re-propagate if an overlap rejection broke a downstream dependency.
|
||||
const beforeSecondPass = failed.size;
|
||||
propagateFailures(definitions, failed);
|
||||
const writes = failed.size === beforeSecondPass
|
||||
? accepted
|
||||
: accepted.filter((write) => !failed.has(write.patchId));
|
||||
const failures = definitions.filter((item) => failed.has(item.id))
|
||||
.map((item) => ({ patchId: item.id, features: item.features, reason: failed.get(item.id)! }));
|
||||
return { writes, failures };
|
||||
}
|
||||
|
||||
function findOverlappingWrite(candidate: PlannedWrite, existing: readonly PlannedWrite[]): PlannedWrite | undefined {
|
||||
const cStart = candidate.fileOffset;
|
||||
const cEnd = cStart + candidate.payload.length;
|
||||
return existing.find((write) => {
|
||||
const wStart = write.fileOffset;
|
||||
const wEnd = wStart + write.payload.length;
|
||||
return cStart < wEnd && wStart < cEnd;
|
||||
});
|
||||
}
|
||||
|
||||
export function describePlan(plan: PatchPlan): string {
|
||||
const lines = [`${plan.writes.length} patch(es) ready, ${plan.failures.length} unavailable`];
|
||||
for (const write of plan.writes) lines.push(` ready ${write.patchId} at ${hex(write.rva)} (variant ${write.variant})`);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "@wto/mods",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@wto/blk": "*",
|
||||
"@wto/jsonc": "*"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
/**
|
||||
* Structured, type-preserving incremental patches for BLK documents (`*.blk.patch.jsonc`).
|
||||
*
|
||||
* Allows multiple mods to add vehicles to config/shop.blk, adjust prices/BR in config/wpcost.blk,
|
||||
* tweak weapon/FM parameters, or clone an existing vehicle block and customize it without
|
||||
* shipping whole stock files.
|
||||
*/
|
||||
import {
|
||||
appendParam,
|
||||
cloneBlock,
|
||||
emptyBlock,
|
||||
ensureBlock,
|
||||
findParam,
|
||||
setParam,
|
||||
type BlkBlock,
|
||||
type BlkValue,
|
||||
type BlkValueType,
|
||||
} from '@wto/blk';
|
||||
import { parseJsonc } from '@wto/jsonc';
|
||||
|
||||
export interface BlkPathStep {
|
||||
readonly name: string;
|
||||
/** Zero-based occurrence index when multiple sibling blocks share the same name (e.g. `range[2]`). */
|
||||
readonly index?: number;
|
||||
}
|
||||
|
||||
export type BlkPatchValueInput =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| { readonly type: BlkValueType; readonly value: unknown };
|
||||
|
||||
export interface BlkBlockBlueprint {
|
||||
readonly name?: string;
|
||||
readonly params?: ReadonlyArray<{ readonly name: string; readonly value: BlkPatchValueInput }>;
|
||||
readonly blocks?: readonly BlkBlockBlueprint[];
|
||||
}
|
||||
|
||||
export type BlkPatchOp =
|
||||
| {
|
||||
readonly op: 'setParam';
|
||||
readonly path: readonly string[];
|
||||
readonly name: string;
|
||||
readonly value: BlkPatchValueInput;
|
||||
readonly createBlocks?: boolean;
|
||||
}
|
||||
| {
|
||||
readonly op: 'addParam';
|
||||
readonly path: readonly string[];
|
||||
readonly name: string;
|
||||
readonly value: BlkPatchValueInput;
|
||||
readonly createBlocks?: boolean;
|
||||
}
|
||||
| {
|
||||
readonly op: 'removeParam';
|
||||
readonly path: readonly string[];
|
||||
readonly name: string;
|
||||
readonly value?: string | number | boolean;
|
||||
}
|
||||
| {
|
||||
readonly op: 'upsertBlock';
|
||||
readonly path: readonly string[];
|
||||
readonly block?: BlkBlockBlueprint;
|
||||
}
|
||||
| {
|
||||
readonly op: 'addBlock';
|
||||
readonly path: readonly string[];
|
||||
readonly name: string;
|
||||
readonly block?: BlkBlockBlueprint;
|
||||
readonly before?: string;
|
||||
readonly after?: string;
|
||||
readonly createBlocks?: boolean;
|
||||
}
|
||||
| {
|
||||
readonly op: 'removeBlock';
|
||||
readonly path: readonly string[];
|
||||
}
|
||||
| {
|
||||
readonly op: 'cloneBlock';
|
||||
readonly from: readonly string[];
|
||||
readonly toParent: readonly string[];
|
||||
readonly newName: string;
|
||||
readonly replaceExisting?: boolean;
|
||||
readonly before?: string;
|
||||
readonly after?: string;
|
||||
readonly ops?: readonly BlkPatchOp[];
|
||||
};
|
||||
|
||||
export interface BlkPatchDocument {
|
||||
readonly ops: readonly BlkPatchOp[];
|
||||
}
|
||||
|
||||
export class BlkPatchError extends Error {
|
||||
override name = 'BlkPatchError';
|
||||
}
|
||||
|
||||
export function parseBlkPatchDocument(text: string, where = 'blk patch'): BlkPatchDocument {
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = parseJsonc(text);
|
||||
} catch (error) {
|
||||
throw new BlkPatchError(`${where}: cannot parse JSONC: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
throw new BlkPatchError(`${where}: root must be an object with an "ops" array`);
|
||||
}
|
||||
const opsRaw = (raw as Record<string, unknown>).ops;
|
||||
if (!Array.isArray(opsRaw)) {
|
||||
throw new BlkPatchError(`${where}: missing "ops" array`);
|
||||
}
|
||||
return { ops: opsRaw.map((item, idx) => validateOp(item, `${where}.ops[${idx}]`)) };
|
||||
}
|
||||
|
||||
export function applyBlkPatch(root: BlkBlock, patch: BlkPatchDocument, where = 'blk patch'): void {
|
||||
for (let i = 0; i < patch.ops.length; i += 1) {
|
||||
applyOp(root, patch.ops[i]!, `${where}.ops[${i}]`);
|
||||
}
|
||||
}
|
||||
|
||||
function applyOp(root: BlkBlock, op: BlkPatchOp, where: string): void {
|
||||
switch (op.op) {
|
||||
case 'setParam': {
|
||||
const target = resolveBlock(root, op.path, op.createBlocks ?? false, where);
|
||||
const existing = findParam(target, op.name);
|
||||
const value = toBlkValue(op.value, existing?.value.type, where);
|
||||
setParam(target, op.name, value);
|
||||
return;
|
||||
}
|
||||
case 'addParam': {
|
||||
const target = resolveBlock(root, op.path, op.createBlocks ?? false, where);
|
||||
const existing = findParam(target, op.name);
|
||||
const value = toBlkValue(op.value, existing?.value.type, where);
|
||||
appendParam(target, op.name, value);
|
||||
return;
|
||||
}
|
||||
case 'removeParam': {
|
||||
const target = tryResolveBlock(root, op.path);
|
||||
if (!target) return;
|
||||
target.params = target.params.filter((param) => {
|
||||
if (param.name !== op.name) return true;
|
||||
if (op.value === undefined) return false;
|
||||
return !paramValueMatchesPrimitive(param.value, op.value);
|
||||
});
|
||||
return;
|
||||
}
|
||||
case 'upsertBlock': {
|
||||
const target = resolveBlock(root, op.path, true, where);
|
||||
if (op.block) mergeBlockBlueprint(target, op.block, where);
|
||||
return;
|
||||
}
|
||||
case 'addBlock': {
|
||||
const parent = resolveBlock(root, op.path, op.createBlocks ?? false, where);
|
||||
const created = emptyBlock(op.name);
|
||||
if (op.block) mergeBlockBlueprint(created, op.block, where);
|
||||
insertBlockPositioned(parent, created, op.before, op.after);
|
||||
return;
|
||||
}
|
||||
case 'removeBlock': {
|
||||
if (op.path.length === 0) throw new BlkPatchError(`${where}: cannot remove root block`);
|
||||
const parent = tryResolveBlock(root, op.path.slice(0, -1));
|
||||
if (!parent) return;
|
||||
const step = parsePathStep(op.path[op.path.length - 1]!, where);
|
||||
const index = findChildBlockIndex(parent, step);
|
||||
if (index >= 0) parent.blocks.splice(index, 1);
|
||||
return;
|
||||
}
|
||||
case 'cloneBlock': {
|
||||
const source = resolveBlock(root, op.from, false, `${where}.from`);
|
||||
const parent = resolveBlock(root, op.toParent, true, `${where}.toParent`);
|
||||
const cloned = cloneBlock(source, op.newName);
|
||||
if (op.ops) {
|
||||
for (let i = 0; i < op.ops.length; i += 1) {
|
||||
applyOp(cloned, op.ops[i]!, `${where}.ops[${i}]`);
|
||||
}
|
||||
}
|
||||
if (op.replaceExisting) {
|
||||
const existingIdx = parent.blocks.findIndex((child) => child.name === op.newName);
|
||||
if (existingIdx >= 0) {
|
||||
parent.blocks[existingIdx] = cloned;
|
||||
return;
|
||||
}
|
||||
}
|
||||
insertBlockPositioned(parent, cloned, op.before, op.after);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function insertBlockPositioned(parent: BlkBlock, block: BlkBlock, before?: string, after?: string): void {
|
||||
if (before !== undefined) {
|
||||
const idx = parent.blocks.findIndex((child) => child.name === before);
|
||||
if (idx >= 0) {
|
||||
parent.blocks.splice(idx, 0, block);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (after !== undefined) {
|
||||
const idx = parent.blocks.findIndex((child) => child.name === after);
|
||||
if (idx >= 0) {
|
||||
parent.blocks.splice(idx + 1, 0, block);
|
||||
return;
|
||||
}
|
||||
}
|
||||
parent.blocks.push(block);
|
||||
}
|
||||
|
||||
function mergeBlockBlueprint(target: BlkBlock, blueprint: BlkBlockBlueprint, where: string): void {
|
||||
if (blueprint.params) {
|
||||
for (const [idx, param] of blueprint.params.entries()) {
|
||||
const existing = findParam(target, param.name);
|
||||
const value = toBlkValue(param.value, existing?.value.type, `${where}.params[${idx}]`);
|
||||
appendParam(target, param.name, value);
|
||||
}
|
||||
}
|
||||
if (blueprint.blocks) {
|
||||
for (const [idx, childBlueprint] of blueprint.blocks.entries()) {
|
||||
const name = childBlueprint.name;
|
||||
if (!name) throw new BlkPatchError(`${where}.blocks[${idx}]: child block must have a "name"`);
|
||||
const child = emptyBlock(name);
|
||||
mergeBlockBlueprint(child, childBlueprint, `${where}.blocks[${idx}]`);
|
||||
target.blocks.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function resolveBlock(root: BlkBlock, path: readonly string[], createMissing: boolean, where: string): BlkBlock {
|
||||
let current = root;
|
||||
for (const rawStep of path) {
|
||||
const step = parsePathStep(rawStep, where);
|
||||
const idx = findChildBlockIndex(current, step);
|
||||
if (idx >= 0) {
|
||||
current = current.blocks[idx]!;
|
||||
} else if (createMissing && step.index === undefined) {
|
||||
current = ensureBlock(current, step.name);
|
||||
} else {
|
||||
throw new BlkPatchError(`${where}: block "${rawStep}" not found along path [${path.join(' / ')}]`);
|
||||
}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function tryResolveBlock(root: BlkBlock, path: readonly string[]): BlkBlock | undefined {
|
||||
let current = root;
|
||||
for (const rawStep of path) {
|
||||
const step = parsePathStep(rawStep, 'path');
|
||||
const idx = findChildBlockIndex(current, step);
|
||||
if (idx < 0) return undefined;
|
||||
current = current.blocks[idx]!;
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function parsePathStep(raw: string, where: string): BlkPathStep {
|
||||
const match = /^(.+)\[(\d+)\]$/.exec(raw);
|
||||
if (!match) {
|
||||
if (!raw) throw new BlkPatchError(`${where}: empty path segment`);
|
||||
return { name: raw };
|
||||
}
|
||||
return { name: match[1]!, index: Number(match[2]!) };
|
||||
}
|
||||
|
||||
function findChildBlockIndex(parent: BlkBlock, step: BlkPathStep): number {
|
||||
const wanted = step.index ?? 0;
|
||||
let seen = 0;
|
||||
for (let i = 0; i < parent.blocks.length; i += 1) {
|
||||
if (parent.blocks[i]!.name !== step.name) continue;
|
||||
if (seen === wanted) return i;
|
||||
seen += 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function toBlkValue(input: BlkPatchValueInput, inferredType: BlkValueType | undefined, where: string): BlkValue {
|
||||
if (typeof input === 'string') return { type: 'string', value: input };
|
||||
if (typeof input === 'boolean') return { type: 'bool', value: input };
|
||||
if (typeof input === 'number') {
|
||||
if (inferredType === 'real') return { type: 'real', value: input };
|
||||
if (inferredType === 'int') return { type: 'int', value: input | 0 };
|
||||
if (inferredType === 'int64') return { type: 'int64', value: BigInt(Math.trunc(input)) };
|
||||
return Number.isInteger(input) ? { type: 'int', value: input | 0 } : { type: 'real', value: input };
|
||||
}
|
||||
if (!input || typeof input !== 'object') {
|
||||
throw new BlkPatchError(`${where}: invalid BLK value`);
|
||||
}
|
||||
const { type, value } = input;
|
||||
switch (type) {
|
||||
case 'string':
|
||||
if (typeof value !== 'string') throw new BlkPatchError(`${where}: string value expected`);
|
||||
return { type: 'string', value };
|
||||
case 'bool':
|
||||
if (typeof value !== 'boolean') throw new BlkPatchError(`${where}: bool value expected`);
|
||||
return { type: 'bool', value };
|
||||
case 'int':
|
||||
if (typeof value !== 'number' || !Number.isInteger(value)) throw new BlkPatchError(`${where}: int value expected`);
|
||||
return { type: 'int', value: value | 0 };
|
||||
case 'real':
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) throw new BlkPatchError(`${where}: real value expected`);
|
||||
return { type: 'real', value };
|
||||
case 'int64':
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') {
|
||||
return { type: 'int64', value: BigInt(value) };
|
||||
}
|
||||
throw new BlkPatchError(`${where}: int64 value expected`);
|
||||
case 'color':
|
||||
if (typeof value === 'number' && Number.isInteger(value)) return { type: 'color', value: value >>> 0 };
|
||||
if (Array.isArray(value) && value.length === 4 && value.every((n) => typeof n === 'number')) {
|
||||
const [r, g, b, a] = value as [number, number, number, number];
|
||||
return { type: 'color', value: (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff)) >>> 0 };
|
||||
}
|
||||
throw new BlkPatchError(`${where}: color expects integer or [r,g,b,a]`);
|
||||
case 'point2': return { type: 'point2', value: expectNumberTuple(value, 2, false, where) as [number, number] };
|
||||
case 'point3': return { type: 'point3', value: expectNumberTuple(value, 3, false, where) as [number, number, number] };
|
||||
case 'point4': return { type: 'point4', value: expectNumberTuple(value, 4, false, where) as [number, number, number, number] };
|
||||
case 'ipoint2': return { type: 'ipoint2', value: expectNumberTuple(value, 2, true, where) as [number, number] };
|
||||
case 'ipoint3': return { type: 'ipoint3', value: expectNumberTuple(value, 3, true, where) as [number, number, number] };
|
||||
case 'ipoint4': return { type: 'ipoint4', value: expectNumberTuple(value, 4, true, where) as [number, number, number, number] };
|
||||
case 'matrix': return { type: 'matrix', value: expectNumberTuple(value, 12, false, where) };
|
||||
default:
|
||||
throw new BlkPatchError(`${where}: unsupported BLK type "${String(type)}"`);
|
||||
}
|
||||
}
|
||||
|
||||
function expectNumberTuple(raw: unknown, length: number, integerOnly: boolean, where: string): number[] {
|
||||
if (!Array.isArray(raw) || raw.length !== length) {
|
||||
throw new BlkPatchError(`${where}: expected array of ${length} numbers`);
|
||||
}
|
||||
return raw.map((item) => {
|
||||
if (typeof item !== 'number' || !Number.isFinite(item) || (integerOnly && !Number.isInteger(item))) {
|
||||
throw new BlkPatchError(`${where}: invalid numeric element in tuple`);
|
||||
}
|
||||
return integerOnly ? (item | 0) : item;
|
||||
});
|
||||
}
|
||||
|
||||
function paramValueMatchesPrimitive(value: BlkValue, expected: string | number | boolean): boolean {
|
||||
if (typeof expected === 'string') return value.type === 'string' && value.value === expected;
|
||||
if (typeof expected === 'boolean') return value.type === 'bool' && value.value === expected;
|
||||
return (value.type === 'int' || value.type === 'real') && value.value === expected;
|
||||
}
|
||||
|
||||
function validateOp(raw: unknown, where: string): BlkPatchOp {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
throw new BlkPatchError(`${where}: operation must be an object`);
|
||||
}
|
||||
const obj = raw as Record<string, unknown>;
|
||||
const op = obj.op;
|
||||
switch (op) {
|
||||
case 'setParam':
|
||||
case 'addParam':
|
||||
return {
|
||||
op,
|
||||
path: expectStringArray(obj.path ?? [], `${where}.path`),
|
||||
name: expectNonEmptyString(obj.name, `${where}.name`),
|
||||
value: obj.value as BlkPatchValueInput,
|
||||
...(typeof obj.createBlocks === 'boolean' ? { createBlocks: obj.createBlocks } : {}),
|
||||
};
|
||||
case 'removeParam':
|
||||
return {
|
||||
op,
|
||||
path: expectStringArray(obj.path ?? [], `${where}.path`),
|
||||
name: expectNonEmptyString(obj.name, `${where}.name`),
|
||||
...(typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean'
|
||||
? { value: obj.value }
|
||||
: {}),
|
||||
};
|
||||
case 'upsertBlock':
|
||||
return {
|
||||
op,
|
||||
path: expectStringArray(obj.path, `${where}.path`),
|
||||
...(obj.block !== undefined ? { block: validateBlueprint(obj.block, `${where}.block`) } : {}),
|
||||
};
|
||||
case 'addBlock':
|
||||
return {
|
||||
op,
|
||||
path: expectStringArray(obj.path ?? [], `${where}.path`),
|
||||
name: expectNonEmptyString(obj.name, `${where}.name`),
|
||||
...(obj.block !== undefined ? { block: validateBlueprint(obj.block, `${where}.block`) } : {}),
|
||||
...(typeof obj.before === 'string' ? { before: obj.before } : {}),
|
||||
...(typeof obj.after === 'string' ? { after: obj.after } : {}),
|
||||
...(typeof obj.createBlocks === 'boolean' ? { createBlocks: obj.createBlocks } : {}),
|
||||
};
|
||||
case 'removeBlock':
|
||||
return {
|
||||
op,
|
||||
path: expectStringArray(obj.path, `${where}.path`),
|
||||
};
|
||||
case 'cloneBlock':
|
||||
return {
|
||||
op,
|
||||
from: expectStringArray(obj.from, `${where}.from`),
|
||||
toParent: expectStringArray(obj.toParent ?? [], `${where}.toParent`),
|
||||
newName: expectNonEmptyString(obj.newName, `${where}.newName`),
|
||||
...(typeof obj.replaceExisting === 'boolean' ? { replaceExisting: obj.replaceExisting } : {}),
|
||||
...(typeof obj.before === 'string' ? { before: obj.before } : {}),
|
||||
...(typeof obj.after === 'string' ? { after: obj.after } : {}),
|
||||
...(Array.isArray(obj.ops)
|
||||
? { ops: obj.ops.map((nested, idx) => validateOp(nested, `${where}.ops[${idx}]`)) }
|
||||
: {}),
|
||||
};
|
||||
default:
|
||||
throw new BlkPatchError(`${where}: unsupported op "${String(op)}"`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateBlueprint(raw: unknown, where: string): BlkBlockBlueprint {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
throw new BlkPatchError(`${where}: block blueprint must be an object`);
|
||||
}
|
||||
const obj = raw as Record<string, unknown>;
|
||||
const name = obj.name === undefined ? undefined : expectNonEmptyString(obj.name, `${where}.name`);
|
||||
const params = obj.params === undefined ? undefined : expectParamList(obj.params, `${where}.params`);
|
||||
const blocks = obj.blocks === undefined
|
||||
? undefined
|
||||
: (Array.isArray(obj.blocks)
|
||||
? obj.blocks.map((child, idx) => validateBlueprint(child, `${where}.blocks[${idx}]`))
|
||||
: (() => { throw new BlkPatchError(`${where}.blocks: must be an array`); })());
|
||||
return {
|
||||
...(name !== undefined ? { name } : {}),
|
||||
...(params !== undefined ? { params } : {}),
|
||||
...(blocks !== undefined ? { blocks } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function expectParamList(raw: unknown, where: string): Array<{ readonly name: string; readonly value: BlkPatchValueInput }> {
|
||||
if (!Array.isArray(raw)) throw new BlkPatchError(`${where}: must be an array`);
|
||||
return raw.map((item, idx) => {
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
||||
throw new BlkPatchError(`${where}[${idx}]: expected { name, value }`);
|
||||
}
|
||||
const entry = item as Record<string, unknown>;
|
||||
return {
|
||||
name: expectNonEmptyString(entry.name, `${where}[${idx}].name`),
|
||||
value: entry.value as BlkPatchValueInput,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function expectStringArray(raw: unknown, where: string): string[] {
|
||||
if (!Array.isArray(raw) || raw.some((item) => typeof item !== 'string' || item.length === 0)) {
|
||||
throw new BlkPatchError(`${where}: must be an array of non-empty strings`);
|
||||
}
|
||||
return raw as string[];
|
||||
}
|
||||
|
||||
function expectNonEmptyString(raw: unknown, where: string): string {
|
||||
if (typeof raw !== 'string' || raw.length === 0) {
|
||||
throw new BlkPatchError(`${where}: must be a non-empty string`);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Incremental semicolon-separated localization CSV merger for `lang.vromfs.bin` (`*.csv.patch.csv`).
|
||||
*
|
||||
* Keeps the stock file's column layout and quoting conventions while merging matching row keys
|
||||
* (column 0) and appending new entries from each enabled mod in load order.
|
||||
*/
|
||||
|
||||
export function mergeLocalizationCsv(baseCsv: string, patchCsv: string): string {
|
||||
const hasBom = baseCsv.startsWith('\uFEFF');
|
||||
const newline = baseCsv.includes('\r\n') ? '\r\n' : '\n';
|
||||
const cleanBase = hasBom ? baseCsv.slice(1) : baseCsv;
|
||||
const cleanPatch = patchCsv.startsWith('\uFEFF') ? patchCsv.slice(1) : patchCsv;
|
||||
|
||||
const baseLines = splitCsvLines(cleanBase);
|
||||
const patchLines = splitCsvLines(cleanPatch);
|
||||
if (baseLines.length === 0 || patchLines.length <= 1) return baseCsv;
|
||||
|
||||
const baseHeader = parseSemicolonRow(baseLines[0]!);
|
||||
const patchHeader = parseSemicolonRow(patchLines[0]!);
|
||||
const baseColIndex = new Map<string, number>();
|
||||
baseHeader.forEach((name, idx) => baseColIndex.set(name.trim(), idx));
|
||||
|
||||
const colMapping: Array<{ readonly patchIdx: number; readonly baseIdx: number }> = [];
|
||||
for (let pIdx = 1; pIdx < patchHeader.length; pIdx += 1) {
|
||||
const colName = patchHeader[pIdx]!.trim();
|
||||
const bIdx = baseColIndex.get(colName);
|
||||
if (bIdx !== undefined) colMapping.push({ patchIdx: pIdx, baseIdx: bIdx });
|
||||
}
|
||||
if (colMapping.length === 0) return baseCsv;
|
||||
|
||||
// Map existing key -> line index in baseLines for fast in-place updates.
|
||||
const rowIndexByKey = new Map<string, number>();
|
||||
for (let i = 1; i < baseLines.length; i += 1) {
|
||||
const line = baseLines[i]!;
|
||||
if (!line.trim()) continue;
|
||||
const key = firstField(line);
|
||||
if (key) rowIndexByKey.set(key, i);
|
||||
}
|
||||
|
||||
const outLines = [...baseLines];
|
||||
const trailingBlank = outLines.length > 0 && outLines[outLines.length - 1] === '';
|
||||
if (trailingBlank) outLines.pop();
|
||||
|
||||
for (let i = 1; i < patchLines.length; i += 1) {
|
||||
const line = patchLines[i]!;
|
||||
if (!line.trim()) continue;
|
||||
const patchCols = parseSemicolonRow(line);
|
||||
const key = patchCols[0] ?? '';
|
||||
if (!key) continue;
|
||||
|
||||
const existingIdx = rowIndexByKey.get(key);
|
||||
if (existingIdx !== undefined) {
|
||||
const merged = parseSemicolonRow(outLines[existingIdx]!);
|
||||
while (merged.length < baseHeader.length) merged.push('');
|
||||
for (const { patchIdx, baseIdx } of colMapping) {
|
||||
const replacement = patchCols[patchIdx];
|
||||
if (replacement !== undefined && replacement !== '') merged[baseIdx] = replacement;
|
||||
}
|
||||
outLines[existingIdx] = formatSemicolonRow(merged);
|
||||
} else {
|
||||
const created = new Array<string>(baseHeader.length).fill('');
|
||||
created[0] = key;
|
||||
for (const { patchIdx, baseIdx } of colMapping) {
|
||||
const val = patchCols[patchIdx];
|
||||
if (val !== undefined) created[baseIdx] = val;
|
||||
}
|
||||
rowIndexByKey.set(key, outLines.length);
|
||||
outLines.push(formatSemicolonRow(created));
|
||||
}
|
||||
}
|
||||
|
||||
const result = outLines.join(newline) + (trailingBlank ? newline : '');
|
||||
return hasBom ? `\uFEFF${result}` : result;
|
||||
}
|
||||
|
||||
function splitCsvLines(text: string): string[] {
|
||||
// Handle quoted fields that may span multiple lines.
|
||||
const lines: string[] = [];
|
||||
let current = '';
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
const ch = text[i]!;
|
||||
if (ch === '"') {
|
||||
if (inQuotes && text[i + 1] === '"') {
|
||||
current += '""';
|
||||
i += 1;
|
||||
} else {
|
||||
inQuotes = !inQuotes;
|
||||
current += ch;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!inQuotes && (ch === '\n' || (ch === '\r' && text[i + 1] === '\n'))) {
|
||||
lines.push(current);
|
||||
current = '';
|
||||
if (ch === '\r') i += 1;
|
||||
continue;
|
||||
}
|
||||
current += ch;
|
||||
}
|
||||
lines.push(current);
|
||||
return lines;
|
||||
}
|
||||
|
||||
function parseSemicolonRow(line: string): string[] {
|
||||
const fields: string[] = [];
|
||||
let current = '';
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < line.length; i += 1) {
|
||||
const ch = line[i]!;
|
||||
if (ch === '"') {
|
||||
if (inQuotes && line[i + 1] === '"') {
|
||||
current += '"';
|
||||
i += 1;
|
||||
} else {
|
||||
inQuotes = !inQuotes;
|
||||
}
|
||||
} else if (ch === ';' && !inQuotes) {
|
||||
fields.push(current);
|
||||
current = '';
|
||||
} else {
|
||||
current += ch;
|
||||
}
|
||||
}
|
||||
fields.push(current);
|
||||
return fields;
|
||||
}
|
||||
|
||||
function firstField(line: string): string {
|
||||
if (line.startsWith('"')) {
|
||||
const cols = parseSemicolonRow(line);
|
||||
return cols[0] ?? '';
|
||||
}
|
||||
const semi = line.indexOf(';');
|
||||
return semi >= 0 ? line.slice(0, semi) : line;
|
||||
}
|
||||
|
||||
function formatSemicolonRow(fields: readonly string[]): string {
|
||||
return fields.map((field) => `"${field.replaceAll('"', '""')}"`).join(';');
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/**
|
||||
* Discover installed mods inside the global mods directory and inspect their capabilities
|
||||
* (server tuning/script, client pack patches, GUI patches, declarative exe patches,
|
||||
* 3D model addons, and optional companion files).
|
||||
*/
|
||||
import { existsSync, readdirSync, statSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import { MOD_MANIFEST_FILE, readModManifest } from './manifest.ts';
|
||||
import {
|
||||
MODDABLE_CLIENT_PACKS,
|
||||
type DiscoveredMod,
|
||||
type ModContentSummary,
|
||||
type ModDiscoveryError,
|
||||
type ModDiscoveryResult,
|
||||
type ModManifest,
|
||||
type ModPackOperation,
|
||||
type ModRiskBadge,
|
||||
type ModdableClientPack,
|
||||
} from './types.ts';
|
||||
|
||||
const DEFAULT_SERVER_ENTRIES = ['server/index.ts', 'server/index.mjs', 'server/index.js'] as const;
|
||||
const DEFAULT_SERVER_TUNING_DIR = 'server/tuning';
|
||||
const BLK_PATCH_SUFFIX = '.patch.jsonc';
|
||||
const CSV_PATCH_SUFFIX = '.patch.csv';
|
||||
const CONFIG_BLK_PATCH_PATH = 'client/config-blk.patch.jsonc';
|
||||
|
||||
export function discoverMods(modsRootDir: string): ModDiscoveryResult {
|
||||
if (!existsSync(modsRootDir)) return { mods: [], errors: [] };
|
||||
|
||||
const mods: DiscoveredMod[] = [];
|
||||
const errors: ModDiscoveryError[] = [];
|
||||
const seenIds = new Map<string, string>();
|
||||
|
||||
let entries;
|
||||
try {
|
||||
entries = readdirSync(modsRootDir, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
return {
|
||||
mods: [],
|
||||
errors: [{ folderName: '.', rootDir: modsRootDir, reason: error instanceof Error ? error.message : String(error) }],
|
||||
};
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const rootDir = join(modsRootDir, entry.name);
|
||||
if (!existsSync(join(rootDir, MOD_MANIFEST_FILE))) continue;
|
||||
try {
|
||||
const manifest = readModManifest(rootDir);
|
||||
const duplicateFolder = seenIds.get(manifest.id);
|
||||
if (duplicateFolder) {
|
||||
errors.push({
|
||||
folderName: entry.name,
|
||||
rootDir,
|
||||
reason: `duplicate mod id "${manifest.id}" (already provided by folder "${duplicateFolder}")`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
seenIds.set(manifest.id, entry.name);
|
||||
const content = inspectModContent(rootDir, manifest);
|
||||
mods.push({ folderName: entry.name, rootDir, manifest, content });
|
||||
} catch (error) {
|
||||
errors.push({
|
||||
folderName: entry.name,
|
||||
rootDir,
|
||||
reason: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
mods.sort((left, right) => left.manifest.id.localeCompare(right.manifest.id));
|
||||
errors.sort((left, right) => left.folderName.localeCompare(right.folderName));
|
||||
return { mods, errors };
|
||||
}
|
||||
|
||||
export function inspectModContent(rootDir: string, manifest: ModManifest): ModContentSummary {
|
||||
const serverEntry = resolveServerEntry(rootDir, manifest);
|
||||
const tuningDirRel = manifest.server?.tuning ?? DEFAULT_SERVER_TUNING_DIR;
|
||||
const serverTuningFiles = listTuningFiles(rootDir, tuningDirRel);
|
||||
const packOperations = scanClientPackOperations(rootDir);
|
||||
const guiPatchDirs = scanPatchDirectories(rootDir, 'client/gui-patches');
|
||||
const exePatchDirs = scanPatchDirectories(rootDir, 'client/exe-patches');
|
||||
|
||||
const addonDir = join(rootDir, 'client', 'addon');
|
||||
const addonRelativeFiles = existsSync(addonDir) && isDirectory(addonDir)
|
||||
? listRelativeFiles(addonDir)
|
||||
: [];
|
||||
const hasClientAddon = addonRelativeFiles.length > 0;
|
||||
const addonHasGrpHdr = addonRelativeFiles.some((file) => file.toLowerCase() === 'res/grp_hdr.vromfs.bin');
|
||||
|
||||
const filesDir = join(rootDir, 'client', 'files');
|
||||
const clientFiles = existsSync(filesDir) && isDirectory(filesDir)
|
||||
? listRelativeFiles(filesDir)
|
||||
: [];
|
||||
|
||||
const configBlkPatch = isFile(join(rootDir, ...CONFIG_BLK_PATCH_PATH.split('/')))
|
||||
? CONFIG_BLK_PATCH_PATH
|
||||
: undefined;
|
||||
|
||||
const badges = computeRiskBadges({
|
||||
hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0 || configBlkPatch !== undefined,
|
||||
hasGui: guiPatchDirs.length > 0,
|
||||
hasScript: serverEntry !== undefined,
|
||||
hasExe: exePatchDirs.length > 0,
|
||||
});
|
||||
|
||||
return {
|
||||
...(serverEntry !== undefined ? { serverEntry } : {}),
|
||||
serverTuningFiles,
|
||||
packOperations,
|
||||
guiPatchDirs,
|
||||
exePatchDirs,
|
||||
hasClientAddon,
|
||||
addonHasGrpHdr,
|
||||
addonRelativeFiles,
|
||||
clientFiles,
|
||||
...(configBlkPatch !== undefined ? { configBlkPatch } : {}),
|
||||
badges,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveServerEntry(rootDir: string, manifest: ModManifest): string | undefined {
|
||||
if (manifest.server?.entry) {
|
||||
const full = join(rootDir, ...manifest.server.entry.split('/'));
|
||||
if (!isFile(full)) {
|
||||
throw new Error(`declared server.entry "${manifest.server.entry}" does not exist`);
|
||||
}
|
||||
return manifest.server.entry;
|
||||
}
|
||||
for (const candidate of DEFAULT_SERVER_ENTRIES) {
|
||||
if (isFile(join(rootDir, ...candidate.split('/')))) return candidate;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function listTuningFiles(rootDir: string, tuningDirRel: string): string[] {
|
||||
const dir = join(rootDir, ...tuningDirRel.split('/'));
|
||||
if (!isDirectory(dir)) return [];
|
||||
return readdirSync(dir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && entry.name.endsWith('.jsonc'))
|
||||
.map((entry) => entry.name.slice(0, -'.jsonc'.length))
|
||||
.sort();
|
||||
}
|
||||
|
||||
function scanClientPackOperations(rootDir: string): ModPackOperation[] {
|
||||
const packsRoot = join(rootDir, 'client', 'packs');
|
||||
if (!isDirectory(packsRoot)) return [];
|
||||
|
||||
const ops: ModPackOperation[] = [];
|
||||
for (const pack of MODDABLE_CLIENT_PACKS) {
|
||||
const packDir = join(packsRoot, ...pack.split('/'));
|
||||
if (!isDirectory(packDir)) continue;
|
||||
for (const rel of listRelativeFiles(packDir)) {
|
||||
const sourceRelativePath = `client/packs/${pack}/${rel}`;
|
||||
if (rel.toLowerCase().endsWith(BLK_PATCH_SUFFIX)) {
|
||||
ops.push({
|
||||
pack,
|
||||
targetPath: rel.slice(0, -BLK_PATCH_SUFFIX.length),
|
||||
action: 'blk-patch',
|
||||
sourceRelativePath,
|
||||
});
|
||||
} else if (rel.toLowerCase().endsWith(CSV_PATCH_SUFFIX)) {
|
||||
ops.push({
|
||||
pack,
|
||||
targetPath: rel.slice(0, -CSV_PATCH_SUFFIX.length),
|
||||
action: 'csv-patch',
|
||||
sourceRelativePath,
|
||||
});
|
||||
} else {
|
||||
ops.push({
|
||||
pack,
|
||||
targetPath: rel,
|
||||
action: 'file',
|
||||
sourceRelativePath,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return ops;
|
||||
}
|
||||
|
||||
function scanPatchDirectories(rootDir: string, subPath: string): string[] {
|
||||
const base = join(rootDir, ...subPath.split('/'));
|
||||
if (!isDirectory(base)) return [];
|
||||
const results: string[] = [];
|
||||
const walk = (current: string) => {
|
||||
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const full = join(current, entry.name);
|
||||
if (isFile(join(full, 'patch.jsonc'))) {
|
||||
results.push(relative(rootDir, full).replaceAll('\\', '/'));
|
||||
} else {
|
||||
walk(full);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(base);
|
||||
return results.sort();
|
||||
}
|
||||
|
||||
function listRelativeFiles(dir: string): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (current: string) => {
|
||||
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
||||
const full = join(current, entry.name);
|
||||
if (entry.isDirectory()) walk(full);
|
||||
else if (entry.isFile()) out.push(relative(dir, full).replaceAll('\\', '/'));
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
function computeRiskBadges(flags: {
|
||||
readonly hasData: boolean;
|
||||
readonly hasGui: boolean;
|
||||
readonly hasScript: boolean;
|
||||
readonly hasExe: boolean;
|
||||
}): ModRiskBadge[] {
|
||||
const badges: ModRiskBadge[] = [];
|
||||
if (flags.hasData || (!flags.hasGui && !flags.hasScript && !flags.hasExe)) badges.push('data');
|
||||
if (flags.hasGui) badges.push('gui');
|
||||
if (flags.hasScript) badges.push('script');
|
||||
if (flags.hasExe) badges.push('exe');
|
||||
return badges;
|
||||
}
|
||||
|
||||
function isFile(path: string): boolean {
|
||||
try {
|
||||
return statSync(path).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isDirectory(path: string): boolean {
|
||||
try {
|
||||
return statSync(path).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function touchedClientPacks(mods: readonly DiscoveredMod[]): ModdableClientPack[] {
|
||||
const set = new Set<ModdableClientPack>();
|
||||
for (const mod of mods) {
|
||||
for (const op of mod.content.packOperations) set.add(op.pack);
|
||||
if (mod.content.guiPatchDirs.length > 0) set.add('gui.vromfs.bin');
|
||||
if (mod.content.hasClientAddon) set.add('aces.vromfs.bin');
|
||||
}
|
||||
return MODDABLE_CLIENT_PACKS.filter((pack) => set.has(pack));
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Shared additive mod system core: manifest parsing, mod discovery, load-order & conflict
|
||||
* resolution, type-preserving BLK incremental patching, localization CSV merging, multi-layer
|
||||
* tuning `$listOps` merging, and experimental server mod contracts.
|
||||
*/
|
||||
export {
|
||||
MOD_API_VERSION,
|
||||
MOD_FORMAT_VERSION,
|
||||
MODDABLE_CLIENT_PACKS,
|
||||
resolveLocalizedText,
|
||||
type ClientModsConfig,
|
||||
type DiscoveredMod,
|
||||
type LocalizedText,
|
||||
type ModContentSummary,
|
||||
type ModDiscoveryError,
|
||||
type ModDiscoveryResult,
|
||||
type ModIssue,
|
||||
type ModIssueKind,
|
||||
type ModIssueSeverity,
|
||||
type ModManifest,
|
||||
type ModPackOperation,
|
||||
type ModPreset,
|
||||
type ModRiskBadge,
|
||||
type ModServerConfig,
|
||||
type ModdableClientPack,
|
||||
type PackFileAction,
|
||||
type ResolvedModLoadOrder,
|
||||
} from './types.ts';
|
||||
export {
|
||||
MOD_MANIFEST_FILE,
|
||||
ModManifestError,
|
||||
expectSafeRelativePath,
|
||||
parseModManifest,
|
||||
readModManifest,
|
||||
} from './manifest.ts';
|
||||
export { discoverMods, inspectModContent, touchedClientPacks } from './discovery.ts';
|
||||
export {
|
||||
computeAutoSortOrder,
|
||||
emptyClientModsConfig,
|
||||
matchesVersionPattern,
|
||||
normalizeClientModsConfig,
|
||||
resolveModLoadOrder,
|
||||
} from './resolve.ts';
|
||||
export {
|
||||
BlkPatchError,
|
||||
applyBlkPatch,
|
||||
parseBlkPatchDocument,
|
||||
type BlkBlockBlueprint,
|
||||
type BlkPatchDocument,
|
||||
type BlkPatchOp,
|
||||
type BlkPatchValueInput,
|
||||
type BlkPathStep,
|
||||
} from './blk-patch.ts';
|
||||
export { mergeLocalizationCsv } from './csv-patch.ts';
|
||||
export { mergeTuningLayer, type TuningListOp } from './tuning-merge.ts';
|
||||
export type {
|
||||
BattleFilterMissionsContext,
|
||||
BattleLiveFactContext,
|
||||
BattleMatchmakeContext,
|
||||
BattleMissionCandidate,
|
||||
BattleSettlementContext,
|
||||
ModCharHandler,
|
||||
ModCharRequest,
|
||||
ModCharResponse,
|
||||
ModCharWrapper,
|
||||
ModHttpHandler,
|
||||
ModHttpRequest,
|
||||
ModHttpResponse,
|
||||
ModLogger,
|
||||
ModMatchingHandler,
|
||||
ModMatchingRequest,
|
||||
ModMatchingWrapper,
|
||||
ModPlayerStorage,
|
||||
ModStorageApi,
|
||||
ServerModCataloguesView,
|
||||
ServerModDatasetsView,
|
||||
ServerModHooksApi,
|
||||
ServerModRoutesApi,
|
||||
WtoServerMod,
|
||||
WtoServerModContext,
|
||||
} from './server-api.ts';
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* Parse and validate `mod.jsonc` manifests.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { parseJsonc } from '@wto/jsonc';
|
||||
import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig } from './types.ts';
|
||||
|
||||
export const MOD_MANIFEST_FILE = 'mod.jsonc';
|
||||
|
||||
const MOD_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
||||
const ALLOWED_ROOT_KEYS = new Set([
|
||||
'format',
|
||||
'id',
|
||||
'name',
|
||||
'version',
|
||||
'author',
|
||||
'description',
|
||||
'api_version',
|
||||
'game_versions',
|
||||
'requires',
|
||||
'conflicts',
|
||||
'load_after',
|
||||
'load_before',
|
||||
'server',
|
||||
]);
|
||||
const ALLOWED_SERVER_KEYS = new Set(['entry', 'tuning']);
|
||||
|
||||
export class ModManifestError extends Error {
|
||||
override name = 'ModManifestError';
|
||||
}
|
||||
|
||||
export function readModManifest(modDir: string): ModManifest {
|
||||
const filePath = join(modDir, MOD_MANIFEST_FILE);
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = parseJsonc(readFileSync(filePath, 'utf8'));
|
||||
} catch (error) {
|
||||
throw new ModManifestError(`cannot parse ${MOD_MANIFEST_FILE}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
return parseModManifest(raw, filePath);
|
||||
}
|
||||
|
||||
export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModManifest {
|
||||
const obj = expectObject(raw, where);
|
||||
rejectUnknownKeys(obj, ALLOWED_ROOT_KEYS, where);
|
||||
|
||||
if (obj.format !== MOD_FORMAT_VERSION) {
|
||||
throw new ModManifestError(`${where}: "format" must be ${MOD_FORMAT_VERSION}`);
|
||||
}
|
||||
const id = expectString(obj.id, `${where} "id"`);
|
||||
if (!MOD_ID_PATTERN.test(id)) {
|
||||
throw new ModManifestError(`${where}: "id" must match ${MOD_ID_PATTERN.source} (got "${id}")`);
|
||||
}
|
||||
const name = expectLocalizedText(obj.name, `${where} "name"`);
|
||||
const version = expectString(obj.version, `${where} "version"`);
|
||||
const author = expectString(obj.author, `${where} "author"`);
|
||||
const description = obj.description === undefined ? undefined : expectLocalizedText(obj.description, `${where} "description"`);
|
||||
const apiVersion = expectString(obj.api_version, `${where} "api_version"`);
|
||||
const gameVersions = optionalStringList(obj.game_versions, `${where} "game_versions"`);
|
||||
const requires = optionalIdList(obj.requires, `${where} "requires"`, id);
|
||||
const conflicts = optionalIdList(obj.conflicts, `${where} "conflicts"`, id);
|
||||
const loadAfter = optionalIdList(obj.load_after, `${where} "load_after"`, id);
|
||||
const loadBefore = optionalIdList(obj.load_before, `${where} "load_before"`, id);
|
||||
const server = obj.server === undefined ? undefined : parseServerConfig(obj.server, `${where} "server"`);
|
||||
|
||||
return {
|
||||
format: MOD_FORMAT_VERSION,
|
||||
id,
|
||||
name,
|
||||
version,
|
||||
author,
|
||||
...(description !== undefined ? { description } : {}),
|
||||
apiVersion,
|
||||
gameVersions,
|
||||
requires,
|
||||
conflicts,
|
||||
loadAfter,
|
||||
loadBefore,
|
||||
...(server !== undefined ? { server } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseServerConfig(raw: unknown, where: string): ModServerConfig {
|
||||
const obj = expectObject(raw, where);
|
||||
rejectUnknownKeys(obj, ALLOWED_SERVER_KEYS, where);
|
||||
const entry = obj.entry === undefined ? undefined : expectSafeRelativePath(obj.entry, `${where} "entry"`);
|
||||
const tuning = obj.tuning === undefined ? undefined : expectSafeRelativePath(obj.tuning, `${where} "tuning"`);
|
||||
return {
|
||||
...(entry !== undefined ? { entry } : {}),
|
||||
...(tuning !== undefined ? { tuning } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function expectSafeRelativePath(raw: unknown, where: string): string {
|
||||
const text = expectString(raw, where).replaceAll('\\', '/');
|
||||
if (text.startsWith('/') || /^[A-Za-z]:/.test(text)) {
|
||||
throw new ModManifestError(`${where}: path must be relative to the mod folder (got "${text}")`);
|
||||
}
|
||||
const segments = text.split('/').filter((segment) => segment.length > 0);
|
||||
if (segments.length === 0 || segments.some((segment) => segment === '.' || segment === '..')) {
|
||||
throw new ModManifestError(`${where}: path must not contain "." or ".." segments (got "${text}")`);
|
||||
}
|
||||
return segments.join('/');
|
||||
}
|
||||
|
||||
function expectObject(value: unknown, where: string): Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new ModManifestError(`${where}: expected an object`);
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function rejectUnknownKeys(obj: Record<string, unknown>, allowed: ReadonlySet<string>, where: string): void {
|
||||
const unknown = Object.keys(obj).filter((key) => !allowed.has(key));
|
||||
if (unknown.length > 0) {
|
||||
throw new ModManifestError(`${where}: unknown field(s): ${unknown.join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
function expectString(value: unknown, where: string): string {
|
||||
if (typeof value !== 'string' || value.trim().length === 0) {
|
||||
throw new ModManifestError(`${where}: must be a non-empty string`);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function expectLocalizedText(value: unknown, where: string): LocalizedText {
|
||||
if (typeof value === 'string') {
|
||||
if (value.trim().length === 0) throw new ModManifestError(`${where}: must not be empty`);
|
||||
return value.trim();
|
||||
}
|
||||
const obj = expectObject(value, where);
|
||||
const entries = Object.entries(obj);
|
||||
if (entries.length === 0) throw new ModManifestError(`${where}: localized map must not be empty`);
|
||||
const out: Record<string, string> = {};
|
||||
for (const [lang, text] of entries) {
|
||||
out[lang] = expectString(text, `${where}.${lang}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function optionalStringList(value: unknown, where: string): readonly string[] {
|
||||
if (value === undefined) return [];
|
||||
if (!Array.isArray(value)) throw new ModManifestError(`${where}: must be an array of strings`);
|
||||
return value.map((item, index) => expectString(item, `${where}[${index}]`));
|
||||
}
|
||||
|
||||
function optionalIdList(value: unknown, where: string, selfId: string): readonly string[] {
|
||||
const ids = optionalStringList(value, where);
|
||||
const seen = new Set<string>();
|
||||
for (const id of ids) {
|
||||
if (!MOD_ID_PATTERN.test(id)) throw new ModManifestError(`${where}: invalid mod id "${id}"`);
|
||||
if (id === selfId) throw new ModManifestError(`${where}: mod cannot reference itself ("${id}")`);
|
||||
if (seen.has(id)) throw new ModManifestError(`${where}: duplicate mod id "${id}"`);
|
||||
seen.add(id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
/**
|
||||
* Resolve effective mod load order, check dependencies/conflicts/version compatibility,
|
||||
* detect overlapping pack or companion file targets, and offer topological auto-sorting.
|
||||
*/
|
||||
import {
|
||||
MOD_API_VERSION,
|
||||
type ClientModsConfig,
|
||||
type DiscoveredMod,
|
||||
type ModIssue,
|
||||
type ResolvedModLoadOrder,
|
||||
} from './types.ts';
|
||||
|
||||
export function emptyClientModsConfig(): ClientModsConfig {
|
||||
return {
|
||||
format: 1,
|
||||
order: [],
|
||||
enabled: {},
|
||||
activePresetId: null,
|
||||
presets: [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile a saved client config with the currently discovered mods:
|
||||
* keep saved order for known mods, append newly discovered mods alphabetically (disabled by default),
|
||||
* and drop removed mod ids from the active ordering without destroying saved presets.
|
||||
*/
|
||||
export function normalizeClientModsConfig(
|
||||
config: ClientModsConfig,
|
||||
discovered: readonly DiscoveredMod[],
|
||||
): ClientModsConfig {
|
||||
const knownIds = new Set(discovered.map((mod) => mod.manifest.id));
|
||||
const seen = new Set<string>();
|
||||
const order: string[] = [];
|
||||
for (const id of config.order) {
|
||||
if (knownIds.has(id) && !seen.has(id)) {
|
||||
seen.add(id);
|
||||
order.push(id);
|
||||
}
|
||||
}
|
||||
for (const mod of discovered) {
|
||||
if (!seen.has(mod.manifest.id)) {
|
||||
seen.add(mod.manifest.id);
|
||||
order.push(mod.manifest.id);
|
||||
}
|
||||
}
|
||||
const enabled: Record<string, boolean> = {};
|
||||
for (const id of order) {
|
||||
enabled[id] = config.enabled[id] === true;
|
||||
}
|
||||
return {
|
||||
format: 1,
|
||||
order,
|
||||
enabled,
|
||||
activePresetId: config.activePresetId,
|
||||
presets: config.presets,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveModLoadOrder(
|
||||
discovered: readonly DiscoveredMod[],
|
||||
config: Pick<ClientModsConfig, 'order' | 'enabled'>,
|
||||
gameVersion?: string | null,
|
||||
): ResolvedModLoadOrder {
|
||||
const byId = new Map(discovered.map((mod) => [mod.manifest.id, mod]));
|
||||
const orderedIds: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const id of config.order) {
|
||||
if (byId.has(id) && !seen.has(id)) {
|
||||
seen.add(id);
|
||||
orderedIds.push(id);
|
||||
}
|
||||
}
|
||||
for (const mod of discovered) {
|
||||
if (!seen.has(mod.manifest.id)) {
|
||||
seen.add(mod.manifest.id);
|
||||
orderedIds.push(mod.manifest.id);
|
||||
}
|
||||
}
|
||||
|
||||
const enabledMods = orderedIds
|
||||
.filter((id) => config.enabled[id] === true)
|
||||
.map((id) => byId.get(id)!);
|
||||
const enabledIndex = new Map(enabledMods.map((mod, index) => [mod.manifest.id, index]));
|
||||
const issues: ModIssue[] = [];
|
||||
|
||||
for (const mod of enabledMods) {
|
||||
const id = mod.manifest.id;
|
||||
const pos = enabledIndex.get(id)!;
|
||||
|
||||
if (mod.manifest.apiVersion !== MOD_API_VERSION) {
|
||||
issues.push({
|
||||
severity: 'warning',
|
||||
kind: 'api-version-mismatch',
|
||||
modId: id,
|
||||
detail: `mod targets api_version "${mod.manifest.apiVersion}", current experimental API is "${MOD_API_VERSION}"`,
|
||||
});
|
||||
}
|
||||
|
||||
if (gameVersion && mod.manifest.gameVersions.length > 0 && !matchesAnyVersionPattern(gameVersion, mod.manifest.gameVersions)) {
|
||||
issues.push({
|
||||
severity: 'warning',
|
||||
kind: 'game-version-mismatch',
|
||||
modId: id,
|
||||
detail: `mod lists game_versions [${mod.manifest.gameVersions.join(', ')}], client is ${gameVersion}`,
|
||||
});
|
||||
}
|
||||
|
||||
for (const reqId of mod.manifest.requires) {
|
||||
if (!byId.has(reqId)) {
|
||||
issues.push({
|
||||
severity: 'error',
|
||||
kind: 'missing-dependency',
|
||||
modId: id,
|
||||
otherModId: reqId,
|
||||
detail: `requires missing mod "${reqId}"`,
|
||||
});
|
||||
} else if (!enabledIndex.has(reqId)) {
|
||||
issues.push({
|
||||
severity: 'error',
|
||||
kind: 'dependency-disabled',
|
||||
modId: id,
|
||||
otherModId: reqId,
|
||||
detail: `requires disabled mod "${reqId}"`,
|
||||
});
|
||||
} else if (enabledIndex.get(reqId)! > pos) {
|
||||
issues.push({
|
||||
severity: 'warning',
|
||||
kind: 'dependency-order',
|
||||
modId: id,
|
||||
otherModId: reqId,
|
||||
detail: `loaded before required dependency "${reqId}"`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const conflictId of mod.manifest.conflicts) {
|
||||
if (enabledIndex.has(conflictId) && id < conflictId) {
|
||||
issues.push({
|
||||
severity: 'error',
|
||||
kind: 'declared-conflict',
|
||||
modId: id,
|
||||
otherModId: conflictId,
|
||||
detail: `declares incompatibility with "${conflictId}"`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const afterId of mod.manifest.loadAfter) {
|
||||
const otherPos = enabledIndex.get(afterId);
|
||||
if (otherPos !== undefined && otherPos > pos) {
|
||||
issues.push({
|
||||
severity: 'warning',
|
||||
kind: 'load-order-hint',
|
||||
modId: id,
|
||||
otherModId: afterId,
|
||||
detail: `recommends loading after "${afterId}"`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const beforeId of mod.manifest.loadBefore) {
|
||||
const otherPos = enabledIndex.get(beforeId);
|
||||
if (otherPos !== undefined && otherPos < pos) {
|
||||
issues.push({
|
||||
severity: 'warning',
|
||||
kind: 'load-order-hint',
|
||||
modId: id,
|
||||
otherModId: beforeId,
|
||||
detail: `recommends loading before "${beforeId}"`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
detectTargetOverlaps(enabledMods, issues);
|
||||
|
||||
return {
|
||||
enabledMods,
|
||||
issues,
|
||||
hasBlockingErrors: issues.some((issue) => issue.severity === 'error'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Topologically sort mods using `requires`, `load_after`, and `load_before` constraints.
|
||||
* Falls back gracefully to existing relative order when cycles exist.
|
||||
*/
|
||||
export function computeAutoSortOrder(
|
||||
discovered: readonly DiscoveredMod[],
|
||||
currentOrder: readonly string[],
|
||||
): string[] {
|
||||
const rank = new Map<string, number>();
|
||||
currentOrder.forEach((id, index) => rank.set(id, index));
|
||||
const ids = discovered.map((mod) => mod.manifest.id);
|
||||
const idSet = new Set(ids);
|
||||
const edges = new Map<string, Set<string>>(ids.map((id) => [id, new Set()]));
|
||||
const inDegree = new Map<string, number>(ids.map((id) => [id, 0]));
|
||||
|
||||
const addEdge = (before: string, after: string) => {
|
||||
if (!idSet.has(before) || !idSet.has(after) || before === after) return;
|
||||
const outgoing = edges.get(before)!;
|
||||
if (!outgoing.has(after)) {
|
||||
outgoing.add(after);
|
||||
inDegree.set(after, (inDegree.get(after) ?? 0) + 1);
|
||||
}
|
||||
};
|
||||
|
||||
for (const mod of discovered) {
|
||||
const id = mod.manifest.id;
|
||||
for (const req of mod.manifest.requires) addEdge(req, id);
|
||||
for (const after of mod.manifest.loadAfter) addEdge(after, id);
|
||||
for (const before of mod.manifest.loadBefore) addEdge(id, before);
|
||||
}
|
||||
|
||||
const comparePriority = (a: string, b: string) => {
|
||||
const ra = rank.get(a) ?? Number.MAX_SAFE_INTEGER;
|
||||
const rb = rank.get(b) ?? Number.MAX_SAFE_INTEGER;
|
||||
return ra !== rb ? ra - rb : a.localeCompare(b);
|
||||
};
|
||||
|
||||
const ready = ids.filter((id) => (inDegree.get(id) ?? 0) === 0).sort(comparePriority);
|
||||
const result: string[] = [];
|
||||
|
||||
while (ready.length > 0) {
|
||||
const next = ready.shift()!;
|
||||
result.push(next);
|
||||
for (const target of edges.get(next)!) {
|
||||
const deg = (inDegree.get(target) ?? 1) - 1;
|
||||
inDegree.set(target, deg);
|
||||
if (deg === 0) {
|
||||
ready.push(target);
|
||||
ready.sort(comparePriority);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (result.length < ids.length) {
|
||||
const placed = new Set(result);
|
||||
const remaining = ids.filter((id) => !placed.has(id)).sort(comparePriority);
|
||||
result.push(...remaining);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function detectTargetOverlaps(enabledMods: readonly DiscoveredMod[], issues: ModIssue[]): void {
|
||||
const packFiles = new Map<string, string>();
|
||||
const packPatches = new Map<string, string>();
|
||||
const companionFiles = new Map<string, string>();
|
||||
const tuningFiles = new Map<string, string>();
|
||||
|
||||
for (const mod of enabledMods) {
|
||||
const id = mod.manifest.id;
|
||||
|
||||
for (const op of mod.content.packOperations) {
|
||||
const key = `${op.pack}:${op.targetPath.toLowerCase()}`;
|
||||
if (op.action === 'file') {
|
||||
const previous = packFiles.get(key) ?? packPatches.get(key);
|
||||
if (previous && previous !== id) {
|
||||
issues.push({
|
||||
severity: 'warning',
|
||||
kind: 'pack-file-override',
|
||||
modId: id,
|
||||
otherModId: previous,
|
||||
detail: `replaces "${op.pack}/${op.targetPath}" already modified by "${previous}"`,
|
||||
});
|
||||
}
|
||||
packFiles.set(key, id);
|
||||
} else {
|
||||
const previousFile = packFiles.get(key);
|
||||
const previousPatch = packPatches.get(key);
|
||||
if (previousFile && previousFile !== id) {
|
||||
issues.push({
|
||||
severity: 'info',
|
||||
kind: 'pack-blk-shared-target',
|
||||
modId: id,
|
||||
otherModId: previousFile,
|
||||
detail: `patches "${op.pack}/${op.targetPath}" after "${previousFile}"`,
|
||||
});
|
||||
} else if (previousPatch && previousPatch !== id) {
|
||||
issues.push({
|
||||
severity: 'info',
|
||||
kind: 'pack-blk-shared-target',
|
||||
modId: id,
|
||||
otherModId: previousPatch,
|
||||
detail: `merges into "${op.pack}/${op.targetPath}" after "${previousPatch}"`,
|
||||
});
|
||||
}
|
||||
packPatches.set(key, id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const file of mod.content.clientFiles) {
|
||||
const key = file.toLowerCase();
|
||||
const previous = companionFiles.get(key);
|
||||
if (previous && previous !== id) {
|
||||
issues.push({
|
||||
severity: 'warning',
|
||||
kind: 'client-file-conflict',
|
||||
modId: id,
|
||||
otherModId: previous,
|
||||
detail: `companion file "${file}" overrides "${previous}"`,
|
||||
});
|
||||
}
|
||||
companionFiles.set(key, id);
|
||||
}
|
||||
|
||||
for (const tuning of mod.content.serverTuningFiles) {
|
||||
const key = tuning.toLowerCase();
|
||||
const previous = tuningFiles.get(key);
|
||||
if (previous && previous !== id) {
|
||||
issues.push({
|
||||
severity: 'info',
|
||||
kind: 'tuning-file-shared',
|
||||
modId: id,
|
||||
otherModId: previous,
|
||||
detail: `merges server tuning "${tuning}.jsonc" after "${previous}"`,
|
||||
});
|
||||
}
|
||||
tuningFiles.set(key, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function matchesVersionPattern(version: string, pattern: string): boolean {
|
||||
if (pattern === '*') return true;
|
||||
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*');
|
||||
return new RegExp(`^${escaped}$`).test(version);
|
||||
}
|
||||
|
||||
function matchesAnyVersionPattern(version: string, patterns: readonly string[]): boolean {
|
||||
return patterns.some((pattern) => matchesVersionPattern(version, pattern));
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* Public TypeScript contract for WTOffline server-side JS/TS mods.
|
||||
*
|
||||
* EXPERIMENTAL / UNSTABLE:
|
||||
* WTOffline is in early development. Internal server types, dataset shapes, hook signatures,
|
||||
* and route contracts may change without backwards compatibility across releases. Mod authors
|
||||
* using server scripts should expect breaking changes and maintain compatibility with updates.
|
||||
*/
|
||||
import type { BlkBlock } from '@wto/blk';
|
||||
import type { ModManifest } from './types.ts';
|
||||
|
||||
export interface ModLogger {
|
||||
info(message: string): void;
|
||||
warn(message: string): void;
|
||||
error(message: string): void;
|
||||
}
|
||||
|
||||
/** Per-account JSON storage isolated under `<dataFolder>/saves/<userId>/mods/<modId>.json`. */
|
||||
export interface ModPlayerStorage {
|
||||
read<T = unknown>(): T | undefined;
|
||||
write(value: unknown): void;
|
||||
remove(): void;
|
||||
}
|
||||
|
||||
export interface ModStorageApi {
|
||||
/** Storage scoped to one local player account (never mutates stock `profile.blk`). */
|
||||
forPlayer(userId: string): ModPlayerStorage;
|
||||
/** Shared mod storage under `<dataFolder>/mods-data/<modId>.json`. */
|
||||
shared(): ModPlayerStorage;
|
||||
}
|
||||
|
||||
/** Mutable snapshot of extracted static datasets exposed before domain catalogues are built. */
|
||||
export interface ServerModDatasetsView {
|
||||
readonly vehicles: unknown[];
|
||||
readonly battleEconomy: Record<string, unknown>;
|
||||
readonly battleSpawnRules: unknown;
|
||||
readonly multiplayerMissions: Record<string, unknown>;
|
||||
readonly uiLabels: Record<string, unknown>;
|
||||
readonly unitNames: Record<string, unknown>;
|
||||
/** Escape hatch: read or replace any dataset object by its dataset id. */
|
||||
get<T = unknown>(datasetId: string): T | undefined;
|
||||
set(datasetId: string, value: unknown): void;
|
||||
}
|
||||
|
||||
/** Exposed domain catalogues and services after server initialization. */
|
||||
export interface ServerModCataloguesView {
|
||||
readonly tuning: Readonly<Record<string, unknown>>;
|
||||
readonly gameModes: unknown;
|
||||
readonly profiles: unknown;
|
||||
readonly accounts: unknown;
|
||||
readonly research: unknown;
|
||||
readonly equipment: unknown;
|
||||
readonly repair: unknown;
|
||||
readonly store: unknown;
|
||||
readonly inventory: unknown;
|
||||
readonly trophies: unknown;
|
||||
readonly items: unknown;
|
||||
readonly crew: unknown;
|
||||
readonly decor: unknown;
|
||||
readonly unlocks: unknown;
|
||||
readonly clans: unknown;
|
||||
readonly battleMatchmaker: unknown;
|
||||
readonly battleEconomy: unknown;
|
||||
readonly battleStreaks: unknown;
|
||||
readonly notifyInventoryChanged: () => void;
|
||||
readonly notifyUser: (userId: string, eventName: string, payload: Record<string, unknown>) => void;
|
||||
}
|
||||
|
||||
export interface BattleMatchmakeContext {
|
||||
readonly userId: string;
|
||||
readonly eventName: string;
|
||||
/** Mutable room / matchmake request parameters or generated launch plan. */
|
||||
readonly request: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BattleMissionCandidate {
|
||||
readonly name: string;
|
||||
readonly path: string;
|
||||
readonly level?: string;
|
||||
readonly type?: string;
|
||||
readonly locName?: string;
|
||||
readonly postfix?: string;
|
||||
}
|
||||
|
||||
export interface BattleFilterMissionsContext {
|
||||
readonly userId: string;
|
||||
readonly modeId: number;
|
||||
readonly modeName: string;
|
||||
readonly economicName: string;
|
||||
readonly minMrank: number;
|
||||
readonly maxMrank: number;
|
||||
readonly missions: readonly BattleMissionCandidate[];
|
||||
}
|
||||
|
||||
export interface BattleLiveFactContext {
|
||||
readonly userId: string;
|
||||
readonly roomId: string;
|
||||
readonly fact: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BattleSettlementContext {
|
||||
readonly userId: string;
|
||||
readonly roomId: string;
|
||||
/** Mutable settlement payload before final rewards are committed to the profile. */
|
||||
readonly summary: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ModCharRequest {
|
||||
readonly action: string;
|
||||
readonly userId: string;
|
||||
readonly headers: Readonly<Record<string, string | undefined>>;
|
||||
readonly body: Buffer;
|
||||
readonly query: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface ModCharResponse {
|
||||
readonly status?: number;
|
||||
readonly contentType?: string;
|
||||
readonly headers?: Readonly<Record<string, string>>;
|
||||
readonly body: Buffer | Uint8Array | string;
|
||||
}
|
||||
|
||||
export type ModCharHandler = (request: ModCharRequest) => ModCharResponse | Promise<ModCharResponse>;
|
||||
export type ModCharWrapper = (
|
||||
request: ModCharRequest,
|
||||
next: (request: ModCharRequest) => Promise<ModCharResponse>,
|
||||
) => ModCharResponse | Promise<ModCharResponse>;
|
||||
|
||||
export interface ModMatchingRequest {
|
||||
readonly method: string;
|
||||
readonly params: Readonly<Record<string, unknown>>;
|
||||
readonly userId: string | undefined;
|
||||
}
|
||||
|
||||
export type ModMatchingHandler = (request: ModMatchingRequest) => Record<string, unknown>;
|
||||
export type ModMatchingWrapper = (
|
||||
request: ModMatchingRequest,
|
||||
next: (request: ModMatchingRequest) => Record<string, unknown>,
|
||||
) => Record<string, unknown>;
|
||||
|
||||
export interface ModHttpRequest {
|
||||
readonly method: string;
|
||||
readonly path: string;
|
||||
readonly query: Readonly<Record<string, string>>;
|
||||
readonly headers: Readonly<Record<string, string | undefined>>;
|
||||
readonly body: Buffer;
|
||||
}
|
||||
|
||||
export interface ModHttpResponse {
|
||||
readonly status?: number;
|
||||
readonly contentType?: string;
|
||||
readonly headers?: Readonly<Record<string, string>>;
|
||||
readonly body: Buffer | Uint8Array | string;
|
||||
}
|
||||
|
||||
export type ModHttpHandler = (request: ModHttpRequest) => ModHttpResponse | Promise<ModHttpResponse>;
|
||||
|
||||
export interface ServerModHooksApi {
|
||||
onDatasetsLoaded(handler: (datasets: ServerModDatasetsView) => void | Promise<void>): void;
|
||||
onCataloguesReady(handler: (catalogues: ServerModCataloguesView) => void | Promise<void>): void;
|
||||
onServerListening(handler: (info: { readonly port: number }) => void | Promise<void>): void;
|
||||
onServerClosing(handler: () => void | Promise<void>): void;
|
||||
readonly profile: {
|
||||
onRefresh(handler: (profile: BlkBlock, userId: string) => void): void;
|
||||
};
|
||||
readonly battle: {
|
||||
onBeforeMatchmake(handler: (ctx: BattleMatchmakeContext) => void): void;
|
||||
/** Filter or reorder candidate missions before matchmaking picks one; return the desired subset. */
|
||||
onFilterMissions(handler: (ctx: BattleFilterMissionsContext) => readonly BattleMissionCandidate[] | void): void;
|
||||
onLiveFact(handler: (ctx: BattleLiveFactContext) => void): void;
|
||||
onAfterSettle(handler: (ctx: BattleSettlementContext) => void): void;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ServerModRoutesApi {
|
||||
readonly char: {
|
||||
register(action: string, handler: ModCharHandler): void;
|
||||
wrap(action: string, wrapper: ModCharWrapper): void;
|
||||
};
|
||||
readonly matching: {
|
||||
register(method: string, handler: ModMatchingHandler): void;
|
||||
wrap(method: string, wrapper: ModMatchingWrapper): void;
|
||||
};
|
||||
readonly http: {
|
||||
/** Register a route under `/mods/<modId>/...` (automatically namespaced to this mod). */
|
||||
register(subPath: string, handler: ModHttpHandler): void;
|
||||
};
|
||||
}
|
||||
|
||||
export interface WtoServerModContext {
|
||||
readonly apiVersion: string;
|
||||
readonly manifest: ModManifest;
|
||||
readonly modDir: string;
|
||||
readonly gameFolder: string;
|
||||
readonly dataFolder: string;
|
||||
readonly port: number;
|
||||
readonly logger: ModLogger;
|
||||
readonly storage: ModStorageApi;
|
||||
readonly hooks: ServerModHooksApi;
|
||||
readonly routes: ServerModRoutesApi;
|
||||
}
|
||||
|
||||
export interface WtoServerMod {
|
||||
setup(ctx: WtoServerModContext): void | Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Multi-layer tuning merge helper with additive list operations (`$listOps`).
|
||||
*
|
||||
* Objects merge key-by-key. Plain arrays replace the base value (preserving existing player
|
||||
* override behaviour). An object containing only `{ "$listOps": [...] }` applies incremental
|
||||
* append/prepend/upsertBy/removeBy operations to the base array so multiple mods can add
|
||||
* store packs, redeem codes, trophies, or preset clans without clobbering one another.
|
||||
*/
|
||||
|
||||
export type TuningListOp =
|
||||
| { readonly op: 'append'; readonly items: readonly unknown[] }
|
||||
| { readonly op: 'prepend'; readonly items: readonly unknown[] }
|
||||
| { readonly op: 'upsertBy'; readonly key: string; readonly item: Record<string, unknown> }
|
||||
| { readonly op: 'removeBy'; readonly key: string; readonly value: unknown };
|
||||
|
||||
export function mergeTuningLayer(base: unknown, override: unknown): unknown {
|
||||
if (isListOpsEnvelope(override)) {
|
||||
const list = Array.isArray(base) ? [...base] : [];
|
||||
return applyListOps(list, override.$listOps);
|
||||
}
|
||||
if (!isPlainObject(base) || !isPlainObject(override)) return override;
|
||||
const merged: Record<string, unknown> = { ...base };
|
||||
for (const [key, value] of Object.entries(override)) {
|
||||
merged[key] = key in base ? mergeTuningLayer(base[key], value) : value;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
function applyListOps(base: unknown[], ops: readonly unknown[]): unknown[] {
|
||||
const result = [...base];
|
||||
for (const rawOp of ops) {
|
||||
if (!isPlainObject(rawOp) || typeof rawOp.op !== 'string') {
|
||||
throw new Error('invalid $listOps entry: expected object with string "op"');
|
||||
}
|
||||
switch (rawOp.op) {
|
||||
case 'append':
|
||||
if (!Array.isArray(rawOp.items)) throw new Error('$listOps append requires an "items" array');
|
||||
result.push(...rawOp.items);
|
||||
break;
|
||||
case 'prepend':
|
||||
if (!Array.isArray(rawOp.items)) throw new Error('$listOps prepend requires an "items" array');
|
||||
result.unshift(...rawOp.items);
|
||||
break;
|
||||
case 'upsertBy': {
|
||||
if (typeof rawOp.key !== 'string' || !isPlainObject(rawOp.item)) {
|
||||
throw new Error('$listOps upsertBy requires string "key" and object "item"');
|
||||
}
|
||||
const matchValue = rawOp.item[rawOp.key];
|
||||
const idx = result.findIndex((entry) => isPlainObject(entry) && entry[rawOp.key as string] === matchValue);
|
||||
if (idx >= 0) result[idx] = mergeTuningLayer(result[idx], rawOp.item);
|
||||
else result.push(rawOp.item);
|
||||
break;
|
||||
}
|
||||
case 'removeBy': {
|
||||
if (typeof rawOp.key !== 'string') throw new Error('$listOps removeBy requires string "key"');
|
||||
for (let i = result.length - 1; i >= 0; i -= 1) {
|
||||
const entry = result[i];
|
||||
if (isPlainObject(entry) && entry[rawOp.key] === rawOp.value) result.splice(i, 1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error(`unsupported $listOps operation "${rawOp.op}"`);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function isListOpsEnvelope(value: unknown): value is { readonly $listOps: readonly unknown[] } {
|
||||
if (!isPlainObject(value)) return false;
|
||||
const keys = Object.keys(value);
|
||||
return keys.length === 1 && keys[0] === '$listOps' && Array.isArray(value.$listOps);
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* Shared types for the additive mod system.
|
||||
*
|
||||
* EXPERIMENTAL: Mod manifest fields, conflict structures, and runtime contracts are under active
|
||||
* early development and may change without backwards compatibility.
|
||||
*/
|
||||
|
||||
export const MOD_FORMAT_VERSION = 1;
|
||||
export const MOD_API_VERSION = '0.1-experimental';
|
||||
|
||||
/** Supported client .vromfs.bin packs that mods may patch or add files to. */
|
||||
export const MODDABLE_CLIENT_PACKS = [
|
||||
'char.vromfs.bin',
|
||||
'aces.vromfs.bin',
|
||||
'gui.vromfs.bin',
|
||||
'lang.vromfs.bin',
|
||||
'mis.vromfs.bin',
|
||||
'game.vromfs.bin',
|
||||
'ui/atlases.vromfs.bin',
|
||||
'ui/images.vromfs.bin',
|
||||
] as const;
|
||||
|
||||
export type ModdableClientPack = (typeof MODDABLE_CLIENT_PACKS)[number];
|
||||
|
||||
export type LocalizedText = string | Readonly<Record<string, string>>;
|
||||
|
||||
export type ModRiskBadge = 'data' | 'gui' | 'script' | 'exe';
|
||||
|
||||
export interface ModServerConfig {
|
||||
/** Relative path to the server script entry (.ts, .mjs, or .js), when present. */
|
||||
readonly entry?: string;
|
||||
/** Relative path to the server tuning override directory (defaults to "server/tuning"). */
|
||||
readonly tuning?: string;
|
||||
}
|
||||
|
||||
export interface ModManifest {
|
||||
readonly format: 1;
|
||||
readonly id: string;
|
||||
readonly name: LocalizedText;
|
||||
readonly version: string;
|
||||
readonly author: string;
|
||||
readonly description?: LocalizedText;
|
||||
readonly apiVersion: string;
|
||||
readonly gameVersions: readonly string[];
|
||||
readonly requires: readonly string[];
|
||||
readonly conflicts: readonly string[];
|
||||
readonly loadAfter: readonly string[];
|
||||
readonly loadBefore: readonly string[];
|
||||
readonly server?: ModServerConfig;
|
||||
}
|
||||
|
||||
export type PackFileAction = 'blk-patch' | 'csv-patch' | 'file';
|
||||
|
||||
export interface ModPackOperation {
|
||||
readonly pack: ModdableClientPack;
|
||||
/** Target path inside the pack (without .patch.jsonc / .patch.csv suffix). */
|
||||
readonly targetPath: string;
|
||||
readonly action: PackFileAction;
|
||||
/** Path relative to the mod root folder. */
|
||||
readonly sourceRelativePath: string;
|
||||
}
|
||||
|
||||
export interface ModContentSummary {
|
||||
readonly serverEntry?: string;
|
||||
readonly serverTuningFiles: readonly string[];
|
||||
readonly packOperations: readonly ModPackOperation[];
|
||||
readonly guiPatchDirs: readonly string[];
|
||||
readonly exePatchDirs: readonly string[];
|
||||
readonly hasClientAddon: boolean;
|
||||
/** True when client/addon includes a compiled res/grp_hdr.vromfs.bin index. */
|
||||
readonly addonHasGrpHdr: boolean;
|
||||
readonly addonRelativeFiles: readonly string[];
|
||||
/** Relative paths under client/files (mapped into the game copy root). */
|
||||
readonly clientFiles: readonly string[];
|
||||
/** Optional relative path to client/config-blk.patch.jsonc. */
|
||||
readonly configBlkPatch?: string;
|
||||
readonly badges: readonly ModRiskBadge[];
|
||||
}
|
||||
|
||||
export interface DiscoveredMod {
|
||||
readonly folderName: string;
|
||||
readonly rootDir: string;
|
||||
readonly manifest: ModManifest;
|
||||
readonly content: ModContentSummary;
|
||||
}
|
||||
|
||||
export interface ModDiscoveryError {
|
||||
readonly folderName: string;
|
||||
readonly rootDir: string;
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
export interface ModDiscoveryResult {
|
||||
readonly mods: readonly DiscoveredMod[];
|
||||
readonly errors: readonly ModDiscoveryError[];
|
||||
}
|
||||
|
||||
export interface ModPreset {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly order: readonly string[];
|
||||
readonly enabled: Readonly<Record<string, boolean>>;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ClientModsConfig {
|
||||
readonly format: 1;
|
||||
readonly order: readonly string[];
|
||||
readonly enabled: Readonly<Record<string, boolean>>;
|
||||
readonly activePresetId: string | null;
|
||||
readonly presets: readonly ModPreset[];
|
||||
}
|
||||
|
||||
export type ModIssueSeverity = 'error' | 'warning' | 'info';
|
||||
|
||||
export type ModIssueKind =
|
||||
| 'missing-dependency'
|
||||
| 'dependency-disabled'
|
||||
| 'dependency-order'
|
||||
| 'declared-conflict'
|
||||
| 'load-order-hint'
|
||||
| 'game-version-mismatch'
|
||||
| 'api-version-mismatch'
|
||||
| 'pack-file-override'
|
||||
| 'pack-blk-shared-target'
|
||||
| 'client-file-conflict'
|
||||
| 'tuning-file-shared';
|
||||
|
||||
export interface ModIssue {
|
||||
readonly severity: ModIssueSeverity;
|
||||
readonly kind: ModIssueKind;
|
||||
readonly modId: string;
|
||||
readonly otherModId?: string;
|
||||
readonly detail: string;
|
||||
}
|
||||
|
||||
export interface ResolvedModLoadOrder {
|
||||
readonly enabledMods: readonly DiscoveredMod[];
|
||||
readonly issues: readonly ModIssue[];
|
||||
readonly hasBlockingErrors: boolean;
|
||||
}
|
||||
|
||||
/** Pick the best localized display string for a mod field. */
|
||||
export function resolveLocalizedText(value: LocalizedText, language: string): string {
|
||||
if (typeof value === 'string') return value;
|
||||
const exact = value[language];
|
||||
if (exact) return exact;
|
||||
const prefix = language.split('-')[0];
|
||||
if (prefix) {
|
||||
const partial = Object.entries(value).find(([key]) => key === prefix || key.startsWith(`${prefix}-`));
|
||||
if (partial?.[1]) return partial[1];
|
||||
}
|
||||
return value.en ?? value['en-US'] ?? Object.values(value)[0] ?? '';
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
"@wto/blk": "*",
|
||||
"@wto/exepatch": "*",
|
||||
"@wto/jsonc": "*",
|
||||
"@wto/mods": "*",
|
||||
"@wto/vromfs": "*",
|
||||
"fflate": "^0.8.2"
|
||||
}
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
/**
|
||||
* Build the files of the game copy in memory: the three rebuilt data packs,
|
||||
* the patched executable, the network hook library and its settings. Nothing is written here
|
||||
* Build the files of the game copy in memory: the rebuilt data packs (with optional additive mod
|
||||
* overlays), the patched executable (with protected core patches + optional declarative mod exe
|
||||
* patches), the network hook library and its settings. Nothing is written here
|
||||
* (write-game-copy.ts does that), so a caller can show the report first and let the player decide.
|
||||
*
|
||||
* Everything the build needs from outside comes in as an input: the stock files, the patch set
|
||||
* (patch-set.ts), the hook library, and the multi-vehicle pack ids the local server will sell from its
|
||||
* data folder.
|
||||
* (patch-set.ts), the hook library, the multi-vehicle pack ids the local server will sell, and
|
||||
* optionally the ordered list of enabled mods with any additional stock packs they touch.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { PeImage, type PatchFailure } from '@wto/exepatch';
|
||||
import { touchedClientPacks, type DiscoveredMod, type ModdableClientPack } from '@wto/mods';
|
||||
import { rebuildCharPack, type CharPackResult } from './char-pack.ts';
|
||||
import { blockingFailures } from './essential-features.ts';
|
||||
import { patchExecutable } from './executable.ts';
|
||||
import { patchExecutableWithMods, type ModExePatchFailure } from './executable.ts';
|
||||
import { GAME_FILES } from './game-copy.ts';
|
||||
import { rebuildGuiPack } from './gui-pack.ts';
|
||||
import { rebuildMainPack } from './main-pack.ts';
|
||||
import { collectModAddonMounts, type ModAddonMount } from './mods/addon-register.ts';
|
||||
import { CORE_BUILD_PACKS } from './mods/deploy-external.ts';
|
||||
import { applyModGuiPatches } from './mods/gui-overlay.ts';
|
||||
import { applyModPackOverlays, type PackOverlayReport } from './mods/pack-overlay.ts';
|
||||
import type { AddressChange } from './network/address-rewrite.ts';
|
||||
import { localEndpoint, type LocalEndpoint } from './network/local-endpoint.ts';
|
||||
import { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hook.ts';
|
||||
@@ -49,6 +55,10 @@ export interface GameCopyInputs {
|
||||
readonly decalIndexFiles?: readonly AddedFile[];
|
||||
/** Whether wto_ws.dll writes win64/wto_ws.log; defaults to true. */
|
||||
readonly hookLogging?: boolean;
|
||||
/** Ordered list of enabled additive mods to overlay onto this build. */
|
||||
readonly mods?: readonly DiscoveredMod[];
|
||||
/** Stock bytes of optional packs (lang/mis/game/ui/*) touched by enabled mods. */
|
||||
readonly extraStockPacks?: Partial<Record<ModdableClientPack, Uint8Array>>;
|
||||
}
|
||||
|
||||
/** One file of the game copy, by its path relative to the copy folder. */
|
||||
@@ -57,6 +67,20 @@ export interface GameCopyFile {
|
||||
readonly content: Uint8Array;
|
||||
}
|
||||
|
||||
export interface ModBuildReport {
|
||||
readonly enabledModIds: readonly string[];
|
||||
readonly packOverlays: readonly PackOverlayReport[];
|
||||
readonly addonMounts: readonly ModAddonMount[];
|
||||
readonly guiPatches: {
|
||||
readonly applied: readonly { readonly modId: string; readonly patchId: string }[];
|
||||
readonly failures: readonly (PatchFailure & { readonly modId: string })[];
|
||||
};
|
||||
readonly exePatches: {
|
||||
readonly applied: readonly { readonly modId: string; readonly patchId: string; readonly rva: number }[];
|
||||
readonly failures: readonly ModExePatchFailure[];
|
||||
};
|
||||
}
|
||||
|
||||
export interface GameCopyBuild {
|
||||
/** Every file to write, with unavailable patches left out. */
|
||||
readonly files: readonly GameCopyFile[];
|
||||
@@ -72,6 +96,8 @@ export interface GameCopyBuild {
|
||||
readonly engineAddresses: readonly AddressChange[];
|
||||
/** Store bundle GUIDs registered in config/gui.blk. */
|
||||
readonly bundleGuids: number;
|
||||
/** Details of additive mod overlays applied during this build. */
|
||||
readonly mods: ModBuildReport;
|
||||
}
|
||||
|
||||
export function readStockGameFiles(folder: string): StockGameFiles {
|
||||
@@ -86,44 +112,86 @@ export function readStockGameFiles(folder: string): StockGameFiles {
|
||||
export function buildGameCopy(inputs: GameCopyInputs): GameCopyBuild {
|
||||
const endpoint = localEndpoint(inputs.port);
|
||||
const folders = patchSetFolders(inputs.patches);
|
||||
const executable = patchExecutable(inputs.stock.executable, folders.exe);
|
||||
const enabledMods = inputs.mods ?? [];
|
||||
const packOverlays: PackOverlayReport[] = [];
|
||||
|
||||
const executable = patchExecutableWithMods(inputs.stock.executable, folders.exe, enabledMods);
|
||||
const stockImage = new PeImage(inputs.stock.executable);
|
||||
const native = resolveNativeModules(stockImage, loadNativeModules(folders.native));
|
||||
const guiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui);
|
||||
const appliedGuiPatches = guiPack.applied.map((item) => item.patch.id);
|
||||
|
||||
const coreGuiPack = rebuildGuiPack(inputs.stock.guiPack, endpoint, folders.gui);
|
||||
const appliedGuiPatches = coreGuiPack.applied.map((item) => item.patch.id);
|
||||
const guiPackFileOverlay = applyModPackOverlays(coreGuiPack.pack, 'gui.vromfs.bin', enabledMods);
|
||||
if (guiPackFileOverlay.report.operationsApplied > 0) packOverlays.push(guiPackFileOverlay.report);
|
||||
const modGuiResult = applyModGuiPatches(guiPackFileOverlay.pack, endpoint, enabledMods);
|
||||
|
||||
const localRegistration = appliedGuiPatches.includes('registration/open-local-page') &&
|
||||
appliedGuiPatches.includes('registration/keep-local-page-embedded');
|
||||
const { pack: charPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, {
|
||||
const { pack: coreCharPack, ...charReport } = rebuildCharPack(inputs.stock.charPack, endpoint, {
|
||||
placeholderDecals: inputs.placeholderDecals,
|
||||
...(inputs.decalIndexFiles ? { decalIndexFiles: inputs.decalIndexFiles } : {}),
|
||||
localRegistration,
|
||||
});
|
||||
const bundles = offlinePackBundleGuids(inputs.stock.charPack, inputs.multiVehiclePackIds);
|
||||
const mainPack = rebuildMainPack(inputs.stock.mainPack, endpoint, bundles);
|
||||
const charOverlay = applyModPackOverlays(coreCharPack, 'char.vromfs.bin', enabledMods);
|
||||
if (charOverlay.report.operationsApplied > 0) packOverlays.push(charOverlay.report);
|
||||
|
||||
// Derive store bundle GUIDs from the mod-overlaid charPack so newly added mod gift vehicles
|
||||
// automatically receive deterministic offline store bundle GUIDs.
|
||||
const bundles = offlinePackBundleGuids(charOverlay.pack, inputs.multiVehiclePackIds);
|
||||
const addonMounts = collectModAddonMounts(enabledMods);
|
||||
const coreMainPack = rebuildMainPack(
|
||||
inputs.stock.mainPack,
|
||||
endpoint,
|
||||
bundles,
|
||||
addonMounts.map((mount) => mount.mountFolder),
|
||||
);
|
||||
const mainOverlay = applyModPackOverlays(coreMainPack.pack, 'aces.vromfs.bin', enabledMods);
|
||||
if (mainOverlay.report.operationsApplied > 0) packOverlays.push(mainOverlay.report);
|
||||
|
||||
const executableFolder = dirname(GAME_FILES.executable);
|
||||
const hookSettings = networkHookSettings(endpoint, stockImage, native.values, {
|
||||
loggingEnabled: inputs.hookLogging ?? true,
|
||||
});
|
||||
const files: GameCopyFile[] = [
|
||||
{ path: GAME_FILES.charPack, content: charPack },
|
||||
{ path: GAME_FILES.mainPack, content: mainPack.pack },
|
||||
{ path: GAME_FILES.guiPack, content: guiPack.pack },
|
||||
{ path: GAME_FILES.charPack, content: charOverlay.pack },
|
||||
{ path: GAME_FILES.mainPack, content: mainOverlay.pack },
|
||||
{ path: GAME_FILES.guiPack, content: modGuiResult.pack },
|
||||
{ path: GAME_FILES.executable, content: executable.executable },
|
||||
{ path: join(executableFolder, NETWORK_HOOK_LIBRARY), content: inputs.networkHookLibrary },
|
||||
{ path: join(executableFolder, hookSettings.name), content: hookSettings.content },
|
||||
];
|
||||
|
||||
const failures = [...executable.plan.failures, ...guiPack.failures, ...native.failures];
|
||||
// Rebuild any optional client packs (lang, mis, game, ui/atlases, ui/images) touched by enabled mods.
|
||||
for (const pack of touchedClientPacks(enabledMods)) {
|
||||
if (CORE_BUILD_PACKS.has(pack)) continue;
|
||||
const stockBytes = inputs.extraStockPacks?.[pack];
|
||||
if (!stockBytes) {
|
||||
throw new Error(`mod overlay requires stock pack "${pack}" in extraStockPacks`);
|
||||
}
|
||||
const overlay = applyModPackOverlays(stockBytes, pack, enabledMods);
|
||||
if (overlay.report.operationsApplied > 0) {
|
||||
packOverlays.push(overlay.report);
|
||||
files.push({ path: join(...pack.split('/')), content: overlay.pack });
|
||||
}
|
||||
}
|
||||
|
||||
const failures = [...executable.plan.failures, ...coreGuiPack.failures, ...native.failures];
|
||||
return {
|
||||
files,
|
||||
endpoint,
|
||||
exePatches: { applied: executable.plan.writes.map((write) => ({ patchId: write.patchId, rva: write.rva })), failures: executable.plan.failures },
|
||||
guiPatches: { applied: appliedGuiPatches, failures: guiPack.failures },
|
||||
guiPatches: { applied: appliedGuiPatches, failures: coreGuiPack.failures },
|
||||
nativeModules: { available: [...native.available.keys()], failures: native.failures },
|
||||
blocking: blockingFailures(failures),
|
||||
charPack: charReport,
|
||||
engineAddresses: mainPack.addresses,
|
||||
engineAddresses: coreMainPack.addresses,
|
||||
bundleGuids: bundles.length,
|
||||
mods: {
|
||||
enabledModIds: enabledMods.map((mod) => mod.manifest.id),
|
||||
packOverlays,
|
||||
addonMounts,
|
||||
guiPatches: { applied: modGuiResult.applied, failures: modGuiResult.failures },
|
||||
exePatches: { applied: executable.modApplied, failures: executable.modFailures },
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,10 +1,21 @@
|
||||
/**
|
||||
* Patch a copy of aces.exe with every definition under the exe patch folder. A patch that cannot
|
||||
* be applied (site missing or ambiguous, original bytes differ, or a patch it requires failed) is
|
||||
* left out and listed with the features it covers; whether a copy with
|
||||
* patches missing may be installed is the caller's decision (essential-features.ts).
|
||||
* Patch a copy of aces.exe with every definition under the core exe patch folder, and optionally
|
||||
* apply declarative mod exe patches on top while keeping every core patch byte range locked.
|
||||
*/
|
||||
import { applyWrites, describePlan, loadPatches, PeImage, planPatches, type PatchPlan } from '@wto/exepatch';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
applyWrites,
|
||||
describePlan,
|
||||
loadPatches,
|
||||
PeImage,
|
||||
planAdditionalPatches,
|
||||
planPatches,
|
||||
type PatchDefinition,
|
||||
type PatchFailure,
|
||||
type PatchPlan,
|
||||
type PlannedWrite,
|
||||
} from '@wto/exepatch';
|
||||
import type { DiscoveredMod } from '@wto/mods';
|
||||
|
||||
export interface ExecutableResult {
|
||||
/** The executable with every available patch written. */
|
||||
@@ -13,7 +24,85 @@ export interface ExecutableResult {
|
||||
readonly description: string;
|
||||
}
|
||||
|
||||
export interface ModExePatchFailure extends PatchFailure {
|
||||
readonly modId: string;
|
||||
}
|
||||
|
||||
export interface ModExecutableResult extends ExecutableResult {
|
||||
readonly modApplied: readonly { readonly modId: string; readonly patchId: string; readonly rva: number }[];
|
||||
readonly modFailures: readonly ModExePatchFailure[];
|
||||
}
|
||||
|
||||
export function patchExecutable(stockExecutable: Uint8Array, patchesRoot: string): ExecutableResult {
|
||||
const plan = planPatches(new PeImage(stockExecutable), loadPatches(patchesRoot));
|
||||
return { executable: applyWrites(stockExecutable, plan.writes), plan, description: describePlan(plan) };
|
||||
}
|
||||
|
||||
export function patchExecutableWithMods(
|
||||
stockExecutable: Uint8Array,
|
||||
corePatchesRoot: string,
|
||||
mods: readonly DiscoveredMod[],
|
||||
): ModExecutableResult {
|
||||
const image = new PeImage(stockExecutable);
|
||||
const corePlan = planPatches(image, loadPatches(corePatchesRoot));
|
||||
const modsWithExe = mods.filter((mod) => mod.content.exePatchDirs.length > 0);
|
||||
if (modsWithExe.length === 0) {
|
||||
return {
|
||||
executable: applyWrites(stockExecutable, corePlan.writes),
|
||||
plan: corePlan,
|
||||
description: describePlan(corePlan),
|
||||
modApplied: [],
|
||||
modFailures: [],
|
||||
};
|
||||
}
|
||||
|
||||
const allModDefs: PatchDefinition[] = [];
|
||||
const ownerById = new Map<string, string>();
|
||||
const loadFailures: ModExePatchFailure[] = [];
|
||||
|
||||
for (const mod of modsWithExe) {
|
||||
const exeRoot = join(mod.rootDir, 'client', 'exe-patches');
|
||||
try {
|
||||
const defs = loadPatches(exeRoot);
|
||||
for (const def of defs) {
|
||||
const namespacedId = `${mod.manifest.id}/${def.id}`;
|
||||
ownerById.set(namespacedId, mod.manifest.id);
|
||||
allModDefs.push({
|
||||
...def,
|
||||
id: namespacedId,
|
||||
requires: def.requires.map((req) => (req.includes('/') ? req : `${mod.manifest.id}/${req}`)),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
loadFailures.push({
|
||||
modId: mod.manifest.id,
|
||||
patchId: `${mod.manifest.id}:exe-patches`,
|
||||
features: [],
|
||||
reason: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const modPlan = planAdditionalPatches(image, allModDefs, corePlan.writes);
|
||||
const combinedWrites: readonly PlannedWrite[] = [...corePlan.writes, ...modPlan.writes];
|
||||
const modApplied = modPlan.writes.map((write) => ({
|
||||
modId: ownerById.get(write.patchId) ?? 'unknown',
|
||||
patchId: write.patchId,
|
||||
rva: write.rva,
|
||||
}));
|
||||
const modFailures: ModExePatchFailure[] = [
|
||||
...loadFailures,
|
||||
...modPlan.failures.map((failure) => ({
|
||||
...failure,
|
||||
modId: ownerById.get(failure.patchId) ?? 'unknown',
|
||||
})),
|
||||
];
|
||||
|
||||
return {
|
||||
executable: applyWrites(stockExecutable, combinedWrites),
|
||||
plan: corePlan,
|
||||
description: describePlan(corePlan),
|
||||
modApplied,
|
||||
modFailures,
|
||||
};
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export {
|
||||
type GameCopyBuild,
|
||||
type GameCopyFile,
|
||||
type GameCopyInputs,
|
||||
type ModBuildReport,
|
||||
type StockGameFiles,
|
||||
} from './build-game-copy.ts';
|
||||
export { NETWORK_CONFIG_PATH, rebuildCharPack, type CharPackResult } from './char-pack.ts';
|
||||
@@ -21,7 +22,35 @@ export {
|
||||
writeDecalCacheIndexSnapshot,
|
||||
} from './decals/player-decal-cache.ts';
|
||||
export { blockingFailures, ESSENTIAL_FEATURES } from './essential-features.ts';
|
||||
export { patchExecutable, type ExecutableResult } from './executable.ts';
|
||||
export {
|
||||
patchExecutable,
|
||||
patchExecutableWithMods,
|
||||
type ExecutableResult,
|
||||
type ModExecutableResult,
|
||||
type ModExePatchFailure,
|
||||
} from './executable.ts';
|
||||
export {
|
||||
addonMountFolderForMod,
|
||||
collectModAddonMounts,
|
||||
registerModAddonsInSettings,
|
||||
type ModAddonMount,
|
||||
} from './mods/addon-register.ts';
|
||||
export {
|
||||
computeModsBuildFingerprint,
|
||||
CORE_BUILD_PACKS,
|
||||
MODS_STATE_FILE,
|
||||
prepareOptionalStockPacks,
|
||||
readModsDeployState,
|
||||
syncExternalModFiles,
|
||||
writeModsDeployState,
|
||||
type DeployedModEntry,
|
||||
type DeployEntryKind,
|
||||
type ModDeployWarning,
|
||||
type ModExternalDeployResult,
|
||||
type ModsDeployState,
|
||||
} from './mods/deploy-external.ts';
|
||||
export { applyModGuiPatches, type ModGuiPatchResult } from './mods/gui-overlay.ts';
|
||||
export { applyModPackOverlays, type PackOverlayReport } from './mods/pack-overlay.ts';
|
||||
export { assertWritableCopy, GAME_FILES, isInSteamLibrary, type WritableCopyOptions } from './game-copy.ts';
|
||||
export { executableVersion } from './game-version.ts';
|
||||
export {
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
* server addresses.
|
||||
*/
|
||||
import { ensureBlock, findBlock, setParam, type BlkBlock } from '@wto/blk';
|
||||
import { registerModAddonsInSettings } from './mods/addon-register.ts';
|
||||
import { redirectAddresses, type AddressChange } from './network/address-rewrite.ts';
|
||||
import type { LocalEndpoint } from './network/local-endpoint.ts';
|
||||
import { editPackBlks } from './pack-edit.ts';
|
||||
@@ -42,6 +43,7 @@ export function rebuildMainPack(
|
||||
stockPack: Uint8Array,
|
||||
endpoint: LocalEndpoint,
|
||||
extraBundles: ReadonlyArray<readonly [string, string]> = [],
|
||||
extraAddonFolders: readonly string[] = [],
|
||||
): MainPackResult {
|
||||
let addresses: AddressChange[] = [];
|
||||
const pack = editPackBlks(stockPack, [
|
||||
@@ -51,6 +53,7 @@ export function rebuildMainPack(
|
||||
const network = findBlock(root, NETWORK_BLOCK);
|
||||
if (!network) throw new Error(`${ENGINE_SETTINGS_PATH} has no "${NETWORK_BLOCK}" block; this game build differs from the verified ones`);
|
||||
addresses = redirectAddresses(network, endpoint, [NETWORK_BLOCK]);
|
||||
registerModAddonsInSettings(root, extraAddonFolders);
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Compute engine addon mount paths for mods shipping 3D models/textures (`client/addon/`)
|
||||
* and register them into `aces.vromfs.bin` `config/settings.blk`.
|
||||
*
|
||||
* Engine behaviour verified in 2.61.0.x aces.exe (0xc90932..0xc92754):
|
||||
* - Paths containing `/pkg_user/` skip the mandatory `res/grp_hdr.vromfs.bin` check and
|
||||
* directly scan `%s/res/` for all `.grp` and `.dxp.bin` archives.
|
||||
* - Addons that ship a compiled `res/grp_hdr.vromfs.bin` use a dedicated `content/pkg_wto_<id>`
|
||||
* folder so the native grp_hdr loader handles them.
|
||||
*/
|
||||
import { appendParam, ensureBlock, type BlkBlock } from '@wto/blk';
|
||||
import type { DiscoveredMod } from '@wto/mods';
|
||||
|
||||
export interface ModAddonMount {
|
||||
readonly modId: string;
|
||||
/** Relative folder inside the game copy, e.g. `content/pkg_user/example_mod`. */
|
||||
readonly mountFolder: string;
|
||||
/** Absolute source folder `<modRoot>/client/addon`. */
|
||||
readonly sourceDir: string;
|
||||
}
|
||||
|
||||
export function addonMountFolderForMod(mod: DiscoveredMod): string {
|
||||
const safeName = mod.manifest.id.replace(/[^a-z0-9_-]/g, '_');
|
||||
return mod.content.addonHasGrpHdr
|
||||
? `content/pkg_wto_${safeName}`
|
||||
: `content/pkg_user/${safeName}`;
|
||||
}
|
||||
|
||||
export function collectModAddonMounts(mods: readonly DiscoveredMod[]): ModAddonMount[] {
|
||||
const mounts: ModAddonMount[] = [];
|
||||
for (const mod of mods) {
|
||||
if (!mod.content.hasClientAddon) continue;
|
||||
mounts.push({
|
||||
modId: mod.manifest.id,
|
||||
mountFolder: addonMountFolderForMod(mod),
|
||||
sourceDir: `${mod.rootDir}/client/addon`,
|
||||
});
|
||||
}
|
||||
return mounts;
|
||||
}
|
||||
|
||||
export function registerModAddonsInSettings(settingsRoot: BlkBlock, mountFolders: readonly string[]): void {
|
||||
if (mountFolders.length === 0) return;
|
||||
for (const blockName of ['addons', 'addons_no_check', 'addonsWithBasePath'] as const) {
|
||||
const block = ensureBlock(settingsRoot, blockName);
|
||||
const existing = new Set(
|
||||
block.params
|
||||
.filter((param) => param.name === 'folder' && param.value.type === 'string')
|
||||
.map((param) => (param.value as { readonly type: 'string'; readonly value: string }).value.toLowerCase()),
|
||||
);
|
||||
for (const folder of mountFolders) {
|
||||
if (existing.has(folder.toLowerCase())) continue;
|
||||
appendParam(block, 'folder', { type: 'string', value: folder });
|
||||
existing.add(folder.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
/**
|
||||
* Deploy and cleanly roll back external mod assets (3D model addons, optional companion files,
|
||||
* on-demand stock pack backups, and `config.blk` patches) in the game copy.
|
||||
*
|
||||
* Cross-drive zero-copy strategy (Option A):
|
||||
* 1. Dedicated folders (`content/pkg_user/<modId>` and exclusive subdirectories under `client/files`,
|
||||
* such as `UserSkins/<skin>`) use NTFS Directory Junctions — works across drives, needs no admin
|
||||
* privileges, uses 0 extra bytes, and mounts/unmounts in ~1 ms.
|
||||
* 2. Shared flat files (such as `sound/mod/*.bank`) try file symlink (works across drives when
|
||||
* Windows Developer Mode is on) -> NTFS hardlink (same drive) -> size/mtime cached copy.
|
||||
* 3. Player-owned native files (e.g. manually installed UserSkins/UserSights) are never overwritten;
|
||||
* conflicts are reported and skipped.
|
||||
* 4. Hard-linked stock files are unlinked before replacing so online client files are never mutated.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
linkSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { dirname, join, relative } from 'node:path';
|
||||
import { formatBlkText, parseBlkText } from '@wto/blk';
|
||||
import {
|
||||
applyBlkPatch,
|
||||
parseBlkPatchDocument,
|
||||
type DiscoveredMod,
|
||||
type ModdableClientPack,
|
||||
} from '@wto/mods';
|
||||
import { addonMountFolderForMod } from './addon-register.ts';
|
||||
|
||||
export const MODS_STATE_FILE = join('wtoffline', 'mods-state.json');
|
||||
export const CORE_BUILD_PACKS: ReadonlySet<ModdableClientPack> = new Set([
|
||||
'char.vromfs.bin',
|
||||
'aces.vromfs.bin',
|
||||
'gui.vromfs.bin',
|
||||
]);
|
||||
|
||||
export type DeployEntryKind = 'junction' | 'symlink' | 'hardlink' | 'copy';
|
||||
|
||||
export interface DeployedModEntry {
|
||||
readonly modId: string;
|
||||
/** Copy-relative path with forward slashes. */
|
||||
readonly targetRelPath: string;
|
||||
readonly sourcePath: string;
|
||||
readonly kind: DeployEntryKind;
|
||||
readonly size?: number;
|
||||
readonly mtimeMs?: number;
|
||||
}
|
||||
|
||||
export interface ModsDeployState {
|
||||
readonly format: 1;
|
||||
readonly entries: readonly DeployedModEntry[];
|
||||
/** Optional stock packs backed up on demand under `wtoffline/stock/`. */
|
||||
readonly optionalPacksModified: readonly ModdableClientPack[];
|
||||
readonly configBlkModified: boolean;
|
||||
readonly fingerprint?: string;
|
||||
}
|
||||
|
||||
export interface ModDeployWarning {
|
||||
readonly modId: string;
|
||||
readonly targetRelPath: string;
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
export interface ModExternalDeployResult {
|
||||
readonly deployed: readonly DeployedModEntry[];
|
||||
readonly warnings: readonly ModDeployWarning[];
|
||||
readonly restoredOptionalPacks: readonly ModdableClientPack[];
|
||||
readonly configBlkPatched: boolean;
|
||||
}
|
||||
|
||||
export function readModsDeployState(copyFolder: string): ModsDeployState {
|
||||
const path = join(copyFolder, MODS_STATE_FILE);
|
||||
if (!existsSync(path)) {
|
||||
return { format: 1, entries: [], optionalPacksModified: [], configBlkModified: false };
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<ModsDeployState>;
|
||||
return {
|
||||
format: 1,
|
||||
entries: Array.isArray(parsed.entries) ? parsed.entries : [],
|
||||
optionalPacksModified: Array.isArray(parsed.optionalPacksModified) ? parsed.optionalPacksModified : [],
|
||||
configBlkModified: parsed.configBlkModified === true,
|
||||
...(typeof parsed.fingerprint === 'string' ? { fingerprint: parsed.fingerprint } : {}),
|
||||
};
|
||||
} catch {
|
||||
return { format: 1, entries: [], optionalPacksModified: [], configBlkModified: false };
|
||||
}
|
||||
}
|
||||
|
||||
export function writeModsDeployState(copyFolder: string, state: ModsDeployState): void {
|
||||
const path = join(copyFolder, MODS_STATE_FILE);
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, JSON.stringify(state, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure stock copies exist under `<stockBackupFolder>` for any optional .vromfs.bin pack
|
||||
* touched by enabled mods, then read and return their stock bytes for overlay building.
|
||||
*/
|
||||
export function prepareOptionalStockPacks(
|
||||
copyFolder: string,
|
||||
stockBackupFolder: string,
|
||||
touchedPacks: readonly ModdableClientPack[],
|
||||
): Partial<Record<ModdableClientPack, Uint8Array>> {
|
||||
const result: Partial<Record<ModdableClientPack, Uint8Array>> = {};
|
||||
for (const pack of touchedPacks) {
|
||||
if (CORE_BUILD_PACKS.has(pack)) continue;
|
||||
const backupPath = join(stockBackupFolder, ...pack.split('/'));
|
||||
if (!existsSync(backupPath)) {
|
||||
const livePath = join(copyFolder, ...pack.split('/'));
|
||||
if (!existsSync(livePath)) {
|
||||
throw new Error(`optional game pack "${pack}" does not exist in copy folder ${copyFolder}`);
|
||||
}
|
||||
mkdirSync(dirname(backupPath), { recursive: true });
|
||||
copyFileSync(livePath, backupPath);
|
||||
}
|
||||
result[pack] = readFileSync(backupPath);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronize external mod mounts (`client/addon/`, `client/files/`, `config.blk` patches)
|
||||
* and restore any previously modified optional packs that are no longer touched.
|
||||
*/
|
||||
export function syncExternalModFiles(
|
||||
copyFolder: string,
|
||||
stockBackupFolder: string,
|
||||
mods: readonly DiscoveredMod[],
|
||||
optionalPacksInBuild: readonly ModdableClientPack[],
|
||||
fingerprint?: string,
|
||||
): ModExternalDeployResult {
|
||||
const previous = readModsDeployState(copyFolder);
|
||||
const warnings: ModDeployWarning[] = [];
|
||||
|
||||
// Plan desired external mounts for this launch.
|
||||
const desired = planExternalEntries(mods);
|
||||
const desiredByTarget = new Map(desired.map((item) => [item.targetRelPath.toLowerCase(), item]));
|
||||
const previousByTarget = new Map(previous.entries.map((item) => [item.targetRelPath.toLowerCase(), item]));
|
||||
|
||||
// 1. Remove previous entries that are no longer wanted or changed source/mode.
|
||||
for (const oldEntry of previous.entries) {
|
||||
const key = oldEntry.targetRelPath.toLowerCase();
|
||||
const next = desiredByTarget.get(key);
|
||||
const keepUnchanged = next !== undefined
|
||||
&& next.sourcePath === oldEntry.sourcePath
|
||||
&& isEntryStillValid(copyFolder, oldEntry);
|
||||
if (!keepUnchanged) {
|
||||
removeDeployedEntry(copyFolder, oldEntry);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Restore optional packs that were modified previously but are no longer touched.
|
||||
const activeOptionalSet = new Set(optionalPacksInBuild.filter((pack) => !CORE_BUILD_PACKS.has(pack)));
|
||||
const restoredOptionalPacks: ModdableClientPack[] = [];
|
||||
for (const oldPack of previous.optionalPacksModified) {
|
||||
if (activeOptionalSet.has(oldPack)) continue;
|
||||
const backupPath = join(stockBackupFolder, ...oldPack.split('/'));
|
||||
const livePath = join(copyFolder, ...oldPack.split('/'));
|
||||
if (existsSync(backupPath)) {
|
||||
unlinkIfExists(livePath);
|
||||
mkdirSync(dirname(livePath), { recursive: true });
|
||||
copyFileSync(backupPath, livePath);
|
||||
restoredOptionalPacks.push(oldPack);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Deploy desired mounts (skipping already-valid unchanged mounts and protecting native player files).
|
||||
const deployed: DeployedModEntry[] = [];
|
||||
for (const plan of desired) {
|
||||
const key = plan.targetRelPath.toLowerCase();
|
||||
const prev = previousByTarget.get(key);
|
||||
if (prev && prev.sourcePath === plan.sourcePath && isEntryStillValid(copyFolder, prev)) {
|
||||
deployed.push(prev);
|
||||
continue;
|
||||
}
|
||||
|
||||
const targetAbs = join(copyFolder, ...plan.targetRelPath.split('/'));
|
||||
// Protect player-managed native files (e.g. manually installed UserSkins/UserSights).
|
||||
if (existsSyncSafe(targetAbs) && !previousByTarget.has(key)) {
|
||||
warnings.push({
|
||||
modId: plan.modId,
|
||||
targetRelPath: plan.targetRelPath,
|
||||
reason: 'target already exists as a native/player file; skipped to avoid overwriting player content',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const mounted = mountPlannedEntry(copyFolder, plan);
|
||||
deployed.push(mounted);
|
||||
}
|
||||
|
||||
// 4. Apply or restore config.blk patches.
|
||||
const configBlkPatched = syncConfigBlkPatches(copyFolder, stockBackupFolder, mods, previous.configBlkModified);
|
||||
|
||||
writeModsDeployState(copyFolder, {
|
||||
format: 1,
|
||||
entries: deployed,
|
||||
optionalPacksModified: [...activeOptionalSet],
|
||||
configBlkModified: configBlkPatched,
|
||||
...(fingerprint !== undefined ? { fingerprint } : {}),
|
||||
});
|
||||
|
||||
return { deployed, warnings, restoredOptionalPacks, configBlkPatched };
|
||||
}
|
||||
|
||||
/** Compute a deterministic fingerprint of enabled mods and their source file stamps. */
|
||||
export function computeModsBuildFingerprint(
|
||||
mods: readonly DiscoveredMod[],
|
||||
port: number,
|
||||
extraSalt = '',
|
||||
): string {
|
||||
const hash = createHash('sha256');
|
||||
hash.update(`port=${port};salt=${extraSalt}\n`);
|
||||
for (const mod of mods) {
|
||||
hash.update(`mod=${mod.manifest.id}@${mod.manifest.version}\n`);
|
||||
const filesToStamp = [
|
||||
...mod.content.packOperations.map((op) => op.sourceRelativePath),
|
||||
...mod.content.guiPatchDirs,
|
||||
...mod.content.exePatchDirs,
|
||||
...(mod.content.configBlkPatch ? [mod.content.configBlkPatch] : []),
|
||||
];
|
||||
for (const rel of filesToStamp) {
|
||||
const abs = join(mod.rootDir, ...rel.split('/'));
|
||||
try {
|
||||
const st = statSync(abs);
|
||||
hash.update(`${rel}:${st.size}:${Math.trunc(st.mtimeMs)}\n`);
|
||||
} catch {
|
||||
hash.update(`${rel}:missing\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
interface PlannedMount {
|
||||
readonly modId: string;
|
||||
readonly targetRelPath: string;
|
||||
readonly sourcePath: string;
|
||||
readonly isDirectory: boolean;
|
||||
}
|
||||
|
||||
function planExternalEntries(mods: readonly DiscoveredMod[]): PlannedMount[] {
|
||||
const plans: PlannedMount[] = [];
|
||||
const seenTargets = new Map<string, number>();
|
||||
|
||||
const register = (plan: PlannedMount) => {
|
||||
const key = plan.targetRelPath.toLowerCase();
|
||||
const existingIdx = seenTargets.get(key);
|
||||
if (existingIdx !== undefined) {
|
||||
plans[existingIdx] = plan;
|
||||
} else {
|
||||
seenTargets.set(key, plans.length);
|
||||
plans.push(plan);
|
||||
}
|
||||
};
|
||||
|
||||
// Addons are always mod-exclusive directories -> ideal for cross-drive Junctions.
|
||||
for (const mod of mods) {
|
||||
if (!mod.content.hasClientAddon) continue;
|
||||
register({
|
||||
modId: mod.manifest.id,
|
||||
targetRelPath: addonMountFolderForMod(mod),
|
||||
sourcePath: join(mod.rootDir, 'client', 'addon'),
|
||||
isDirectory: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Companion files under `client/files`: group exclusive leaf directories (e.g. `UserSkins/my_skin`)
|
||||
// as cross-drive Junctions whenever only one mod touches that subdirectory.
|
||||
const folderOwners = new Map<string, Set<string>>();
|
||||
for (const mod of mods) {
|
||||
for (const rel of mod.content.clientFiles) {
|
||||
const topSub = exclusiveSubdirCandidate(rel);
|
||||
if (!topSub) continue;
|
||||
const key = topSub.toLowerCase();
|
||||
let set = folderOwners.get(key);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
folderOwners.set(key, set);
|
||||
}
|
||||
set.add(mod.manifest.id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const mod of mods) {
|
||||
const claimedDirs = new Set<string>();
|
||||
for (const rel of mod.content.clientFiles) {
|
||||
const topSub = exclusiveSubdirCandidate(rel);
|
||||
if (topSub && folderOwners.get(topSub.toLowerCase())?.size === 1) {
|
||||
const key = topSub.toLowerCase();
|
||||
if (!claimedDirs.has(key)) {
|
||||
claimedDirs.add(key);
|
||||
register({
|
||||
modId: mod.manifest.id,
|
||||
targetRelPath: topSub,
|
||||
sourcePath: join(mod.rootDir, 'client', 'files', ...topSub.split('/')),
|
||||
isDirectory: true,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
register({
|
||||
modId: mod.manifest.id,
|
||||
targetRelPath: rel,
|
||||
sourcePath: join(mod.rootDir, 'client', 'files', ...rel.split('/')),
|
||||
isDirectory: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return plans;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a safe exclusive subdirectory candidate (e.g. `UserSkins/foo`, `UserSights/bar`,
|
||||
* `UserMissions/baz`) that can be mounted as one cross-drive Junction instead of linking
|
||||
* every file inside it. Flat shared folders like `sound/mod/*.bank` return undefined.
|
||||
*/
|
||||
function exclusiveSubdirCandidate(relPath: string): string | undefined {
|
||||
const parts = relPath.split('/');
|
||||
if (parts.length < 3) return undefined;
|
||||
const root = parts[0]!.toLowerCase();
|
||||
if (root === 'userskins' || root === 'usersights' || root === 'usermissions') {
|
||||
return `${parts[0]!}/${parts[1]!}`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function mountPlannedEntry(copyFolder: string, plan: PlannedMount): DeployedModEntry {
|
||||
const targetAbs = join(copyFolder, ...plan.targetRelPath.split('/'));
|
||||
mkdirSync(dirname(targetAbs), { recursive: true });
|
||||
|
||||
if (plan.isDirectory) {
|
||||
try {
|
||||
symlinkSync(plan.sourcePath, targetAbs, 'junction');
|
||||
return {
|
||||
modId: plan.modId,
|
||||
targetRelPath: plan.targetRelPath,
|
||||
sourcePath: plan.sourcePath,
|
||||
kind: 'junction',
|
||||
};
|
||||
} catch {
|
||||
// Fallback for non-NTFS volumes (e.g. exFAT): incremental directory copy.
|
||||
copyDirectoryIncremental(plan.sourcePath, targetAbs);
|
||||
return {
|
||||
modId: plan.modId,
|
||||
targetRelPath: plan.targetRelPath,
|
||||
sourcePath: plan.sourcePath,
|
||||
kind: 'copy',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Flat single file: try file symlink (cross-drive when Developer Mode is enabled),
|
||||
// then same-drive NTFS hardlink, then cached copy.
|
||||
unlinkIfExists(targetAbs);
|
||||
try {
|
||||
symlinkSync(plan.sourcePath, targetAbs, 'file');
|
||||
return {
|
||||
modId: plan.modId,
|
||||
targetRelPath: plan.targetRelPath,
|
||||
sourcePath: plan.sourcePath,
|
||||
kind: 'symlink',
|
||||
};
|
||||
} catch { /* fall through */ }
|
||||
|
||||
try {
|
||||
linkSync(plan.sourcePath, targetAbs);
|
||||
return {
|
||||
modId: plan.modId,
|
||||
targetRelPath: plan.targetRelPath,
|
||||
sourcePath: plan.sourcePath,
|
||||
kind: 'hardlink',
|
||||
};
|
||||
} catch { /* fall through */ }
|
||||
|
||||
const st = statSync(plan.sourcePath);
|
||||
copyFileSync(plan.sourcePath, targetAbs);
|
||||
return {
|
||||
modId: plan.modId,
|
||||
targetRelPath: plan.targetRelPath,
|
||||
sourcePath: plan.sourcePath,
|
||||
kind: 'copy',
|
||||
size: st.size,
|
||||
mtimeMs: st.mtimeMs,
|
||||
};
|
||||
}
|
||||
|
||||
function isEntryStillValid(copyFolder: string, entry: DeployedModEntry): boolean {
|
||||
const targetAbs = join(copyFolder, ...entry.targetRelPath.split('/'));
|
||||
if (!existsSyncSafe(targetAbs)) return false;
|
||||
if (entry.kind === 'junction' || entry.kind === 'symlink') {
|
||||
try {
|
||||
return lstatSync(targetAbs).isSymbolicLink() && existsSync(entry.sourcePath);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (entry.kind === 'hardlink') {
|
||||
try {
|
||||
const a = statSync(targetAbs);
|
||||
const b = statSync(entry.sourcePath);
|
||||
return a.ino !== 0 && a.ino === b.ino && a.dev === b.dev;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Cached copy check.
|
||||
if (entry.size !== undefined && entry.mtimeMs !== undefined) {
|
||||
try {
|
||||
const src = statSync(entry.sourcePath);
|
||||
const dst = statSync(targetAbs);
|
||||
return src.size === entry.size && Math.abs(src.mtimeMs - entry.mtimeMs) < 2 && dst.size === src.size;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function removeDeployedEntry(copyFolder: string, entry: DeployedModEntry): void {
|
||||
const targetAbs = join(copyFolder, ...entry.targetRelPath.split('/'));
|
||||
if (!existsSyncSafe(targetAbs)) return;
|
||||
try {
|
||||
const stat = lstatSync(targetAbs);
|
||||
if (entry.kind === 'junction' || stat.isSymbolicLink()) {
|
||||
// Remove only the reparse point / symlink, never descending into the source mod folder.
|
||||
try {
|
||||
unlinkSync(targetAbs);
|
||||
} catch {
|
||||
rmdirSync(targetAbs);
|
||||
}
|
||||
} else if (stat.isDirectory()) {
|
||||
rmSync(targetAbs, { recursive: true, force: true });
|
||||
} else {
|
||||
unlinkSync(targetAbs);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
pruneEmptyParents(dirname(targetAbs), copyFolder);
|
||||
}
|
||||
|
||||
function copyDirectoryIncremental(srcDir: string, dstDir: string): void {
|
||||
mkdirSync(dstDir, { recursive: true });
|
||||
for (const entry of readdirSync(srcDir, { withFileTypes: true })) {
|
||||
const src = join(srcDir, entry.name);
|
||||
const dst = join(dstDir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
copyDirectoryIncremental(src, dst);
|
||||
} else if (entry.isFile()) {
|
||||
const st = statSync(src);
|
||||
let same = false;
|
||||
try {
|
||||
const dstStat = statSync(dst);
|
||||
same = dstStat.size === st.size && Math.abs(dstStat.mtimeMs - st.mtimeMs) < 2;
|
||||
} catch { /* missing */ }
|
||||
if (!same) {
|
||||
unlinkIfExists(dst);
|
||||
copyFileSync(src, dst);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function syncConfigBlkPatches(
|
||||
copyFolder: string,
|
||||
stockBackupFolder: string,
|
||||
mods: readonly DiscoveredMod[],
|
||||
previouslyModified: boolean,
|
||||
): boolean {
|
||||
const patchingMods = mods.filter((mod) => mod.content.configBlkPatch !== undefined);
|
||||
const liveConfig = join(copyFolder, 'config.blk');
|
||||
const backupConfig = join(stockBackupFolder, 'config.blk');
|
||||
|
||||
if (patchingMods.length === 0) {
|
||||
if (previouslyModified && existsSync(backupConfig)) {
|
||||
unlinkIfExists(liveConfig);
|
||||
copyFileSync(backupConfig, liveConfig);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!existsSync(backupConfig) && existsSync(liveConfig)) {
|
||||
mkdirSync(dirname(backupConfig), { recursive: true });
|
||||
copyFileSync(liveConfig, backupConfig);
|
||||
}
|
||||
const sourceText = existsSync(backupConfig)
|
||||
? readFileSync(backupConfig, 'utf8')
|
||||
: existsSync(liveConfig) ? readFileSync(liveConfig, 'utf8') : '';
|
||||
const root = parseBlkText(sourceText);
|
||||
|
||||
for (const mod of patchingMods) {
|
||||
const patchPath = join(mod.rootDir, ...mod.content.configBlkPatch!.split('/'));
|
||||
const patch = parseBlkPatchDocument(readFileSync(patchPath, 'utf8'), `mod "${mod.manifest.id}" config.blk patch`);
|
||||
applyBlkPatch(root, patch, `mod "${mod.manifest.id}" config.blk patch`);
|
||||
}
|
||||
|
||||
unlinkIfExists(liveConfig);
|
||||
writeFileSync(liveConfig, formatBlkText(root), 'utf8');
|
||||
return true;
|
||||
}
|
||||
|
||||
function pruneEmptyParents(dir: string, stopAt: string): void {
|
||||
let current = dir;
|
||||
while (relative(stopAt, current) !== '' && !relative(stopAt, current).startsWith('..')) {
|
||||
try {
|
||||
if (readdirSync(current).length > 0) return;
|
||||
rmdirSync(current);
|
||||
current = dirname(current);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function existsSyncSafe(path: string): boolean {
|
||||
try {
|
||||
lstatSync(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function unlinkIfExists(path: string): void {
|
||||
if (!existsSyncSafe(path)) return;
|
||||
try {
|
||||
unlinkSync(path);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Apply mod GUI script patches (`client/gui-patches/<name>/patch.jsonc`) on top of an already
|
||||
* core-patched gui.vromfs.bin archive. Failures are collected per mod rather than breaking core
|
||||
* offline GUI patches.
|
||||
*/
|
||||
import { join } from 'node:path';
|
||||
import { chooseVariant, PatchError, type PatchFailure } from '@wto/exepatch';
|
||||
import type { DiscoveredMod } from '@wto/mods';
|
||||
import { getFile, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
|
||||
import { loadGuiPatches, type GuiScriptVariant } from '../gui-patch-definition.ts';
|
||||
import type { LocalEndpoint } from '../network/local-endpoint.ts';
|
||||
|
||||
const ENDPOINT_PLACEHOLDER = '{{LOCAL_ENDPOINT}}';
|
||||
|
||||
export interface ModGuiPatchResult {
|
||||
readonly pack: Uint8Array;
|
||||
readonly applied: readonly { readonly modId: string; readonly patchId: string }[];
|
||||
readonly failures: readonly (PatchFailure & { readonly modId: string })[];
|
||||
}
|
||||
|
||||
class ModGuiPatchMismatch extends PatchError {
|
||||
override name = 'ModGuiPatchMismatch';
|
||||
}
|
||||
|
||||
export function applyModGuiPatches(
|
||||
baseGuiPack: Uint8Array,
|
||||
endpoint: LocalEndpoint,
|
||||
mods: readonly DiscoveredMod[],
|
||||
): ModGuiPatchResult {
|
||||
const modsWithGui = mods.filter((mod) => mod.content.guiPatchDirs.length > 0);
|
||||
if (modsWithGui.length === 0) {
|
||||
return { pack: baseGuiPack, applied: [], failures: [] };
|
||||
}
|
||||
|
||||
const archive = readArchive(baseGuiPack);
|
||||
const hostPortText = `${endpoint.host}:${endpoint.port}`;
|
||||
const applied: { readonly modId: string; readonly patchId: string }[] = [];
|
||||
const failures: (PatchFailure & { readonly modId: string })[] = [];
|
||||
|
||||
for (const mod of modsWithGui) {
|
||||
const patchesRoot = join(mod.rootDir, 'client', 'gui-patches');
|
||||
let patches;
|
||||
try {
|
||||
patches = loadGuiPatches(patchesRoot);
|
||||
} catch (error) {
|
||||
failures.push({
|
||||
modId: mod.manifest.id,
|
||||
patchId: `${mod.manifest.id}:gui-patches`,
|
||||
features: [],
|
||||
reason: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const patch of patches) {
|
||||
try {
|
||||
const chosen = chooseVariant(patch.variants, (variant) => patchedScript(archive, variant, hostPortText));
|
||||
putFile(archive, chosen.variant.file, Buffer.from(chosen.value, 'utf8'));
|
||||
applied.push({ modId: mod.manifest.id, patchId: patch.id });
|
||||
} catch (error) {
|
||||
if (!(error instanceof PatchError)) throw error;
|
||||
failures.push({
|
||||
modId: mod.manifest.id,
|
||||
patchId: patch.id,
|
||||
features: patch.features,
|
||||
reason: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { pack: writeArchive(archive), applied, failures };
|
||||
}
|
||||
|
||||
function patchedScript(archive: Archive, variant: GuiScriptVariant, hostPortText: string): string {
|
||||
if (!archive.files.has(variant.file)) throw new ModGuiPatchMismatch(`the data pack has no script ${variant.file}`);
|
||||
let current = Buffer.from(getFile(archive, variant.file)).toString('utf8');
|
||||
const newline = current.includes('\r\n') ? '\r\n' : '\n';
|
||||
for (const [index, edit] of variant.edits.entries()) {
|
||||
const replace = edit.replace.replaceAll('\n', newline).replaceAll(ENDPOINT_PLACEHOLDER, hostPortText);
|
||||
current = replaceUnique(current, edit.find, replace, `edit ${index + 1} in ${variant.file}`);
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
function replaceUnique(text: string, find: string, replace: string, label: string): string {
|
||||
const { normalized, original } = withoutCarriageReturns(text);
|
||||
const first = normalized.indexOf(find);
|
||||
if (first === -1) throw new ModGuiPatchMismatch(`${label}: target text not found`);
|
||||
if (normalized.indexOf(find, first + find.length) !== -1) {
|
||||
throw new ModGuiPatchMismatch(`${label}: target text appears more than once`);
|
||||
}
|
||||
return text.slice(0, original[first]!) + replace + text.slice(original[first + find.length]!);
|
||||
}
|
||||
|
||||
function withoutCarriageReturns(text: string): { readonly normalized: string; readonly original: readonly number[] } {
|
||||
const kept: string[] = [];
|
||||
const original: number[] = [];
|
||||
let index = 0;
|
||||
while (index < text.length) {
|
||||
original.push(index);
|
||||
if (text[index] === '\r' && text[index + 1] === '\n') {
|
||||
kept.push('\n');
|
||||
index += 2;
|
||||
} else {
|
||||
kept.push(text[index]!);
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
original.push(text.length);
|
||||
return { normalized: kept.join(''), original };
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Apply ordered mod pack operations (`blk-patch`, `csv-patch`, or added/replaced files)
|
||||
* onto an in-memory .vromfs.bin archive without modifying stock backups.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap } from '@wto/blk';
|
||||
import {
|
||||
applyBlkPatch,
|
||||
mergeLocalizationCsv,
|
||||
parseBlkPatchDocument,
|
||||
type DiscoveredMod,
|
||||
type ModdableClientPack,
|
||||
} from '@wto/mods';
|
||||
import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
|
||||
|
||||
export interface PackOverlayReport {
|
||||
readonly pack: ModdableClientPack;
|
||||
readonly operationsApplied: number;
|
||||
}
|
||||
|
||||
export function applyModPackOverlays(
|
||||
basePack: Uint8Array,
|
||||
packName: ModdableClientPack,
|
||||
mods: readonly DiscoveredMod[],
|
||||
): { readonly pack: Uint8Array; readonly report: PackOverlayReport } {
|
||||
const relevant = mods.flatMap((mod) =>
|
||||
mod.content.packOperations
|
||||
.filter((op) => op.pack === packName)
|
||||
.map((op) => ({ mod, op })),
|
||||
);
|
||||
if (relevant.length === 0) {
|
||||
return { pack: basePack, report: { pack: packName, operationsApplied: 0 } };
|
||||
}
|
||||
|
||||
const archive = readArchive(basePack);
|
||||
const dictionary = findDictionary(archive);
|
||||
const names = archive.files.has(NAME_MAP_PATH)
|
||||
? parseSharedNameMap(getFile(archive, NAME_MAP_PATH), dictionary).names
|
||||
: [];
|
||||
|
||||
for (const { mod, op } of relevant) {
|
||||
const sourcePath = join(mod.rootDir, ...op.sourceRelativePath.split('/'));
|
||||
const where = `mod "${mod.manifest.id}" (${op.sourceRelativePath})`;
|
||||
switch (op.action) {
|
||||
case 'blk-patch': {
|
||||
const resolvedPath = findArchivePath(archive, op.targetPath);
|
||||
if (!resolvedPath) {
|
||||
throw new Error(`${where}: target BLK "${op.targetPath}" not found in ${packName}`);
|
||||
}
|
||||
const raw = getFile(archive, resolvedPath);
|
||||
const root = isBinaryBlk(raw)
|
||||
? decodeBlk(raw, { names, dictionary })
|
||||
: parseBlkText(Buffer.from(raw).toString('utf8'));
|
||||
const patch = parseBlkPatchDocument(readFileSync(sourcePath, 'utf8'), where);
|
||||
applyBlkPatch(root, patch, where);
|
||||
putFile(archive, resolvedPath, encodeBlk(root));
|
||||
break;
|
||||
}
|
||||
case 'csv-patch': {
|
||||
const resolvedPath = findArchivePath(archive, op.targetPath);
|
||||
if (!resolvedPath) {
|
||||
throw new Error(`${where}: target CSV "${op.targetPath}" not found in ${packName}`);
|
||||
}
|
||||
const baseText = Buffer.from(getFile(archive, resolvedPath)).toString('utf8');
|
||||
const patchText = readFileSync(sourcePath, 'utf8');
|
||||
const merged = mergeLocalizationCsv(baseText, patchText);
|
||||
putFile(archive, resolvedPath, Buffer.from(merged, 'utf8'));
|
||||
break;
|
||||
}
|
||||
case 'file': {
|
||||
const bytes = readFileSync(sourcePath);
|
||||
const resolvedPath = findArchivePath(archive, op.targetPath) ?? op.targetPath;
|
||||
if (op.targetPath.toLowerCase().endsWith('.blk') && !isBinaryBlk(bytes)) {
|
||||
const parsed = parseBlkText(bytes.toString('utf8'));
|
||||
putFile(archive, resolvedPath, encodeBlk(parsed));
|
||||
} else {
|
||||
putFile(archive, resolvedPath, bytes);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
pack: writeArchive(archive),
|
||||
report: { pack: packName, operationsApplied: relevant.length },
|
||||
};
|
||||
}
|
||||
|
||||
function findArchivePath(archive: Archive, wanted: string): string | undefined {
|
||||
if (archive.files.has(wanted)) return wanted;
|
||||
const lower = wanted.toLowerCase();
|
||||
for (const key of archive.files.keys()) {
|
||||
if (key.toLowerCase() === lower) return key;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function findDictionary(archive: Archive): Uint8Array | undefined {
|
||||
const dictionaries = [...archive.files.keys()].filter((path) => path.endsWith('.dict'));
|
||||
return dictionaries.length === 1 ? archive.files.get(dictionaries[0]!) : undefined;
|
||||
}
|
||||
Reference in new issue
Block a user