@niscorp/strata 0.1.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 (48) hide show
  1. package/DESIGN.md +208 -0
  2. package/LICENSE +202 -0
  3. package/README.md +195 -0
  4. package/dist/check/index.cjs +223 -0
  5. package/dist/check/index.cjs.map +1 -0
  6. package/dist/check/index.d.cts +63 -0
  7. package/dist/check/index.d.ts +63 -0
  8. package/dist/check/index.js +4 -0
  9. package/dist/check/index.js.map +1 -0
  10. package/dist/chunk-EGFF63GA.js +16 -0
  11. package/dist/chunk-EGFF63GA.js.map +1 -0
  12. package/dist/chunk-HMT7HHFJ.js +156 -0
  13. package/dist/chunk-HMT7HHFJ.js.map +1 -0
  14. package/dist/chunk-ICWKTTKN.js +129 -0
  15. package/dist/chunk-ICWKTTKN.js.map +1 -0
  16. package/dist/chunk-MY3TGSV3.js +206 -0
  17. package/dist/chunk-MY3TGSV3.js.map +1 -0
  18. package/dist/chunk-U5CPF4LQ.js +175 -0
  19. package/dist/chunk-U5CPF4LQ.js.map +1 -0
  20. package/dist/documents-BjlM94Ea.d.cts +90 -0
  21. package/dist/documents-BjlM94Ea.d.ts +90 -0
  22. package/dist/index.cjs +370 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +16 -0
  25. package/dist/index.d.ts +16 -0
  26. package/dist/index.js +42 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/node/index.cjs +629 -0
  29. package/dist/node/index.cjs.map +1 -0
  30. package/dist/node/index.d.cts +19 -0
  31. package/dist/node/index.d.ts +19 -0
  32. package/dist/node/index.js +164 -0
  33. package/dist/node/index.js.map +1 -0
  34. package/dist/plan-BAewc8DG.d.ts +53 -0
  35. package/dist/plan-BEIlXVUt.d.cts +53 -0
  36. package/dist/postgres/index.cjs +333 -0
  37. package/dist/postgres/index.cjs.map +1 -0
  38. package/dist/postgres/index.d.cts +44 -0
  39. package/dist/postgres/index.d.ts +44 -0
  40. package/dist/postgres/index.js +145 -0
  41. package/dist/postgres/index.js.map +1 -0
  42. package/dist/upgrade/index.cjs +236 -0
  43. package/dist/upgrade/index.cjs.map +1 -0
  44. package/dist/upgrade/index.d.cts +54 -0
  45. package/dist/upgrade/index.d.ts +54 -0
  46. package/dist/upgrade/index.js +5 -0
  47. package/dist/upgrade/index.js.map +1 -0
  48. package/package.json +94 -0
@@ -0,0 +1,223 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var StrataError = class extends Error {
5
+ code;
6
+ details;
7
+ constructor(code, message, details = [], options) {
8
+ super(details.length > 0 ? `${message}
9
+ ${details.map((d) => ` ${d}`).join("\n")}` : message, options);
10
+ this.name = "StrataError";
11
+ this.code = code;
12
+ this.details = details;
13
+ }
14
+ };
15
+
16
+ // src/check/index.ts
17
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18
+ var byKey = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
19
+ var sortKeys = (value) => {
20
+ if (Array.isArray(value)) return value.map(sortKeys);
21
+ if (!isRecord(value)) return value;
22
+ return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));
23
+ };
24
+ var NAMED = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
25
+ var DATA = /* @__PURE__ */ new Set(["const", "enum", "default", "examples"]);
26
+ var normalize = (value) => {
27
+ if (Array.isArray(value)) return value.map(normalize);
28
+ if (!isRecord(value)) return value;
29
+ return Object.fromEntries(
30
+ Object.entries(value).filter(([key]) => key !== "description" && key !== "$schema").sort(byKey).map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)])
31
+ );
32
+ };
33
+ var namedSchemas = (map, each) => Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));
34
+ var snapshotOf = (sequence, schemas) => {
35
+ const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);
36
+ const given = Object.keys(schemas);
37
+ const missing = declared.filter((k) => !given.includes(k));
38
+ const extra = given.filter((k) => !declared.includes(k));
39
+ if (missing.length > 0 || extra.length > 0) {
40
+ throw new StrataError("UNKNOWN_KIND", `The schemas for ${sequence.id} do not match its kinds.`, [
41
+ ...missing.map((k) => `no schema for ${k}`),
42
+ ...extra.map((k) => `${k} is not a kind of ${sequence.id}`)
43
+ ]);
44
+ }
45
+ const kinds = {};
46
+ for (const kind of [...declared].sort()) {
47
+ const schema = schemas[kind];
48
+ if (schema !== void 0) kinds[kind] = sortKeys(schema["~standard"].jsonSchema.input({ target: "draft-2020-12" }));
49
+ }
50
+ return { sequence: sequence.id, version: sequence.migrations.length, kinds };
51
+ };
52
+ var snapshotText = (snapshot) => `${JSON.stringify(sortKeys(snapshot), null, 2)}
53
+ `;
54
+ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
55
+ if (out.length >= limit) return;
56
+ if (JSON.stringify(a) === JSON.stringify(b)) return;
57
+ if (isRecord(a) && isRecord(b)) {
58
+ for (const key of [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
59
+ const at = path === "" ? key : `${path}.${key}`;
60
+ if (!(key in a)) out.push(`+ ${at}`);
61
+ else if (!(key in b)) out.push(`- ${at}`);
62
+ else diffLines(a[key], b[key], at, out, limit, canon, sets);
63
+ if (out.length >= limit) return;
64
+ }
65
+ return;
66
+ }
67
+ if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {
68
+ a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));
69
+ return;
70
+ }
71
+ if (Array.isArray(a) && Array.isArray(b)) {
72
+ const text = (v) => JSON.stringify(canon(v));
73
+ const label = (v) => isRecord(v) && isRecord(v["properties"]) ? Object.keys(v["properties"]).join(",") : (text(v) ?? "").slice(0, 50);
74
+ const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));
75
+ const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));
76
+ const byLabel = new Map(onlyB.map((y) => [label(y), y]));
77
+ for (const x of onlyA) {
78
+ const partner = byLabel.get(label(x));
79
+ if (partner !== void 0) {
80
+ diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);
81
+ byLabel.delete(label(x));
82
+ } else {
83
+ out.push(`- ${path}[${label(x)}]`);
84
+ }
85
+ if (out.length >= limit) return;
86
+ }
87
+ for (const [name] of byLabel) {
88
+ out.push(`+ ${path}[${name}]`);
89
+ if (out.length >= limit) return;
90
+ }
91
+ return;
92
+ }
93
+ out.push(`~ ${path || "(root)"}: ${JSON.stringify(a)?.slice(0, 60)} \u2192 ${JSON.stringify(b)?.slice(0, 60)}`);
94
+ };
95
+ var REF_PREFIX = /^#\/(\$defs|definitions)\//;
96
+ var respell = (value) => {
97
+ let node = value;
98
+ const anyOf = node["anyOf"];
99
+ if (!("type" in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m["type"] === "string")) {
100
+ const { anyOf: _union, ...rest } = node;
101
+ node = { ...rest, type: anyOf.map((m) => isRecord(m) ? m["type"] : void 0) };
102
+ }
103
+ const type = node["type"];
104
+ if (Array.isArray(type)) {
105
+ const types = [...new Set(type.map(String))].sort();
106
+ node = { ...node, type: types.length === 1 ? types[0] : types };
107
+ }
108
+ const allOf = node["allOf"];
109
+ const only = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : void 0;
110
+ if (!("$ref" in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only["$ref"] === "string") {
111
+ const { allOf: _wrapper, ...rest } = node;
112
+ node = { ...rest, $ref: only["$ref"] };
113
+ }
114
+ return node;
115
+ };
116
+ var schemaChildren = (node) => Object.entries(node).flatMap(
117
+ ([key, child]) => key === "$ref" || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child]
118
+ );
119
+ var canonical = (recorded) => {
120
+ const schema = normalize(recorded);
121
+ if (!isRecord(schema)) return schema;
122
+ const defs = {
123
+ ...isRecord(schema["definitions"]) ? schema["definitions"] : {},
124
+ ...isRecord(schema["$defs"]) ? schema["$defs"] : {}
125
+ };
126
+ const { $defs: _defs, definitions: _definitions, ...body } = schema;
127
+ const target = (ref) => ref === "#" ? { key: "#", node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, "")] };
128
+ const recursive = /* @__PURE__ */ new Set();
129
+ const findCycles = (value, stack) => {
130
+ if (Array.isArray(value)) {
131
+ for (const item of value) findCycles(item, stack);
132
+ return;
133
+ }
134
+ if (!isRecord(value)) return;
135
+ const node = respell(value);
136
+ for (const child of schemaChildren(node)) findCycles(child, stack);
137
+ const ref = node["$ref"];
138
+ if (typeof ref !== "string") return;
139
+ const { key, node: next } = target(ref);
140
+ if (stack.includes(key)) recursive.add(key);
141
+ else findCycles(next, [...stack, key]);
142
+ };
143
+ findCycles(body, ["#"]);
144
+ const names = /* @__PURE__ */ new Map();
145
+ const named = {};
146
+ const nameOf = (key, node) => {
147
+ const known = names.get(key);
148
+ if (known !== void 0) return known;
149
+ const name = `d${names.size}`;
150
+ names.set(key, name);
151
+ named[name] = emit(node);
152
+ return name;
153
+ };
154
+ const emit = (value) => {
155
+ if (Array.isArray(value)) return value.map(emit);
156
+ if (!isRecord(value)) return value;
157
+ const node = respell(value);
158
+ const rest = Object.fromEntries(
159
+ Object.entries(node).filter(([key2]) => key2 !== "$ref").sort(byKey).map(([key2, child]) => [key2, NAMED.has(key2) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key2) ? child : emit(child)])
160
+ );
161
+ const ref = node["$ref"];
162
+ if (typeof ref !== "string") return rest;
163
+ const { key, node: next } = target(ref);
164
+ const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);
165
+ return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;
166
+ };
167
+ const root = recursive.has("#") ? { $ref: `#/$defs/${nameOf("#", body)}` } : emit(body);
168
+ return Object.keys(named).length === 0 ? root : sortKeys({ ...isRecord(root) ? root : { allOf: [root] }, $defs: named });
169
+ };
170
+ var compareSnapshot = (recorded, current) => {
171
+ if (recorded === void 0) return { status: "missing" };
172
+ const changes = [];
173
+ for (const kind of [.../* @__PURE__ */ new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {
174
+ const lines = [];
175
+ if (!(kind in recorded.kinds)) lines.push("+ (a new kind)");
176
+ else if (!(kind in current.kinds)) lines.push("- (the kind is gone)");
177
+ else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), "", lines, 12);
178
+ if (lines.length > 0) changes.push({ kind, lines });
179
+ }
180
+ return changes.length === 0 ? { status: "same" } : { status: "changed", changes };
181
+ };
182
+ var issueText = (issue) => {
183
+ const path = (issue.path ?? []).map((p) => typeof p === "object" ? String(p.key) : String(p)).join(".");
184
+ return `${path === "" ? "" : `${path}: `}${issue.message}`;
185
+ };
186
+ var diffJson = (a, b, limit = 20) => {
187
+ const out = [];
188
+ diffLines(a, b, "", out, limit, sortKeys, false);
189
+ return out;
190
+ };
191
+ var checkCorpus = async (upgrader, schemas, documents) => {
192
+ const failures = [];
193
+ let passed = 0;
194
+ for (const doc of documents) {
195
+ const schema = schemas[doc.kind];
196
+ if (schema === void 0) {
197
+ failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });
198
+ continue;
199
+ }
200
+ let upgraded;
201
+ try {
202
+ upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;
203
+ } catch (error) {
204
+ failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split("\n")[0] ?? error.message : String(error) });
205
+ continue;
206
+ }
207
+ const result = await schema["~standard"].validate(upgraded);
208
+ if (result.issues !== void 0) {
209
+ failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join("; ") });
210
+ } else {
211
+ passed += 1;
212
+ }
213
+ }
214
+ return { passed, failures };
215
+ };
216
+
217
+ exports.checkCorpus = checkCorpus;
218
+ exports.compareSnapshot = compareSnapshot;
219
+ exports.diffJson = diffJson;
220
+ exports.snapshotOf = snapshotOf;
221
+ exports.snapshotText = snapshotText;
222
+ //# sourceMappingURL=index.cjs.map
223
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/errors.ts","../../src/check/index.ts"],"names":["key"],"mappings":";;;AA0BO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAC5B,IAAA;AAAA,EACA,OAAA;AAAA,EAET,YAAY,IAAA,EAAuB,OAAA,EAAiB,OAAA,GAA6B,IAAI,OAAA,EAA+B;AAClH,IAAA,KAAA,CAAM,OAAA,CAAQ,MAAA,GAAS,CAAA,GAAI,CAAA,EAAG,OAAO;AAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,GAAK,SAAS,OAAO,CAAA;AACtG,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF,CAAA;;;ACKA,IAAM,QAAA,GAAW,CAAC,KAAA,KAChB,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAErE,IAAM,KAAA,GAAQ,CAAC,CAAC,CAAC,CAAA,EAAsB,CAAC,CAAC,CAAA,KAAkC,CAAA,GAAI,CAAA,GAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAA;AAIpG,IAAM,QAAA,GAAW,CAAC,KAAA,KAA4B;AAC5C,EAAA,IAAI,MAAM,OAAA,CAAQ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EAAO;AACd,MAAA,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,GAAA,CAAI,IAAI,IAAA,EAAM,GAAA,CAAI,IAAA,EAAM,MAAA,EAAQ,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,CAAE,CAAC,CAAA,IAAK,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAA,EAAG,CAAA;AAC5I,MAAA;AAAA,IACF;AACA,IAAA,MAAM,SAAS,MAAM,MAAA,CAAO,WAAW,CAAA,CAAE,SAAS,QAAQ,CAAA;AAC1D,IAAA,IAAI,MAAA,CAAO,WAAW,MAAA,EAAW;AAC/B,MAAA,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,GAAA,CAAI,IAAI,IAAA,EAAM,GAAA,CAAI,MAAM,MAAA,EAAQ,MAAA,CAAO,OAAO,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA,CAAE,GAAA,CAAI,SAAS,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA,EAAG,CAAA;AAAA,IAC3G,CAAA,MAAO;AACL,MAAA,MAAA,IAAU,CAAA;AAAA,IACZ;AAAA,EACF;AACA,EAAA,OAAO,EAAE,QAAQ,QAAA,EAAS;AAC5B","file":"index.cjs","sourcesContent":["// Every refusal strata makes, by name. The message is a sentence for a person;\n// the code is for the program that has to decide what to do about it.\nexport type StrataErrorCode =\n // A sequence failed its schema, or two sequences share an id.\n | 'INVALID_SEQUENCE'\n // An applied migration's steps no longer match what the code says it ran.\n | 'EDITED'\n // The database has migrations of a sequence this code does not know yet —\n // it was migrated by newer code.\n | 'TOO_NEW'\n // A `dependsOn` names a migration nobody provides and the ledger lacks.\n | 'UNKNOWN_DEPENDENCY'\n // Pending migrations wait on each other.\n | 'CYCLE'\n // Verify mode found work to do.\n | 'PENDING'\n // A step threw; the whole run was rolled back.\n | 'STEP_FAILED'\n // The pool cannot hold one connection for a transaction.\n | 'NO_TRANSACTION'\n // A document kind nobody declares — as the root being upgraded, a step's\n // `at`, or an embedding's target.\n | 'UNKNOWN_KIND'\n // A grammar sequence handed to the ledger, or a table sequence to upgrade().\n | 'WRONG_OWNER';\n\nexport class StrataError extends Error {\n readonly code: StrataErrorCode;\n readonly details: readonly string[];\n\n constructor(code: StrataErrorCode, message: string, details: readonly string[] = [], options?: { cause?: unknown }) {\n super(details.length > 0 ? `${message}\\n${details.map((d) => ` ${d}`).join('\\n')}` : message, options);\n this.name = 'StrataError';\n this.code = code;\n this.details = details;\n }\n}\n","import type { Sequence } from '../schema';\nimport type { Stamp, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/check — the gate a grammar change has to pass.\n//\n// Two questions, both mechanical:\n//\n// 1. SNAPSHOT — did a kind's schema change without the grammar gaining a\n// migration? Each kind's JSON Schema, taken through the schema's OWN\n// Standard JSON Schema hook, is recorded per grammar version. Same version,\n// different schema: something changed that older readers were never told.\n// Append a migration (an empty marker is enough for an addition — strict\n// readers still have to refuse the newer documents), then record the new\n// version.\n//\n// 2. CORPUS — does every real document ever captured, at the stamp it was\n// captured at, still upgrade to the current grammar and pass the current\n// strict schema? This is the judge: a snapshot only says something moved,\n// the corpus says whether old documents survive it. No JSON Schema diff\n// tool is trusted to decide compatibility.\n//\n// Pure: no files, no process. A host reads and writes snapshots where it keeps\n// them (nisc's own live in the repo's `strata/` directory).\n// ═══════════════════════════════════════════════════════════════\n\ntype Issue = { message: string; path?: readonly (PropertyKey | { key: PropertyKey })[] };\ntype StandardResult = { value: unknown; issues?: undefined } | { issues: readonly Issue[] };\n\n// Any validator implementing Standard Schema + Standard JSON Schema (Zod ≥ 4.2,\n// Valibot, ArkType). Structural: strata depends on none of them.\nexport type GrammarSchema = {\n '~standard': {\n validate: (value: unknown) => StandardResult | Promise<StandardResult>;\n jsonSchema: { input: (options: { target: string }) => Record<string, unknown> };\n };\n};\n\nexport type Snapshot = { sequence: string; version: number; kinds: Readonly<Record<string, unknown>> };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst byKey = ([a]: [string, unknown], [b]: [string, unknown]): number => (a < b ? -1 : a > b ? 1 : 0);\n\n// Sorted keys, nothing else — for documents, where every key (a `description`\n// too) is content, and for a snapshot file, which keeps what the validator wrote.\nconst sortKeys = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (!isRecord(value)) return value;\n return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));\n};\n\n// Where a schema's keys are NAMES, not keywords — a field called `description`\n// or an op called `$ref` is grammar — and where its values are instance data\n// rather than schemas.\nconst NAMED = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);\nconst DATA = new Set(['const', 'enum', 'default', 'examples']);\n\n// A schema without its prose: the `description` KEYWORD is documentation, and\n// rewording a `.describe()` must not demand a migration. `$schema` is the same\n// everywhere. Applied when comparing, never to what is recorded — so what the\n// gate ignores can change without touching a snapshot file.\nconst normalize = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(normalize);\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => key !== 'description' && key !== '$schema')\n .sort(byKey)\n .map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)]),\n );\n};\n\n// A name → schema map, each schema through `each`, the names untouched.\nconst namedSchemas = (map: Record<string, unknown>, each: (schema: unknown) => unknown): Record<string, unknown> =>\n Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));\n\n// The grammar as it stands: every kind it declares, as JSON Schema — as the\n// validator wrote it, keys sorted. `schemas` must cover exactly the sequence's\n// kinds — a kind without a schema cannot be checked, and a schema without a\n// kind belongs to some other grammar.\nexport const snapshotOf = (sequence: Sequence, schemas: Readonly<Record<string, GrammarSchema>>): Snapshot => {\n const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);\n const given = Object.keys(schemas);\n const missing = declared.filter((k) => !given.includes(k));\n const extra = given.filter((k) => !declared.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new StrataError('UNKNOWN_KIND', `The schemas for ${sequence.id} do not match its kinds.`, [\n ...missing.map((k) => `no schema for ${k}`),\n ...extra.map((k) => `${k} is not a kind of ${sequence.id}`),\n ]);\n }\n const kinds: Record<string, unknown> = {};\n for (const kind of [...declared].sort()) {\n const schema = schemas[kind];\n if (schema !== undefined) kinds[kind] = sortKeys(schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }));\n }\n return { sequence: sequence.id, version: sequence.migrations.length, kinds };\n};\n\n// Stable text for a snapshot file: sorted keys, two-space indent, newline.\nexport const snapshotText = (snapshot: Snapshot): string => `${JSON.stringify(sortKeys(snapshot), null, 2)}\n`;\n\n// Schema arrays are compared as sets (`sets`); a document's arrays by position —\n// `layout.children[1]` is how a person finds the thing that changed.\nconst diffLines = (a: unknown, b: unknown, path: string, out: string[], limit: number, canon: (v: unknown) => unknown = normalize, sets = true): void => {\n if (out.length >= limit) return;\n if (JSON.stringify(a) === JSON.stringify(b)) return;\n if (isRecord(a) && isRecord(b)) {\n for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {\n const at = path === '' ? key : `${path}.${key}`;\n if (!(key in a)) out.push(`+ ${at}`);\n else if (!(key in b)) out.push(`- ${at}`);\n else diffLines(a[key], b[key], at, out, limit, canon, sets);\n if (out.length >= limit) return;\n }\n return;\n }\n if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {\n a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));\n return;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n // Schema arrays are SETS more often than sequences — a union's `anyOf`, a\n // `required` list, an `enum` — and one added branch shifts every index\n // after it. Match elements by what they describe (an object schema by its\n // property names — for Prism's union, the op), report the ones on one side\n // only, and diff the ones that changed in place.\n const text = (v: unknown): string => JSON.stringify(canon(v));\n const label = (v: unknown): string =>\n isRecord(v) && isRecord(v['properties']) ? Object.keys(v['properties']).join(',') : (text(v) ?? '').slice(0, 50);\n const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));\n const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));\n const byLabel = new Map(onlyB.map((y) => [label(y), y]));\n for (const x of onlyA) {\n const partner = byLabel.get(label(x));\n if (partner !== undefined) {\n diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);\n byLabel.delete(label(x));\n } else {\n out.push(`- ${path}[${label(x)}]`);\n }\n if (out.length >= limit) return;\n }\n for (const [name] of byLabel) {\n out.push(`+ ${path}[${name}]`);\n if (out.length >= limit) return;\n }\n return;\n }\n out.push(`~ ${path || '(root)'}: ${JSON.stringify(a)?.slice(0, 60)} → ${JSON.stringify(b)?.slice(0, 60)}`);\n};\n\n// ── canonical form ──────────────────────────────────────────────\n//\n// A snapshot records what the validator WROTE, and validators spell one schema\n// many ways: they name and inline definitions as they please (zod numbers them\n// in visit order, and 4.3 and 4.4 visit differently), write a described\n// reference as `allOf: [{ $ref }]` or as `$ref`, and a union of bare types as\n// `anyOf: [{ type }, …]` or `type: […]`. None of that is the grammar, so a\n// comparison reads both sides in one spelling: every definition inlined unless\n// it is recursive, the recursive ones renamed by first use, and every schema\n// identity above written one way. A snapshot FILE stays what the validator\n// wrote — only the comparison is canonical.\n\nconst REF_PREFIX = /^#\\/(\\$defs|definitions)\\//;\n\n// One spelling for the equivalences the node itself can show.\nconst respell = (value: Record<string, unknown>): Record<string, unknown> => {\n let node = value;\n const anyOf = node['anyOf'];\n if (!('type' in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m['type'] === 'string')) {\n const { anyOf: _union, ...rest } = node;\n node = { ...rest, type: anyOf.map((m) => (isRecord(m) ? m['type'] : undefined)) };\n }\n const type = node['type'];\n if (Array.isArray(type)) {\n const types = [...new Set(type.map(String))].sort();\n node = { ...node, type: types.length === 1 ? types[0] : types };\n }\n const allOf = node['allOf'];\n const only: unknown = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : undefined;\n if (!('$ref' in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only['$ref'] === 'string') {\n const { allOf: _wrapper, ...rest } = node;\n node = { ...rest, $ref: only['$ref'] };\n }\n return node;\n};\n\n// A schema node's own children — keyword values, and each schema of a name\n// map — but never the names, and never instance data.\nconst schemaChildren = (node: Record<string, unknown>): unknown[] =>\n Object.entries(node).flatMap(([key, child]) =>\n key === '$ref' || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child],\n );\n\nconst canonical = (recorded: unknown): unknown => {\n const schema = normalize(recorded);\n if (!isRecord(schema)) return schema;\n const defs: Record<string, unknown> = {\n ...(isRecord(schema['definitions']) ? schema['definitions'] : {}),\n ...(isRecord(schema['$defs']) ? schema['$defs'] : {}),\n };\n const { $defs: _defs, definitions: _definitions, ...body } = schema;\n const target = (ref: string): { key: string; node: unknown } =>\n ref === '#' ? { key: '#', node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, '')] };\n\n // Which targets are reached from inside their own expansion: those, and\n // only those, stay definitions.\n const recursive = new Set<string>();\n const findCycles = (value: unknown, stack: readonly string[]): void => {\n if (Array.isArray(value)) {\n for (const item of value) findCycles(item, stack);\n return;\n }\n if (!isRecord(value)) return;\n const node = respell(value);\n for (const child of schemaChildren(node)) findCycles(child, stack);\n const ref = node['$ref'];\n if (typeof ref !== 'string') return;\n const { key, node: next } = target(ref);\n if (stack.includes(key)) recursive.add(key);\n else findCycles(next, [...stack, key]);\n };\n findCycles(body, ['#']);\n\n const names = new Map<string, string>();\n const named: Record<string, unknown> = {};\n const nameOf = (key: string, node: unknown): string => {\n const known = names.get(key);\n if (known !== undefined) return known;\n const name = `d${names.size}`;\n names.set(key, name);\n named[name] = emit(node);\n return name;\n };\n const emit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(emit);\n if (!isRecord(value)) return value;\n const node = respell(value);\n const rest: Record<string, unknown> = Object.fromEntries(\n Object.entries(node)\n .filter(([key]) => key !== '$ref')\n .sort(byKey)\n .map(([key, child]) => [key, NAMED.has(key) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key) ? child : emit(child)]),\n );\n const ref = node['$ref'];\n if (typeof ref !== 'string') return rest;\n const { key, node: next } = target(ref);\n const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);\n return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;\n };\n\n const root = recursive.has('#') ? { $ref: `#/$defs/${nameOf('#', body)}` } : emit(body);\n return Object.keys(named).length === 0 ? root : sortKeys({ ...(isRecord(root) ? root : { allOf: [root] }), $defs: named });\n};\n\nexport type SnapshotComparison =\n | { status: 'same' }\n | { status: 'missing' }\n | { status: 'changed'; changes: readonly { kind: string; lines: readonly string[] }[] };\n\n// `recorded` is the snapshot kept for the grammar's CURRENT version (or\n// undefined if none was kept). Changed means: a migration is owed. Both sides\n// are read in canonical form, so a validator's respelling is not a change.\nexport const compareSnapshot = (recorded: Snapshot | undefined, current: Snapshot): SnapshotComparison => {\n if (recorded === undefined) return { status: 'missing' };\n const changes: { kind: string; lines: string[] }[] = [];\n for (const kind of [...new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {\n const lines: string[] = [];\n if (!(kind in recorded.kinds)) lines.push('+ (a new kind)');\n else if (!(kind in current.kinds)) lines.push('- (the kind is gone)');\n else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), '', lines, 12);\n if (lines.length > 0) changes.push({ kind, lines });\n }\n return changes.length === 0 ? { status: 'same' } : { status: 'changed', changes };\n};\n\n// ── the corpus ──────────────────────────────────────────────────\n\nexport type CorpusDocument = { id: string; kind: string; stamp: Stamp; document: unknown };\nexport type CorpusFailure = { id: string; kind: string; reason: string };\nexport type CorpusReport = { passed: number; failures: readonly CorpusFailure[] };\n\nconst issueText = (issue: Issue): string => {\n const path = (issue.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return `${path === '' ? '' : `${path}: `}${issue.message}`;\n};\n\n// What differs between two JSON values, as short lines (`+ a.b`, `- c`,\n// `~ d: 1 → 2`) — for a report a person or an agent acts on.\nexport const diffJson = (a: unknown, b: unknown, limit = 20): string[] => {\n const out: string[] = [];\n diffLines(a, b, '', out, limit, sortKeys, false);\n return out;\n};\n\n// Every document, upgraded from its stamp, must pass the current schema of its kind.\nexport const checkCorpus = async (\n upgrader: Upgrader,\n schemas: Readonly<Record<string, GrammarSchema>>,\n documents: readonly CorpusDocument[],\n): Promise<CorpusReport> => {\n const failures: CorpusFailure[] = [];\n let passed = 0;\n for (const doc of documents) {\n const schema = schemas[doc.kind];\n if (schema === undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });\n continue;\n }\n let upgraded: unknown;\n try {\n upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;\n } catch (error) {\n failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split('\\n')[0] ?? error.message : String(error) });\n continue;\n }\n const result = await schema['~standard'].validate(upgraded);\n if (result.issues !== undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join('; ') });\n } else {\n passed += 1;\n }\n }\n return { passed, failures };\n};\n"]}
@@ -0,0 +1,63 @@
1
+ import { k as Stamp, n as Upgrader, a as Sequence } from '../documents-BjlM94Ea.cjs';
2
+ import 'zod';
3
+
4
+ type Issue = {
5
+ message: string;
6
+ path?: readonly (PropertyKey | {
7
+ key: PropertyKey;
8
+ })[];
9
+ };
10
+ type StandardResult = {
11
+ value: unknown;
12
+ issues?: undefined;
13
+ } | {
14
+ issues: readonly Issue[];
15
+ };
16
+ type GrammarSchema = {
17
+ '~standard': {
18
+ validate: (value: unknown) => StandardResult | Promise<StandardResult>;
19
+ jsonSchema: {
20
+ input: (options: {
21
+ target: string;
22
+ }) => Record<string, unknown>;
23
+ };
24
+ };
25
+ };
26
+ type Snapshot = {
27
+ sequence: string;
28
+ version: number;
29
+ kinds: Readonly<Record<string, unknown>>;
30
+ };
31
+ declare const snapshotOf: (sequence: Sequence, schemas: Readonly<Record<string, GrammarSchema>>) => Snapshot;
32
+ declare const snapshotText: (snapshot: Snapshot) => string;
33
+ type SnapshotComparison = {
34
+ status: 'same';
35
+ } | {
36
+ status: 'missing';
37
+ } | {
38
+ status: 'changed';
39
+ changes: readonly {
40
+ kind: string;
41
+ lines: readonly string[];
42
+ }[];
43
+ };
44
+ declare const compareSnapshot: (recorded: Snapshot | undefined, current: Snapshot) => SnapshotComparison;
45
+ type CorpusDocument = {
46
+ id: string;
47
+ kind: string;
48
+ stamp: Stamp;
49
+ document: unknown;
50
+ };
51
+ type CorpusFailure = {
52
+ id: string;
53
+ kind: string;
54
+ reason: string;
55
+ };
56
+ type CorpusReport = {
57
+ passed: number;
58
+ failures: readonly CorpusFailure[];
59
+ };
60
+ declare const diffJson: (a: unknown, b: unknown, limit?: number) => string[];
61
+ declare const checkCorpus: (upgrader: Upgrader, schemas: Readonly<Record<string, GrammarSchema>>, documents: readonly CorpusDocument[]) => Promise<CorpusReport>;
62
+
63
+ export { type CorpusDocument, type CorpusFailure, type CorpusReport, type GrammarSchema, type Snapshot, type SnapshotComparison, checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText };
@@ -0,0 +1,63 @@
1
+ import { k as Stamp, n as Upgrader, a as Sequence } from '../documents-BjlM94Ea.js';
2
+ import 'zod';
3
+
4
+ type Issue = {
5
+ message: string;
6
+ path?: readonly (PropertyKey | {
7
+ key: PropertyKey;
8
+ })[];
9
+ };
10
+ type StandardResult = {
11
+ value: unknown;
12
+ issues?: undefined;
13
+ } | {
14
+ issues: readonly Issue[];
15
+ };
16
+ type GrammarSchema = {
17
+ '~standard': {
18
+ validate: (value: unknown) => StandardResult | Promise<StandardResult>;
19
+ jsonSchema: {
20
+ input: (options: {
21
+ target: string;
22
+ }) => Record<string, unknown>;
23
+ };
24
+ };
25
+ };
26
+ type Snapshot = {
27
+ sequence: string;
28
+ version: number;
29
+ kinds: Readonly<Record<string, unknown>>;
30
+ };
31
+ declare const snapshotOf: (sequence: Sequence, schemas: Readonly<Record<string, GrammarSchema>>) => Snapshot;
32
+ declare const snapshotText: (snapshot: Snapshot) => string;
33
+ type SnapshotComparison = {
34
+ status: 'same';
35
+ } | {
36
+ status: 'missing';
37
+ } | {
38
+ status: 'changed';
39
+ changes: readonly {
40
+ kind: string;
41
+ lines: readonly string[];
42
+ }[];
43
+ };
44
+ declare const compareSnapshot: (recorded: Snapshot | undefined, current: Snapshot) => SnapshotComparison;
45
+ type CorpusDocument = {
46
+ id: string;
47
+ kind: string;
48
+ stamp: Stamp;
49
+ document: unknown;
50
+ };
51
+ type CorpusFailure = {
52
+ id: string;
53
+ kind: string;
54
+ reason: string;
55
+ };
56
+ type CorpusReport = {
57
+ passed: number;
58
+ failures: readonly CorpusFailure[];
59
+ };
60
+ declare const diffJson: (a: unknown, b: unknown, limit?: number) => string[];
61
+ declare const checkCorpus: (upgrader: Upgrader, schemas: Readonly<Record<string, GrammarSchema>>, documents: readonly CorpusDocument[]) => Promise<CorpusReport>;
62
+
63
+ export { type CorpusDocument, type CorpusFailure, type CorpusReport, type GrammarSchema, type Snapshot, type SnapshotComparison, checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText };
@@ -0,0 +1,4 @@
1
+ export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText } from '../chunk-MY3TGSV3.js';
2
+ import '../chunk-EGFF63GA.js';
3
+ //# sourceMappingURL=index.js.map
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,16 @@
1
+ // src/errors.ts
2
+ var StrataError = class extends Error {
3
+ code;
4
+ details;
5
+ constructor(code, message, details = [], options) {
6
+ super(details.length > 0 ? `${message}
7
+ ${details.map((d) => ` ${d}`).join("\n")}` : message, options);
8
+ this.name = "StrataError";
9
+ this.code = code;
10
+ this.details = details;
11
+ }
12
+ };
13
+
14
+ export { StrataError };
15
+ //# sourceMappingURL=chunk-EGFF63GA.js.map
16
+ //# sourceMappingURL=chunk-EGFF63GA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";AA0BO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAC5B,IAAA;AAAA,EACA,OAAA;AAAA,EAET,YAAY,IAAA,EAAuB,OAAA,EAAiB,OAAA,GAA6B,IAAI,OAAA,EAA+B;AAClH,IAAA,KAAA,CAAM,OAAA,CAAQ,MAAA,GAAS,CAAA,GAAI,CAAA,EAAG,OAAO;AAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,GAAK,SAAS,OAAO,CAAA;AACtG,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF","file":"chunk-EGFF63GA.js","sourcesContent":["// Every refusal strata makes, by name. The message is a sentence for a person;\n// the code is for the program that has to decide what to do about it.\nexport type StrataErrorCode =\n // A sequence failed its schema, or two sequences share an id.\n | 'INVALID_SEQUENCE'\n // An applied migration's steps no longer match what the code says it ran.\n | 'EDITED'\n // The database has migrations of a sequence this code does not know yet —\n // it was migrated by newer code.\n | 'TOO_NEW'\n // A `dependsOn` names a migration nobody provides and the ledger lacks.\n | 'UNKNOWN_DEPENDENCY'\n // Pending migrations wait on each other.\n | 'CYCLE'\n // Verify mode found work to do.\n | 'PENDING'\n // A step threw; the whole run was rolled back.\n | 'STEP_FAILED'\n // The pool cannot hold one connection for a transaction.\n | 'NO_TRANSACTION'\n // A document kind nobody declares — as the root being upgraded, a step's\n // `at`, or an embedding's target.\n | 'UNKNOWN_KIND'\n // A grammar sequence handed to the ledger, or a table sequence to upgrade().\n | 'WRONG_OWNER';\n\nexport class StrataError extends Error {\n readonly code: StrataErrorCode;\n readonly details: readonly string[];\n\n constructor(code: StrataErrorCode, message: string, details: readonly string[] = [], options?: { cause?: unknown }) {\n super(details.length > 0 ? `${message}\\n${details.map((d) => ` ${d}`).join('\\n')}` : message, options);\n this.name = 'StrataError';\n this.code = code;\n this.details = details;\n }\n}\n"]}
@@ -0,0 +1,156 @@
1
+ import { diffJson } from './chunk-MY3TGSV3.js';
2
+ import { StrataError } from './chunk-EGFF63GA.js';
3
+
4
+ // src/upgrade/index.ts
5
+ var keyOf = (doc) => `${doc.kind}:${doc.id}`;
6
+ var sortKeys = (value) => {
7
+ if (Array.isArray(value)) return value.map(sortKeys);
8
+ if (typeof value !== "object" || value === null) return value;
9
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, sortKeys(v)]));
10
+ };
11
+ var sameJson = (a, b) => JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b));
12
+ var changedStrings = (before, after) => {
13
+ const found = /* @__PURE__ */ new Set();
14
+ const visit = (a, b) => {
15
+ if (JSON.stringify(a) === JSON.stringify(b)) return;
16
+ if (typeof a === "string") {
17
+ found.add(a);
18
+ return;
19
+ }
20
+ if (Array.isArray(a)) {
21
+ a.forEach((item, i) => visit(item, Array.isArray(b) ? b[i] : void 0));
22
+ return;
23
+ }
24
+ if (typeof a === "object" && a !== null) {
25
+ for (const [k, v] of Object.entries(a)) visit(v, typeof b === "object" && b !== null && !Array.isArray(b) ? Reflect.get(b, k) : void 0);
26
+ }
27
+ };
28
+ visit(before, after);
29
+ return [...found].filter((s) => s.length >= 4);
30
+ };
31
+ var planSourceUpgrade = async (options) => {
32
+ const { upgrader, stamp, documents, schemas, describe } = options;
33
+ const seen = /* @__PURE__ */ new Set();
34
+ const planned = [];
35
+ const untouched = [];
36
+ const problems = [];
37
+ for (const doc of documents) {
38
+ const key = keyOf(doc);
39
+ if (seen.has(key)) throw new StrataError("INVALID_SEQUENCE", `Two artifacts are both ${key} \u2014 an artifact needs one identity to be planned.`);
40
+ seen.add(key);
41
+ const result = upgrader.upgrade(doc.document, { kind: doc.kind, stamp });
42
+ if (sameJson(result.document, doc.document)) {
43
+ untouched.push(key);
44
+ continue;
45
+ }
46
+ planned.push({
47
+ kind: doc.kind,
48
+ id: doc.id,
49
+ ...doc.file === void 0 ? {} : { file: doc.file },
50
+ applied: result.applied,
51
+ changes: diffJson(doc.document, result.document),
52
+ expected: result.document
53
+ });
54
+ const schema = schemas?.[doc.kind];
55
+ if (schema !== void 0) {
56
+ const checked = await schema["~standard"].validate(result.document);
57
+ if (checked.issues !== void 0) {
58
+ problems.push(`${key}: the migrated artifact does not pass ${doc.kind}'s current schema \u2014 ${checked.issues.slice(0, 2).map((i) => i.message).join("; ")}`);
59
+ }
60
+ }
61
+ }
62
+ const from = stamp;
63
+ const to = upgrader.stamp;
64
+ const migrations = Object.entries(to).flatMap(
65
+ ([id, n]) => Array.from({ length: Math.max(0, n - (from[id] ?? 0)) }, (_, i) => `${id}/${(from[id] ?? 0) + i + 1}`)
66
+ );
67
+ return {
68
+ from,
69
+ to,
70
+ migrations: migrations.map((ref) => ({ ref, description: describe(ref) })),
71
+ documents: planned.sort((a, b) => keyOf(a) < keyOf(b) ? -1 : 1),
72
+ untouched: untouched.sort(),
73
+ problems
74
+ };
75
+ };
76
+ var verifySourceUpgrade = (options) => {
77
+ const { plan, upgrader, documents } = options;
78
+ const now = new Map(documents.map((d) => [keyOf(d), d]));
79
+ const lines = [];
80
+ for (const want of plan.documents) {
81
+ const key = keyOf(want);
82
+ const got = now.get(key);
83
+ if (got === void 0) {
84
+ lines.push({ ok: false, text: `${key} is gone \u2014 the plan expected it rewritten, not removed` });
85
+ } else if (sameJson(got.document, want.expected)) {
86
+ lines.push({ ok: true, text: `${key} matches its migrated JSON` });
87
+ } else {
88
+ lines.push({ ok: false, text: `${key} does not match its migrated JSON yet`, detail: diffJson(got.document, want.expected, 12) });
89
+ }
90
+ }
91
+ for (const key of plan.untouched) {
92
+ const got = now.get(key);
93
+ if (got === void 0) {
94
+ lines.push({ ok: false, text: `${key} is gone \u2014 no migration asked for that` });
95
+ continue;
96
+ }
97
+ const again = upgrader.upgrade(got.document, { kind: got.kind, stamp: plan.from });
98
+ if (!sameJson(again.document, got.document)) {
99
+ lines.push({ ok: false, text: `${key} was not in the plan, but the migrations would change it now`, detail: diffJson(got.document, again.document, 12) });
100
+ }
101
+ }
102
+ const known = /* @__PURE__ */ new Set([...plan.documents.map(keyOf), ...plan.untouched]);
103
+ for (const key of now.keys()) {
104
+ if (!known.has(key)) lines.push({ ok: false, text: `${key} is new since the plan \u2014 plan again so it is checked too` });
105
+ }
106
+ const ok = lines.every((l) => l.ok);
107
+ if (ok) lines.push({ ok: true, text: `${plan.untouched.length} artifact(s) no migration touches, still untouched` });
108
+ return { ok, lines };
109
+ };
110
+ var renderReport = (plan, expectedPathOf) => {
111
+ const stamp = (s) => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(", ");
112
+ const out = [
113
+ "# strata upgrade",
114
+ "",
115
+ `The source is written at **${stamp(plan.from)}**; the installed grammars are at **${stamp(plan.to)}**.`,
116
+ "",
117
+ "## Migrations",
118
+ "",
119
+ ...plan.migrations.map((m) => `- \`${m.ref}\` \u2014 ${m.description}`),
120
+ ""
121
+ ];
122
+ if (plan.problems.length > 0) {
123
+ out.push("## Stop: a migration is wrong", "", "These artifacts would not pass their current schema after migrating \u2014 no edit can make `verify` pass. Fix the migration, then plan again.", "", ...plan.problems.map((p) => `- ${p}`), "");
124
+ }
125
+ if (plan.documents.length === 0) {
126
+ out.push("## Nothing to edit", "", `No artifact changes (${plan.untouched.length} checked). Run \`verify\` to move the lock.`, "");
127
+ } else {
128
+ out.push(
129
+ `## ${plan.documents.length} artifact(s) to edit`,
130
+ "",
131
+ "Edit each so that it serialises to EXACTLY its expected JSON (key order aside) \u2014 then run `verify`. Only what is listed changes; every other artifact must stay as it is.",
132
+ ""
133
+ );
134
+ for (const doc of plan.documents) {
135
+ out.push(
136
+ `### \`${doc.id}\` (${doc.kind})`,
137
+ "",
138
+ doc.file === void 0 ? "" : `- **File:** \`${doc.file}\``,
139
+ doc.lookIn === void 0 || doc.lookIn.length === 0 ? "" : `- **Look in:** ${doc.lookIn.map((f) => `\`${f}\``).join(", ")} \u2014 where the changing values are written`,
140
+ `- **Migrations:** ${doc.applied.map((r) => `\`${r}\``).join(", ")}`,
141
+ `- **Expected JSON:** \`${expectedPathOf(doc)}\``,
142
+ "- **Changes:**",
143
+ "",
144
+ "```",
145
+ ...doc.changes,
146
+ "```",
147
+ ""
148
+ );
149
+ }
150
+ }
151
+ return out.filter((line, i, all) => !(line === "" && all[i - 1] === "")).join("\n");
152
+ };
153
+
154
+ export { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade };
155
+ //# sourceMappingURL=chunk-HMT7HHFJ.js.map
156
+ //# sourceMappingURL=chunk-HMT7HHFJ.js.map