hoi4-agent-tools 4.19.0 → 4.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/hoi4_agent_tools/core/diagnostic-rollup.js +9 -1
  3. package/dist/hoi4_agent_tools/core/domain-validation.js +3 -16
  4. package/dist/hoi4_agent_tools/core/engine-operation.js +27 -0
  5. package/dist/hoi4_agent_tools/core/job-worker-host.js +127 -11
  6. package/dist/hoi4_agent_tools/core/transactions.js +127 -5
  7. package/dist/hoi4_agent_tools/core/workspace.js +118 -67
  8. package/dist/hoi4_agent_tools/event/algorithms.js +14 -2
  9. package/dist/hoi4_agent_tools/gui/layout.js +10 -6
  10. package/dist/hoi4_agent_tools/gui/renderer.js +74 -34
  11. package/dist/hoi4_agent_tools/gui/source-graph.js +12 -0
  12. package/dist/hoi4_agent_tools/gui/studio.js +2 -0
  13. package/dist/hoi4_agent_tools/map/baseline.js +143 -0
  14. package/dist/hoi4_agent_tools/map/diagnostic-limit.js +14 -13
  15. package/dist/hoi4_agent_tools/map/service.js +112 -15
  16. package/dist/hoi4_agent_tools/map/tool-operations.js +10 -0
  17. package/dist/hoi4_agent_tools/map/validation.js +13 -5
  18. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -0
  19. package/dist/hoi4_agent_tools/schemas/map-requests.js +6 -0
  20. package/dist/hoi4_agent_tools/version.js +1 -1
  21. package/docs/map.md +29 -0
  22. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  23. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  24. package/engine/bin/linux-x64/hoi4-engine +0 -0
  25. package/engine/bin/manifest.json +8 -8
  26. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  27. package/npm-shrinkwrap.json +2 -2
  28. package/package.json +1 -1
  29. package/schemas/configuration.schema.json +1 -1
  30. package/schemas/continuous-focus-palette.schema.json +1 -1
  31. package/schemas/custom-weighted-pool.schema.json +1 -1
  32. package/schemas/decision-inspect-input.schema.json +1 -1
  33. package/schemas/error-log-input.schema.json +1 -1
  34. package/schemas/event-feature-manifest.schema.json +1 -1
  35. package/schemas/focus-plan.schema.json +1 -1
  36. package/schemas/focus-planning-sidecar.schema.json +1 -1
  37. package/schemas/geography-model.schema.json +1 -1
  38. package/schemas/gui-animation-source.schema.json +1 -1
  39. package/schemas/gui-helper.schema.json +1 -1
  40. package/schemas/gui-scenario.schema.json +1 -1
  41. package/schemas/helper-expansion-request.schema.json +1 -1
  42. package/schemas/helper-expansion-summary.schema.json +1 -1
  43. package/schemas/impact-inspect-input.schema.json +1 -1
  44. package/schemas/map-operation.schema.json +1 -1
  45. package/schemas/mechanic-test-input.schema.json +1 -1
  46. package/schemas/mod-index-input.schema.json +1 -1
  47. package/schemas/operation-result.schema.json +1 -1
  48. package/schemas/package-check-input.schema.json +1 -1
  49. package/schemas/package-manifest.schema.json +1 -1
  50. package/schemas/probability-analysis-result.schema.json +1 -1
  51. package/schemas/probability-compare-input.schema.json +1 -1
  52. package/schemas/probability-evaluate-input.schema.json +1 -1
  53. package/schemas/probability-inspect-input.schema.json +1 -1
  54. package/schemas/probability-render-input.schema.json +1 -1
  55. package/schemas/probability-scenario-set.schema.json +1 -1
  56. package/schemas/probability-sequence-input.schema.json +1 -1
  57. package/schemas/probability-simulate-input.schema.json +1 -1
  58. package/schemas/probability-sweep-input.schema.json +1 -1
  59. package/schemas/reference-context-input.schema.json +1 -1
  60. package/schemas/reference-read-input.schema.json +1 -1
  61. package/schemas/reference-search-input.schema.json +1 -1
  62. package/schemas/reference-sheets.schema.json +1 -1
  63. package/schemas/scenario-suite.schema.json +1 -1
  64. package/schemas/scenario-test-input.schema.json +1 -1
  65. package/schemas/script-validate-input.schema.json +1 -1
  66. package/schemas/shared-scenario.schema.json +1 -1
  67. package/schemas/source-lookup-input.schema.json +1 -1
  68. package/server.json +2 -2
@@ -2,6 +2,8 @@ import { lstat, mkdir, opendir, readFile, readdir, realpath } from 'node:fs/prom
2
2
  import path from 'node:path';
3
3
  import { WORKSPACE_MAX_REGISTRATIONS, workspaceRegistrationSchema, } from './configuration.js';
4
4
  import { compareCodeUnits, hashCanonical, sha256Bytes } from './canonical.js';
5
+ import { z } from 'zod/v4';
6
+ import { sharedResidentEngine } from './resident-engine.js';
5
7
  import { ServiceError } from './result.js';
6
8
  import { ServerState } from './server-state.js';
7
9
  import { parseClausewitz } from './source/parser.js';
@@ -299,30 +301,77 @@ export async function containedGeneratedPath(root, ...segments) {
299
301
  }
300
302
  return candidate;
301
303
  }
302
- function assertRelative(relativePath) {
303
- if (relativePath.length === 0)
304
- throw new ServiceError('PATH_EMPTY', 'Workspace-relative path cannot be empty');
305
- if (relativePath.includes('\0'))
306
- throw new ServiceError('PATH_NUL', 'Path contains a NUL byte');
307
- if (path.isAbsolute(relativePath)) {
308
- throw new ServiceError('PATH_ABSOLUTE_REJECTED', 'Only workspace-relative paths are accepted');
309
- }
310
- const segments = relativePath.replaceAll('\\', '/').split('/');
311
- if (segments.some((segment) => segment === '..')) {
312
- throw new ServiceError('PATH_TRAVERSAL', 'Parent path segments are not allowed', {
313
- relativePath,
314
- });
315
- }
316
- if (segments.some((segment) => segment.includes(':'))) {
317
- throw new ServiceError('PATH_ALTERNATE_STREAM', 'Colon characters and alternate data streams are not allowed', {
318
- relativePath,
319
- });
320
- }
321
- if (segments.some((segment) => segment !== '.' && segment.length > 0 && !isPortablePathSegment(segment))) {
322
- throw new ServiceError('PATH_WINDOWS_DEVICE', 'Portable paths cannot contain device names, control characters, or ambiguous characters', {
323
- relativePath,
324
- });
325
- }
304
+ /** The refusals that name the offending relative path in their details. */
305
+ const PATH_REFUSALS_WITH_PATH = new Set([
306
+ 'PATH_TRAVERSAL',
307
+ 'PATH_ALTERNATE_STREAM',
308
+ 'PATH_WINDOWS_DEVICE',
309
+ ]);
310
+ const enginePathAnswerSchema = z.union([
311
+ z
312
+ .object({
313
+ resolved: z
314
+ .object({ path: z.string().min(1), root: z.number().int().nonnegative() })
315
+ .strict()
316
+ .nullable(),
317
+ })
318
+ .strict(),
319
+ z
320
+ .object({ refusal: z.object({ code: z.string().min(1), message: z.string() }).strict() })
321
+ .strict(),
322
+ ]);
323
+ /**
324
+ * Resolve a workspace-relative path in `roots` with the engine's `paths.resolve` (ADR 0089): its
325
+ * refusal, its real path and the index of the root it resolved in, or `undefined` when no root
326
+ * holds it. A missing engine is `ENGINE_UNAVAILABLE`; a file system failure is rethrown with its
327
+ * error code, as the TypeScript walk threw it.
328
+ */
329
+ async function engineResolvePath(request) {
330
+ const outcome = await sharedResidentEngine().request('paths.resolve', {
331
+ relativePath: request.relativePath,
332
+ access: request.access,
333
+ roots: request.roots.map(({ path: rootPath, kind, loadOrder, writable }) => ({
334
+ path: rootPath,
335
+ kind,
336
+ loadOrder,
337
+ writable,
338
+ })),
339
+ ...(request.rootKinds === undefined ? {} : { rootKinds: request.rootKinds }),
340
+ ...(request.reserved === undefined ? {} : { reserved: request.reserved }),
341
+ ...(request.inRoot === true ? { inRoot: true } : {}),
342
+ });
343
+ if (!outcome.ok) {
344
+ if (outcome.kind === 'error' && outcome.code === 'io_error')
345
+ throw Object.assign(new Error(outcome.message), {
346
+ code: typeof outcome.details.errno === 'string' ? outcome.details.errno : 'EIO',
347
+ });
348
+ throw new ServiceError('ENGINE_UNAVAILABLE', outcome.message, outcome.kind === 'unavailable' ? { reason: outcome.reason } : { code: outcome.code });
349
+ }
350
+ const parsed = enginePathAnswerSchema.safeParse(outcome.response.result);
351
+ if (!parsed.success)
352
+ throw new ServiceError('ENGINE_UNAVAILABLE', 'hoi4-engine paths.resolve answered out of shape');
353
+ const answer = parsed.data;
354
+ if ('refusal' in answer)
355
+ return { refusal: answer.refusal };
356
+ if (answer.resolved === null)
357
+ return undefined;
358
+ if (answer.resolved.root >= request.roots.length)
359
+ throw new ServiceError('ENGINE_UNAVAILABLE', 'hoi4-engine paths.resolve named an unknown root');
360
+ return answer.resolved;
361
+ }
362
+ function pathRefusal(refusal, relativePath) {
363
+ return new ServiceError(refusal.code, refusal.message, PATH_REFUSALS_WITH_PATH.has(refusal.code) ? { relativePath } : undefined);
364
+ }
365
+ /**
366
+ * Refuse a relative path that could leave a root or is not portable, without resolving it. The
367
+ * `.hoi4-agent` rule needs a workspace, so it is left to the resolution itself.
368
+ */
369
+ async function refuseUnsafeRelativePath(relativePath) {
370
+ const checked = await engineResolvePath({ relativePath, access: 'read', roots: [] });
371
+ if (checked !== undefined &&
372
+ 'refusal' in checked &&
373
+ checked.refusal.code !== 'PATH_GENERATED_STORAGE_RESERVED')
374
+ throw pathRefusal(checked.refusal, relativePath);
326
375
  }
327
376
  export class WorkspaceResolver {
328
377
  configuration;
@@ -612,61 +661,63 @@ export class WorkspaceResolver {
612
661
  return workspace;
613
662
  }
614
663
  async resolvePath(workspaceId, relativePath, access, rootKinds, principal) {
615
- assertRelative(relativePath);
616
- const workspace = this.get(workspaceId, principal);
617
- const firstSegment = path.posix
618
- .normalize(relativePath.replaceAll('\\', '/'))
619
- .split('/')
620
- .find((segment) => segment !== '.' && segment.length > 0)
621
- ?.toLowerCase();
622
- // Server storage holds other principals' proposals and journals; it is never mod source,
623
- // for reads as well as writes.
624
- if (firstSegment === '.hoi4-agent') {
625
- throw new ServiceError('PATH_GENERATED_STORAGE_RESERVED', 'Generated .hoi4-agent storage cannot be targeted as mod source');
626
- }
627
- const roots = workspace.roots.filter((root) => (rootKinds === undefined || rootKinds.includes(root.kind)) &&
628
- (access === 'read' || root.writable));
629
- for (const root of roots.sort((a, b) => b.loadOrder - a.loadOrder)) {
630
- const candidate = await canonicalPath(path.join(root.path, relativePath));
631
- if (!isWithin(root.path, candidate))
632
- continue;
633
- if (access === 'read' && !(await exists(candidate)))
634
- continue;
635
- if (root.kind === 'mod' &&
636
- (pathsOverlap(workspace.artifactRoot, candidate) ||
637
- pathsOverlap(workspace.cacheRoot, candidate))) {
638
- throw new ServiceError('PATH_GENERATED_STORAGE_RESERVED', 'Artifact and cache storage cannot be targeted as mod source');
639
- }
640
- if (access === 'write') {
641
- const existingParent = await canonicalPath(path.dirname(candidate));
642
- if (!isWithin(root.path, existingParent))
643
- continue;
644
- }
645
- return { path: candidate, root };
646
- }
664
+ // The engine checks the path, resolves it in the roots and refuses an escape (ADR 0089). Server
665
+ // storage (`.hoi4-agent`, artifacts, cache) holds other principals' proposals and journals; it
666
+ // is never mod source, for reads as well as writes.
667
+ const workspace = await this.getAfterPathCheck(workspaceId, relativePath, principal);
668
+ const resolved = await engineResolvePath({
669
+ relativePath,
670
+ access,
671
+ roots: workspace.roots,
672
+ ...(rootKinds === undefined ? {} : { rootKinds: [...rootKinds] }),
673
+ reserved: [workspace.artifactRoot, workspace.cacheRoot],
674
+ });
675
+ if (resolved !== undefined && 'refusal' in resolved)
676
+ throw pathRefusal(resolved.refusal, relativePath);
677
+ if (resolved !== undefined)
678
+ return { path: resolved.path, root: workspace.roots[resolved.root] };
647
679
  throw new ServiceError(access === 'write' ? 'PATH_WRITE_OUTSIDE_ROOTS' : 'PATH_NOT_FOUND_IN_ROOTS', `Path cannot be resolved for ${access} access`, { workspaceId, relativePath, rootKinds });
648
680
  }
649
681
  async resolvePathInRoot(workspaceId, relativePath, rootKind, loadOrder, principal) {
650
- assertRelative(relativePath);
651
- const workspace = this.get(workspaceId, principal);
682
+ const workspace = await this.getAfterPathCheck(workspaceId, relativePath, principal);
652
683
  const root = workspace.roots.find((candidate) => candidate.kind === rootKind && candidate.loadOrder === loadOrder);
653
684
  if (root === undefined) {
685
+ await refuseUnsafeRelativePath(relativePath);
654
686
  throw new ServiceError('PATH_ROOT_NOT_FOUND', 'Configured source root no longer exists', {
655
687
  workspaceId,
656
688
  rootKind,
657
689
  loadOrder,
658
690
  });
659
691
  }
660
- const candidate = await canonicalPath(path.join(root.path, relativePath));
661
- if (!isWithin(root.path, candidate) || !(await exists(candidate))) {
662
- throw new ServiceError('PATH_NOT_FOUND_IN_ROOT', 'Path cannot be resolved in the selected source root', {
663
- workspaceId,
664
- relativePath,
665
- rootKind,
666
- loadOrder,
667
- });
692
+ const resolved = await engineResolvePath({
693
+ relativePath,
694
+ access: 'read',
695
+ roots: [root],
696
+ inRoot: true,
697
+ });
698
+ if (resolved !== undefined && 'refusal' in resolved)
699
+ throw pathRefusal(resolved.refusal, relativePath);
700
+ if (resolved !== undefined)
701
+ return { path: resolved.path, root };
702
+ throw new ServiceError('PATH_NOT_FOUND_IN_ROOT', 'Path cannot be resolved in the selected source root', {
703
+ workspaceId,
704
+ relativePath,
705
+ rootKind,
706
+ loadOrder,
707
+ });
708
+ }
709
+ /**
710
+ * `get`, except that an unsafe relative path is refused first, as the path check ran before the
711
+ * workspace lookup when it was TypeScript.
712
+ */
713
+ async getAfterPathCheck(workspaceId, relativePath, principal) {
714
+ try {
715
+ return this.get(workspaceId, principal);
716
+ }
717
+ catch (error) {
718
+ await refuseUnsafeRelativePath(relativePath);
719
+ throw error;
668
720
  }
669
- return { path: candidate, root };
670
721
  }
671
722
  allowedWorkspaceIds(principal) {
672
723
  const token = this.configuration.http.tokens.find((entry) => entry.principal === principal);
@@ -304,7 +304,19 @@ export function shortestEventPath(graph, fromNodeIds, toNodeIds, options, signal
304
304
  const nodes = nodeMap(graph);
305
305
  const starts = sortedUnique(fromNodeIds).filter((id) => nodes.has(id));
306
306
  const targets = new Set(toNodeIds.filter((id) => nodes.has(id)));
307
- const maps = edgeMaps(eventFlowEdges(graph, options.expandHelpers));
307
+ // Issue 278: a focused graph has helper nodes and no derived edge, so the collapsed projection
308
+ // is built lazily per node, exactly as the trace does. Reading only the flow edges would drop
309
+ // every route that passes through a helper, although the trace reports it.
310
+ const lazyCollapse = !options.expandHelpers &&
311
+ !graph.edges.some(({ derived }) => derived) &&
312
+ graph.nodes.some(({ kind }) => kind === 'helper');
313
+ const structural = lazyCollapse
314
+ ? edgeMaps(graph.edges.filter(({ derived }) => !derived))
315
+ : undefined;
316
+ const maps = edgeMaps(lazyCollapse ? [] : eventFlowEdges(graph, options.expandHelpers));
317
+ const outgoingOf = (nodeId) => structural === undefined
318
+ ? (maps.outgoing.get(nodeId) ?? [])
319
+ : lazyCollapsedEdges(nodes, nodeId, 'downstream', structural, Math.max(256, options.maxNodes * 2), signal);
308
320
  const queue = starts.map((nodeId) => ({ nodeId, depth: 0 }));
309
321
  const visited = new Set(starts);
310
322
  const predecessor = new Map();
@@ -316,7 +328,7 @@ export function shortestEventPath(graph, fromNodeIds, toNodeIds, options, signal
316
328
  const current = queue[cursor++];
317
329
  if (current.depth >= options.maxDepth)
318
330
  continue;
319
- for (const edge of maps.outgoing.get(current.nodeId) ?? []) {
331
+ for (const edge of outgoingOf(current.nodeId)) {
320
332
  if (visited.has(edge.to))
321
333
  continue;
322
334
  if (visited.size >= options.maxNodes)
@@ -1510,10 +1510,14 @@ async function layoutElement(definition, parentRect, inheritedClip, parentScale,
1510
1510
  displayText = `\u00a7R${rawText}_MISSING\u00a7!`;
1511
1511
  const fontName = scalarString(property(definition.attributes, 'font', 'buttonFont'));
1512
1512
  const fontDefinition = fontName === undefined ? undefined : catalog.fontDefinition(fontName);
1513
- const visibleText = visibleHoiText(displayText, {
1514
- ...context.graph.textColours,
1515
- ...fontDefinition?.textColours,
1516
- });
1513
+ const textColours = { ...context.graph.textColours, ...fontDefinition?.textColours };
1514
+ // `text_color_code` names the box's base colour with the same codes as in-text § markup;
1515
+ // an unknown code leaves the font's own colour.
1516
+ const colourCode = scalarString(property(definition.attributes, 'text_color_code'));
1517
+ const baseColour = (colourCode === undefined
1518
+ ? undefined
1519
+ : (textColours[colourCode] ?? hoi4TextColours[colourCode])) ?? fontDefinition?.colour;
1520
+ const visibleText = visibleHoiText(displayText, textColours);
1517
1521
  displayText = visibleText.text;
1518
1522
  context.work.admitText(displayText, `GUI text for ${definition.name}`);
1519
1523
  const resolvedFontMetrics = catalog.resolvedFontMetrics(fontName);
@@ -1574,7 +1578,7 @@ async function layoutElement(definition, parentRect, inheritedClip, parentScale,
1574
1578
  inlineIcons.push(...shaped.icons);
1575
1579
  }
1576
1580
  const colourRuns = visibleText.hasColourMarkup
1577
- ? wrapped.lines.map((line, index) => colourRunsForLine(catalog, fontName, line, wrapped.colourLines[index] ?? [], fontSize * scale, context.work, resolvedInlineIcons, fontDefinition?.colour ?? defaultTextColour))
1581
+ ? wrapped.lines.map((line, index) => colourRunsForLine(catalog, fontName, line, wrapped.colourLines[index] ?? [], fontSize * scale, context.work, resolvedInlineIcons, baseColour ?? defaultTextColour))
1578
1582
  : undefined;
1579
1583
  const maximumLineWidth = wrapped.widths.reduce((maximum, value) => Math.max(maximum, value), 0);
1580
1584
  if (width === 0 && inferWidth)
@@ -1594,7 +1598,7 @@ async function layoutElement(definition, parentRect, inheritedClip, parentScale,
1594
1598
  metricSource: wrapped.metricSource,
1595
1599
  ...alignment(definition.attributes, embeddedButtonText),
1596
1600
  ...(fontName === undefined ? {} : { fontName }),
1597
- ...(fontDefinition?.colour === undefined ? {} : { colour: fontDefinition.colour }),
1601
+ ...(baseColour === undefined ? {} : { colour: baseColour }),
1598
1602
  ...(fontDefinition?.borderColour === undefined
1599
1603
  ? {}
1600
1604
  : { borderColour: fontDefinition.borderColour }),
@@ -36,6 +36,32 @@ function outlineDefinitionId(key) {
36
36
  function bitmapDefinitionId(key, layer = 'face') {
37
37
  return `gui-font-bitmap-${layer === 'face' ? '' : 'border-'}${sha256Bytes(key).slice(0, 20)}`;
38
38
  }
39
+ /**
40
+ * The textures of one SVG. Each texture's bytes are written once, as a unit-square symbol in
41
+ * `<defs>`, and every draw is a `<use>` that stretches it over its rectangle. Writing the bytes
42
+ * at every use made one nine-slice texture shared by many elements fill the artifact ceiling.
43
+ */
44
+ class TextureDefinitions {
45
+ ids = new Map();
46
+ id(dataUri) {
47
+ let id = this.ids.get(dataUri);
48
+ if (id === undefined) {
49
+ id = `gui-texture-${sha256Bytes(dataUri).slice(0, 20)}`;
50
+ this.ids.set(dataUri, id);
51
+ }
52
+ return id;
53
+ }
54
+ /** The texture stretched over `rect`, like `<image preserveAspectRatio="none">`. */
55
+ use(dataUri, rect, attributes = '') {
56
+ return `<use${attributes} href="#${this.id(dataUri)}" ${rectAttributes(rect)}/>`;
57
+ }
58
+ definitions() {
59
+ return [...this.ids.entries()]
60
+ .sort(([, left], [, right]) => compareCodeUnits(left, right))
61
+ .map(([dataUri, id]) => `<symbol id="${id}" viewBox="0 0 1 1" preserveAspectRatio="none"><image width="1" height="1" href="${dataUri}" preserveAspectRatio="none"/></symbol>`)
62
+ .join('');
63
+ }
64
+ }
39
65
  function sceneGlyphDefinitions(scene) {
40
66
  const outlines = new Map();
41
67
  const bitmaps = new Map();
@@ -92,7 +118,7 @@ function actualGlyphMarkup(glyphLine, originX, baseline, horizontalScale, bitmap
92
118
  .join('');
93
119
  return '';
94
120
  }
95
- function renderText(element, toolText) {
121
+ function renderText(element, toolText, textures) {
96
122
  const text = element.text;
97
123
  if (text === undefined || text.lines.length === 0)
98
124
  return '';
@@ -127,7 +153,7 @@ function renderText(element, toolText) {
127
153
  height: icon.height,
128
154
  };
129
155
  if (icon.sprite?.supported === true && icon.sprite.dataUri !== undefined)
130
- return `<image data-inline-icon="${escapeXml(icon.token)}" ${rectAttributes(iconRect)} href="${icon.sprite.dataUri}" preserveAspectRatio="xMidYMid meet"/>`;
156
+ return textures.use(icon.sprite.dataUri, containedRect(iconRect, icon.sprite.width, icon.sprite.height), ` data-inline-icon="${escapeXml(icon.token)}"`);
131
157
  return `<g data-inline-icon-missing="${escapeXml(icon.token)}"><rect ${rectAttributes(iconRect)} fill="#331f3f" stroke="#ff42d0" stroke-width="1"/><path d="M ${finite(iconRect.x)} ${finite(iconRect.y)} L ${finite(iconRect.x + iconRect.width)} ${finite(iconRect.y + iconRect.height)} M ${finite(iconRect.x + iconRect.width)} ${finite(iconRect.y)} L ${finite(iconRect.x)} ${finite(iconRect.y + iconRect.height)}" stroke="#ff42d0"/></g>`;
132
158
  })
133
159
  .join('');
@@ -209,12 +235,24 @@ function renderText(element, toolText) {
209
235
  const clip = text.fixedSize ? ` clip-path="url(#${textClipId})"` : '';
210
236
  return `${clipDefinition}<g data-source-id="${escapeXml(element.sourceId)}" fill="#f5f2e8" stroke="#12151a" stroke-width="0.6" paint-order="stroke"${clip}>${lines.join('')}</g>`;
211
237
  }
212
- function renderSpriteImage(sprite, rect) {
238
+ /** `rect` shrunk to the texture's aspect ratio and centred, like `xMidYMid meet`. */
239
+ function containedRect(rect, width, height) {
240
+ if (!(width > 0) || !(height > 0) || rect.width <= 0 || rect.height <= 0)
241
+ return rect;
242
+ const scale = Math.min(rect.width / width, rect.height / height);
243
+ return {
244
+ x: rect.x + (rect.width - width * scale) / 2,
245
+ y: rect.y + (rect.height - height * scale) / 2,
246
+ width: width * scale,
247
+ height: height * scale,
248
+ };
249
+ }
250
+ function renderSpriteImage(sprite, rect, textures) {
213
251
  if (!sprite.supported || sprite.dataUri === undefined)
214
252
  return '';
215
- return `<image ${rectAttributes(rect)} href="${sprite.dataUri}" preserveAspectRatio="none"/>`;
253
+ return textures.use(sprite.dataUri, rect);
216
254
  }
217
- function renderSpriteSlice(sprite, source, destination) {
255
+ function renderSpriteSlice(sprite, source, destination, textures) {
218
256
  if (!sprite.supported ||
219
257
  sprite.dataUri === undefined ||
220
258
  source.width <= 0 ||
@@ -222,9 +260,9 @@ function renderSpriteSlice(sprite, source, destination) {
222
260
  destination.width <= 0 ||
223
261
  destination.height <= 0)
224
262
  return '';
225
- return `<svg ${rectAttributes(destination)} viewBox="${finite(source.x)} ${finite(source.y)} ${finite(source.width)} ${finite(source.height)}" preserveAspectRatio="none" overflow="hidden"><image x="0" y="0" width="${finite(sprite.width)}" height="${finite(sprite.height)}" href="${sprite.dataUri}" preserveAspectRatio="none"/></svg>`;
263
+ return `<svg ${rectAttributes(destination)} viewBox="${finite(source.x)} ${finite(source.y)} ${finite(source.width)} ${finite(source.height)}" preserveAspectRatio="none" overflow="hidden">${textures.use(sprite.dataUri, { x: 0, y: 0, width: sprite.width, height: sprite.height })}</svg>`;
226
264
  }
227
- function renderTiledSpriteSlice(element, sprite, source, destination) {
265
+ function renderTiledSpriteSlice(element, sprite, source, destination, textures) {
228
266
  if (!sprite.supported ||
229
267
  sprite.dataUri === undefined ||
230
268
  source.width <= 0 ||
@@ -235,9 +273,9 @@ function renderTiledSpriteSlice(element, sprite, source, destination) {
235
273
  const tileWidth = Math.max(1, source.width * element.scale);
236
274
  const tileHeight = Math.max(1, source.height * element.scale);
237
275
  const id = `gui-tile-${sha256Bytes(`${element.id}:${source.x}:${source.y}:${source.width}:${source.height}`).slice(0, 20)}`;
238
- return `<defs><pattern id="${id}" patternUnits="userSpaceOnUse" x="${finite(destination.x)}" y="${finite(destination.y)}" width="${finite(tileWidth)}" height="${finite(tileHeight)}"><svg width="${finite(tileWidth)}" height="${finite(tileHeight)}" viewBox="${finite(source.x)} ${finite(source.y)} ${finite(source.width)} ${finite(source.height)}" preserveAspectRatio="none" overflow="hidden"><image x="0" y="0" width="${finite(sprite.width)}" height="${finite(sprite.height)}" href="${sprite.dataUri}" preserveAspectRatio="none"/></svg></pattern></defs><rect ${rectAttributes(destination)} fill="url(#${id})"/>`;
276
+ return `<defs><pattern id="${id}" patternUnits="userSpaceOnUse" x="${finite(destination.x)}" y="${finite(destination.y)}" width="${finite(tileWidth)}" height="${finite(tileHeight)}"><svg width="${finite(tileWidth)}" height="${finite(tileHeight)}" viewBox="${finite(source.x)} ${finite(source.y)} ${finite(source.width)} ${finite(source.height)}" preserveAspectRatio="none" overflow="hidden">${textures.use(sprite.dataUri, { x: 0, y: 0, width: sprite.width, height: sprite.height })}</svg></pattern></defs><rect ${rectAttributes(destination)} fill="url(#${id})"/>`;
239
277
  }
240
- function renderCorneredTile(element) {
278
+ function renderCorneredTile(element, textures) {
241
279
  const sprite = element.sprite;
242
280
  const rect = element.unclippedRect;
243
281
  const border = element.spriteBorderSize;
@@ -246,7 +284,7 @@ function renderCorneredTile(element) {
246
284
  border === undefined ||
247
285
  border.width < 0 ||
248
286
  border.height < 0)
249
- return sprite === undefined ? '' : renderSpriteImage(sprite, rect);
287
+ return sprite === undefined ? '' : renderSpriteImage(sprite, rect, textures);
250
288
  const sourceBorderX = Math.min(border.width, sprite.width / 2);
251
289
  const sourceBorderY = Math.min(border.height, sprite.height / 2);
252
290
  const destinationBorderX = Math.min(sourceBorderX * element.scale, rect.width / 2);
@@ -291,13 +329,13 @@ function renderCorneredTile(element) {
291
329
  height: destinationHeights[row] ?? 0,
292
330
  };
293
331
  parts.push(row === 1 && column === 1 && element.spriteTilingCenter === true
294
- ? renderTiledSpriteSlice(element, sprite, source, destination)
295
- : renderSpriteSlice(sprite, source, destination));
332
+ ? renderTiledSpriteSlice(element, sprite, source, destination, textures)
333
+ : renderSpriteSlice(sprite, source, destination, textures));
296
334
  }
297
335
  }
298
336
  return parts.join('');
299
337
  }
300
- function renderProgressbar(element) {
338
+ function renderProgressbar(element, textures) {
301
339
  const rect = element.unclippedRect;
302
340
  const sprite = element.sprite;
303
341
  const secondary = element.secondarySprite;
@@ -332,7 +370,7 @@ function renderProgressbar(element) {
332
370
  width: (region.width / rect.width) * texture.width,
333
371
  height: (region.height / rect.height) * texture.height,
334
372
  };
335
- return renderSpriteSlice(texture, source, region);
373
+ return renderSpriteSlice(texture, source, region, textures);
336
374
  };
337
375
  const content = `${layer(secondary, remainder, element.progressColours?.second)}${layer(sprite, filled, element.progressColours?.first)}`;
338
376
  const filtering = element.progressShader?.textureFiltering;
@@ -342,39 +380,39 @@ function renderProgressbar(element) {
342
380
  const mode = filtering[shrinking ? 'minification' : 'magnification'];
343
381
  return `<g image-rendering="${mode === 'nearest' ? 'optimizeSpeed' : 'optimizeQuality'}">${content}</g>`;
344
382
  }
345
- function renderMaskedShield(element) {
383
+ function renderMaskedShield(element, textures) {
346
384
  const rect = element.unclippedRect;
347
385
  const sprite = element.sprite;
348
386
  const mask = element.secondarySprite;
349
387
  if (sprite?.supported !== true || sprite.dataUri === undefined)
350
388
  return '';
351
389
  if (mask?.supported !== true || mask.dataUri === undefined)
352
- return renderSpriteImage(sprite, rect);
390
+ return renderSpriteImage(sprite, rect, textures);
353
391
  const id = `gui-mask-${sha256Bytes(element.id).slice(0, 20)}`;
354
- return `<defs><mask id="${id}" maskUnits="userSpaceOnUse" ${rectAttributes(rect)}><image ${rectAttributes(rect)} href="${mask.dataUri}" preserveAspectRatio="none"/></mask></defs><image ${rectAttributes(rect)} href="${sprite.dataUri}" preserveAspectRatio="none" mask="url(#${id})"/>`;
392
+ return `<defs><mask id="${id}" maskUnits="userSpaceOnUse" ${rectAttributes(rect)}>${textures.use(mask.dataUri, rect)}</mask></defs>${textures.use(sprite.dataUri, rect, ` mask="url(#${id})"`)}`;
355
393
  }
356
- function renderElementSprite(element) {
394
+ function renderElementSprite(element, textures) {
357
395
  if (element.sprite?.supported !== true || element.sprite.dataUri === undefined)
358
396
  return '';
359
397
  if (element.spriteRenderMode === 'cornered-tile')
360
- return renderCorneredTile(element);
398
+ return renderCorneredTile(element, textures);
361
399
  if (element.spriteRenderMode === 'progressbar')
362
- return renderProgressbar(element);
400
+ return renderProgressbar(element, textures);
363
401
  if (element.spriteRenderMode === 'masked-shield')
364
- return renderMaskedShield(element);
365
- return renderSpriteImage(element.sprite, element.unclippedRect);
402
+ return renderMaskedShield(element, textures);
403
+ return renderSpriteImage(element.sprite, element.unclippedRect, textures);
366
404
  }
367
- function renderBaseElement(element, clipId, toolText) {
405
+ function renderBaseElement(element, clipId, toolText, textures) {
368
406
  if (!element.visible)
369
407
  return '';
370
408
  const rect = element.unclippedRect;
371
409
  const clip = clipId === undefined ? '' : ` clip-path="url(#${clipId})"`;
372
410
  const content = [];
373
411
  if (element.spriteRenderMode === 'progressbar' && element.progressColours !== undefined) {
374
- content.push(renderProgressbar(element));
412
+ content.push(renderProgressbar(element, textures));
375
413
  }
376
414
  else if (element.sprite?.supported === true && element.sprite.dataUri !== undefined) {
377
- const sprite = renderElementSprite(element);
415
+ const sprite = renderElementSprite(element, textures);
378
416
  if (element.spriteShader === undefined)
379
417
  content.push(sprite);
380
418
  else {
@@ -393,7 +431,7 @@ function renderBaseElement(element, clipId, toolText) {
393
431
  if (element.progressRatio !== undefined && element.spriteRenderMode !== 'progressbar') {
394
432
  content.push(`<rect x="${finite(rect.x)}" y="${finite(rect.y)}" width="${finite(rect.width * element.progressRatio)}" height="${finite(rect.height)}" fill="#5ecf8d" fill-opacity="0.65"/>`);
395
433
  }
396
- content.push(renderText(element, toolText));
434
+ content.push(renderText(element, toolText, textures));
397
435
  return `<g id="${escapeXml(element.id)}" data-source="${escapeXml(element.sourcePath)}" data-source-id="${escapeXml(element.sourceId)}"${clip}>${content.join('')}</g>`;
398
436
  }
399
437
  function renderOverlay(element, variant, toolText) {
@@ -423,12 +461,12 @@ function renderOverlay(element, variant, toolText) {
423
461
  }
424
462
  return '';
425
463
  }
426
- function renderTooltipPreview(scene, toolText) {
464
+ function renderTooltipPreview(scene, toolText, textures) {
427
465
  const tooltip = scene.tooltipPreview;
428
466
  if (tooltip === undefined)
429
467
  return '';
430
- return (renderBaseElement(tooltip.element, undefined, toolText) +
431
- renderBaseElement(tooltip.textElement, undefined, toolText));
468
+ return (renderBaseElement(tooltip.element, undefined, toolText, textures) +
469
+ renderBaseElement(tooltip.textElement, undefined, toolText, textures));
432
470
  }
433
471
  function viewFor(scene, variant) {
434
472
  if (variant !== 'cropped' || scene.bounds.width <= 0 || scene.bounds.height <= 0) {
@@ -466,17 +504,18 @@ export function sceneToSvg(scene, variant) {
466
504
  const view = viewFor(scene, variant);
467
505
  assertRenderDimensions(view.width, view.height, `GUI ${variant} SVG`);
468
506
  const toolText = new DeterministicSvgTextRenderer();
507
+ const textures = new TextureDefinitions();
469
508
  const clipDefinitions = scene.elements.flatMap((element, index) => element.clipRect === undefined
470
509
  ? []
471
510
  : [`<clipPath id="clip-${index}"><rect ${rectAttributes(element.clipRect)}/></clipPath>`]);
472
511
  const body = scene.elements
473
- .map((element, index) => renderBaseElement(element, element.clipRect === undefined ? undefined : `clip-${index}`, toolText))
474
- .join('') + renderTooltipPreview(scene, toolText);
512
+ .map((element, index) => renderBaseElement(element, element.clipRect === undefined ? undefined : `clip-${index}`, toolText, textures))
513
+ .join('') + renderTooltipPreview(scene, toolText, textures);
475
514
  const overlays = scene.elements
476
515
  .map((element) => renderOverlay(element, variant, toolText))
477
516
  .join('');
478
517
  const fidelity = escapeXml(canonicalJson(scene.fidelity));
479
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${view.width}" height="${view.height}" viewBox="${finite(view.viewBox.x)} ${finite(view.viewBox.y)} ${finite(view.viewBox.width)} ${finite(view.viewBox.height)}"><metadata data-renderer="hoi4-agent-tools" data-mode="offline">${fidelity}</metadata><defs>${clipDefinitions.join('')}${sceneGlyphDefinitions(scene)}${toolText.definitions()}</defs>${backdrop(scene, view.viewBox)}${body}${overlays}</svg>`;
518
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${view.width}" height="${view.height}" viewBox="${finite(view.viewBox.x)} ${finite(view.viewBox.y)} ${finite(view.viewBox.width)} ${finite(view.viewBox.height)}"><metadata data-renderer="hoi4-agent-tools" data-mode="offline">${fidelity}</metadata><defs>${clipDefinitions.join('')}${textures.definitions()}${sceneGlyphDefinitions(scene)}${toolText.definitions()}</defs>${backdrop(scene, view.viewBox)}${body}${overlays}</svg>`;
480
519
  }
481
520
  async function cooperativeParts(values, render, signal) {
482
521
  const output = [];
@@ -494,13 +533,14 @@ async function sceneToSvgCooperative(scene, variant, signal) {
494
533
  const view = viewFor(scene, variant);
495
534
  assertRenderDimensions(view.width, view.height, `GUI ${variant} SVG`);
496
535
  const toolText = new DeterministicSvgTextRenderer();
536
+ const textures = new TextureDefinitions();
497
537
  const clipDefinitions = await cooperativeParts(scene.elements, (element, index) => element.clipRect === undefined
498
538
  ? ''
499
539
  : `<clipPath id="clip-${index}"><rect ${rectAttributes(element.clipRect)}/></clipPath>`, signal);
500
- const body = (await cooperativeParts(scene.elements, (element, index) => renderBaseElement(element, element.clipRect === undefined ? undefined : `clip-${index}`, toolText), signal)) + renderTooltipPreview(scene, toolText);
540
+ const body = (await cooperativeParts(scene.elements, (element, index) => renderBaseElement(element, element.clipRect === undefined ? undefined : `clip-${index}`, toolText, textures), signal)) + renderTooltipPreview(scene, toolText, textures);
501
541
  const overlays = await cooperativeParts(scene.elements, (element) => renderOverlay(element, variant, toolText), signal);
502
542
  const fidelity = escapeXml(canonicalJson(scene.fidelity));
503
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${view.width}" height="${view.height}" viewBox="${finite(view.viewBox.x)} ${finite(view.viewBox.y)} ${finite(view.viewBox.width)} ${finite(view.viewBox.height)}"><metadata data-renderer="hoi4-agent-tools" data-mode="offline">${fidelity}</metadata><defs>${clipDefinitions}${sceneGlyphDefinitions(scene)}${toolText.definitions()}</defs>${backdrop(scene, view.viewBox)}${body}${overlays}</svg>`;
543
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${view.width}" height="${view.height}" viewBox="${finite(view.viewBox.x)} ${finite(view.viewBox.y)} ${finite(view.viewBox.width)} ${finite(view.viewBox.height)}"><metadata data-renderer="hoi4-agent-tools" data-mode="offline">${fidelity}</metadata><defs>${clipDefinitions}${textures.definitions()}${sceneGlyphDefinitions(scene)}${toolText.definitions()}</defs>${backdrop(scene, view.viewBox)}${body}${overlays}</svg>`;
504
544
  }
505
545
  export function hierarchyToSvg(scene) {
506
546
  const rows = scene.elements.toSorted((left, right) => left.depth - right.depth || left.zIndex - right.zIndex || compareCodeUnits(left.id, right.id));
@@ -54,6 +54,7 @@ const modelledElementAttributes = new Set([
54
54
  'text',
55
55
  'font',
56
56
  'fontSize',
57
+ 'text_color_code',
57
58
  'maxWidth',
58
59
  'maxHeight',
59
60
  'fixedsize',
@@ -1317,6 +1318,13 @@ function referenceLabel(edge) {
1317
1318
  return String(value);
1318
1319
  return value === undefined ? edge.to : JSON.stringify(value);
1319
1320
  }
1321
+ /** `localisation/replace/**` or `localisation/<language>/replace/**`. */
1322
+ function inLocalisationReplaceFolder(relativePath) {
1323
+ const segments = relativePath.replaceAll('\\', '/').toLowerCase().split('/');
1324
+ return (segments[0] === 'localisation' &&
1325
+ ((segments[1] === 'replace' && segments.length > 2) ||
1326
+ (segments[2] === 'replace' && segments.length > 3)));
1327
+ }
1320
1328
  export function buildGuiSourceGraph(files, providedIndex, additionalLocalisationKeys = [], limits = {}) {
1321
1329
  const sharedIndex = providedIndex ?? new SymbolIndex();
1322
1330
  const activeFiles = files.filter(({ shadowedBy }) => shadowedBy === undefined);
@@ -1456,7 +1464,11 @@ export function buildGuiSourceGraph(files, providedIndex, additionalLocalisation
1456
1464
  throw new ServiceError('GUI_LOCALISATION_BUDGET_INVALID', 'Localisation candidate limit must be a positive safe integer');
1457
1465
  let candidateCount = 0;
1458
1466
  const localisationCandidates = new Map();
1467
+ // The first candidate of a key is the one the game shows: higher load order first, and within
1468
+ // one root a file in a `replace` folder before the root's other files.
1459
1469
  for (const { file, fileNodeId } of localisationFiles.sort((left, right) => right.file.loadOrder - left.file.loadOrder ||
1470
+ Number(inLocalisationReplaceFolder(right.file.relativePath)) -
1471
+ Number(inLocalisationReplaceFolder(left.file.relativePath)) ||
1460
1472
  compareCodeUnits(left.file.displayPath, right.file.displayPath))) {
1461
1473
  const document = parseLocalisation(file.bytes, file.displayPath);
1462
1474
  if (providedIndex === undefined &&
@@ -210,6 +210,8 @@ function guiLocalisationPatterns(workspace, languages = ['l_english']) {
210
210
  ...new Set([
211
211
  ...under(roots.localisation, [
212
212
  '*.{yml,yaml}',
213
+ // The game reads `localisation/replace/` (any language) over every other definition.
214
+ 'replace/**/*.{yml,yaml}',
213
215
  ...languageDirectories.flatMap((directory) => [
214
216
  `${directory}/**/*.yml`,
215
217
  `${directory}/**/*.yaml`,