File size: 12,053 Bytes
37a34fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// 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<string, {path:string, layer:'vanilla'|'mod'}>, 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<string, {path:string, layer:'vanilla'|'mod'}>} entries
 * @param {(entry: {path:string, layer:'vanilla'|'mod'}) => Promise<any>} 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));
    },
  };
}