File size: 14,908 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// The reference graph: defined-sets (what identifiers are LEGAL) merged
// across vanilla+mod, plus generic forward/reverse resolution driven by
// registry `refs` declarations (registry.mjs / registry/*.mjs) — nothing
// here is hand-written per province/country, it all falls out of walking
// whatever `refs` a registry happens to declare.
//
// Every extraction rule below was measured against the real vanilla+mod
// install before being encoded here (see the Phase 3 plan for the
// research notes); none of these are guesses from EU4 documentation.

import { readdir, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tokenize } from './lexer.mjs';
import { parse } from './ast.mjs';
import { readGameText } from './codec.mjs';
import { isDateKey } from './node.mjs';

async function listTxtFiles(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) => join(dir, e.name));
}

async function listYmlFilesRecursive(dir, out = []) {
  let entries;
  try {
    entries = await readdir(dir, { withFileTypes: true });
  } catch {
    return out;
  }
  for (const entry of entries) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) {
      await listYmlFilesRecursive(path, out);
    } else if (entry.isFile() && entry.name.toLowerCase().endsWith('.yml')) {
      out.push(path);
    }
  }
  return out;
}

async function listYmlFilesFlat(dir) {
  let entries;
  try {
    entries = await readdir(dir, { withFileTypes: true });
  } catch {
    return [];
  }
  return entries
    .filter((e) => e.isFile() && e.name.toLowerCase().endsWith('.yml'))
    .map((e) => join(dir, e.name));
}

// country_tags files are simple `TAG = "path"` line tables (see
// overlay.mjs's header note) — a line-level regex is exact here, no false
// positives observed against the real data, and it's far cheaper than
// tokenizing every file just to read a bare key.
const TAG_LINE_RE = /^\s*([A-Z0-9]{3})\s*=/;

/**
 * Every legal 3-letter country tag, merged across vanilla + mod
 * common/country_tags/*.txt. This is the correct validity check for "is
 * this tag legal" for province/country reference fields — NOT the set of
 * tags that happen to have a history/countries file (many legal tags,
 * including REB, have no history file at all; REB itself resolves here
 * with zero special-casing because it is a normal entry in vanilla's
 * country_tags files, used 628 times across real province data).
 *
 * @param {{ gameRoot: string, modRoot: string }} roots
 * @returns {Promise<Set<string>>}
 */
export async function buildTagSet({ gameRoot, modRoot }) {
  const tags = new Set();
  const dirs = [join(gameRoot, 'common', 'country_tags'), join(modRoot, 'common', 'country_tags')];
  for (const dir of dirs) {
    for (const file of await listTxtFiles(dir)) {
      const { text } = await readGameText(file);
      for (const line of text.split(/\r?\n/)) {
        const m = TAG_LINE_RE.exec(line);
        if (m) tags.add(m[1]);
      }
    }
  }
  return tags;
}

// Depth-2 keys that are real fields of a culture GROUP or of the pooled
// name lists, never a culture identifier by themselves. `country`/
// `province` are group-level trigger/effect blocks seen only under
// iberian/japanese_g in the real file, not culture ids. Deliberately does
// NOT require a `primary` child as a discriminator — confirmed real,
// referenced cultures (norse, acholi, cherven, ...) have no `primary`.
const CULTURE_EXCLUDE = new Set([
  'dynasty_names',
  'male_names',
  'female_names',
  'graphical_culture',
  'second_graphical_culture',
  'country',
  'province',
]);

/**
 * Every legal culture identifier, from the mod's merged
 * common/cultures/00_cultures.txt (the only file in either layer today;
 * mod's file already reflects the 'cultures' overlay mode's same-filename
 * replace, mod wins — see overlay.mjs).
 *
 * @param {{ gameRoot: string, modRoot: string }} roots
 * @returns {Promise<Set<string>>}
 */
export async function buildCultureSet({ gameRoot, modRoot }) {
  const path = await pickWinningCulturesFile({ gameRoot, modRoot });
  const cultures = new Set();
  if (!path) return cultures;
  const { text } = await readGameText(path);
  const tree = parse(tokenize(text));
  for (const groupItem of tree.items) {
    if (groupItem.kind !== 'pair' || groupItem.value.type !== 'block') continue;
    for (const inner of groupItem.value.items) {
      if (inner.kind !== 'pair') continue;
      if (CULTURE_EXCLUDE.has(inner.keyToken.value)) continue;
      cultures.add(inner.keyToken.value);
    }
  }
  return cultures;
}

// common/cultures uses 'cultures' overlay mode (same filename replaces,
// mod wins) — the winning file for the one real filename
// (00_cultures.txt) is the mod's if present, else vanilla's.
async function pickWinningCulturesFile({ gameRoot, modRoot }) {
  const modFile = join(modRoot, 'common', 'cultures', '00_cultures.txt');
  const gameFile = join(gameRoot, 'common', 'cultures', '00_cultures.txt');
  if (await fileExists(modFile)) return modFile;
  if (await fileExists(gameFile)) return gameFile;
  return null;
}

async function fileExists(path) {
  try {
    await readFile(path);
    return true;
  } catch {
    return false;
  }
}

/**
 * Every legal religion identifier: depth-1 blocks inside
 * common/religions/00_religion.txt (vanilla only — no mod override exists
 * today) that themselves contain a `color` child. The `color` check is
 * what discriminates real religions from group-level fields like
 * `flag_emblem_index_range`, `religious_schools`, `defender_of_faith`,
 * `crusade_name`, `harmonized_modifier`, etc.
 *
 * @param {{ gameRoot: string, modRoot: string }} roots
 * @returns {Promise<Set<string>>}
 */
export async function buildReligionSet({ gameRoot, modRoot }) {
  const modFile = join(modRoot, 'common', 'religions', '00_religion.txt');
  const gameFile = join(gameRoot, 'common', 'religions', '00_religion.txt');
  const path = (await fileExists(modFile)) ? modFile : gameFile;
  const religions = new Set();
  if (!(await fileExists(path))) return religions;
  const { text } = await readGameText(path);
  const tree = parse(tokenize(text));
  for (const groupItem of tree.items) {
    if (groupItem.kind !== 'pair' || groupItem.value.type !== 'block') continue;
    for (const inner of groupItem.value.items) {
      if (inner.kind !== 'pair' || inner.value.type !== 'block') continue;
      const hasColor = inner.value.items.some((gi) => gi.kind === 'pair' && gi.keyToken.value === 'color');
      if (hasColor) religions.add(inner.keyToken.value);
    }
  }
  return religions;
}

/**
 * Every legal trade good identifier: every top-level pair-with-block key
 * in common/tradegoods/00_tradegoods.txt (vanilla only, no mod override
 * exists today).
 *
 * @param {{ gameRoot: string, modRoot: string }} roots
 * @returns {Promise<Set<string>>}
 */
export async function buildTradegoodSet({ gameRoot, modRoot }) {
  const modFile = join(modRoot, 'common', 'tradegoods', '00_tradegoods.txt');
  const gameFile = join(gameRoot, 'common', 'tradegoods', '00_tradegoods.txt');
  const path = (await fileExists(modFile)) ? modFile : gameFile;
  const tradegoods = new Set();
  if (!(await fileExists(path))) return tradegoods;
  const { text } = await readGameText(path);
  const tree = parse(tokenize(text));
  for (const item of tree.items) {
    if (item.kind === 'pair' && item.value.type === 'block') tradegoods.add(item.keyToken.value);
  }
  return tradegoods;
}

// Localisation key lines look like ` KEY:0 "value"` (or ` KEY:N "value"`),
// possibly with no leading space. A bare key regex (stop at the first `:`)
// is exact for both mod (no BOM, plain UTF-8) and vanilla (leading UTF-8
// BOM, stripped defensively below) files.
const LOC_LINE_RE = /^\s*([A-Za-z0-9_.'-]+):/;

/**
 * Every localisation key defined anywhere across mod
 * localisation_source/**\/*.yml (recursive — has a nested replace/
 * subdir) plus vanilla localisation/*.yml (flat, one level).
 *
 * @param {{ gameRoot: string, modRoot: string }} roots
 * @returns {Promise<Set<string>>}
 */
export async function buildLocKeySet({ gameRoot, modRoot }) {
  const keys = new Set();
  const files = [
    ...(await listYmlFilesRecursive(join(modRoot, 'localisation_source'))),
    ...(await listYmlFilesFlat(join(gameRoot, 'localisation'))),
  ];
  for (const file of files) {
    const { text } = await readGameText(file);
    const stripped = text.startsWith('') ? text.slice(1) : text;
    for (const line of stripped.split(/\r?\n/)) {
      if (/^\s*l_[a-z_]+:\s*$/.test(line)) continue; // the `l_english:` header line itself
      const m = LOC_LINE_RE.exec(line);
      if (m) keys.add(m[1]);
    }
  }
  return keys;
}

/**
 * Build every defined-set at once. Convenience wrapper so callers (the
 * validator, tests) don't have to remember all five builder names.
 *
 * @param {{ gameRoot: string, modRoot: string }} roots
 */
export async function buildDefinedSets(roots) {
  const [tags, cultures, religions, tradegoods, locKeys] = await Promise.all([
    buildTagSet(roots),
    buildCultureSet(roots),
    buildReligionSet(roots),
    buildTradegoodSet(roots),
    buildLocKeySet(roots),
  ]);
  return { tags, cultures, religions, tradegoods, locKeys };
}

// refs targets that resolve against a defined-set rather than against
// another registry's own record collection. `countries` deliberately maps
// to the tag defined-set, not to the `countries` registry's collection —
// see this module's header note and registry/provinces.mjs's comment.
const DEFINED_SET_TARGETS = {
  countries: 'tags',
  cultures: 'cultures',
  religions: 'religions',
  tradegoods: 'tradegoods',
};

/**
 * Walk every record of every given registry's collection and check every
 * field the registry's `refs` map declares against the appropriate
 * defined-set, building both a forward list of resolutions (including
 * failures) and a reverse index (definedSetName -> value -> [{registry,
 * id, field}]) of who references what. Nothing here is specific to
 * provinces/countries — it's entirely driven by `registry.refs`.
 *
 * Skips date-block keys at the top level (isDateKey) so only
 * start-of-game (bare, pre-date) fields are checked — matching how
 * province ownership etc. is actually authored: the bare top-level field
 * IS the start-of-game value, per node.mjs's at() semantics.
 *
 * @param {Object} eu4 - the loaded session (src/index.mjs's `load()` result); needs `dir()`
 * @param {{ gameRoot: string, modRoot: string }} roots - same roots `eu4` was built with; needed to enumerate a directory's keys (overlay.mjs's makeCollection doesn't expose its key list, only get/all/where)
 * @param {import('./registry.mjs').RegistryDescriptor[]} registries
 * @param {{ tags: Set, cultures: Set, religions: Set, tradegoods: Set, locKeys: Set }} definedSets
 */
export async function buildRefGraph(eu4, roots, registries, definedSets) {
  const forward = []; // { registry, id, field, value, target, ok }
  const reverse = new Map(); // targetSetName -> value -> [{registry, id, field}]

  function recordReverse(targetSetName, value, entry) {
    let byValue = reverse.get(targetSetName);
    if (!byValue) {
      byValue = new Map();
      reverse.set(targetSetName, byValue);
    }
    let list = byValue.get(value);
    if (!list) {
      list = [];
      byValue.set(value, list);
    }
    list.push(entry);
  }

  for (const registry of registries) {
    const refFields = Object.keys(registry.refs ?? {});
    if (refFields.length === 0) continue;

    const collection = await eu4.dir(registry.path);
    const keys = await collectionKeys(roots, registry);

    for (const id of keys) {
      const node = await collection.get(id);
      for (const field of refFields) {
        const targetRegistryName = registry.refs[field];
        const targetSetName = DEFINED_SET_TARGETS[targetRegistryName] ?? targetRegistryName;
        const definedSet = definedSets[targetSetName];
        if (!definedSet) continue; // target not built (e.g. a registry with no defined-set yet) — skip, not an error

        const values = readFieldValues(node, field, registry.multi.includes(field));
        for (const value of values) {
          const ok = definedSet.has(value);
          forward.push({ registry: registry.as, id, field, value, target: targetSetName, ok });
          recordReverse(targetSetName, value, { registry: registry.as, id, field });
        }
      }
    }
  }

  return { forward, reverse };
}

// Registries here are keyed by extracted-prefix (province-id / country-tag)
// or by filename, matching overlay.mjs's loadDir output — the collection's
// underlying entries Map already has exactly the right key set, but
// makeCollection() doesn't expose the key list directly, so we go back to
// loadDir ourselves rather than threading a new method through overlay.mjs.
async function collectionKeys(roots, registry) {
  const { loadDir } = await import('./overlay.mjs');
  const { entries } = await loadDir({ gameRoot: roots.gameRoot, modRoot: roots.modRoot, relPath: registry.path });
  return [...entries.keys()];
}

/**
 * Read a field's start-of-game (non-date-block) values off a plain Node
 * (not sugared) as an array — [] if absent, one entry for a scalar field,
 * every entry for a multi field. Skips date-key items entirely (only the
 * bare/top pre-date fields represent start-of-game state).
 *
 * @param {import('./node.mjs').Node} node
 * @param {string} field
 * @param {boolean} isMulti
 */
export function readFieldValues(node, field, isMulti) {
  // node.keys() already excludes nothing by date — but get()/all() operate
  // over ALL matches of a key regardless of whether they're inside a date
  // block, because date-block contents are only reachable via blocks(),
  // never via get()/all() on the outer node (see node.mjs: matches() only
  // scans `this.items`, and a date block's inner pairs live in a nested
  // BlockValue's own `items`, not in the outer node's `items`). So get()/
  // all() on the un-resolved node are ALREADY start-of-game-only by
  // construction — no extra isDateKey filtering is needed here.
  //
  // Deliberately ALWAYS uses all() here, never get() — even for fields not
  // declared `multi`. Real data has at least one case (a Wild-Fields-style
  // province's `tribal_owner`) repeating at top level despite not being on
  // the spec's given multi-list; get() throws on any duplicate, which would
  // crash the whole validation run over one unexpected-but-real repeat.
  // `isMulti` is accepted for API symmetry/documentation but not required
  // for correctness here.
  return node.all(field);
}

export { isDateKey };