@kinloom/cli 0.1.1 → 0.3.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.
Files changed (111) hide show
  1. package/dist/assets/cached-ocr.py +786 -0
  2. package/dist/assets/ocr.md +76 -0
  3. package/dist/assets/prep-scan.md +97 -0
  4. package/dist/assets/prep-scan.py +1313 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +162 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +130 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +129 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +154 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +488 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +30 -5
  50. package/dist/client.js.map +1 -1
  51. package/dist/commands/ops/audit.d.ts +138 -0
  52. package/dist/commands/ops/audit.d.ts.map +1 -0
  53. package/dist/commands/ops/audit.js +872 -0
  54. package/dist/commands/ops/audit.js.map +1 -0
  55. package/dist/commands/ops/context.d.ts +100 -0
  56. package/dist/commands/ops/context.d.ts.map +1 -0
  57. package/dist/commands/ops/context.js +917 -0
  58. package/dist/commands/ops/context.js.map +1 -0
  59. package/dist/commands/ops/dates.d.ts +87 -0
  60. package/dist/commands/ops/dates.d.ts.map +1 -0
  61. package/dist/commands/ops/dates.js +228 -0
  62. package/dist/commands/ops/dates.js.map +1 -0
  63. package/dist/commands/ops/help.d.ts +8 -0
  64. package/dist/commands/ops/help.d.ts.map +1 -0
  65. package/dist/commands/ops/help.js +107 -0
  66. package/dist/commands/ops/help.js.map +1 -0
  67. package/dist/commands/ops/index.d.ts +8 -0
  68. package/dist/commands/ops/index.d.ts.map +1 -0
  69. package/dist/commands/ops/index.js +8 -0
  70. package/dist/commands/ops/index.js.map +1 -0
  71. package/dist/commands/ops/integrate.d.ts +61 -0
  72. package/dist/commands/ops/integrate.d.ts.map +1 -0
  73. package/dist/commands/ops/integrate.js +1063 -0
  74. package/dist/commands/ops/integrate.js.map +1 -0
  75. package/dist/commands/ops/sync.d.ts +194 -0
  76. package/dist/commands/ops/sync.d.ts.map +1 -0
  77. package/dist/commands/ops/sync.js +1251 -0
  78. package/dist/commands/ops/sync.js.map +1 -0
  79. package/dist/commands/ops/telemetry.d.ts +79 -0
  80. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  81. package/dist/commands/ops/telemetry.js +249 -0
  82. package/dist/commands/ops/telemetry.js.map +1 -0
  83. package/dist/commands/ops/verify.d.ts +76 -0
  84. package/dist/commands/ops/verify.d.ts.map +1 -0
  85. package/dist/commands/ops/verify.js +325 -0
  86. package/dist/commands/ops/verify.js.map +1 -0
  87. package/dist/commands/records/help.d.ts +18 -0
  88. package/dist/commands/records/help.d.ts.map +1 -0
  89. package/dist/commands/records/help.js +174 -0
  90. package/dist/commands/records/help.js.map +1 -0
  91. package/dist/commands/records/index.d.ts +5 -0
  92. package/dist/commands/records/index.d.ts.map +1 -0
  93. package/dist/commands/records/index.js +5 -0
  94. package/dist/commands/records/index.js.map +1 -0
  95. package/dist/commands/records/registry.d.ts +32 -0
  96. package/dist/commands/records/registry.d.ts.map +1 -0
  97. package/dist/commands/records/registry.js +227 -0
  98. package/dist/commands/records/registry.js.map +1 -0
  99. package/dist/commands/records/resolve.d.ts +14 -0
  100. package/dist/commands/records/resolve.d.ts.map +1 -0
  101. package/dist/commands/records/resolve.js +61 -0
  102. package/dist/commands/records/resolve.js.map +1 -0
  103. package/dist/commands/records/runner.d.ts +27 -0
  104. package/dist/commands/records/runner.d.ts.map +1 -0
  105. package/dist/commands/records/runner.js +255 -0
  106. package/dist/commands/records/runner.js.map +1 -0
  107. package/dist/index.d.ts +2 -0
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +2 -0
  110. package/dist/index.js.map +1 -1
  111. package/package.json +3 -3
@@ -0,0 +1,1251 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import { readFile } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { computeEntityDiff, deriveKinshipEdgeId, filterMediaForPrivacy, parseEntityPayload, parseEventsYaml, parseKinloomConfigYaml, parseKinshipYaml, parseMediaYaml, parseNarrativesYaml, parsePeopleYaml, parsePlacesYaml, parseSourcesYaml, resolveEffectiveLiving, sanitizeEventForWrite, sanitizePersonForWrite, } from '@kinloom/core';
8
+ import { CliValidationError } from '../../errors.js';
9
+ const execFileAsync = promisify(execFile);
10
+ export const SYNC_DEPENDENCY_ORDER = [
11
+ 'place',
12
+ 'source',
13
+ 'person',
14
+ 'event',
15
+ 'kinship_edge',
16
+ 'media',
17
+ 'narrative',
18
+ ];
19
+ const ENTITY_TYPE_ALIASES = {
20
+ place: 'place',
21
+ places: 'place',
22
+ source: 'source',
23
+ sources: 'source',
24
+ person: 'person',
25
+ people: 'person',
26
+ event: 'event',
27
+ events: 'event',
28
+ kinship: 'kinship_edge',
29
+ kinship_edge: 'kinship_edge',
30
+ kinship_edges: 'kinship_edge',
31
+ media: 'media',
32
+ narrative: 'narrative',
33
+ narratives: 'narrative',
34
+ };
35
+ const MIME_BY_EXT = {
36
+ '.jpg': 'image/jpeg',
37
+ '.jpeg': 'image/jpeg',
38
+ '.png': 'image/png',
39
+ '.webp': 'image/webp',
40
+ '.gif': 'image/gif',
41
+ '.svg': 'image/svg+xml',
42
+ '.pdf': 'application/pdf',
43
+ '.mp4': 'video/mp4',
44
+ '.webm': 'video/webm',
45
+ '.mp3': 'audio/mpeg',
46
+ '.m4a': 'audio/mp4',
47
+ '.wav': 'audio/wav',
48
+ '.txt': 'text/plain; charset=utf-8',
49
+ '.json': 'application/json; charset=utf-8',
50
+ };
51
+ const DEFAULT_CHUNK_SIZE = 25;
52
+ const DEFAULT_UPLOAD_CONCURRENCY = 6;
53
+ const MEDIA_PROBE_CONCURRENCY = 12;
54
+ const LIVE_VERIFY_CONCURRENCY = 6;
55
+ const LIVE_VERIFY_TIMEOUT_MS = 15_000;
56
+ const DEFAULT_BACKUP_TOKEN_LABEL = 'github-actions-nightly-backup';
57
+ const TEMP_TOKEN_LABEL = 'tmp-kinloom-sync';
58
+ const TEMP_TOKEN_ID_PREFIX = 'tmp_sync_';
59
+ export { SYNC_HELP } from './help.js';
60
+ function isPlainRecord(value) {
61
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
62
+ }
63
+ export function normalizeSyncEntityType(raw) {
64
+ const key = raw.trim().toLowerCase();
65
+ const mapped = ENTITY_TYPE_ALIASES[key];
66
+ if (!mapped) {
67
+ throw new CliValidationError(`Unknown entity type '${raw}'. Valid types: ${SYNC_DEPENDENCY_ORDER.join(', ')}.`);
68
+ }
69
+ return mapped;
70
+ }
71
+ export function parseEntityTypeList(csv) {
72
+ const requested = new Set(csv
73
+ .split(',')
74
+ .map((part) => part.trim())
75
+ .filter(Boolean)
76
+ .map(normalizeSyncEntityType));
77
+ if (requested.size === 0) {
78
+ throw new CliValidationError('Option `--types` must include at least one entity type.');
79
+ }
80
+ return SYNC_DEPENDENCY_ORDER.filter((t) => requested.has(t));
81
+ }
82
+ export function parseDeleteTargets(csv) {
83
+ const targets = [];
84
+ for (const token of csv.split(',').map((s) => s.trim()).filter(Boolean)) {
85
+ const sep = token.indexOf(':');
86
+ if (sep <= 0 || sep === token.length - 1) {
87
+ throw new CliValidationError(`Invalid \`--delete\` entry '${token}'. Expected <entity_type>:<entity_id>.`);
88
+ }
89
+ const entityType = normalizeSyncEntityType(token.slice(0, sep));
90
+ const entityId = token.slice(sep + 1).trim();
91
+ targets.push({ entity_type: entityType, entity_id: entityId });
92
+ }
93
+ return targets;
94
+ }
95
+ export function stripJsoncCommentsAndTrailingCommas(text) {
96
+ let out = '';
97
+ let inString = false;
98
+ let escapeNext = false;
99
+ for (let i = 0; i < text.length; i += 1) {
100
+ const ch = text[i];
101
+ const next = text[i + 1];
102
+ if (inString) {
103
+ out += ch;
104
+ if (escapeNext) {
105
+ escapeNext = false;
106
+ }
107
+ else if (ch === '\\') {
108
+ escapeNext = true;
109
+ }
110
+ else if (ch === '"') {
111
+ inString = false;
112
+ }
113
+ continue;
114
+ }
115
+ if (ch === '"') {
116
+ inString = true;
117
+ out += ch;
118
+ continue;
119
+ }
120
+ if (ch === '/' && next === '/') {
121
+ while (i < text.length && text[i] !== '\n') {
122
+ i += 1;
123
+ }
124
+ if (i < text.length) {
125
+ out += '\n';
126
+ }
127
+ continue;
128
+ }
129
+ if (ch === '/' && next === '*') {
130
+ i += 2;
131
+ while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) {
132
+ i += 1;
133
+ }
134
+ i += 1;
135
+ continue;
136
+ }
137
+ out += ch;
138
+ }
139
+ return out.replaceAll(/,\s*([}\]])/g, '$1');
140
+ }
141
+ function normalizeSiteUrl(rawUrl) {
142
+ const trimmed = rawUrl.trim();
143
+ const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
144
+ let parsed;
145
+ try {
146
+ parsed = new URL(withScheme);
147
+ }
148
+ catch {
149
+ throw new CliValidationError(`Invalid site URL '${rawUrl}'. Expected an http:// or https:// URL.`);
150
+ }
151
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
152
+ throw new CliValidationError(`Unsupported site URL protocol '${parsed.protocol}'. Expected http: or https:.`);
153
+ }
154
+ return {
155
+ baseUrl: `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, ''),
156
+ domain: parsed.host,
157
+ };
158
+ }
159
+ export function loadWranglerBindings(repoDir, siteUrlOverride) {
160
+ const jsoncPath = path.join(repoDir, 'wrangler.jsonc');
161
+ const jsonPath = path.join(repoDir, 'wrangler.json');
162
+ const configPath = fs.existsSync(jsoncPath) ? jsoncPath : jsonPath;
163
+ if (!fs.existsSync(configPath)) {
164
+ throw new CliValidationError(`Missing wrangler.jsonc (or wrangler.json) under ${repoDir}.`);
165
+ }
166
+ const raw = fs.readFileSync(configPath, 'utf8');
167
+ let parsed;
168
+ try {
169
+ parsed = JSON.parse(stripJsoncCommentsAndTrailingCommas(raw));
170
+ }
171
+ catch (err) {
172
+ throw new CliValidationError(`Failed to parse ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
173
+ }
174
+ if (!isPlainRecord(parsed)) {
175
+ throw new CliValidationError(`Expected a JSON object in ${configPath}.`);
176
+ }
177
+ const d1List = Array.isArray(parsed.d1_databases) ? parsed.d1_databases : [];
178
+ const r2List = Array.isArray(parsed.r2_buckets) ? parsed.r2_buckets : [];
179
+ const routesList = Array.isArray(parsed.routes) ? parsed.routes : [];
180
+ const firstD1 = isPlainRecord(d1List[0]) ? d1List[0] : null;
181
+ const firstR2 = isPlainRecord(r2List[0]) ? r2List[0] : null;
182
+ const firstRoute = isPlainRecord(routesList[0]) ? routesList[0] : null;
183
+ const dbName = typeof firstD1?.database_name === 'string' ? firstD1.database_name.trim() : '';
184
+ const r2Bucket = typeof firstR2?.bucket_name === 'string' ? firstR2.bucket_name.trim() : '';
185
+ const routePattern = typeof firstRoute?.pattern === 'string'
186
+ ? firstRoute.pattern.trim()
187
+ : typeof routesList[0] === 'string'
188
+ ? routesList[0].trim()
189
+ : '';
190
+ if (!dbName) {
191
+ throw new CliValidationError(`Could not read d1_databases[0].database_name from ${configPath}.`);
192
+ }
193
+ if (!r2Bucket) {
194
+ throw new CliValidationError(`Could not read r2_buckets[0].bucket_name from ${configPath}.`);
195
+ }
196
+ let resolved;
197
+ if (siteUrlOverride && siteUrlOverride.trim().length > 0) {
198
+ resolved = normalizeSiteUrl(siteUrlOverride);
199
+ }
200
+ else if (routePattern.length > 0) {
201
+ const cleanedHost = routePattern
202
+ .replace(/^https?:\/\//i, '')
203
+ .replace(/\/.*$/, '')
204
+ .trim();
205
+ if (!cleanedHost) {
206
+ throw new CliValidationError(`Could not derive a site URL from routes[0].pattern '${routePattern}' in ${configPath}. Pass --site-url <url>.`);
207
+ }
208
+ resolved = normalizeSiteUrl(`https://${cleanedHost}`);
209
+ }
210
+ else {
211
+ throw new CliValidationError(`No --site-url provided and no routes[0].pattern found in ${configPath}. Pass --site-url <url>.`);
212
+ }
213
+ return {
214
+ configPath,
215
+ dbName,
216
+ r2Bucket,
217
+ domain: resolved.domain,
218
+ baseUrl: resolved.baseUrl,
219
+ };
220
+ }
221
+ function resolveWranglerBin(repoDir, explicitBin) {
222
+ if (explicitBin && explicitBin.trim().length > 0) {
223
+ return explicitBin.trim();
224
+ }
225
+ const localBin = path.join(repoDir, 'node_modules', '.bin', 'wrangler');
226
+ if (fs.existsSync(localBin)) {
227
+ return localBin;
228
+ }
229
+ return 'wrangler';
230
+ }
231
+ const defaultWranglerExecutor = async (wranglerBin, args, options) => {
232
+ const { stdout, stderr } = await execFileAsync(wranglerBin, [...args], {
233
+ cwd: options.cwd,
234
+ encoding: 'utf8',
235
+ maxBuffer: options.maxBufferBytes,
236
+ timeout: options.timeoutMs,
237
+ });
238
+ return { stdout, stderr };
239
+ };
240
+ export function sqlLiteral(value) {
241
+ return `'${value.replaceAll("'", "''")}'`;
242
+ }
243
+ export function generateTempToken(scope) {
244
+ const prefix = scope === 'write_batch' ? TEMP_TOKEN_ID_PREFIX : `${TEMP_TOKEN_ID_PREFIX}read_`;
245
+ const tokenId = `${prefix}${randomUUID()}`;
246
+ const rawToken = randomBytes(32).toString('base64url');
247
+ const tokenHash = createHash('sha256').update(rawToken).digest('hex');
248
+ return { tokenId, rawToken, tokenHash, scope };
249
+ }
250
+ export function buildTempTokenInsertSql(tokens, nowIso) {
251
+ const statements = [];
252
+ for (const token of tokens) {
253
+ if (!token.tokenId.startsWith(TEMP_TOKEN_ID_PREFIX)) {
254
+ throw new Error(`Refusing to mint temp token without required '${TEMP_TOKEN_ID_PREFIX}' prefix: ${token.tokenId}`);
255
+ }
256
+ statements.push(`INSERT INTO agent_tokens (token_id, token_hash, label, scope, created_by, created_at, revoked_at) VALUES (${sqlLiteral(token.tokenId)}, ${sqlLiteral(token.tokenHash)}, ${sqlLiteral(TEMP_TOKEN_LABEL)}, ${sqlLiteral(token.scope)}, ${sqlLiteral('kinloom sync')}, ${sqlLiteral(nowIso)}, NULL);`);
257
+ }
258
+ return statements.join(' ');
259
+ }
260
+ export function buildTempTokenCleanupSql(tokenIds, backupTokenLabel = DEFAULT_BACKUP_TOKEN_LABEL) {
261
+ if (tokenIds.length === 0) {
262
+ throw new Error('Cannot build temp token cleanup SQL with empty tokenIds list.');
263
+ }
264
+ const statements = [];
265
+ for (const id of tokenIds) {
266
+ if (!id.startsWith(TEMP_TOKEN_ID_PREFIX)) {
267
+ throw new Error(`SAFETY REFUSAL: Refusing to delete non-temporary token_id '${id}'. Only '${TEMP_TOKEN_ID_PREFIX}*' tokens may be deleted.`);
268
+ }
269
+ statements.push(`DELETE FROM agent_tokens WHERE token_id = ${sqlLiteral(id)};`);
270
+ }
271
+ statements.push(`SELECT COUNT(*) AS count FROM agent_tokens WHERE label = ${sqlLiteral(backupTokenLabel)} AND revoked_at IS NULL;`);
272
+ statements.push(`SELECT COUNT(*) AS count FROM agent_tokens WHERE token_id IN (${tokenIds
273
+ .map(sqlLiteral)
274
+ .join(', ')});`);
275
+ return statements.join(' ');
276
+ }
277
+ async function executeD1(ctx, sql) {
278
+ const { stdout } = await ctx.execWrangler(ctx.wranglerBin, [
279
+ 'd1',
280
+ 'execute',
281
+ ctx.bindings.dbName,
282
+ '--remote',
283
+ '--json',
284
+ '--config',
285
+ ctx.bindings.configPath,
286
+ '--command',
287
+ sql,
288
+ ], {
289
+ cwd: ctx.repoDir,
290
+ maxBufferBytes: 16 * 1024 * 1024,
291
+ timeoutMs: 45_000,
292
+ });
293
+ const jsonStart = stdout.indexOf('[');
294
+ if (jsonStart === -1) {
295
+ throw new Error(`Unexpected wrangler D1 output for ${ctx.bindings.dbName}.`);
296
+ }
297
+ const parsed = JSON.parse(stdout.slice(jsonStart));
298
+ if (!Array.isArray(parsed) || parsed.length === 0) {
299
+ throw new Error(`Empty wrangler D1 response for ${ctx.bindings.dbName}.`);
300
+ }
301
+ const results = [];
302
+ for (const stmt of parsed) {
303
+ if (!isPlainRecord(stmt) || stmt.success !== true) {
304
+ throw new Error(`D1 statement failed on ${ctx.bindings.dbName}.`);
305
+ }
306
+ results.push({
307
+ success: true,
308
+ results: Array.isArray(stmt.results)
309
+ ? stmt.results.filter(isPlainRecord)
310
+ : [],
311
+ });
312
+ }
313
+ return results;
314
+ }
315
+ async function mintTempTokens(ctx) {
316
+ const readToken = generateTempToken('read_backup');
317
+ const writeToken = generateTempToken('write_batch');
318
+ const sql = buildTempTokenInsertSql([readToken, writeToken], new Date().toISOString());
319
+ await executeD1(ctx, sql);
320
+ return { read_backup: readToken, write_batch: writeToken };
321
+ }
322
+ async function cleanupTempTokens(ctx, tokenIds) {
323
+ const sql = buildTempTokenCleanupSql(tokenIds, ctx.backupTokenLabel);
324
+ const results = await executeD1(ctx, sql);
325
+ const backupRow = results[results.length - 2]?.results?.[0];
326
+ const remainingTmpRow = results[results.length - 1]?.results?.[0];
327
+ const backupCount = Number(backupRow?.count ?? 0);
328
+ const remainingTmpCount = Number(remainingTmpRow?.count ?? -1);
329
+ if (remainingTmpCount !== 0) {
330
+ throw new Error(`Temporary token cleanup verification failed: ${remainingTmpCount} temp token(s) still present.`);
331
+ }
332
+ return {
333
+ deletedTokenIds: [...tokenIds],
334
+ remainingTmpCount,
335
+ backupTokenLabel: ctx.backupTokenLabel,
336
+ backupCount,
337
+ };
338
+ }
339
+ async function readOptionalUtf8(filePath) {
340
+ try {
341
+ return await readFile(filePath, 'utf8');
342
+ }
343
+ catch (err) {
344
+ if (typeof err === 'object' && err !== null && 'code' in err && err.code === 'ENOENT') {
345
+ return null;
346
+ }
347
+ throw err;
348
+ }
349
+ }
350
+ async function loadLocalArchive(repoDir) {
351
+ const dataDir = path.join(repoDir, 'data');
352
+ const configPath = path.join(repoDir, 'kinloom.config.yaml');
353
+ const [configText, placesText, sourcesText, peopleText, eventsText, kinshipText, mediaText, narrativesText,] = await Promise.all([
354
+ readOptionalUtf8(configPath),
355
+ readOptionalUtf8(path.join(dataDir, 'places.yaml')),
356
+ readOptionalUtf8(path.join(dataDir, 'sources.yaml')),
357
+ readOptionalUtf8(path.join(dataDir, 'people.yaml')),
358
+ readOptionalUtf8(path.join(dataDir, 'events.yaml')),
359
+ readOptionalUtf8(path.join(dataDir, 'kinship.yaml')),
360
+ readOptionalUtf8(path.join(dataDir, 'media.yaml')),
361
+ readOptionalUtf8(path.join(dataDir, 'narratives.yaml')),
362
+ ]);
363
+ if (!configText) {
364
+ throw new CliValidationError(`Missing kinloom.config.yaml at ${configPath}.`);
365
+ }
366
+ const siteConfig = parseKinloomConfigYaml(configText);
367
+ return {
368
+ siteConfig,
369
+ places: placesText ? parsePlacesYaml(placesText) : [],
370
+ sources: sourcesText ? parseSourcesYaml(sourcesText) : [],
371
+ people: peopleText ? parsePeopleYaml(peopleText) : [],
372
+ events: eventsText ? parseEventsYaml(eventsText) : [],
373
+ kinship: kinshipText ? parseKinshipYaml(kinshipText) : [],
374
+ media: mediaText ? parseMediaYaml(mediaText) : [],
375
+ narratives: narrativesText ? parseNarrativesYaml(narrativesText) : [],
376
+ };
377
+ }
378
+ function normalizeForDiff(entityType, data) {
379
+ if (entityType === 'kinship_edge') {
380
+ return data;
381
+ }
382
+ return {
383
+ ...data,
384
+ has_primary_source: data.has_primary_source ?? true,
385
+ };
386
+ }
387
+ export function buildSanitizedLocalEntries(local) {
388
+ const privacy = local.siteConfig.privacy;
389
+ const livingIds = new Set();
390
+ const sanitizedPeople = local.people.map((person) => {
391
+ const isLiving = resolveEffectiveLiving(person, privacy);
392
+ if (isLiving) {
393
+ livingIds.add(person.id);
394
+ }
395
+ const sanitized = sanitizePersonForWrite(person, privacy);
396
+ return {
397
+ entity_type: 'person',
398
+ entity_id: sanitized.id,
399
+ data: parseEntityPayload('person', sanitized),
400
+ has_primary_source: sanitized.has_primary_source ?? true,
401
+ isLiving,
402
+ };
403
+ });
404
+ const sanitizedEvents = local.events.map((event) => {
405
+ const sanitized = sanitizeEventForWrite(event, livingIds, privacy);
406
+ return {
407
+ entity_type: 'event',
408
+ entity_id: sanitized.id,
409
+ data: parseEntityPayload('event', sanitized),
410
+ has_primary_source: sanitized.has_primary_source ?? true,
411
+ isLiving: false,
412
+ };
413
+ });
414
+ const peopleById = new Map(sanitizedPeople.map((p) => [p.entity_id, parseEntityPayload('person', p.data)]));
415
+ const eventsById = new Map(sanitizedEvents.map((e) => {
416
+ const parsed = parseEntityPayload('event', e.data);
417
+ return [e.entity_id, { id: e.entity_id, participants: parsed.participants }];
418
+ }));
419
+ const allowedMedia = filterMediaForPrivacy(local.media, peopleById, eventsById, {
420
+ stripLivingPortraits: privacy.stripLivingPortraits,
421
+ });
422
+ const byType = {
423
+ place: local.places.map((item) => ({
424
+ entity_type: 'place',
425
+ entity_id: item.id,
426
+ data: parseEntityPayload('place', item),
427
+ has_primary_source: item.has_primary_source ?? true,
428
+ isLiving: false,
429
+ })),
430
+ source: local.sources.map((item) => ({
431
+ entity_type: 'source',
432
+ entity_id: item.id,
433
+ data: parseEntityPayload('source', item),
434
+ has_primary_source: item.has_primary_source ?? true,
435
+ isLiving: false,
436
+ })),
437
+ person: sanitizedPeople,
438
+ event: sanitizedEvents,
439
+ kinship_edge: local.kinship.map((edge) => ({
440
+ entity_type: 'kinship_edge',
441
+ entity_id: deriveKinshipEdgeId(edge),
442
+ data: parseEntityPayload('kinship_edge', edge),
443
+ has_primary_source: true,
444
+ isLiving: false,
445
+ })),
446
+ media: allowedMedia.map((item) => ({
447
+ entity_type: 'media',
448
+ entity_id: item.id,
449
+ data: parseEntityPayload('media', item),
450
+ has_primary_source: item.has_primary_source ?? true,
451
+ isLiving: false,
452
+ })),
453
+ narrative: local.narratives.map((item) => ({
454
+ entity_type: 'narrative',
455
+ entity_id: item.id,
456
+ data: parseEntityPayload('narrative', item),
457
+ has_primary_source: item.has_primary_source ?? true,
458
+ isLiving: false,
459
+ })),
460
+ };
461
+ return {
462
+ byType,
463
+ livingIds,
464
+ filteredOutMediaCount: local.media.length - allowedMedia.length,
465
+ };
466
+ }
467
+ async function fetchRemoteSnapshot(ctx, readToken) {
468
+ const response = await ctx.fetchImpl(`${ctx.bindings.baseUrl}/api/export/snapshot`, {
469
+ method: 'GET',
470
+ headers: {
471
+ Accept: 'application/json',
472
+ Authorization: `Bearer ${readToken}`,
473
+ },
474
+ });
475
+ if (!response.ok) {
476
+ const text = await response.text();
477
+ throw new Error(`GET /api/export/snapshot failed with HTTP ${response.status}: ${text.slice(0, 300)}`);
478
+ }
479
+ const body = await response.json();
480
+ const snapshotRaw = isPlainRecord(body) && isPlainRecord(body.snapshot) ? body.snapshot : body;
481
+ if (!isPlainRecord(snapshotRaw) ||
482
+ !Array.isArray(snapshotRaw.entities) ||
483
+ !Array.isArray(snapshotRaw.kinship)) {
484
+ throw new Error('Unexpected response shape from GET /api/export/snapshot.');
485
+ }
486
+ const headRaw = snapshotRaw.head_revision_id ?? (isPlainRecord(body) ? body.head_revision_id : 0) ?? 0;
487
+ return {
488
+ etag: response.headers.get('etag'),
489
+ headRevisionId: Number(headRaw),
490
+ snapshot: snapshotRaw,
491
+ };
492
+ }
493
+ export function indexRemoteSnapshot(snapshot) {
494
+ const byType = {
495
+ place: new Map(),
496
+ source: new Map(),
497
+ person: new Map(),
498
+ event: new Map(),
499
+ kinship_edge: new Map(),
500
+ media: new Map(),
501
+ narrative: new Map(),
502
+ };
503
+ for (const row of snapshot.entities) {
504
+ if (row.deleted_at !== null && row.deleted_at !== undefined) {
505
+ continue;
506
+ }
507
+ const rawData = row.data.has_primary_source === undefined && row.has_primary_source === false
508
+ ? { ...row.data, has_primary_source: false }
509
+ : row.data;
510
+ const normalized = parseEntityPayload(row.entity_type, rawData);
511
+ byType[row.entity_type].set(row.entity_id, {
512
+ revisionId: Number(row.current_revision_id),
513
+ data: normalized,
514
+ has_primary_source: row.has_primary_source !== false,
515
+ });
516
+ }
517
+ for (const row of snapshot.kinship) {
518
+ if (row.deleted_at !== null && row.deleted_at !== undefined) {
519
+ continue;
520
+ }
521
+ const normalized = parseEntityPayload('kinship_edge', row.edge);
522
+ byType.kinship_edge.set(row.edge_id, {
523
+ revisionId: Number(row.current_revision_id),
524
+ data: normalized,
525
+ has_primary_source: true,
526
+ });
527
+ }
528
+ return byType;
529
+ }
530
+ export function computeSyncPlan(params) {
531
+ const patches = [];
532
+ const countsByType = {};
533
+ const changedSamples = [];
534
+ const plannedDeleteKeys = new Set();
535
+ for (const entityType of params.selectedTypes) {
536
+ const localEntries = params.localByType[entityType] ?? [];
537
+ const remoteMap = params.remoteByType[entityType] ?? new Map();
538
+ const localIds = new Set();
539
+ let created = 0;
540
+ let updated = 0;
541
+ let unchanged = 0;
542
+ let deleted = 0;
543
+ let skippedLiving = 0;
544
+ for (const entry of localEntries) {
545
+ localIds.add(entry.entity_id);
546
+ if (entityType === 'person' && entry.isLiving && !params.includeLiving) {
547
+ skippedLiving += 1;
548
+ continue;
549
+ }
550
+ const remote = remoteMap.get(entry.entity_id);
551
+ if (!remote) {
552
+ patches.push({
553
+ action: 'create',
554
+ entity_type: entityType,
555
+ entity_id: entry.entity_id,
556
+ data: entry.data,
557
+ has_primary_source: entry.has_primary_source,
558
+ });
559
+ created += 1;
560
+ if (changedSamples.length < 25) {
561
+ changedSamples.push({
562
+ action: 'create',
563
+ entity_type: entityType,
564
+ entity_id: entry.entity_id,
565
+ });
566
+ }
567
+ continue;
568
+ }
569
+ const diff = computeEntityDiff(normalizeForDiff(entityType, remote.data), normalizeForDiff(entityType, entry.data));
570
+ if (!diff.hasChanges) {
571
+ unchanged += 1;
572
+ continue;
573
+ }
574
+ patches.push({
575
+ action: 'update',
576
+ entity_type: entityType,
577
+ entity_id: entry.entity_id,
578
+ ...(remote.revisionId > 0 ? { parent_revision_id: remote.revisionId } : {}),
579
+ data: entry.data,
580
+ merge: false,
581
+ has_primary_source: entry.has_primary_source,
582
+ });
583
+ updated += 1;
584
+ if (changedSamples.length < 25) {
585
+ changedSamples.push({
586
+ action: 'update',
587
+ entity_type: entityType,
588
+ entity_id: entry.entity_id,
589
+ changedFields: diff.fields.slice(0, 6).map((f) => f.path),
590
+ });
591
+ }
592
+ }
593
+ if (params.allowDeletes) {
594
+ for (const [remoteId, remote] of remoteMap.entries()) {
595
+ if (localIds.has(remoteId)) {
596
+ continue;
597
+ }
598
+ const key = `${entityType}:${remoteId}`;
599
+ plannedDeleteKeys.add(key);
600
+ patches.push({
601
+ action: 'delete',
602
+ entity_type: entityType,
603
+ entity_id: remoteId,
604
+ ...(remote.revisionId > 0 ? { parent_revision_id: remote.revisionId } : {}),
605
+ });
606
+ deleted += 1;
607
+ if (changedSamples.length < 25) {
608
+ changedSamples.push({
609
+ action: 'delete',
610
+ entity_type: entityType,
611
+ entity_id: remoteId,
612
+ });
613
+ }
614
+ }
615
+ }
616
+ countsByType[entityType] = {
617
+ local: localEntries.length,
618
+ remote: remoteMap.size,
619
+ create: created,
620
+ update: updated,
621
+ delete: deleted,
622
+ unchanged,
623
+ skippedLiving,
624
+ };
625
+ }
626
+ for (const target of params.explicitDeletes) {
627
+ const key = `${target.entity_type}:${target.entity_id}`;
628
+ if (plannedDeleteKeys.has(key)) {
629
+ continue;
630
+ }
631
+ const remoteMap = params.remoteByType[target.entity_type];
632
+ const remote = remoteMap.get(target.entity_id);
633
+ if (!remote) {
634
+ continue;
635
+ }
636
+ plannedDeleteKeys.add(key);
637
+ patches.push({
638
+ action: 'delete',
639
+ entity_type: target.entity_type,
640
+ entity_id: target.entity_id,
641
+ ...(remote.revisionId > 0 ? { parent_revision_id: remote.revisionId } : {}),
642
+ });
643
+ const existingCounts = countsByType[target.entity_type];
644
+ if (existingCounts) {
645
+ existingCounts.delete += 1;
646
+ }
647
+ else {
648
+ countsByType[target.entity_type] = {
649
+ local: params.localByType[target.entity_type].length,
650
+ remote: remoteMap.size,
651
+ create: 0,
652
+ update: 0,
653
+ delete: 1,
654
+ unchanged: 0,
655
+ skippedLiving: 0,
656
+ };
657
+ }
658
+ if (changedSamples.length < 25) {
659
+ changedSamples.push({
660
+ action: 'delete',
661
+ entity_type: target.entity_type,
662
+ entity_id: target.entity_id,
663
+ });
664
+ }
665
+ }
666
+ return { patches, countsByType, changedSamples };
667
+ }
668
+ function guessMimeType(filePath) {
669
+ const ext = path.extname(filePath).toLowerCase();
670
+ return MIME_BY_EXT[ext] ?? 'application/octet-stream';
671
+ }
672
+ function detectSyncMediaLayout(repoDir) {
673
+ const archiveMediaDir = path.join(repoDir, 'archive-media');
674
+ if (fs.existsSync(archiveMediaDir) && fs.statSync(archiveMediaDir).isDirectory()) {
675
+ return 'archive-media';
676
+ }
677
+ return 'media';
678
+ }
679
+ function resolveMediaUploadTarget(repoDir, mediaLayout, rawInput) {
680
+ const mediaRoot = mediaLayout === 'archive-media' ? path.join(repoDir, 'archive-media') : repoDir;
681
+ let localPath;
682
+ let r2Key;
683
+ if (rawInput.startsWith('/media/') || rawInput.startsWith('media/')) {
684
+ const cleanRel = rawInput.replace(/^\/+/, '');
685
+ localPath = path.join(mediaRoot, cleanRel);
686
+ r2Key = cleanRel;
687
+ }
688
+ else {
689
+ localPath = path.isAbsolute(rawInput) ? path.resolve(rawInput) : path.resolve(repoDir, rawInput);
690
+ const relFromArchiveMedia = path.relative(path.join(repoDir, 'archive-media'), localPath);
691
+ const relFromRepo = path.relative(repoDir, localPath);
692
+ if (mediaLayout === 'archive-media' && !relFromArchiveMedia.startsWith('..')) {
693
+ r2Key = relFromArchiveMedia.split(path.sep).join('/');
694
+ }
695
+ else if (!relFromRepo.startsWith('..') && relFromRepo.startsWith(`media${path.sep}`)) {
696
+ r2Key = relFromRepo.split(path.sep).join('/');
697
+ }
698
+ else {
699
+ const base = path.basename(localPath);
700
+ r2Key = mediaLayout === 'archive-media' ? `media/scans/${base}` : `media/${base}`;
701
+ }
702
+ }
703
+ if (!fs.existsSync(localPath)) {
704
+ throw new CliValidationError(`Media file not found on disk: ${localPath} (from '${rawInput}').`);
705
+ }
706
+ return {
707
+ localPath,
708
+ r2Key,
709
+ contentType: guessMimeType(localPath),
710
+ };
711
+ }
712
+ async function runWithConcurrency(items, limit, worker) {
713
+ const results = Array.from({ length: items.length });
714
+ let nextIndex = 0;
715
+ const workerCount = Math.min(limit, items.length);
716
+ await Promise.all(Array.from({ length: workerCount }, async () => {
717
+ while (true) {
718
+ const idx = nextIndex;
719
+ nextIndex += 1;
720
+ if (idx >= items.length) {
721
+ return;
722
+ }
723
+ results[idx] = await worker(items[idx], idx);
724
+ }
725
+ }));
726
+ return results;
727
+ }
728
+ async function findMissingRemoteMedia(ctx, writeToken, mediaEntries) {
729
+ const mediaRoot = ctx.mediaLayout === 'archive-media' ? path.join(ctx.repoDir, 'archive-media') : ctx.repoDir;
730
+ const candidates = [];
731
+ const seenKeys = new Set();
732
+ for (const entry of mediaEntries) {
733
+ const fileUrl = typeof entry.data.file === 'string' ? entry.data.file.trim() : '';
734
+ if (!fileUrl.startsWith('/media/')) {
735
+ continue;
736
+ }
737
+ const r2Key = fileUrl.replace(/^\/+/, '');
738
+ if (seenKeys.has(r2Key)) {
739
+ continue;
740
+ }
741
+ seenKeys.add(r2Key);
742
+ const localPath = path.join(mediaRoot, r2Key);
743
+ if (!fs.existsSync(localPath)) {
744
+ continue;
745
+ }
746
+ const mime = typeof entry.data.mime_type === 'string' && entry.data.mime_type.trim()
747
+ ? entry.data.mime_type.trim()
748
+ : guessMimeType(localPath);
749
+ candidates.push({
750
+ localPath,
751
+ r2Key,
752
+ contentType: mime,
753
+ url: `${ctx.bindings.baseUrl}/${r2Key}`,
754
+ });
755
+ }
756
+ const probeResults = await runWithConcurrency(candidates, MEDIA_PROBE_CONCURRENCY, async (cand) => {
757
+ const resp = await ctx.fetchImpl(cand.url, {
758
+ method: 'GET',
759
+ headers: {
760
+ Authorization: `Bearer ${writeToken}`,
761
+ Range: 'bytes=0-0',
762
+ },
763
+ });
764
+ await resp.body?.cancel().catch(() => undefined);
765
+ return {
766
+ localPath: cand.localPath,
767
+ r2Key: cand.r2Key,
768
+ contentType: cand.contentType,
769
+ existsRemote: resp.status === 200 || resp.status === 206,
770
+ };
771
+ });
772
+ return {
773
+ checkedCount: candidates.length,
774
+ missing: probeResults
775
+ .filter((r) => !r.existsRemote)
776
+ .map(({ localPath, r2Key, contentType }) => ({ localPath, r2Key, contentType })),
777
+ };
778
+ }
779
+ async function uploadMediaTargets(ctx, targets, concurrency) {
780
+ if (targets.length === 0) {
781
+ return [];
782
+ }
783
+ return runWithConcurrency(targets, concurrency, async (target) => {
784
+ await ctx.execWrangler(ctx.wranglerBin, [
785
+ 'r2',
786
+ 'object',
787
+ 'put',
788
+ `${ctx.bindings.r2Bucket}/${target.r2Key}`,
789
+ '--file',
790
+ target.localPath,
791
+ '--content-type',
792
+ target.contentType,
793
+ '--remote',
794
+ '--config',
795
+ ctx.bindings.configPath,
796
+ ], {
797
+ cwd: ctx.repoDir,
798
+ maxBufferBytes: 8 * 1024 * 1024,
799
+ timeoutMs: 60_000,
800
+ });
801
+ return target.r2Key;
802
+ });
803
+ }
804
+ async function submitPatchChunks(params) {
805
+ const totalChunks = Math.ceil(params.patches.length / params.chunkSize);
806
+ const padWidth = String(totalChunks).length;
807
+ const runStamp = new Date().toISOString().replaceAll(/[^0-9]/g, '').slice(0, 14);
808
+ const safeLabel = params.batchLabel.toLowerCase().replaceAll(/[^a-z0-9-]+/g, '-').replaceAll(/^-|-$/g, '') || 'archive';
809
+ const baseBatchId = `sync-${safeLabel}-${runStamp}-${randomBytes(3).toString('hex')}`;
810
+ const responses = [];
811
+ for (let i = 0; i < totalChunks; i += 1) {
812
+ const slice = params.patches.slice(i * params.chunkSize, (i + 1) * params.chunkSize);
813
+ const batchId = totalChunks === 1
814
+ ? baseBatchId
815
+ : `${baseBatchId}-p${String(i + 1).padStart(padWidth, '0')}`;
816
+ const chunkSummary = totalChunks === 1 ? params.summary : `${params.summary} (part ${i + 1}/${totalChunks})`;
817
+ const payload = {
818
+ batch_id: batchId,
819
+ author_type: 'agent',
820
+ summary: chunkSummary,
821
+ has_primary_source: true,
822
+ patches: slice,
823
+ };
824
+ const response = await params.ctx.fetchImpl(`${params.ctx.bindings.baseUrl}/api/batches`, {
825
+ method: 'POST',
826
+ headers: {
827
+ Accept: 'application/json',
828
+ 'Content-Type': 'application/json',
829
+ Authorization: `Bearer ${params.writeToken}`,
830
+ },
831
+ body: JSON.stringify(payload),
832
+ });
833
+ const text = await response.text();
834
+ if (!response.ok) {
835
+ throw new Error(`POST /api/batches (${batchId}, ${slice.length} patches) failed with HTTP ${response.status}: ${text.slice(0, 500)}`);
836
+ }
837
+ const parsed = JSON.parse(text);
838
+ const parsedRec = isPlainRecord(parsed) ? parsed : {};
839
+ responses.push({
840
+ batch_id: typeof parsedRec.batch_id === 'string' ? parsedRec.batch_id : batchId,
841
+ patchCount: slice.length,
842
+ head_revision_id: Number(parsedRec.head_revision_id ?? 0),
843
+ etag: typeof parsedRec.etag === 'string' ? parsedRec.etag : '',
844
+ });
845
+ }
846
+ return responses;
847
+ }
848
+ async function purgeCompiledBundleAndRecompile(ctx, bearerToken) {
849
+ await ctx.execWrangler(ctx.wranglerBin, [
850
+ 'r2',
851
+ 'object',
852
+ 'delete',
853
+ `${ctx.bindings.r2Bucket}/compiled/archive.json`,
854
+ '--remote',
855
+ '--config',
856
+ ctx.bindings.configPath,
857
+ ], {
858
+ cwd: ctx.repoDir,
859
+ maxBufferBytes: 4 * 1024 * 1024,
860
+ timeoutMs: 45_000,
861
+ });
862
+ const response = await ctx.fetchImpl(`${ctx.bindings.baseUrl}/api/bundle`, {
863
+ method: 'GET',
864
+ headers: {
865
+ Accept: 'application/json',
866
+ Authorization: `Bearer ${bearerToken}`,
867
+ 'Cache-Control': 'no-cache',
868
+ },
869
+ });
870
+ if (!response.ok) {
871
+ const text = await response.text();
872
+ throw new Error(`Post-purge GET /api/bundle failed with HTTP ${response.status}: ${text.slice(0, 300)}`);
873
+ }
874
+ const bundle = await response.json();
875
+ const meta = isPlainRecord(bundle) && isPlainRecord(bundle.meta) ? bundle.meta : null;
876
+ const maxRevisionId = typeof meta?.max_revision_id === 'number' ? meta.max_revision_id : null;
877
+ const counts = isPlainRecord(meta?.counts)
878
+ ? meta.counts
879
+ : null;
880
+ return {
881
+ httpStatus: response.status,
882
+ etag: response.headers.get('etag'),
883
+ maxRevisionId,
884
+ counts,
885
+ };
886
+ }
887
+ async function verifyLiveEndpoints(params) {
888
+ const failures = [];
889
+ let bundleStatus = null;
890
+ let bundleRevision = null;
891
+ const bundleUrl = `${params.ctx.bindings.baseUrl}/api/bundle`;
892
+ try {
893
+ const response = await params.ctx.fetchImpl(bundleUrl, {
894
+ method: 'GET',
895
+ headers: {
896
+ Accept: 'application/json',
897
+ Authorization: `Bearer ${params.writeToken}`,
898
+ 'Cache-Control': 'no-cache',
899
+ },
900
+ signal: AbortSignal.timeout(LIVE_VERIFY_TIMEOUT_MS),
901
+ });
902
+ bundleStatus = response.status;
903
+ if (response.status !== 200) {
904
+ const text = await response.text().catch(() => '');
905
+ failures.push({
906
+ target: 'bundle',
907
+ url: bundleUrl,
908
+ status: response.status,
909
+ reason: `Expected HTTP 200 from /api/bundle, got HTTP ${response.status}${text.trim() ? `: ${text.trim().slice(0, 160)}` : ''}`,
910
+ });
911
+ }
912
+ else {
913
+ let body;
914
+ try {
915
+ body = await response.json();
916
+ }
917
+ catch (err) {
918
+ failures.push({
919
+ target: 'bundle',
920
+ url: bundleUrl,
921
+ status: response.status,
922
+ reason: `Invalid JSON from /api/bundle: ${err instanceof Error ? err.message : String(err)}`,
923
+ });
924
+ body = null;
925
+ }
926
+ if (body !== null) {
927
+ const meta = isPlainRecord(body) && isPlainRecord(body.meta) ? body.meta : null;
928
+ bundleRevision = typeof meta?.max_revision_id === 'number' ? meta.max_revision_id : null;
929
+ if (params.expectedRevision !== null &&
930
+ bundleRevision !== params.expectedRevision) {
931
+ failures.push({
932
+ target: 'bundle',
933
+ url: bundleUrl,
934
+ status: response.status,
935
+ reason: `Bundle revision mismatch: expected r${params.expectedRevision}, got ${bundleRevision !== null ? `r${bundleRevision}` : 'none'}`,
936
+ });
937
+ }
938
+ }
939
+ }
940
+ }
941
+ catch (err) {
942
+ failures.push({
943
+ target: 'bundle',
944
+ url: bundleUrl,
945
+ status: null,
946
+ reason: err instanceof Error ? err.message : String(err),
947
+ });
948
+ }
949
+ let mediaFailed = 0;
950
+ const probeConcurrency = Math.max(1, Math.min(params.concurrency, LIVE_VERIFY_CONCURRENCY));
951
+ const mediaProbeFailures = await runWithConcurrency(params.uploadedKeys, probeConcurrency, async (r2Key) => {
952
+ const mediaUrl = `${params.ctx.bindings.baseUrl}/${r2Key}`;
953
+ try {
954
+ const response = await params.ctx.fetchImpl(mediaUrl, {
955
+ method: 'GET',
956
+ headers: {
957
+ Authorization: `Bearer ${params.writeToken}`,
958
+ 'Cache-Control': 'no-cache',
959
+ },
960
+ signal: AbortSignal.timeout(LIVE_VERIFY_TIMEOUT_MS),
961
+ });
962
+ if (response.status !== 200) {
963
+ await response.body?.cancel().catch(() => undefined);
964
+ return {
965
+ target: r2Key,
966
+ url: mediaUrl,
967
+ status: response.status,
968
+ reason: `Expected HTTP 200, got HTTP ${response.status}`,
969
+ };
970
+ }
971
+ const contentLengthHeader = response.headers.get('content-length');
972
+ if (contentLengthHeader !== null && Number(contentLengthHeader) === 0) {
973
+ await response.body?.cancel().catch(() => undefined);
974
+ return {
975
+ target: r2Key,
976
+ url: mediaUrl,
977
+ status: response.status,
978
+ reason: 'Empty response (content-length: 0)',
979
+ };
980
+ }
981
+ let firstChunkBytes = 0;
982
+ const reader = response.body?.getReader();
983
+ if (reader) {
984
+ try {
985
+ while (firstChunkBytes === 0) {
986
+ const chunk = await reader.read();
987
+ if (chunk.done) {
988
+ break;
989
+ }
990
+ firstChunkBytes = chunk.value ? chunk.value.byteLength : 0;
991
+ }
992
+ }
993
+ finally {
994
+ await reader.cancel().catch(() => undefined);
995
+ }
996
+ }
997
+ else {
998
+ const buf = await response.arrayBuffer();
999
+ firstChunkBytes = buf.byteLength;
1000
+ }
1001
+ if (firstChunkBytes === 0) {
1002
+ return {
1003
+ target: r2Key,
1004
+ url: mediaUrl,
1005
+ status: response.status,
1006
+ reason: 'Empty response body (0 bytes)',
1007
+ };
1008
+ }
1009
+ return null;
1010
+ }
1011
+ catch (err) {
1012
+ return {
1013
+ target: r2Key,
1014
+ url: mediaUrl,
1015
+ status: null,
1016
+ reason: err instanceof Error ? err.message : String(err),
1017
+ };
1018
+ }
1019
+ });
1020
+ for (const failure of mediaProbeFailures) {
1021
+ if (failure) {
1022
+ mediaFailed += 1;
1023
+ failures.push(failure);
1024
+ }
1025
+ }
1026
+ return {
1027
+ ok: failures.length === 0,
1028
+ bundleStatus,
1029
+ bundleRevision,
1030
+ expectedRevision: params.expectedRevision,
1031
+ mediaChecked: params.uploadedKeys.length,
1032
+ mediaFailed,
1033
+ failures,
1034
+ };
1035
+ }
1036
+ export function formatSyncReport(report) {
1037
+ const lines = [
1038
+ `Archive: ${report.baseUrl}`,
1039
+ `Mode: ${report.dryRun ? 'DRY RUN (no remote D1/R2 mutations)' : 'LIVE SYNC'}`,
1040
+ `Bindings: D1=${report.dbName}, R2=${report.r2Bucket}`,
1041
+ `Remote head before sync: r${report.remoteHeadBefore} (etag=${report.remoteEtagBefore ?? 'none'})`,
1042
+ `Entity diff by type (${report.selectedTypes.join(', ')}):`,
1043
+ ];
1044
+ for (const type of SYNC_DEPENDENCY_ORDER) {
1045
+ const c = report.countsByType[type];
1046
+ if (!c) {
1047
+ continue;
1048
+ }
1049
+ const parts = [
1050
+ `local=${c.local}`,
1051
+ `remote=${c.remote}`,
1052
+ `create=${c.create}`,
1053
+ `update=${c.update}`,
1054
+ `delete=${c.delete}`,
1055
+ `unchanged=${c.unchanged}`,
1056
+ ];
1057
+ if (c.skippedLiving > 0) {
1058
+ parts.push(`skipped_living=${c.skippedLiving}`);
1059
+ }
1060
+ lines.push(` - ${type}: ${parts.join(', ')}`);
1061
+ }
1062
+ lines.push(`Planned patches: ${report.totalPatches} (chunk_size=${report.chunkSize}, planned_batches=${report.plannedBatches})`);
1063
+ if (report.changedSamples.length > 0) {
1064
+ lines.push('Sample planned changes:');
1065
+ for (const sample of report.changedSamples) {
1066
+ const fields = sample.changedFields?.length
1067
+ ? ` [${sample.changedFields.join(', ')}]`
1068
+ : '';
1069
+ lines.push(` - ${sample.action} ${sample.entity_type}:${sample.entity_id}${fields}`);
1070
+ }
1071
+ }
1072
+ if (report.media.checkedRemoteCount > 0 || report.media.plannedUploads.length > 0) {
1073
+ lines.push(`Media R2 sync: checked=${report.media.checkedRemoteCount}, planned_uploads=${report.media.plannedUploads.length}, uploaded=${report.media.uploadedKeys.length}, concurrency=${report.media.concurrency}`);
1074
+ }
1075
+ if (report.batchesSubmitted.length > 0) {
1076
+ lines.push(`Batches submitted: ${report.batchesSubmitted.length}`);
1077
+ const last = report.batchesSubmitted[report.batchesSubmitted.length - 1];
1078
+ lines.push(`Last batch: ${last.batch_id} -> r${last.head_revision_id} (${last.etag})`);
1079
+ }
1080
+ if (report.recompile) {
1081
+ lines.push(`Recompiled live /api/bundle: HTTP ${report.recompile.httpStatus}, ETag=${report.recompile.etag ?? 'none'}, max_revision_id=${report.recompile.maxRevisionId}`);
1082
+ }
1083
+ if (report.liveVerification) {
1084
+ const lv = report.liveVerification;
1085
+ lines.push(`Live verification [${lv.ok ? 'PASS' : 'FAIL'}]: bundle=HTTP ${lv.bundleStatus ?? 'error'} (rev=${lv.bundleRevision ?? 'none'}, expected=${lv.expectedRevision ?? 'none'}), media=${lv.mediaChecked - lv.mediaFailed}/${lv.mediaChecked} ok`);
1086
+ for (const failure of lv.failures) {
1087
+ lines.push(` VERIFY FAIL [${failure.target}] ${failure.url}: ${failure.reason}`);
1088
+ }
1089
+ }
1090
+ if (report.cleanup) {
1091
+ lines.push(`Token cleanup: deleted ${report.cleanup.deletedTokenIds.length} temp token(s), verified ${report.cleanup.remainingTmpCount} remaining; active '${report.cleanup.backupTokenLabel}' count=${report.cleanup.backupCount}`);
1092
+ }
1093
+ return `${lines.join('\n')}\n`;
1094
+ }
1095
+ export async function runSyncCommand(options = {}) {
1096
+ const repoDir = path.resolve(options.repoDir?.trim() || process.cwd());
1097
+ const selectedTypes = options.types && options.types.length > 0
1098
+ ? SYNC_DEPENDENCY_ORDER.filter((t) => options.types?.includes(t))
1099
+ : [...SYNC_DEPENDENCY_ORDER];
1100
+ const concurrency = options.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY;
1101
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
1102
+ const dryRun = Boolean(options.dryRun);
1103
+ const verifyLive = Boolean(options.verifyLive);
1104
+ const includeLiving = Boolean(options.includeLiving);
1105
+ const allowDeletes = Boolean(options.allowDeletes);
1106
+ const syncMissingMedia = Boolean(options.syncMissingMedia);
1107
+ const uploadMediaPaths = options.uploadMediaPaths ?? [];
1108
+ const explicitDeletes = options.explicitDeletes ?? [];
1109
+ const backupTokenLabel = options.backupTokenLabel?.trim() || DEFAULT_BACKUP_TOKEN_LABEL;
1110
+ if (!Number.isInteger(concurrency) || concurrency <= 0) {
1111
+ throw new CliValidationError('Option `--concurrency` must be a positive integer.');
1112
+ }
1113
+ if (!Number.isInteger(chunkSize) || chunkSize <= 0) {
1114
+ throw new CliValidationError('Option `--chunk-size` must be a positive integer.');
1115
+ }
1116
+ if (options.summary !== undefined && options.summary.trim().length < 3) {
1117
+ throw new CliValidationError('Option `--summary` requires text of at least 3 characters.');
1118
+ }
1119
+ const bindings = loadWranglerBindings(repoDir, options.siteUrl);
1120
+ const wranglerBin = resolveWranglerBin(repoDir, options.wranglerBin);
1121
+ const mediaLayout = detectSyncMediaLayout(repoDir);
1122
+ const ctx = {
1123
+ repoDir,
1124
+ mediaLayout,
1125
+ bindings,
1126
+ wranglerBin,
1127
+ fetchImpl: options.fetchImpl ?? globalThis.fetch,
1128
+ execWrangler: options.execWrangler ?? defaultWranglerExecutor,
1129
+ backupTokenLabel,
1130
+ };
1131
+ const local = await loadLocalArchive(repoDir);
1132
+ const sanitizedLocal = buildSanitizedLocalEntries(local);
1133
+ const summary = options.summary?.trim() || `Sync ${local.siteConfig.site.familyName} archive from local YAML`;
1134
+ const minted = await mintTempTokens(ctx);
1135
+ const mintedIds = [minted.read_backup.tokenId, minted.write_batch.tokenId];
1136
+ let cleanupResult = null;
1137
+ let primaryError = null;
1138
+ let baseReport = null;
1139
+ try {
1140
+ const remoteSnap = await fetchRemoteSnapshot(ctx, minted.read_backup.rawToken);
1141
+ const remoteByType = indexRemoteSnapshot(remoteSnap.snapshot);
1142
+ const plan = computeSyncPlan({
1143
+ selectedTypes,
1144
+ localByType: sanitizedLocal.byType,
1145
+ remoteByType,
1146
+ includeLiving,
1147
+ allowDeletes,
1148
+ explicitDeletes,
1149
+ });
1150
+ const mediaUploadTargetsMap = new Map();
1151
+ for (const rawMediaPath of uploadMediaPaths) {
1152
+ const target = resolveMediaUploadTarget(repoDir, mediaLayout, rawMediaPath);
1153
+ mediaUploadTargetsMap.set(target.r2Key, target);
1154
+ }
1155
+ let checkedRemoteMediaCount = 0;
1156
+ if (syncMissingMedia) {
1157
+ const missingRes = await findMissingRemoteMedia(ctx, minted.write_batch.rawToken, sanitizedLocal.byType.media);
1158
+ checkedRemoteMediaCount = missingRes.checkedCount;
1159
+ for (const item of missingRes.missing) {
1160
+ mediaUploadTargetsMap.set(item.r2Key, item);
1161
+ }
1162
+ }
1163
+ const mediaUploadTargets = [...mediaUploadTargetsMap.values()];
1164
+ let uploadedKeys = [];
1165
+ let batchesSubmitted = [];
1166
+ let recompile = null;
1167
+ let liveVerification = null;
1168
+ if (!dryRun) {
1169
+ if (mediaUploadTargets.length > 0) {
1170
+ uploadedKeys = await uploadMediaTargets(ctx, mediaUploadTargets, concurrency);
1171
+ }
1172
+ if (plan.patches.length > 0) {
1173
+ batchesSubmitted = await submitPatchChunks({
1174
+ ctx,
1175
+ writeToken: minted.write_batch.rawToken,
1176
+ batchLabel: local.siteConfig.site.familyName,
1177
+ summary,
1178
+ patches: plan.patches,
1179
+ chunkSize,
1180
+ });
1181
+ recompile = await purgeCompiledBundleAndRecompile(ctx, minted.write_batch.rawToken);
1182
+ }
1183
+ if (verifyLive) {
1184
+ const expectedRevision = batchesSubmitted.length > 0
1185
+ ? batchesSubmitted[batchesSubmitted.length - 1].head_revision_id
1186
+ : remoteSnap.headRevisionId;
1187
+ liveVerification = await verifyLiveEndpoints({
1188
+ ctx,
1189
+ writeToken: minted.write_batch.rawToken,
1190
+ expectedRevision,
1191
+ uploadedKeys,
1192
+ concurrency,
1193
+ });
1194
+ }
1195
+ }
1196
+ baseReport = {
1197
+ repoDir,
1198
+ baseUrl: bindings.baseUrl,
1199
+ dbName: bindings.dbName,
1200
+ r2Bucket: bindings.r2Bucket,
1201
+ dryRun,
1202
+ selectedTypes,
1203
+ remoteHeadBefore: remoteSnap.headRevisionId,
1204
+ remoteEtagBefore: remoteSnap.etag,
1205
+ countsByType: plan.countsByType,
1206
+ totalPatches: plan.patches.length,
1207
+ chunkSize,
1208
+ plannedBatches: Math.ceil(plan.patches.length / chunkSize),
1209
+ changedSamples: plan.changedSamples,
1210
+ filteredOutLivingMedia: sanitizedLocal.filteredOutMediaCount,
1211
+ media: {
1212
+ checkedRemoteCount: checkedRemoteMediaCount,
1213
+ plannedUploads: mediaUploadTargets.map((t) => t.r2Key),
1214
+ uploadedKeys,
1215
+ concurrency,
1216
+ },
1217
+ batchesSubmitted,
1218
+ recompile,
1219
+ liveVerification,
1220
+ cleanup: null,
1221
+ };
1222
+ }
1223
+ catch (err) {
1224
+ primaryError = err;
1225
+ }
1226
+ finally {
1227
+ try {
1228
+ cleanupResult = await cleanupTempTokens(ctx, mintedIds);
1229
+ }
1230
+ catch (cleanupErr) {
1231
+ if (!primaryError) {
1232
+ primaryError = cleanupErr;
1233
+ }
1234
+ }
1235
+ }
1236
+ if (primaryError !== null) {
1237
+ throw primaryError;
1238
+ }
1239
+ if (!baseReport) {
1240
+ throw new Error('Sync completed without producing a report.');
1241
+ }
1242
+ baseReport.cleanup = cleanupResult;
1243
+ const rendered = options.json
1244
+ ? `${JSON.stringify(baseReport, null, 2)}\n`
1245
+ : formatSyncReport(baseReport);
1246
+ return {
1247
+ ...baseReport,
1248
+ rendered,
1249
+ };
1250
+ }
1251
+ //# sourceMappingURL=sync.js.map