hoi4-agent-tools 4.12.0 → 4.13.0
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.
- package/CHANGELOG.md +10 -0
- package/README.md +3 -3
- package/dist/bin/setup.js +38 -0
- package/dist/bin/stdio.js +5 -1
- package/dist/hoi4_agent_tools/core/configuration.js +16 -0
- package/dist/hoi4_agent_tools/core/domain-tools.js +4 -0
- package/dist/hoi4_agent_tools/core/engine-check.js +87 -0
- package/dist/hoi4_agent_tools/core/engine-client.js +1 -1
- package/dist/hoi4_agent_tools/core/job-operation-registration.js +2 -0
- package/dist/hoi4_agent_tools/localisation/job-operations.js +42 -0
- package/dist/hoi4_agent_tools/localisation/write-diff.js +96 -0
- package/dist/hoi4_agent_tools/localisation/write-format.js +329 -0
- package/dist/hoi4_agent_tools/localisation/write-operations.js +213 -0
- package/dist/hoi4_agent_tools/localisation/write-plan.js +557 -0
- package/dist/hoi4_agent_tools/map/gameplay/crossing-validation.js +17 -0
- package/dist/hoi4_agent_tools/map/model.js +31 -1
- package/dist/hoi4_agent_tools/map/world-edge.js +0 -25
- package/dist/hoi4_agent_tools/map/world.js +13 -24
- package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +5 -0
- package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +8 -3
- package/dist/hoi4_agent_tools/mcp/server/create.js +5 -1
- package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +10 -2
- package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +2 -0
- package/dist/hoi4_agent_tools/mcp/server/tool-profiles.js +83 -0
- package/dist/hoi4_agent_tools/mcp/tools/localisation-write.js +21 -0
- package/dist/hoi4_agent_tools/mcp/tools/reference.js +34 -0
- package/dist/hoi4_agent_tools/mcp/transports/http.js +6 -1
- package/dist/hoi4_agent_tools/reference/compat-patch.js +555 -0
- package/dist/hoi4_agent_tools/reference/compat.js +255 -0
- package/dist/hoi4_agent_tools/reference/docs-pack.js +164 -0
- package/dist/hoi4_agent_tools/reference/docs-pack.json +339 -0
- package/dist/hoi4_agent_tools/reference/documented-commands.js +26 -0
- package/dist/hoi4_agent_tools/reference/error-explain.js +235 -0
- package/dist/hoi4_agent_tools/reference/error-explanations.json +262 -0
- package/dist/hoi4_agent_tools/reference/error-log.js +30 -10
- package/dist/hoi4_agent_tools/reference/mod-health.js +255 -0
- package/dist/hoi4_agent_tools/reference/operations.js +435 -21
- package/dist/hoi4_agent_tools/reference/script-guard.js +109 -0
- package/dist/hoi4_agent_tools/reference/service.js +58 -20
- package/dist/hoi4_agent_tools/runtime.js +11 -0
- package/dist/hoi4_agent_tools/schemas/compat.js +153 -0
- package/dist/hoi4_agent_tools/schemas/localisation-write.js +154 -0
- package/dist/hoi4_agent_tools/schemas/map.js +1 -1
- package/dist/hoi4_agent_tools/schemas/modder-tools.js +191 -0
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +4 -1
- package/docs/jobs.md +2 -1
- package/docs/map.md +2 -2
- package/docs/reference.md +45 -5
- package/docs/setup.md +23 -3
- package/docs/tools.md +16 -1
- package/engine/bin/manifest.json +1 -1
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/schemas/configuration.schema.json +140 -113
- package/schemas/continuous-focus-palette.schema.json +1 -1
- package/schemas/custom-weighted-pool.schema.json +1 -1
- package/schemas/decision-inspect-input.schema.json +1 -1
- package/schemas/error-log-input.schema.json +1 -1
- package/schemas/event-feature-manifest.schema.json +1 -1
- package/schemas/focus-plan.schema.json +1 -1
- package/schemas/focus-planning-sidecar.schema.json +1 -1
- package/schemas/geography-model.schema.json +1 -1
- package/schemas/gui-animation-source.schema.json +1 -1
- package/schemas/gui-helper.schema.json +1 -1
- package/schemas/gui-scenario.schema.json +1 -1
- package/schemas/helper-expansion-request.schema.json +1 -1
- package/schemas/helper-expansion-summary.schema.json +1 -1
- package/schemas/impact-inspect-input.schema.json +1 -1
- package/schemas/map-operation.schema.json +2 -2
- package/schemas/mechanic-test-input.schema.json +1 -1
- package/schemas/mod-index-input.schema.json +1 -1
- package/schemas/operation-result.schema.json +1 -1
- package/schemas/package-check-input.schema.json +1 -1
- package/schemas/package-manifest.schema.json +1 -1
- package/schemas/probability-analysis-result.schema.json +1 -1
- package/schemas/probability-compare-input.schema.json +1 -1
- package/schemas/probability-evaluate-input.schema.json +1 -1
- package/schemas/probability-inspect-input.schema.json +1 -1
- package/schemas/probability-render-input.schema.json +1 -1
- package/schemas/probability-scenario-set.schema.json +1 -1
- package/schemas/probability-sequence-input.schema.json +1 -1
- package/schemas/probability-simulate-input.schema.json +1 -1
- package/schemas/probability-sweep-input.schema.json +1 -1
- package/schemas/reference-context-input.schema.json +1 -1
- package/schemas/reference-read-input.schema.json +1 -1
- package/schemas/reference-search-input.schema.json +1 -1
- package/schemas/reference-sheets.schema.json +1 -1
- package/schemas/scenario-suite.schema.json +1 -1
- package/schemas/scenario-test-input.schema.json +1 -1
- package/schemas/script-validate-input.schema.json +1 -1
- package/schemas/shared-scenario.schema.json +1 -1
- package/schemas/source-lookup-input.schema.json +1 -1
- package/server.json +2 -2
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { readdir } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { compareCodeUnits } from '../core/canonical.js';
|
|
4
|
+
import { runEngineCheck, } from '../core/engine-check.js';
|
|
5
|
+
import { ServiceError } from '../core/result.js';
|
|
6
|
+
import { canonicalPath, isWithin } from '../core/workspace.js';
|
|
7
|
+
/**
|
|
8
|
+
* `hoi4.compat_check` mode `mod` (decision R-5): one mod against another, in both load orders.
|
|
9
|
+
* The shared engine's `check` reads every layer in load order; this side runs it twice, with each
|
|
10
|
+
* mod loaded after the other, and keeps the findings that involve both mods. Findings about one
|
|
11
|
+
* mod and the game are not compatibility problems and are left out.
|
|
12
|
+
*/
|
|
13
|
+
/** The data of a result stays well under the 32 KiB tool result limit, which also holds the envelope. */
|
|
14
|
+
export const COMPAT_DATA_BUDGET_BYTES = 24_000;
|
|
15
|
+
const MESSAGE_LIMIT = 400;
|
|
16
|
+
const REPLACE_FILES_SHOWN = 5;
|
|
17
|
+
export function clip(text, limit = MESSAGE_LIMIT) {
|
|
18
|
+
const single = text.replace(/\s+/gu, ' ').trim();
|
|
19
|
+
return single.length <= limit ? single : `${single.slice(0, limit - 1)}…`;
|
|
20
|
+
}
|
|
21
|
+
/** Keep the first `limit` items and count the rest. */
|
|
22
|
+
export function bounded(items, limit) {
|
|
23
|
+
return {
|
|
24
|
+
count: items.length,
|
|
25
|
+
omitted: Math.max(0, items.length - limit),
|
|
26
|
+
items: items.slice(0, limit),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Build a result with the largest list limit (at most `limit`) whose JSON stays within the data
|
|
31
|
+
* budget. The counts stay complete; only the listed items shrink.
|
|
32
|
+
*/
|
|
33
|
+
export function fitToBudget(build, limit, budget = COMPAT_DATA_BUDGET_BYTES) {
|
|
34
|
+
let current = limit;
|
|
35
|
+
let data = build(current);
|
|
36
|
+
while (current > 0 && Buffer.byteLength(JSON.stringify(data), 'utf8') > budget) {
|
|
37
|
+
current = current > 4 ? Math.floor(current / 2) : current - 1;
|
|
38
|
+
data = build(current);
|
|
39
|
+
}
|
|
40
|
+
return data;
|
|
41
|
+
}
|
|
42
|
+
function severityRank(severity) {
|
|
43
|
+
return severity === 'error' ? 0 : severity === 'warning' ? 1 : 2;
|
|
44
|
+
}
|
|
45
|
+
function sortFindings(items) {
|
|
46
|
+
return items.sort((left, right) => severityRank(left.severity) - severityRank(right.severity) ||
|
|
47
|
+
compareCodeUnits(left.code, right.code) ||
|
|
48
|
+
compareCodeUnits(left.path, right.path) ||
|
|
49
|
+
compareCodeUnits(left.subject ?? '', right.subject ?? '') ||
|
|
50
|
+
compareCodeUnits(left.message, right.message));
|
|
51
|
+
}
|
|
52
|
+
function toFinding(finding) {
|
|
53
|
+
return {
|
|
54
|
+
code: finding.code,
|
|
55
|
+
severity: finding.severity,
|
|
56
|
+
subject: finding.subject ?? null,
|
|
57
|
+
layer: finding.layer,
|
|
58
|
+
path: finding.path,
|
|
59
|
+
message: clip(finding.message),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** The engine's layer names for the pair: the checked mod is the last layer, the other mod just before it. */
|
|
63
|
+
export function pairLayerNames(report) {
|
|
64
|
+
const layers = report.inputs.layers;
|
|
65
|
+
const second = layers.at(-1);
|
|
66
|
+
const first = layers.at(-2);
|
|
67
|
+
if (second?.kind !== 'mod' || first?.kind !== 'dependency')
|
|
68
|
+
throw new ServiceError('COMPAT_ENGINE_LAYERS', 'The engine report does not list the two mods as the last two layers');
|
|
69
|
+
return { first: first.name, second: second.name };
|
|
70
|
+
}
|
|
71
|
+
/** Everything one load order tells about the pair, from one engine report. */
|
|
72
|
+
export function summariseLoadOrder(input, limit) {
|
|
73
|
+
const names = pairLayerNames(input.report);
|
|
74
|
+
const firstMarker = ` ${names.first}:`;
|
|
75
|
+
const involvesFirst = (finding) => finding.message.includes(firstMarker);
|
|
76
|
+
const sameFile = input.report.overrides
|
|
77
|
+
.filter((entry) => entry.replaced.some((replaced) => replaced.startsWith(`${names.first}:`)))
|
|
78
|
+
.map((entry) => ({ path: entry.path, winner: input.second.name }))
|
|
79
|
+
.sort((left, right) => compareCodeUnits(left.path, right.path));
|
|
80
|
+
const duplicates = sortFindings(input.report.findings
|
|
81
|
+
.filter((finding) => finding.code === 'LINT_DUPLICATE_ACROSS_LAYERS' &&
|
|
82
|
+
finding.message.includes(`dependency ${names.first} in `))
|
|
83
|
+
.map(toFinding));
|
|
84
|
+
const droppedCodes = new Set([
|
|
85
|
+
'OVERRIDE_DROPS_DEFINITION',
|
|
86
|
+
'OVERRIDE_DROPS_ON_ACTION_HOOK',
|
|
87
|
+
'OVERRIDE_BREAKS_REFERENCE',
|
|
88
|
+
'OVERRIDE_CASE_ONLY_SHADOW',
|
|
89
|
+
]);
|
|
90
|
+
const dropped = sortFindings(input.report.findings
|
|
91
|
+
.filter((finding) => droppedCodes.has(finding.code) &&
|
|
92
|
+
finding.severity !== 'info' &&
|
|
93
|
+
(finding.code === 'OVERRIDE_BREAKS_REFERENCE'
|
|
94
|
+
? finding.message.includes(firstMarker)
|
|
95
|
+
: involvesFirst(finding)))
|
|
96
|
+
.map(toFinding));
|
|
97
|
+
const replacePathDrops = input.replacePathFiles
|
|
98
|
+
.filter(({ files }) => files.length > 0)
|
|
99
|
+
.map(({ folder, files }) => ({
|
|
100
|
+
folder,
|
|
101
|
+
fileCount: files.length,
|
|
102
|
+
files: files.slice(0, REPLACE_FILES_SHOWN),
|
|
103
|
+
}))
|
|
104
|
+
.sort((left, right) => compareCodeUnits(left.folder, right.folder));
|
|
105
|
+
const droppedFiles = replacePathDrops.reduce((sum, { fileCount }) => sum + fileCount, 0);
|
|
106
|
+
const countSeverity = (items, severity) => items.filter((item) => item.severity === severity).length;
|
|
107
|
+
return {
|
|
108
|
+
first: input.first,
|
|
109
|
+
second: input.second,
|
|
110
|
+
errors: countSeverity(duplicates, 'error') + countSeverity(dropped, 'error'),
|
|
111
|
+
warnings: countSeverity(duplicates, 'warning') + countSeverity(dropped, 'warning') + droppedFiles,
|
|
112
|
+
sameFile: bounded(sameFile, limit),
|
|
113
|
+
duplicateDefinitions: bounded(duplicates, limit),
|
|
114
|
+
dropped: bounded(dropped, limit),
|
|
115
|
+
replacePathDrops: bounded(replacePathDrops, limit),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
export function compareLoadOrders(orders) {
|
|
119
|
+
const [a, b] = orders;
|
|
120
|
+
const clashes = orders.some((order) => order.sameFile.count + order.errors + order.warnings + order.replacePathDrops.count > 0);
|
|
121
|
+
const verdict = clashes ? 'conflicts' : 'no_conflicts';
|
|
122
|
+
const difference = a.errors - b.errors || a.warnings - b.warnings;
|
|
123
|
+
const winner = difference === 0 ? undefined : difference < 0 ? a : b;
|
|
124
|
+
const loser = winner === a ? b : a;
|
|
125
|
+
const lessLoss = winner === undefined || !clashes
|
|
126
|
+
? null
|
|
127
|
+
: {
|
|
128
|
+
loadsLast: winner.second,
|
|
129
|
+
errors: winner.errors,
|
|
130
|
+
warnings: winner.warnings,
|
|
131
|
+
otherOrderErrors: loser.errors,
|
|
132
|
+
otherOrderWarnings: loser.warnings,
|
|
133
|
+
};
|
|
134
|
+
const describe = (order) => `${order.second.name} after ${order.first.name}: ${order.errors} errors, ${order.warnings} warnings, ${order.sameFile.count} files at the same path`;
|
|
135
|
+
const summary = verdict === 'no_conflicts'
|
|
136
|
+
? `No conflicts between ${a.first.name} and ${a.second.name} in either load order.`
|
|
137
|
+
: `Conflicts. ${describe(a)}. ${describe(b)}. ${lessLoss === null
|
|
138
|
+
? 'Both load orders lose the same number of errors and warnings.'
|
|
139
|
+
: `Loading ${lessLoss.loadsLast.name} last loses less (${lessLoss.errors} errors and ${lessLoss.warnings} warnings, against ${lessLoss.otherOrderErrors} and ${lessLoss.otherOrderWarnings}).`}`;
|
|
140
|
+
return { orders, verdict, lessLoss, summary: clip(summary, 600) };
|
|
141
|
+
}
|
|
142
|
+
/** A descriptor's replace_path as a folder below the mod root, or undefined when it is not one. */
|
|
143
|
+
function replaceFolder(raw) {
|
|
144
|
+
const folder = raw.replaceAll('\\', '/').replace(/^\/+|\/+$/gu, '');
|
|
145
|
+
if (folder.length === 0 || folder.includes('\0') || folder.includes(':'))
|
|
146
|
+
return undefined;
|
|
147
|
+
const segments = folder.split('/');
|
|
148
|
+
if (segments.some((segment) => segment === '' || segment === '.' || segment === '..'))
|
|
149
|
+
return undefined;
|
|
150
|
+
return folder;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Files a mod ships directly in the folders another mod replaces. The folders come from a
|
|
154
|
+
* descriptor, so each is checked to stay inside the mod root, and only plain files count.
|
|
155
|
+
*/
|
|
156
|
+
export async function shippedInFolders(root, folders, signal) {
|
|
157
|
+
const found = [];
|
|
158
|
+
const seen = new Set();
|
|
159
|
+
for (const raw of folders) {
|
|
160
|
+
signal?.throwIfAborted();
|
|
161
|
+
const folder = replaceFolder(raw);
|
|
162
|
+
if (folder === undefined || seen.has(folder.toLowerCase()))
|
|
163
|
+
continue;
|
|
164
|
+
seen.add(folder.toLowerCase());
|
|
165
|
+
const directory = path.join(root, ...folder.split('/'));
|
|
166
|
+
let entries;
|
|
167
|
+
try {
|
|
168
|
+
const canonical = await canonicalPath(directory);
|
|
169
|
+
if (!isWithin(root, canonical))
|
|
170
|
+
continue;
|
|
171
|
+
entries = await readdir(canonical, { withFileTypes: true });
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const files = entries
|
|
177
|
+
.filter((entry) => entry.isFile())
|
|
178
|
+
.map((entry) => entry.name)
|
|
179
|
+
.sort(compareCodeUnits);
|
|
180
|
+
if (files.length > 0)
|
|
181
|
+
found.push({ folder, files });
|
|
182
|
+
}
|
|
183
|
+
return found;
|
|
184
|
+
}
|
|
185
|
+
function modRef(workspace) {
|
|
186
|
+
return { id: workspace.id, name: workspace.name };
|
|
187
|
+
}
|
|
188
|
+
/** Both mods may name a shared dependency; each is loaded once, before the pair. */
|
|
189
|
+
function dependenciesFor(checked, loadedBefore) {
|
|
190
|
+
const own = checked.dependencyRoots.filter((root) => root !== loadedBefore.modRoot && root !== checked.modRoot);
|
|
191
|
+
return [...new Set([...own, loadedBefore.modRoot])];
|
|
192
|
+
}
|
|
193
|
+
/** Resolve `other` to a mod workspace the principal may read, or refuse. */
|
|
194
|
+
export function resolveOtherMod(engine, workspace, other, principal) {
|
|
195
|
+
const id = engine.resolver.resolveWorkspaceId(other, principal);
|
|
196
|
+
const resolved = engine.resolver.get(id, principal);
|
|
197
|
+
if (resolved.registration.kind !== 'mod')
|
|
198
|
+
throw new ServiceError('COMPAT_OTHER_NOT_A_MOD', 'The other workspace is not a mod');
|
|
199
|
+
if (resolved.id === workspace.id)
|
|
200
|
+
throw new ServiceError('COMPAT_OTHER_IS_SELF', 'The other mod is the mod being checked');
|
|
201
|
+
return resolved;
|
|
202
|
+
}
|
|
203
|
+
export async function checkModCompatibility(engine, workspace, input, principal, signal, services = {}) {
|
|
204
|
+
const started = Date.now();
|
|
205
|
+
const other = resolveOtherMod(engine, workspace, input.other ?? '', principal);
|
|
206
|
+
const runCheck = services.runCheck ?? runEngineCheck;
|
|
207
|
+
const options = signal === undefined ? {} : { signal };
|
|
208
|
+
const request = (checked, before) => ({
|
|
209
|
+
mod: checked.modRoot,
|
|
210
|
+
...(workspace.gameRoot === undefined ? {} : { game: workspace.gameRoot }),
|
|
211
|
+
dependencies: dependenciesFor(checked, before),
|
|
212
|
+
includeDlc: workspace.dlcLayers.length > 0,
|
|
213
|
+
});
|
|
214
|
+
// The pair is read in both orders; the engine runs are independent.
|
|
215
|
+
const [otherFirst, workspaceFirst] = await Promise.all([
|
|
216
|
+
runCheck(request(workspace, other), options),
|
|
217
|
+
runCheck(request(other, workspace), options),
|
|
218
|
+
]);
|
|
219
|
+
const [replaceByWorkspace, replaceByOther] = await Promise.all([
|
|
220
|
+
shippedInFolders(other.modRoot, otherFirst.inputs.layers.at(-1)?.replace_paths ?? [], signal),
|
|
221
|
+
shippedInFolders(workspace.modRoot, workspaceFirst.inputs.layers.at(-1)?.replace_paths ?? [], signal),
|
|
222
|
+
]);
|
|
223
|
+
const build = (limit) => {
|
|
224
|
+
const compared = compareLoadOrders([
|
|
225
|
+
summariseLoadOrder({
|
|
226
|
+
report: otherFirst,
|
|
227
|
+
first: modRef(other),
|
|
228
|
+
second: modRef(workspace),
|
|
229
|
+
replacePathFiles: replaceByWorkspace,
|
|
230
|
+
}, limit),
|
|
231
|
+
summariseLoadOrder({
|
|
232
|
+
report: workspaceFirst,
|
|
233
|
+
first: modRef(workspace),
|
|
234
|
+
second: modRef(other),
|
|
235
|
+
replacePathFiles: replaceByOther,
|
|
236
|
+
}, limit),
|
|
237
|
+
]);
|
|
238
|
+
return {
|
|
239
|
+
mode: 'mod',
|
|
240
|
+
workspace: modRef(workspace),
|
|
241
|
+
other: modRef(other),
|
|
242
|
+
verdict: compared.verdict,
|
|
243
|
+
lessLoss: compared.lessLoss,
|
|
244
|
+
summary: compared.summary,
|
|
245
|
+
loadOrders: compared.orders,
|
|
246
|
+
notes: [
|
|
247
|
+
'Only findings that involve both mods are listed. Findings about one mod and the game are left out.',
|
|
248
|
+
'A file at the same path replaces the whole file of the mod that loads first. What it drops is listed under dropped.',
|
|
249
|
+
'Errors and warnings count every duplicate definition, every dropped or broken definition and every file a replace_path unloads, not only the ones listed.',
|
|
250
|
+
],
|
|
251
|
+
durationMs: Date.now() - started,
|
|
252
|
+
};
|
|
253
|
+
};
|
|
254
|
+
return fitToBudget(build, input.limit);
|
|
255
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { z } from 'zod/v4';
|
|
6
|
+
import manifestFile from './docs-pack.json' with { type: 'json' };
|
|
7
|
+
/**
|
|
8
|
+
* The docs pack: the modding kit's HOI4 wiki pages at one pinned kit commit, downloaded once by
|
|
9
|
+
* `hoi4-agent-tools-setup --fetch-docs` (maintainer decision R-4). It lets the reference tools
|
|
10
|
+
* answer with no mod open, and in a mod that has no copy of the wiki. Every file is checked
|
|
11
|
+
* against the SHA-256 this package version pins, so a pack is either complete and exact or not
|
|
12
|
+
* used at all. The pack lives in the server's data folder, never in a mod.
|
|
13
|
+
*/
|
|
14
|
+
const sha256Schema = z.string().regex(/^[a-f0-9]{64}$/u);
|
|
15
|
+
export const docsPackManifestSchema = z
|
|
16
|
+
.object({
|
|
17
|
+
version: z.literal(1),
|
|
18
|
+
/** The GitHub repository the pages come from, `owner/name`. */
|
|
19
|
+
repository: z.string().regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u),
|
|
20
|
+
commit: z.string().regex(/^[a-f0-9]{40}$/u),
|
|
21
|
+
/** The repository folder that holds the pages. */
|
|
22
|
+
folder: z.string().regex(/^[A-Za-z0-9_.-]+$/u),
|
|
23
|
+
/** Who may use the text, and how; the pack's own LICENSE.txt has the full terms. */
|
|
24
|
+
license: z.string().min(1).max(300),
|
|
25
|
+
files: z
|
|
26
|
+
.array(z
|
|
27
|
+
.object({
|
|
28
|
+
path: z.string().regex(/^[A-Za-z0-9_.-]+\.(?:md|txt|json)$/u),
|
|
29
|
+
sha256: sha256Schema,
|
|
30
|
+
bytes: z
|
|
31
|
+
.number()
|
|
32
|
+
.int()
|
|
33
|
+
.min(0)
|
|
34
|
+
.max(4 * 1024 * 1024),
|
|
35
|
+
})
|
|
36
|
+
.strict())
|
|
37
|
+
.min(1)
|
|
38
|
+
.max(512),
|
|
39
|
+
})
|
|
40
|
+
.strict();
|
|
41
|
+
/** The pack this package version uses. */
|
|
42
|
+
export const docsPackManifest = docsPackManifestSchema.parse(manifestFile);
|
|
43
|
+
/** The pack's subfolder that holds the pages, which the reference tools read as the wiki. */
|
|
44
|
+
export const DOCS_PACK_WIKI_FOLDER = 'hoi4_wiki';
|
|
45
|
+
const MAX_PACK_BYTES = 32 * 1024 * 1024;
|
|
46
|
+
/**
|
|
47
|
+
* Where packs live unless the configuration names `docsRoot`: the same data folder the setup
|
|
48
|
+
* utility gives generated workspaces.
|
|
49
|
+
*/
|
|
50
|
+
export function defaultDocsRoot(environment = process.env, home = homedir()) {
|
|
51
|
+
const dataRoot = environment.XDG_DATA_HOME ?? environment.LOCALAPPDATA ?? path.join(home, '.local', 'share');
|
|
52
|
+
return path.join(dataRoot, 'hoi4-agent-tools', 'docs');
|
|
53
|
+
}
|
|
54
|
+
/** One manifest's folder under the docs root: the first 12 characters of its kit commit. */
|
|
55
|
+
export function docsPackFolder(docsRoot, manifest = docsPackManifest) {
|
|
56
|
+
return path.join(docsRoot, manifest.commit.slice(0, 12));
|
|
57
|
+
}
|
|
58
|
+
/** The marker a complete pack carries: the SHA-256 of the manifest it was installed from. */
|
|
59
|
+
export function docsPackMarker(manifest = docsPackManifest) {
|
|
60
|
+
return createHash('sha256').update(JSON.stringify(manifest)).digest('hex');
|
|
61
|
+
}
|
|
62
|
+
/** The file that marks a pack folder complete. */
|
|
63
|
+
export const DOCS_PACK_MARKER_FILE = '.complete';
|
|
64
|
+
/**
|
|
65
|
+
* The wiki folder of an installed, complete pack for this manifest, or undefined. A pack counts
|
|
66
|
+
* as installed only when its marker names this exact manifest, so a pack of another package
|
|
67
|
+
* version or an interrupted download is never read.
|
|
68
|
+
*/
|
|
69
|
+
export async function installedDocsPackWiki(docsRoot, manifest = docsPackManifest) {
|
|
70
|
+
if (docsRoot === undefined)
|
|
71
|
+
return undefined;
|
|
72
|
+
const folder = docsPackFolder(docsRoot, manifest);
|
|
73
|
+
try {
|
|
74
|
+
const marker = (await readFile(path.join(folder, DOCS_PACK_MARKER_FILE), 'utf8')).trim();
|
|
75
|
+
if (marker !== docsPackMarker(manifest))
|
|
76
|
+
return undefined;
|
|
77
|
+
const wiki = path.join(folder, DOCS_PACK_WIKI_FOLDER);
|
|
78
|
+
return (await stat(wiki)).isDirectory() ? wiki : undefined;
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function fileUrl(manifest, file) {
|
|
85
|
+
return `https://raw.githubusercontent.com/${manifest.repository}/${manifest.commit}/${manifest.folder}/${encodeURIComponent(file)}`;
|
|
86
|
+
}
|
|
87
|
+
export class DocsPackError extends Error {
|
|
88
|
+
code;
|
|
89
|
+
constructor(code, message) {
|
|
90
|
+
super(message);
|
|
91
|
+
this.code = code;
|
|
92
|
+
this.name = 'DocsPackError';
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Download the pinned pages, check every file's size and SHA-256, and install the pack in one
|
|
97
|
+
* rename, so a reader sees either the complete pack or none. A complete pack is reused, and
|
|
98
|
+
* packs of other manifests are removed afterwards.
|
|
99
|
+
*/
|
|
100
|
+
export async function fetchDocsPack(options) {
|
|
101
|
+
const manifest = options.manifest ?? docsPackManifest;
|
|
102
|
+
const doFetch = options.fetch ?? ((url, init) => fetch(url, init));
|
|
103
|
+
const docsRoot = path.resolve(options.docsRoot);
|
|
104
|
+
const folder = docsPackFolder(docsRoot, manifest);
|
|
105
|
+
const total = manifest.files.reduce((sum, file) => sum + file.bytes, 0);
|
|
106
|
+
const summary = {
|
|
107
|
+
folder,
|
|
108
|
+
wiki: path.join(folder, DOCS_PACK_WIKI_FOLDER),
|
|
109
|
+
files: manifest.files.length,
|
|
110
|
+
bytes: total,
|
|
111
|
+
repository: manifest.repository,
|
|
112
|
+
commit: manifest.commit,
|
|
113
|
+
};
|
|
114
|
+
if (total > MAX_PACK_BYTES)
|
|
115
|
+
throw new DocsPackError('DOCS_PACK_TOO_LARGE', `The docs pack lists ${total} bytes`);
|
|
116
|
+
if ((await installedDocsPackWiki(docsRoot, manifest)) !== undefined)
|
|
117
|
+
return { ...summary, reused: true };
|
|
118
|
+
await mkdir(docsRoot, { recursive: true });
|
|
119
|
+
const staging = path.join(docsRoot, `.partial-${randomBytes(6).toString('hex')}`);
|
|
120
|
+
const stagingWiki = path.join(staging, DOCS_PACK_WIKI_FOLDER);
|
|
121
|
+
await mkdir(stagingWiki, { recursive: true });
|
|
122
|
+
try {
|
|
123
|
+
for (const file of manifest.files) {
|
|
124
|
+
options.signal?.throwIfAborted();
|
|
125
|
+
const url = fileUrl(manifest, file.path);
|
|
126
|
+
let response;
|
|
127
|
+
try {
|
|
128
|
+
response = await doFetch(url, options.signal === undefined ? {} : { signal: options.signal });
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error.name === 'AbortError')
|
|
132
|
+
throw error;
|
|
133
|
+
throw new DocsPackError('DOCS_PACK_DOWNLOAD_FAILED', `Could not download ${file.path}: ${error.message}`);
|
|
134
|
+
}
|
|
135
|
+
if (!response.ok)
|
|
136
|
+
throw new DocsPackError('DOCS_PACK_DOWNLOAD_FAILED', `Could not download ${file.path}: HTTP ${response.status}`);
|
|
137
|
+
const bytes = Buffer.from(await response.arrayBuffer());
|
|
138
|
+
const digest = createHash('sha256').update(bytes).digest('hex');
|
|
139
|
+
if (bytes.length !== file.bytes || digest !== file.sha256)
|
|
140
|
+
throw new DocsPackError('DOCS_PACK_HASH_MISMATCH', `${file.path} does not match the pinned SHA-256; nothing was installed`);
|
|
141
|
+
await writeFile(path.join(stagingWiki, file.path), bytes, { flag: 'wx' });
|
|
142
|
+
options.onFile?.(file.path);
|
|
143
|
+
}
|
|
144
|
+
await writeFile(path.join(staging, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
|
145
|
+
await writeFile(path.join(staging, DOCS_PACK_MARKER_FILE), `${docsPackMarker(manifest)}\n`, 'utf8');
|
|
146
|
+
await rm(folder, { recursive: true, force: true });
|
|
147
|
+
await rename(staging, folder);
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
await rm(staging, { recursive: true, force: true });
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
// Older packs and interrupted downloads are no longer read.
|
|
154
|
+
for (const entry of await readdir(docsRoot, { withFileTypes: true })) {
|
|
155
|
+
if (!entry.isDirectory())
|
|
156
|
+
continue;
|
|
157
|
+
const name = entry.name;
|
|
158
|
+
if (name === path.basename(folder))
|
|
159
|
+
continue;
|
|
160
|
+
if (/^[a-f0-9]{12}$/u.test(name) || name.startsWith('.partial-'))
|
|
161
|
+
await rm(path.join(docsRoot, name), { recursive: true, force: true });
|
|
162
|
+
}
|
|
163
|
+
return { ...summary, reused: false };
|
|
164
|
+
}
|