Ame
feat(integration): add merged EU4 content and localization
37a34fd
Raw
History Blame Contribute Delete
14.9 kB
// 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 };