// Vanilla + mod load semantics for EU4's directory-level overlay model. // // There is no `replace_path` entry in this mod's descriptor.mod (confirmed // by direct inspection), so every directory here is loaded as a file-level // overlay: vanilla's files load first, then the mod's files load on top, // per the rules in the table below (measured against the real vanilla + // Ab_Integro install, not assumed from EU4 documentation in general). // // common/country_tags/ merge: every file loads, tags accumulate. Each // file is itself a table of TAG = "path" pointers // (not one-tag-per-file), so the merge unit is tag // *entries inside files*, not whole files. // common/countries/ same-filename whole-file replace // history/provinces/ match by leading numeric ID, replace // history/countries/ match by leading 3-letter TAG, replace // common/cultures/ same filename replaces; different filename is // spec'd to "append" — see the dedicated note on // CULTURES_MODE below, this collapses to the same // file-selection algorithm as `replace`. // (default) same-filename replace // // This module never parses game *data* beyond what's needed to resolve // country_tags pointers (which are themselves TAG = "path" pairs, so // resolving them requires tokenizing+parsing those specific files — every // other directory here is selected by filename alone). import { readdir } from 'node:fs/promises'; import { join } from 'node:path'; import { tokenize } from './lexer.mjs'; import { parse } from './ast.mjs'; import { readGameText } from './codec.mjs'; const PROVINCE_ID_RE = /^(\d+)/; const COUNTRY_TAG_RE = /^([A-Z]{3})\b/; /** * @param {string} filename * @returns {string|null} */ export function extractProvinceId(filename) { const m = PROVINCE_ID_RE.exec(filename); return m ? m[1] : null; } /** * @param {string} filename * @returns {string|null} */ export function extractCountryTag(filename) { const m = COUNTRY_TAG_RE.exec(filename); return m ? m[1] : null; } // Static directory -> mode table. Anything not listed here defaults to // 'replace', which is exactly what makes overlay.dir()/loadDir() work for // any directory with zero registration: they consult this same table with // the same fallback, nothing needs to be declared up front. const MODE_TABLE = new Map([ ['common/country_tags', 'merge'], ['history/provinces', 'province-id'], ['history/countries', 'country-tag'], ['common/cultures', 'cultures'], ]); /** * @param {string} relPath - forward-slash-normalized relative path, e.g. "history/provinces" * @returns {'merge'|'province-id'|'country-tag'|'cultures'|'replace'} */ export function modeFor(relPath) { const normalized = relPath.replace(/\\/g, '/').replace(/\/+$/, ''); return MODE_TABLE.get(normalized) ?? 'replace'; } async function listFiles(dir) { let entries; try { entries = await readdir(dir, { withFileTypes: true }); } catch { return []; } return entries .filter((e) => e.isFile() && e.name.toLowerCase().endsWith('.txt')) .map((e) => e.name); } // Shared by 'replace' and 'cultures' modes: key by filename, mod entries // overlay vanilla entries on the same filename, everything else (unique to // either side) just accumulates. This is deliberately the SAME algorithm // for both modes — see the header note on 'cultures' above. A file unique // to the mod under this algorithm keeps its own filename as its key, which // is indistinguishable at the file-selection level from a true "append"; // the append/replace distinction only becomes meaningful one layer up, once // something merges parsed culture *entries* across files sharing a // namespace, which is out of scope for this function's job of picking // which file wins for a given key. function replaceByFilename(vanillaFiles, modFiles, gameDir, modDir, relPath) { const entries = new Map(); const ambiguities = []; for (const name of vanillaFiles) { entries.set(name, { path: join(gameDir, name), layer: 'vanilla' }); } for (const name of modFiles) { entries.set(name, { path: join(modDir, name), layer: 'mod' }); } return { entries, ambiguities }; } // Shared by 'province-id' and 'country-tag' modes: key by a prefix // extracted from the filename. Mod wins over vanilla on the same key // (normal overlay). Two different filenames resolving to the SAME key // within the same layer (mod-vs-mod, or vanilla-vs-vanilla) is an // ambiguity: EU4 loads both and which one wins depends on filesystem // order, so this is reported rather than silently resolved. Confirmed real // cases: history/countries/ has CMP - Rewa Kantha.txt + CMP - RewaKantha.txt, // and SOF - Segu.txt + SOF - Sofala.txt, both within the mod layer. function replaceByExtractedKey(vanillaFiles, modFiles, gameDir, modDir, relPath, extractKey) { const entries = new Map(); const ambiguities = []; // Track, per layer, every filename seen for a given key so within-layer // collisions can be reported with all competing paths. const seenPerLayer = new Map(); // key -> { vanilla: string[], mod: string[] } function note(key, layer, filename) { let rec = seenPerLayer.get(key); if (!rec) { rec = { vanilla: [], mod: [] }; seenPerLayer.set(key, rec); } rec[layer].push(filename); } for (const name of vanillaFiles) { const key = extractKey(name); if (key === null) continue; note(key, 'vanilla', name); if (!entries.has(key)) { entries.set(key, { path: join(gameDir, name), layer: 'vanilla' }); } } for (const name of modFiles) { const key = extractKey(name); if (key === null) continue; note(key, 'mod', name); const existing = entries.get(key); if (!existing || existing.layer === 'vanilla') { // First mod claim for this key, or overlaying a vanilla entry: normal // overlay, mod wins. entries.set(key, { path: join(modDir, name), layer: 'mod' }); } // Else: a different mod filename already claimed this key — leave the // first mod claim active (deterministic single winner for callers that // just want ONE node), the ambiguity itself is reported below from // seenPerLayer so nothing is silently dropped from view. } for (const [key, rec] of seenPerLayer) { if (rec.vanilla.length > 1) { ambiguities.push({ dir: relPath, key, layer: 'vanilla', paths: rec.vanilla.map((n) => join(gameDir, n)), }); } if (rec.mod.length > 1) { ambiguities.push({ dir: relPath, key, layer: 'mod', paths: rec.mod.map((n) => join(modDir, n)), }); } } return { entries, ambiguities }; } // country_tags is a genuine special case: the files themselves are not // game-data records, they are TAG = "relative/path" pointer tables. The // merge unit is tag *entries*, and "loading" a tag means resolving its // pointer against common/ and reading THAT file's text — which is why this // mode alone needs to tokenize+parse eagerly (every other mode only reads // bytes for whichever winning file a caller actually asks for, deferred to // index.mjs; this one has to look inside every tags file just to know what // keys exist at all). async function loadCountryTagsMerge(gameDir, modDir, relPath, gameRoot, modRoot) { const entries = new Map(); const ambiguities = []; async function ingest(dir, root, layer, filenames) { for (const name of filenames) { const path = join(dir, name); const { text } = await readGameText(path); const tokens = tokenize(text); const tree = parse(tokens); for (const item of tree.items) { if (item.kind !== 'pair' || item.value.type !== 'scalar' || !item.value.token) continue; const tag = item.keyToken.value; const pointer = item.value.token.value; // e.g. "countries/Rebels.txt" const resolvedPath = join(root, 'common', ...pointer.split(/[\\/]/)); const existing = entries.get(tag); if (existing && existing.layer === layer) { ambiguities.push({ dir: relPath, key: tag, layer, paths: [existing.path, resolvedPath], }); continue; } entries.set(tag, { path: resolvedPath, layer }); } } } const vanillaFiles = await listFiles(gameDir); const modFiles = await listFiles(modDir); await ingest(gameDir, gameRoot, 'vanilla', vanillaFiles); await ingest(modDir, modRoot, 'mod', modFiles); // mod entries overlay vanilla on same tag, by insertion after return { entries, ambiguities }; } /** * Resolve which files win for one directory, across vanilla + mod, per the * table above. Does NOT read file contents (except for 'merge' mode, which * must look inside country_tags files to find their tag keys at all) — * callers that need text/bom/encoding should read the winning `path` via * codec.mjs themselves; index.mjs does this when building Nodes. * * @param {{ gameRoot: string, modRoot: string, relPath: string }} spec * @returns {Promise<{ entries: Map, ambiguities: Array }>} */ export async function loadDir({ gameRoot, modRoot, relPath }) { const normalized = relPath.replace(/\\/g, '/').replace(/\/+$/, ''); const gameDir = join(gameRoot, normalized); const modDir = join(modRoot, normalized); const mode = modeFor(normalized); if (mode === 'merge') { return loadCountryTagsMerge(gameDir, modDir, normalized, gameRoot, modRoot); } const vanillaFiles = await listFiles(gameDir); const modFiles = await listFiles(modDir); if (mode === 'province-id') { return replaceByExtractedKey(vanillaFiles, modFiles, gameDir, modDir, normalized, extractProvinceId); } if (mode === 'country-tag') { return replaceByExtractedKey(vanillaFiles, modFiles, gameDir, modDir, normalized, extractCountryTag); } // 'replace' and 'cultures' share the same file-selection algorithm — see // the note on replaceByFilename above for why. return replaceByFilename(vanillaFiles, modFiles, gameDir, modDir, normalized); } /** * Zero-config accessor: resolves any directory's overlay without it being * registered anywhere. Internally this is exactly `loadDir` consulting the * same MODE_TABLE-with-'replace'-fallback that every other path uses. * * @param {string} relPath * @param {{ gameRoot: string, modRoot: string }} roots */ export function dir(relPath, roots) { return loadDir({ gameRoot: roots.gameRoot, modRoot: roots.modRoot, relPath }); } /** * A collection over a resolved directory: identical API for every * directory, parsing files lazily (on first access to a given key) via the * injected `parseFn` so this module never needs to import node.mjs (keeping * the dependency direction one-way: index.mjs wires node construction in). * * @param {Map} entries * @param {(entry: {path:string, layer:'vanilla'|'mod'}) => Promise} parseFn */ export function makeCollection(entries, parseFn) { const cache = new Map(); async function resolve(key) { if (cache.has(key)) return cache.get(key); const entry = entries.get(key); if (!entry) throw new Error(`collection.get(): no entry for key "${key}"`); const node = await parseFn(entry); cache.set(key, node); return node; } return { get(key) { return resolve(key); }, async all() { const out = []; for (const key of entries.keys()) out.push(await resolve(key)); return out; }, async where(predicate) { const nodes = await this.all(); if (typeof predicate === 'function') return nodes.filter(predicate); return nodes.filter((node) => Object.entries(predicate).every(([k, v]) => node.get(k) === v)); }, }; }