@niscorp/strata 0.1.0 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -0
- package/DESIGN.md +12 -5
- package/README.md +19 -3
- package/dist/check/index.cjs +12 -1
- package/dist/check/index.cjs.map +1 -1
- package/dist/check/index.js +1 -1
- package/dist/{chunk-MY3TGSV3.js → chunk-274M232S.js} +14 -3
- package/dist/chunk-274M232S.js.map +1 -0
- package/dist/{chunk-HMT7HHFJ.js → chunk-2FIZEJXW.js} +3 -3
- package/dist/{chunk-HMT7HHFJ.js.map → chunk-2FIZEJXW.js.map} +1 -1
- package/dist/{chunk-ICWKTTKN.js → chunk-TWAEZHTB.js} +10 -5
- package/dist/chunk-TWAEZHTB.js.map +1 -0
- package/dist/index.cjs +8 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/node/index.cjs +20 -4
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.js +3 -3
- package/dist/postgres/index.cjs +8 -10
- package/dist/postgres/index.cjs.map +1 -1
- package/dist/postgres/index.js +8 -10
- package/dist/postgres/index.js.map +1 -1
- package/dist/upgrade/index.cjs +12 -1
- package/dist/upgrade/index.cjs.map +1 -1
- package/dist/upgrade/index.js +2 -2
- package/package.json +3 -2
- package/dist/chunk-ICWKTTKN.js.map +0 -1
- package/dist/chunk-MY3TGSV3.js.map +0 -1
|
@@ -39,7 +39,7 @@ var createUpgrader = async (sequences, options) => {
|
|
|
39
39
|
if (tables.length > 0) {
|
|
40
40
|
throw new StrataError(
|
|
41
41
|
"WRONG_OWNER",
|
|
42
|
-
"Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`).",
|
|
42
|
+
"Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`). If one of them is a grammar, declare its `documents` \u2014 a sequence with no `documents` and no document step is read as owning tables.",
|
|
43
43
|
tables.map((s) => s.id)
|
|
44
44
|
);
|
|
45
45
|
}
|
|
@@ -54,6 +54,11 @@ var createUpgrader = async (sequences, options) => {
|
|
|
54
54
|
];
|
|
55
55
|
if (unknown.length > 0) throw new StrataError("UNKNOWN_KIND", "A document kind is named that no sequence declares.", unknown);
|
|
56
56
|
const stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));
|
|
57
|
+
const ownIds = new Set(grammars.map((s) => s.id));
|
|
58
|
+
const stampAfter = (given) => {
|
|
59
|
+
const others = Object.entries(given ?? {}).filter(([id]) => !ownIds.has(id));
|
|
60
|
+
return others.length === 0 ? stamp : { ...stamp, ...Object.fromEntries(others) };
|
|
61
|
+
};
|
|
57
62
|
const locate = (document, kind) => {
|
|
58
63
|
if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
|
|
59
64
|
const found = [];
|
|
@@ -82,7 +87,7 @@ var createUpgrader = async (sequences, options) => {
|
|
|
82
87
|
const upgrade = (document, { kind, stamp: given }) => {
|
|
83
88
|
if (!isRecord(document)) throw new StrataError("STEP_FAILED", `A ${kind} document must be a JSON object.`);
|
|
84
89
|
if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
|
|
85
|
-
if (!behind(given)) return { document, stamp, applied: [] };
|
|
90
|
+
if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };
|
|
86
91
|
const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));
|
|
87
92
|
const { pending, stuck } = orderPending(
|
|
88
93
|
grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),
|
|
@@ -119,11 +124,11 @@ var createUpgrader = async (sequences, options) => {
|
|
|
119
124
|
for (const step of migration.steps) if (step.kind === "document") runStep(migration, step.at, step.transform);
|
|
120
125
|
applied.push(migration.ref);
|
|
121
126
|
}
|
|
122
|
-
return { document: current, stamp, applied };
|
|
127
|
+
return { document: current, stamp: stampAfter(given), applied };
|
|
123
128
|
};
|
|
124
129
|
return { stamp, upgrade, locate, behind };
|
|
125
130
|
};
|
|
126
131
|
|
|
127
132
|
export { createUpgrader };
|
|
128
|
-
//# sourceMappingURL=chunk-
|
|
129
|
-
//# sourceMappingURL=chunk-
|
|
133
|
+
//# sourceMappingURL=chunk-TWAEZHTB.js.map
|
|
134
|
+
//# sourceMappingURL=chunk-TWAEZHTB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/documents.ts"],"names":[],"mappings":";;;;AAqDA,IAAM,QAAA,GAAW,CAAC,KAAA,KAChB,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAErE,IAAM,QAAA,GAAW,CAAC,IAAA,KAChB,IAAA,CAAK,MAAA,CAAe,CAAC,IAAA,EAAM,GAAA,KAAS,OAAO,GAAA,KAAQ,QAAA,GAAW,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,CAAA,GAAM,IAAA,KAAS,EAAA,GAAK,GAAA,GAAM,GAAG,IAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,EAAK,EAAE,CAAA;AAK7H,IAAM,KAAA,GAAQ,CAAC,KAAA,EAAgB,OAAA,KAAqE;AAClG,EAAA,IAAI,WAA4D,CAAC,EAAE,MAAM,EAAC,EAAG,OAAO,CAAA;AACpF,EAAA,KAAA,MAAW,OAAA,IAAW,OAAA,CAAQ,KAAA,CAAM,GAAG,CAAA,EAAG;AACxC,IAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,QAAA,CAAS,IAAI,CAAA;AACnC,IAAA,MAAM,MAAM,KAAA,GAAQ,OAAA,CAAQ,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,GAAI,OAAA;AAC3C,IAAA,MAAM,OAAwD,EAAC;AAC/D,IAAA,K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EAAG,GAAG,CAAA,IAAK,MAAA,CAAO,SAAS;AAAA,WAC7D,CAAA;AAAA,QACH;AACA,QAAA,MAAM,IAAA,GAAO,KAAA,CAAM,OAAA,EAAS,MAAA,CAAO,MAAM,SAAS,CAAA;AAClD,QAAA,IAAI,QAAA,CAAS,IAAI,CAAA,EAAG,OAAA,GAAU,IAAA;AAAA,MAChC;AAAA,IACF,CAAA;AACA,IAAA,KAAA,MAAW,aAAa,OAAA,EAAS;AAC/B,MAAA,KAAA,MAAW,IAAA,IAAQ,SAAA,CAAU,KAAA,EAAO,IAAI,IAAA,CAAK,IAAA,KAAS,UAAA,EAAY,OAAA,CAAQ,SAAA,EAAW,IAAA,CAAK,EAAA,EAAI,IAAA,CAAK,SAAS,CAAA;AAC5G,MAAA,OAAA,CAAQ,IAAA,CAAK,UAAU,GAAG,CAAA;AAAA,IAC5B;AACA,IAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,OAAO,UAAA,CAAW,KAAK,GAAG,OAAA,EAAQ;AAAA,EAChE,CAAA;AAEA,EAAA,OAAO,EAAE,KAAA,EAAO,OAAA,EAAS,MAAA,EAAQ,MAAA,EAAO;AAC1C","file":"chunk-TWAEZHTB.js","sourcesContent":["import { prepare, orderPending, type PreparedMigration, type PreparedSequence } from './plan';\nimport type { DocumentKind, Sequence } from './schema';\nimport { StrataError } from './errors';\n\n// ═══════════════════════════════════════════════════════════════\n// Documents — the JSON a grammar describes, wherever it is kept.\n//\n// A document carries a STAMP: for each grammar sequence, how far along that\n// sequence the writer was (`{ \"nisc.nova\": 3, \"nisc.prism\": 1 }`). Upgrading\n// runs every document migration the stamp has not seen, in the ledger's order,\n// and hands back the document with a current stamp. The same function serves a\n// row read at boot, a submission at intake and a file in an app's source tree:\n// the document does not care where it was kept.\n//\n// NESTING IS THE GRAMMAR'S, NOT THE MIGRATION'S. A kind declares where other\n// documents sit inside it (its embeddings: nova's layout holds layouts at\n// `children`, `children[]`, `then`, `else`, `do`; an action holds a layout and\n// Prism configs). The walker finds every document of a step's kind at any\n// depth and rewrites each on its own, deepest first. A transform only ever sees\n// ONE node — so migrations stay flat, and a Prism config can express them\n// without recursion of its own.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Stamp = Readonly<Record<string, number>>;\n\n// Where a document sits: the path from the root (keys and indexes) and its kind.\nexport type Location = { path: readonly (string | number)[]; kind: string; value: Record<string, unknown> };\n\n// The injected evaluator — nova's `transform` socket, the same shape: under moss\n// it is Prism's `evaluate`, and a migration runs exactly the way an endpoint does.\nexport type Transform = (config: unknown, source: unknown) => unknown;\n\nexport type UpgradeResult = {\n document: Record<string, unknown>;\n // What to store with the document: current on every grammar the upgrader was\n // given, and the document's entries for any other grammar kept as they were.\n stamp: Stamp;\n // What ran, in order — empty when the document was already current.\n applied: readonly string[];\n};\n\nexport type Upgrader = {\n // The stamp a document written NOW carries.\n stamp: Stamp;\n upgrade: (document: unknown, options: { kind: string; stamp?: Stamp | null }) => UpgradeResult;\n // Every document inside `document` (itself included), by kind — what the\n // walker sees. For a page that shows it, and for a check that asserts it.\n locate: (document: unknown, kind: string) => Location[];\n // Is a document at this stamp behind the code (true), current (false)? Throws\n // TOO_NEW if it is ahead.\n behind: (stamp: Stamp | null | undefined) => boolean;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst pathText = (path: readonly (string | number)[]): string =>\n path.reduce<string>((text, key) => (typeof key === 'number' ? `${text}[${key}]` : text === '' ? key : `${text}.${key}`), '');\n\n// One embedding pattern, applied to one value: every (relative path, value)\n// the pattern reaches. `key` descends, `*` crosses a record's values, and a\n// `[]` suffix crosses the array found there.\nconst reach = (value: unknown, pattern: string): { path: (string | number)[]; value: unknown }[] => {\n let frontier: { path: (string | number)[]; value: unknown }[] = [{ path: [], value }];\n for (const segment of pattern.split('.')) {\n const array = segment.endsWith('[]');\n const key = array ? segment.slice(0, -2) : segment;\n const next: { path: (string | number)[]; value: unknown }[] = [];\n for (const at of frontier) {\n if (!isRecord(at.value)) continue;\n const found: { path: (string | number)[]; value: unknown }[] =\n key === '*'\n ? Object.entries(at.value).map(([k, v]) => ({ path: [...at.path, k], value: v }))\n : key in at.value\n ? [{ path: [...at.path, key], value: at.value[key] }]\n : [];\n for (const f of found) {\n if (!array) next.push(f);\n else if (Array.isArray(f.value)) f.value.forEach((item, i) => next.push({ path: [...f.path, i], value: item }));\n }\n }\n frontier = next;\n }\n return frontier;\n};\n\nconst getAt = (root: unknown, path: readonly (string | number)[]): unknown =>\n path.reduce<unknown>((at, key) => {\n if (typeof key === 'number') return Array.isArray(at) ? at[key] : undefined;\n return isRecord(at) ? at[key] : undefined;\n }, root);\n\nconst setAt = (root: unknown, path: readonly (string | number)[], value: unknown): unknown => {\n const [head, ...rest] = path;\n if (head === undefined) return value;\n if (typeof head === 'number' && Array.isArray(root)) return root.map((item, i) => (i === head ? setAt(item, rest, value) : item));\n if (typeof head === 'string' && isRecord(root)) return { ...root, [head]: setAt(root[head], rest, value) };\n return root;\n};\n\nexport const createUpgrader = async (sequences: readonly Sequence[], options: { transform: Transform }): Promise<Upgrader> => {\n const prepared = await prepare(sequences);\n const tables = prepared.filter((s) => !s.grammar);\n if (tables.length > 0) {\n // A sequence is read as a grammar by what it declares (plan.ts). One with\n // nothing but markers and no `documents` reads as owning tables, so the\n // refusal says how a grammar says it is one — `migrate` alone would send a\n // kit's markers to a database's ledger.\n throw new StrataError(\n 'WRONG_OWNER',\n 'Documents are upgraded by grammar sequences; these own tables and belong to a database\\'s ledger (`migrate`). If one of them is a grammar, declare its `documents` — a sequence with no `documents` and no document step is read as owning tables.',\n tables.map((s) => s.id),\n );\n }\n const grammars: readonly PreparedSequence[] = prepared;\n\n const kinds = new Map<string, DocumentKind>();\n for (const sequence of grammars) {\n for (const [name, kind] of Object.entries(sequence.documents)) kinds.set(`${sequence.id}/${name}`, kind);\n }\n const unknown = [\n ...grammars.flatMap((s) => s.migrations.flatMap((m) => m.steps.flatMap((step) => (step.kind === 'document' && !kinds.has(step.at) ? [`${m.ref} rewrites ${step.at}`] : [])))),\n ...[...kinds].flatMap(([ref, kind]) => Object.entries(kind.embeds ?? {}).flatMap(([path, target]) => (kinds.has(target) ? [] : [`${ref} embeds ${target} at ${path}`]))),\n ];\n if (unknown.length > 0) throw new StrataError('UNKNOWN_KIND', 'A document kind is named that no sequence declares.', unknown);\n\n const stamp: Stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));\n\n // The stamp a document carries once this code has read it: this code's\n // position on every grammar it was given and — as they were — the document's\n // own entries for grammars it was not. Those record code this reader lacks (a\n // kit it does not have); dropping them would let code that does have the\n // grammar run its migrations over the document a second time.\n const ownIds = new Set(grammars.map((s) => s.id));\n const stampAfter = (given: Stamp | null | undefined): Stamp => {\n const others = Object.entries(given ?? {}).filter(([id]) => !ownIds.has(id));\n return others.length === 0 ? stamp : { ...stamp, ...Object.fromEntries(others) };\n };\n\n const locate = (document: unknown, kind: string): Location[] => {\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n const found: Location[] = [];\n const visit = (value: unknown, at: string, path: (string | number)[]): void => {\n if (!isRecord(value)) return;\n found.push({ path, kind: at, value });\n for (const [pattern, target] of Object.entries(kinds.get(at)?.embeds ?? {})) {\n for (const hit of reach(value, pattern)) visit(hit.value, target, [...path, ...hit.path]);\n }\n };\n visit(document, kind, []);\n return found;\n };\n\n const positionOf = (given: Stamp | null | undefined, id: string): number => given?.[id] ?? 0;\n\n const behind = (given: Stamp | null | undefined): boolean => {\n const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);\n if (ahead.length > 0) {\n throw new StrataError(\n 'TOO_NEW',\n 'This document was written by newer code than this — reading it would be guessing.',\n ahead.map((s) => `${s.id}: the document is at ${positionOf(given, s.id)}, this code knows ${s.migrations.length}`),\n );\n }\n return grammars.some((s) => positionOf(given, s.id) < s.migrations.length);\n };\n\n const upgrade = (document: unknown, { kind, stamp: given }: { kind: string; stamp?: Stamp | null }): UpgradeResult => {\n if (!isRecord(document)) throw new StrataError('STEP_FAILED', `A ${kind} document must be a JSON object.`);\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };\n\n // What this document has seen: everything up to its stamp, per sequence.\n // A sequence it has never heard of starts at 0 — a document written before\n // a grammar existed simply has none of its migrations yet.\n const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));\n const { pending, stuck } = orderPending(\n grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),\n done,\n );\n if (stuck.length > 0) throw new StrataError('CYCLE', 'Document migrations wait on each other and can never run.', stuck.map((m) => m.ref));\n\n let current: Record<string, unknown> = document;\n const applied: string[] = [];\n const runStep = (migration: PreparedMigration, at: string, transform: unknown): void => {\n // Deepest first: a parent's rewrite sees its children already rewritten,\n // and replacing a child never moves the path to its parent.\n const targets = locate(current, kind)\n .filter((l) => l.kind === at)\n .sort((a, b) => b.path.length - a.path.length);\n for (const target of targets) {\n // The value NOW, not when the targets were found: a child rewritten a\n // moment ago lives in `current`, and the parent must see — and keep — it.\n const value = getAt(current, target.path);\n let rewritten: unknown;\n try {\n rewritten = options.transform(transform, { document: value, path: pathText(target.path) });\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed on the ${at} at ${pathText(target.path) || '(root)'}.`,\n [cause instanceof Error ? cause.message : String(cause)],\n { cause },\n );\n }\n if (!isRecord(rewritten)) {\n throw new StrataError('STEP_FAILED', `${migration.ref} turned the ${at} at ${pathText(target.path) || '(root)'} into something that is not a document.`, [\n JSON.stringify(rewritten)?.slice(0, 200) ?? String(rewritten),\n ]);\n }\n const next = setAt(current, target.path, rewritten);\n if (isRecord(next)) current = next;\n }\n };\n for (const migration of pending) {\n for (const step of migration.steps) if (step.kind === 'document') runStep(migration, step.at, step.transform);\n applied.push(migration.ref);\n }\n return { document: current, stamp: stampAfter(given), applied };\n };\n\n return { stamp, upgrade, locate, behind };\n};\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -223,7 +223,7 @@ var createUpgrader = async (sequences, options) => {
|
|
|
223
223
|
if (tables.length > 0) {
|
|
224
224
|
throw new StrataError(
|
|
225
225
|
"WRONG_OWNER",
|
|
226
|
-
"Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`).",
|
|
226
|
+
"Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`). If one of them is a grammar, declare its `documents` \u2014 a sequence with no `documents` and no document step is read as owning tables.",
|
|
227
227
|
tables.map((s) => s.id)
|
|
228
228
|
);
|
|
229
229
|
}
|
|
@@ -238,6 +238,11 @@ var createUpgrader = async (sequences, options) => {
|
|
|
238
238
|
];
|
|
239
239
|
if (unknown.length > 0) throw new StrataError("UNKNOWN_KIND", "A document kind is named that no sequence declares.", unknown);
|
|
240
240
|
const stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));
|
|
241
|
+
const ownIds = new Set(grammars.map((s) => s.id));
|
|
242
|
+
const stampAfter = (given) => {
|
|
243
|
+
const others = Object.entries(given ?? {}).filter(([id]) => !ownIds.has(id));
|
|
244
|
+
return others.length === 0 ? stamp : { ...stamp, ...Object.fromEntries(others) };
|
|
245
|
+
};
|
|
241
246
|
const locate = (document, kind) => {
|
|
242
247
|
if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
|
|
243
248
|
const found = [];
|
|
@@ -266,7 +271,7 @@ var createUpgrader = async (sequences, options) => {
|
|
|
266
271
|
const upgrade = (document, { kind, stamp: given }) => {
|
|
267
272
|
if (!isRecord(document)) throw new StrataError("STEP_FAILED", `A ${kind} document must be a JSON object.`);
|
|
268
273
|
if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
|
|
269
|
-
if (!behind(given)) return { document, stamp, applied: [] };
|
|
274
|
+
if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };
|
|
270
275
|
const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));
|
|
271
276
|
const { pending, stuck } = orderPending(
|
|
272
277
|
grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),
|
|
@@ -303,7 +308,7 @@ var createUpgrader = async (sequences, options) => {
|
|
|
303
308
|
for (const step of migration.steps) if (step.kind === "document") runStep(migration, step.at, step.transform);
|
|
304
309
|
applied.push(migration.ref);
|
|
305
310
|
}
|
|
306
|
-
return { document: current, stamp, applied };
|
|
311
|
+
return { document: current, stamp: stampAfter(given), applied };
|
|
307
312
|
};
|
|
308
313
|
return { stamp, upgrade, locate, behind };
|
|
309
314
|
};
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema.ts","../src/checksum.ts","../src/errors.ts","../src/plan.ts","../src/documents.ts","../src/sql.ts","../src/depth.ts","../src/index.ts"],"names":["z"],"mappings":";;;;;AAiBO,IAAM,WAAA,GAAc;AAIpB,IAAM,aAAA,GAAgB;AAItB,IAAM,SAAA,GAAY;AAClB,IAAM,QAAA,GAAW;AAOjB,IAAM,UAAA,GAAa;AAEnB,IAAM,aAAA,GAAgBA,MAC1B,MAAA,CAAO;AAAA,EACN,IAAA,EAAMA,KAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,KAAKA,KAAA,CACF,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,QAAA;AAAA,IACC;AAAA;AAGN,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,yEAAyE;AAE9E,IAAM,kBAAA,GAAqBA,MAC/B,MAAA,CAAO;A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A,EAC9H;AACA,EAAA,OAAO,KAAA;AACT;AAEO,IAAM,YAAA,GAAe,CAAC,KAAA,GAAgB,oBAAA,KAC3C,kCAAkC,KAAK,CAAA,kGAAA;;;ACXlC,IAAM,cAAA,GAAiB,CAA2B,QAAA,KAAmB","file":"index.cjs","sourcesContent":["import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// The grammar of a migration.\n//\n// A SEQUENCE is an append-only list of migrations owned by one grammar owner —\n// a package's tables (`nisc.vex.cache`), a package's documents (`nisc.nova`,\n// later), an app's own (`midas.app`). A migration's number is its POSITION, so\n// the sequence's version is its length: nobody bumps a number, you append.\n//\n// Sequences are data. They are authored in TS for type-checking, but nothing\n// here is a function, so a sequence can be stored, shipped and inspected like\n// every other nisc artifact — and is parsed at the boundary like one.\n// ═══════════════════════════════════════════════════════════════\n\n// Namespaced, lowercase: `<owner>.<name>[.<name>…]`. The owner prefix keeps two\n// packages (or a package and an app) from ever claiming the same sequence.\nexport const SEQUENCE_ID = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+$/;\n\n// `<sequence>/<n>` — how a migration is named everywhere: the ledger, a\n// dependency, an error.\nexport const MIGRATION_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[1-9][0-9]*$/;\n\n// A document kind, named by its owner: `<sequence>/<kind>`, e.g.\n// \"nisc.nova/layout\". The kind part is a plain lowercase word.\nexport const KIND_NAME = /^[a-z][a-z0-9-]*$/;\nexport const KIND_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[a-z][a-z0-9-]*$/;\n\n// Where, inside a document, another document sits. Dot-separated keys, with\n// two wildcards that say WHICH shape they cross — `children[]` is every item of\n// the array at `children`, `endpoints.*` every value of the record at\n// `endpoints`. Kept apart on purpose: nova's `children` is a single node OR an\n// array, and one wildcard for both would read a lone node's `props` as layouts.\nexport const EMBED_PATH = /^([A-Za-z_$][\\w$]*|\\*)(\\[\\])?(\\.([A-Za-z_$][\\w$]*|\\*)(\\[\\])?)*$/;\n\nexport const SqlStepSchema = z\n .object({\n kind: z.literal('sql'),\n sql: z\n .string()\n .min(1)\n .describe(\n 'ONE SQL statement. A driver that prepares statements (PGlite, pg with parameters) refuses a string ' +\n 'carrying several — split them into steps rather than joining them with semicolons.',\n ),\n })\n .strict()\n .describe('A statement run against the database, inside the migration transaction.');\n\nexport const DocumentStepSchema = z\n .object({\n kind: z.literal('document'),\n at: z\n .string()\n .regex(KIND_REF)\n .describe('The kind of document this step rewrites, e.g. \"nisc.nova/layout\" — wherever one sits, at any depth.'),\n transform: z\n .unknown()\n .describe(\n 'A transform config (Prism) run by the injected evaluator over { document, path }: `document` is ONE document of ' +\n 'the `at` kind, `path` where it sits. It returns that document rewritten. Nested documents are found by the ' +\n 'grammar\\'s embeddings and rewritten on their own, deepest first — a transform only ever sees one flat node.',\n ),\n })\n .strict()\n .describe('A rewrite of stored JSON documents of one kind.');\n\nexport const StepSchema = z.discriminatedUnion('kind', [SqlStepSchema, DocumentStepSchema]);\n\nexport const DocumentKindSchema = z\n .object({\n embeds: z\n .record(z.string().regex(EMBED_PATH), z.string().regex(KIND_REF))\n .optional()\n .describe('Where other documents sit inside this one: path → the kind found there (possibly this kind itself).'),\n })\n .strict();\n\nexport const MigrationSchema = z\n .object({\n description: z\n .string()\n .min(1)\n .describe('One sentence: what this migration does. It is the changelog line and the ledger\\'s description.'),\n steps: z\n .array(StepSchema)\n .describe(\n 'Applied in order, in the same transaction as every other pending migration. Empty is a MARKER: ' +\n 'the version moves and nothing runs — how an addition to a strict grammar tells older readers to refuse.',\n ),\n dependsOn: z\n .array(z.string().regex(MIGRATION_REF))\n .optional()\n .describe('Migrations of OTHER sequences that must be applied first, each as \"<sequence>/<n>\".'),\n })\n .strict();\n\nexport const SequenceSchema = z\n .object({\n id: z.string().regex(SEQUENCE_ID).describe('Namespaced and lowercase, e.g. \"nisc.vex.cache\" or \"midas.app\".'),\n documents: z\n .record(z.string().regex(KIND_NAME), DocumentKindSchema)\n .optional()\n .describe('The document kinds this sequence owns (a GRAMMAR sequence), each named \"<id>/<kind>\" elsewhere.'),\n migrations: z\n .array(MigrationSchema)\n .describe('Append-only. A migration is numbered by its position (from 1); the sequence\\'s version is its length.'),\n })\n .strict()\n // TWO KINDS OF OWNER. A table sequence (sql steps) is recorded per DATABASE,\n // in its ledger. A grammar sequence (document steps) is tracked per DOCUMENT,\n // by the stamp the document carries — because documents travel: an add-on\n // built on older code submits older documents to a newer host. One sequence\n // cannot be both; the two versions would mean different things.\n .superRefine((sequence, ctx) => {\n const kinds = new Set(sequence.migrations.flatMap((m) => m.steps.map((s) => s.kind)));\n if (kinds.has('sql') && (kinds.has('document') || sequence.documents !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: 'A sequence either owns tables (sql steps) or documents (document steps and `documents`), not both.',\n });\n }\n });\n\nexport type SqlStep = z.infer<typeof SqlStepSchema>;\nexport type DocumentStep = z.infer<typeof DocumentStepSchema>;\nexport type DocumentKind = z.infer<typeof DocumentKindSchema>;\nexport type Step = z.infer<typeof StepSchema>;\nexport type Migration = z.infer<typeof MigrationSchema>;\nexport type Sequence = z.infer<typeof SequenceSchema>;\n","import type { Migration } from './schema';\n\n// ═══════════════════════════════════════════════════════════════\n// What a migration DID, as a hash — the ledger's proof that the code still says\n// what the database ran.\n//\n// Over the steps only. The description is prose: fixing a typo in it must not\n// read as an edited migration. `dependsOn` orders, it does not act. The steps\n// are the effect, and changing an applied step is the one thing that has to\n// be refused — the database already holds the old effect.\n//\n// For the same reason a step's SQL is hashed without its full-line comments\n// (`-- …` on a line of its own) and without trailing whitespace: a migration\n// can carry its documentation verbatim, and rewording it is not an edit.\n//\n// WebCrypto (SHA-256), which Node ≥ 22 and every browser carry as\n// `crypto.subtle` — the same primitive Prism fingerprints with, so strata runs\n// unchanged in a server, a test and the showroom page.\n// ═══════════════════════════════════════════════════════════════\n\n// Sorted keys, recursively: the same value always serializes the same way,\n// whatever order its object literal was written in.\nconst canonical = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n};\n\nconst effectOf = (sql: string): string =>\n sql\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('--'))\n .map((line) => line.trimEnd())\n .join('\\n')\n .trim();\n\nexport const checksumOf = async (migration: Migration): Promise<string> => {\n const steps = migration.steps.map((step) => (step.kind === 'sql' ? { ...step, sql: effectOf(step.sql) } : step));\n const bytes = new TextEncoder().encode(canonical(steps));\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n};\n","// 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 { SequenceSchema, type DocumentKind, type Sequence, type Step } from './schema';\nimport { checksumOf } from './checksum';\nimport { StrataError, type StrataErrorCode } from './errors';\n\n// ═══════════════════════════════════════════════════════════════\n// The plan — what the code says, against what the database has run.\n//\n// Pure: sequences and ledger rows in, a plan out. No database, no clock. The\n// postgres runner reads the ledger, calls this, and applies what it says; a\n// showroom page or a CI check can call it with a ledger it made up.\n// ═══════════════════════════════════════════════════════════════\n\n// A migration the code declares, numbered and hashed.\nexport type PreparedMigration = {\n sequence: string;\n n: number;\n ref: string;\n description: string;\n checksum: string;\n steps: readonly Step[];\n dependsOn: readonly string[];\n};\n\nexport type PreparedSequence = {\n id: string;\n // A grammar sequence owns documents (tracked by stamps); otherwise it owns\n // tables (tracked by a database's ledger). See SequenceSchema.\n grammar: boolean;\n documents: Readonly<Record<string, DocumentKind>>;\n migrations: readonly PreparedMigration[];\n};\n\n// One row of the ledger, as a runner read it back.\nexport type LedgerRow = { sequence: string; n: number; checksum: string; description: string; appliedAt: string };\n\nexport type Problem = { code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>; detail: string };\n\nexport type Plan = {\n // Already run, per sequence this code knows: how far each one is.\n applied: Readonly<Record<string, number>>;\n // To run, in the order they must run.\n pending: readonly PreparedMigration[];\n // Anything that makes applying unsafe. A plan with problems is never applied.\n problems: readonly Problem[];\n};\n\nconst refOf = (sequence: string, n: number): string => `${sequence}/${n}`;\n\n// Parse, number and hash. Async only for the hash (WebCrypto).\nexport const prepare = async (sequences: readonly Sequence[]): Promise<readonly PreparedSequence[]> => {\n const seen = new Set<string>();\n const prepared: PreparedSequence[] = [];\n for (const input of sequences) {\n const parsed = SequenceSchema.safeParse(input);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);\n throw new StrataError('INVALID_SEQUENCE', `A sequence does not parse${typeof input.id === 'string' ? ` (\"${input.id}\")` : ''}.`, issues);\n }\n const sequence = parsed.data;\n if (seen.has(sequence.id)) {\n throw new StrataError('INVALID_SEQUENCE', `Two sequences are both called \"${sequence.id}\" — a sequence id names one owner.`);\n }\n seen.add(sequence.id);\n const migrations: PreparedMigration[] = [];\n for (const [index, migration] of sequence.migrations.entries()) {\n const n = index + 1;\n migrations.push({\n sequence: sequence.id,\n n,\n ref: refOf(sequence.id, n),\n description: migration.description,\n checksum: await checksumOf(migration),\n steps: migration.steps,\n dependsOn: migration.dependsOn ?? [],\n });\n }\n const grammar = sequence.documents !== undefined || sequence.migrations.some((m) => m.steps.some((s) => s.kind === 'document'));\n prepared.push({ id: sequence.id, grammar, documents: sequence.documents ?? {}, migrations });\n }\n return prepared;\n};\n\n// Order: walk the sequences in the order given, and let each run as far as its\n// dependencies allow before moving on; repeat until nothing moves. The same\n// input always yields the same order, and a sequence's own migrations stay\n// together unless a dependency splits them. Shared by the ledger's plan and a\n// document's upgrade, so both order the same migrations the same way.\nexport const orderPending = (\n queues: readonly { waiting: readonly PreparedMigration[] }[],\n alreadyDone: ReadonlySet<string>,\n): { pending: PreparedMigration[]; stuck: PreparedMigration[] } => {\n const done = new Set(alreadyDone);\n const waiting = queues.map((q) => [...q.waiting]);\n const pending: PreparedMigration[] = [];\n let moved = true;\n while (moved) {\n moved = false;\n for (const queue of waiting) {\n for (let head = queue[0]; head !== undefined; head = queue[0]) {\n if (!head.dependsOn.every((d) => done.has(d))) break;\n pending.push(head);\n done.add(head.ref);\n queue.shift();\n moved = true;\n }\n }\n }\n return { pending, stuck: waiting.flat() };\n};\n\nexport const planMigrations = (sequences: readonly PreparedSequence[], ledger: readonly LedgerRow[]): Plan => {\n const problems: Problem[] = [];\n const applied: Record<string, number> = {};\n const done = new Set(ledger.map((row) => refOf(row.sequence, row.n)));\n const byRef = new Map(ledger.map((row) => [refOf(row.sequence, row.n), row]));\n\n const queues: { id: string; waiting: PreparedMigration[] }[] = [];\n for (const sequence of sequences) {\n const rows = ledger.filter((row) => row.sequence === sequence.id);\n applied[sequence.id] = rows.length;\n\n // The database ran migrations this code has never seen: newer code migrated\n // it. Applying ours on top would be guessing — refuse.\n const beyond = rows.filter((row) => row.n > sequence.migrations.length);\n if (beyond.length > 0) {\n problems.push({\n code: 'TOO_NEW',\n detail: `${sequence.id}: the database is at ${Math.max(...rows.map((r) => r.n))}, this code knows ${sequence.migrations.length} — it was migrated by newer code.`,\n });\n }\n\n const waiting: PreparedMigration[] = [];\n for (const migration of sequence.migrations) {\n const row = byRef.get(migration.ref);\n if (row === undefined) {\n waiting.push(migration);\n } else if (row.checksum !== migration.checksum) {\n problems.push({\n code: 'EDITED',\n detail: `${migration.ref} (\"${migration.description}\") was applied ${row.appliedAt} and its steps have changed since. An applied migration is history — append a new one.`,\n });\n }\n }\n // A hole: something later ran, something earlier did not. The ledger was\n // written by hand, or by a different ordering of the same sequence.\n const firstWaiting = waiting[0];\n if (firstWaiting !== undefined && rows.some((row) => row.n > firstWaiting.n)) {\n problems.push({ code: 'EDITED', detail: `${sequence.id}: ${firstWaiting.ref} never ran, but a later migration of the sequence did.` });\n }\n queues.push({ id: sequence.id, waiting });\n }\n\n // Every dependency must be satisfiable by the ledger or by this plan.\n const provided = new Set(sequences.flatMap((s) => s.migrations.map((m) => m.ref)));\n for (const { waiting } of queues) {\n for (const migration of waiting) {\n for (const dependency of migration.dependsOn) {\n if (!done.has(dependency) && !provided.has(dependency)) {\n problems.push({ code: 'UNKNOWN_DEPENDENCY', detail: `${migration.ref} depends on ${dependency}, which nothing provides and the database has not run.` });\n }\n }\n }\n }\n\n const { pending, stuck } = orderPending(queues, done);\n if (stuck.length > 0 && !problems.some((p) => p.code === 'UNKNOWN_DEPENDENCY')) {\n problems.push({ code: 'CYCLE', detail: `These wait on each other and can never run: ${stuck.map((m) => m.ref).join(', ')}.` });\n }\n\n return { applied, pending, problems };\n};\n\n// Throw the plan's problems as one error, named by the first.\nexport const refuseProblems = (plan: Plan): void => {\n const first = plan.problems[0];\n if (first === undefined) return;\n throw new StrataError(first.code, 'The migrations cannot be applied safely.', plan.problems.map((p) => `${p.code}: ${p.detail}`));\n};\n","import { prepare, orderPending, type PreparedMigration, type PreparedSequence } from './plan';\nimport type { DocumentKind, Sequence } from './schema';\nimport { StrataError } from './errors';\n\n// ═══════════════════════════════════════════════════════════════\n// Documents — the JSON a grammar describes, wherever it is kept.\n//\n// A document carries a STAMP: for each grammar sequence, how far along that\n// sequence the writer was (`{ \"nisc.nova\": 3, \"nisc.prism\": 1 }`). Upgrading\n// runs every document migration the stamp has not seen, in the ledger's order,\n// and hands back the document with a current stamp. The same function serves a\n// row read at boot, a submission at intake and a file in an app's source tree:\n// the document does not care where it was kept.\n//\n// NESTING IS THE GRAMMAR'S, NOT THE MIGRATION'S. A kind declares where other\n// documents sit inside it (its embeddings: nova's layout holds layouts at\n// `children`, `children[]`, `then`, `else`, `do`; an action holds a layout and\n// Prism configs). The walker finds every document of a step's kind at any\n// depth and rewrites each on its own, deepest first. A transform only ever sees\n// ONE node — so migrations stay flat, and a Prism config can express them\n// without recursion of its own.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Stamp = Readonly<Record<string, number>>;\n\n// Where a document sits: the path from the root (keys and indexes) and its kind.\nexport type Location = { path: readonly (string | number)[]; kind: string; value: Record<string, unknown> };\n\n// The injected evaluator — nova's `transform` socket, the same shape: under moss\n// it is Prism's `evaluate`, and a migration runs exactly the way an endpoint does.\nexport type Transform = (config: unknown, source: unknown) => unknown;\n\nexport type UpgradeResult = {\n document: Record<string, unknown>;\n stamp: Stamp;\n // What ran, in order — empty when the document was already current.\n applied: readonly string[];\n};\n\nexport type Upgrader = {\n // The stamp a document written NOW carries.\n stamp: Stamp;\n upgrade: (document: unknown, options: { kind: string; stamp?: Stamp | null }) => UpgradeResult;\n // Every document inside `document` (itself included), by kind — what the\n // walker sees. For a page that shows it, and for a check that asserts it.\n locate: (document: unknown, kind: string) => Location[];\n // Is a document at this stamp behind the code (true), current (false)? Throws\n // TOO_NEW if it is ahead.\n behind: (stamp: Stamp | null | undefined) => boolean;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst pathText = (path: readonly (string | number)[]): string =>\n path.reduce<string>((text, key) => (typeof key === 'number' ? `${text}[${key}]` : text === '' ? key : `${text}.${key}`), '');\n\n// One embedding pattern, applied to one value: every (relative path, value)\n// the pattern reaches. `key` descends, `*` crosses a record's values, and a\n// `[]` suffix crosses the array found there.\nconst reach = (value: unknown, pattern: string): { path: (string | number)[]; value: unknown }[] => {\n let frontier: { path: (string | number)[]; value: unknown }[] = [{ path: [], value }];\n for (const segment of pattern.split('.')) {\n const array = segment.endsWith('[]');\n const key = array ? segment.slice(0, -2) : segment;\n const next: { path: (string | number)[]; value: unknown }[] = [];\n for (const at of frontier) {\n if (!isRecord(at.value)) continue;\n const found: { path: (string | number)[]; value: unknown }[] =\n key === '*'\n ? Object.entries(at.value).map(([k, v]) => ({ path: [...at.path, k], value: v }))\n : key in at.value\n ? [{ path: [...at.path, key], value: at.value[key] }]\n : [];\n for (const f of found) {\n if (!array) next.push(f);\n else if (Array.isArray(f.value)) f.value.forEach((item, i) => next.push({ path: [...f.path, i], value: item }));\n }\n }\n frontier = next;\n }\n return frontier;\n};\n\nconst getAt = (root: unknown, path: readonly (string | number)[]): unknown =>\n path.reduce<unknown>((at, key) => {\n if (typeof key === 'number') return Array.isArray(at) ? at[key] : undefined;\n return isRecord(at) ? at[key] : undefined;\n }, root);\n\nconst setAt = (root: unknown, path: readonly (string | number)[], value: unknown): unknown => {\n const [head, ...rest] = path;\n if (head === undefined) return value;\n if (typeof head === 'number' && Array.isArray(root)) return root.map((item, i) => (i === head ? setAt(item, rest, value) : item));\n if (typeof head === 'string' && isRecord(root)) return { ...root, [head]: setAt(root[head], rest, value) };\n return root;\n};\n\nexport const createUpgrader = async (sequences: readonly Sequence[], options: { transform: Transform }): Promise<Upgrader> => {\n const prepared = await prepare(sequences);\n const tables = prepared.filter((s) => !s.grammar);\n if (tables.length > 0) {\n throw new StrataError(\n 'WRONG_OWNER',\n 'Documents are upgraded by grammar sequences; these own tables and belong to a database\\'s ledger (`migrate`).',\n tables.map((s) => s.id),\n );\n }\n const grammars: readonly PreparedSequence[] = prepared;\n\n const kinds = new Map<string, DocumentKind>();\n for (const sequence of grammars) {\n for (const [name, kind] of Object.entries(sequence.documents)) kinds.set(`${sequence.id}/${name}`, kind);\n }\n const unknown = [\n ...grammars.flatMap((s) => s.migrations.flatMap((m) => m.steps.flatMap((step) => (step.kind === 'document' && !kinds.has(step.at) ? [`${m.ref} rewrites ${step.at}`] : [])))),\n ...[...kinds].flatMap(([ref, kind]) => Object.entries(kind.embeds ?? {}).flatMap(([path, target]) => (kinds.has(target) ? [] : [`${ref} embeds ${target} at ${path}`]))),\n ];\n if (unknown.length > 0) throw new StrataError('UNKNOWN_KIND', 'A document kind is named that no sequence declares.', unknown);\n\n const stamp: Stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));\n\n const locate = (document: unknown, kind: string): Location[] => {\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n const found: Location[] = [];\n const visit = (value: unknown, at: string, path: (string | number)[]): void => {\n if (!isRecord(value)) return;\n found.push({ path, kind: at, value });\n for (const [pattern, target] of Object.entries(kinds.get(at)?.embeds ?? {})) {\n for (const hit of reach(value, pattern)) visit(hit.value, target, [...path, ...hit.path]);\n }\n };\n visit(document, kind, []);\n return found;\n };\n\n const positionOf = (given: Stamp | null | undefined, id: string): number => given?.[id] ?? 0;\n\n const behind = (given: Stamp | null | undefined): boolean => {\n const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);\n if (ahead.length > 0) {\n throw new StrataError(\n 'TOO_NEW',\n 'This document was written by newer code than this — reading it would be guessing.',\n ahead.map((s) => `${s.id}: the document is at ${positionOf(given, s.id)}, this code knows ${s.migrations.length}`),\n );\n }\n return grammars.some((s) => positionOf(given, s.id) < s.migrations.length);\n };\n\n const upgrade = (document: unknown, { kind, stamp: given }: { kind: string; stamp?: Stamp | null }): UpgradeResult => {\n if (!isRecord(document)) throw new StrataError('STEP_FAILED', `A ${kind} document must be a JSON object.`);\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n if (!behind(given)) return { document, stamp, applied: [] };\n\n // What this document has seen: everything up to its stamp, per sequence.\n // A sequence it has never heard of starts at 0 — a document written before\n // a grammar existed simply has none of its migrations yet.\n const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));\n const { pending, stuck } = orderPending(\n grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),\n done,\n );\n if (stuck.length > 0) throw new StrataError('CYCLE', 'Document migrations wait on each other and can never run.', stuck.map((m) => m.ref));\n\n let current: Record<string, unknown> = document;\n const applied: string[] = [];\n const runStep = (migration: PreparedMigration, at: string, transform: unknown): void => {\n // Deepest first: a parent's rewrite sees its children already rewritten,\n // and replacing a child never moves the path to its parent.\n const targets = locate(current, kind)\n .filter((l) => l.kind === at)\n .sort((a, b) => b.path.length - a.path.length);\n for (const target of targets) {\n // The value NOW, not when the targets were found: a child rewritten a\n // moment ago lives in `current`, and the parent must see — and keep — it.\n const value = getAt(current, target.path);\n let rewritten: unknown;\n try {\n rewritten = options.transform(transform, { document: value, path: pathText(target.path) });\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed on the ${at} at ${pathText(target.path) || '(root)'}.`,\n [cause instanceof Error ? cause.message : String(cause)],\n { cause },\n );\n }\n if (!isRecord(rewritten)) {\n throw new StrataError('STEP_FAILED', `${migration.ref} turned the ${at} at ${pathText(target.path) || '(root)'} into something that is not a document.`, [\n JSON.stringify(rewritten)?.slice(0, 200) ?? String(rewritten),\n ]);\n }\n const next = setAt(current, target.path, rewritten);\n if (isRecord(next)) current = next;\n }\n };\n for (const migration of pending) {\n for (const step of migration.steps) if (step.kind === 'document') runStep(migration, step.at, step.transform);\n applied.push(migration.ref);\n }\n return { document: current, stamp, applied };\n };\n\n return { stamp, upgrade, locate, behind };\n};\n","import type { SqlStep } from './schema';\n\n// ═══════════════════════════════════════════════════════════════\n// A DDL file as steps — one statement each, because a driver that prepares\n// statements refuses a string carrying several.\n//\n// Splitting on every `;` is wrong, and quietly: a comment that contains one\n// (\"-- each is a role; `remit` says…\") is cut in two, its tail becomes a line of\n// SQL, and the step fails on the database it was meant to set up. A statement\n// here ends only at a `;` that closes a line of SQL; comment lines never end\n// one. Comments stay in the steps (the checksum ignores full-line comments).\n//\n// Not a SQL parser: a `;` at the end of a line inside a string literal or a\n// function body would still end a statement. Write those as their own steps.\n// ═══════════════════════════════════════════════════════════════\n\nconst isComment = (line: string): boolean => line.trim().startsWith('--');\n\nexport const sqlSteps = (ddl: string): SqlStep[] => {\n const steps: SqlStep[] = [];\n let buffer: string[] = [];\n const flush = (): void => {\n const sql = buffer.join('\\n').trim().replace(/;\\s*$/, '').trim();\n if (sql.split('\\n').some((line) => line.trim() !== '' && !isComment(line))) steps.push({ kind: 'sql', sql });\n buffer = [];\n };\n for (const line of ddl.split('\\n')) {\n buffer.push(line);\n if (!isComment(line) && line.trimEnd().endsWith(';')) flush();\n }\n flush();\n return steps;\n};\n","// ═══════════════════════════════════════════════════════════\n// HOW DEEP A DOCUMENT MAY NEST, checked before a schema reads it. The\n// grammars are recursive (a layout's children, a Prism `$if`, a Vex `and`),\n// and a recursive schema recurses on the call stack: a document a few\n// thousand levels deep does not come back from `safeParse` refused, it throws\n// RangeError from inside the parser — at the one place meant to turn bad input\n// into a refusal. So every boundary that parses a document from outside asks\n// this first, and a document past the limit is refused like any other\n// invalid one.\n//\n// 256 levels of JSON. The deepest document in the lab apps is 25 (relay's\n// deal view: a layout's nodes, their props and bindings); a stranger's is\n// either near that or not a document anybody wrote. The walk is iterative, so\n// asking cannot overflow the stack either.\n// ═══════════════════════════════════════════════════════════\n\nexport const DOCUMENT_DEPTH_LIMIT = 256;\n\nexport const exceedsDepth = (value: unknown, limit: number = DOCUMENT_DEPTH_LIMIT): boolean => {\n const pending: { value: unknown; depth: number }[] = [{ value, depth: 0 }];\n for (let next = pending.pop(); next !== undefined; next = pending.pop()) {\n if (typeof next.value !== 'object' || next.value === null) continue;\n const depth = next.depth + 1;\n if (depth > limit) return true;\n for (const inner of Array.isArray(next.value) ? next.value : Object.values(next.value)) pending.push({ value: inner, depth });\n }\n return false;\n};\n\nexport const depthRefusal = (limit: number = DOCUMENT_DEPTH_LIMIT): string =>\n `the document nests deeper than ${limit} levels — no document is written that deep, and a schema reading one would overflow the stack`;\n","// @niscorp/strata — the core: the grammar of a migration, the plan, the errors.\n// Pure and storage-blind; `@niscorp/strata/postgres` applies a plan to a database.\n\nimport type { Sequence } from './schema';\n\nexport { SequenceSchema, MigrationSchema, StepSchema, SqlStepSchema, DocumentStepSchema, DocumentKindSchema, SEQUENCE_ID, MIGRATION_REF, KIND_NAME, KIND_REF, EMBED_PATH } from './schema';\nexport type { Sequence, Migration, Step, SqlStep, DocumentStep, DocumentKind } from './schema';\nexport { createUpgrader } from './documents';\nexport type { Stamp, Location, Transform, Upgrader, UpgradeResult } from './documents';\nexport { prepare, planMigrations, refuseProblems, orderPending } from './plan';\nexport type { Plan, Problem, PreparedMigration, PreparedSequence, LedgerRow } from './plan';\nexport { checksumOf } from './checksum';\nexport { sqlSteps } from './sql';\nexport { DOCUMENT_DEPTH_LIMIT, exceedsDepth, depthRefusal } from './depth';\nexport { StrataError } from './errors';\nexport type { StrataErrorCode } from './errors';\n\n// Authoring helper: a sequence, type-checked where it is written. Parsing\n// happens where it is applied (`prepare`), like every other artifact.\nexport const defineSequence = <const T extends Sequence>(sequence: T): T => sequence;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts","../src/checksum.ts","../src/errors.ts","../src/plan.ts","../src/documents.ts","../src/sql.ts","../src/depth.ts","../src/index.ts"],"names":["z"],"mappings":";;;;;AAiBO,IAAM,WAAA,GAAc;AAIpB,IAAM,aAAA,GAAgB;AAItB,IAAM,SAAA,GAAY;AAClB,IAAM,QAAA,GAAW;AAOjB,IAAM,UAAA,GAAa;AAEnB,IAAM,aAAA,GAAgBA,MAC1B,MAAA,CAAO;AAAA,EACN,IAAA,EAAMA,KAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,KAAKA,KAAA,CACF,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,QAAA;AAAA,IACC;AAAA;AAGN,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,yEAAyE;AAE9E,IAAM,kBAAA,GAAqBA,MAC/B,MAAA,CAAO;AAAA,EACN,IAAA,EAAMA,KAAA,CAAE,OAAA,CAAQ,UAAU,CAAA;AAAA,EAC1B,EAAA,EAAIA,MACD,MAAA,EAAO,CACP,MAAM,QAAQ,CAAA,CACd,SAAS,0GAAqG,CAAA;AAAA,EACjH,SAAA,EAAWA,KAAA,CACR,OAAA,EAAQ,CACR,QAAA;AAAA,IACC;AAAA;AAIN,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,iDAAiD;AAEtD,IAAM,aAAaA,KAAA,CAAE,kBAAA,CAAmB,QAAQ,CAAC,aAAA,EAAe,kBAAkB,CAAC;AAEnF,IAAM,kBAAA,GAAqBA,MAC/B,MAAA,CAAO;AAAA,EACN,QAAQA,KAAA,CACL,MAAA,CAAOA,MAAE,MAAA,EAAO,CAAE,MAAM,UAAU,CAAA,EAAGA,MAAE,MAAA,EAAO,CAAE,MAAM,QAAQ,CAAC,EAC/D,QAAA,EAAS,CACT,SAAS,0GAAqG;AACnH,CAAC,EACA,MA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AAgB,oBAAA,KAC3C,kCAAkC,KAAK,CAAA,kGAAA;;;ACXlC,IAAM,cAAA,GAAiB,CAA2B,QAAA,KAAmB","file":"index.cjs","sourcesContent":["import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// The grammar of a migration.\n//\n// A SEQUENCE is an append-only list of migrations owned by one grammar owner —\n// a package's tables (`nisc.vex.cache`), a package's documents (`nisc.nova`,\n// later), an app's own (`midas.app`). A migration's number is its POSITION, so\n// the sequence's version is its length: nobody bumps a number, you append.\n//\n// Sequences are data. They are authored in TS for type-checking, but nothing\n// here is a function, so a sequence can be stored, shipped and inspected like\n// every other nisc artifact — and is parsed at the boundary like one.\n// ═══════════════════════════════════════════════════════════════\n\n// Namespaced, lowercase: `<owner>.<name>[.<name>…]`. The owner prefix keeps two\n// packages (or a package and an app) from ever claiming the same sequence.\nexport const SEQUENCE_ID = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+$/;\n\n// `<sequence>/<n>` — how a migration is named everywhere: the ledger, a\n// dependency, an error.\nexport const MIGRATION_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[1-9][0-9]*$/;\n\n// A document kind, named by its owner: `<sequence>/<kind>`, e.g.\n// \"nisc.nova/layout\". The kind part is a plain lowercase word.\nexport const KIND_NAME = /^[a-z][a-z0-9-]*$/;\nexport const KIND_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[a-z][a-z0-9-]*$/;\n\n// Where, inside a document, another document sits. Dot-separated keys, with\n// two wildcards that say WHICH shape they cross — `children[]` is every item of\n// the array at `children`, `endpoints.*` every value of the record at\n// `endpoints`. Kept apart on purpose: nova's `children` is a single node OR an\n// array, and one wildcard for both would read a lone node's `props` as layouts.\nexport const EMBED_PATH = /^([A-Za-z_$][\\w$]*|\\*)(\\[\\])?(\\.([A-Za-z_$][\\w$]*|\\*)(\\[\\])?)*$/;\n\nexport const SqlStepSchema = z\n .object({\n kind: z.literal('sql'),\n sql: z\n .string()\n .min(1)\n .describe(\n 'ONE SQL statement. A driver that prepares statements (PGlite, pg with parameters) refuses a string ' +\n 'carrying several — split them into steps rather than joining them with semicolons.',\n ),\n })\n .strict()\n .describe('A statement run against the database, inside the migration transaction.');\n\nexport const DocumentStepSchema = z\n .object({\n kind: z.literal('document'),\n at: z\n .string()\n .regex(KIND_REF)\n .describe('The kind of document this step rewrites, e.g. \"nisc.nova/layout\" — wherever one sits, at any depth.'),\n transform: z\n .unknown()\n .describe(\n 'A transform config (Prism) run by the injected evaluator over { document, path }: `document` is ONE document of ' +\n 'the `at` kind, `path` where it sits. It returns that document rewritten. Nested documents are found by the ' +\n 'grammar\\'s embeddings and rewritten on their own, deepest first — a transform only ever sees one flat node.',\n ),\n })\n .strict()\n .describe('A rewrite of stored JSON documents of one kind.');\n\nexport const StepSchema = z.discriminatedUnion('kind', [SqlStepSchema, DocumentStepSchema]);\n\nexport const DocumentKindSchema = z\n .object({\n embeds: z\n .record(z.string().regex(EMBED_PATH), z.string().regex(KIND_REF))\n .optional()\n .describe('Where other documents sit inside this one: path → the kind found there (possibly this kind itself).'),\n })\n .strict();\n\nexport const MigrationSchema = z\n .object({\n description: z\n .string()\n .min(1)\n .describe('One sentence: what this migration does. It is the changelog line and the ledger\\'s description.'),\n steps: z\n .array(StepSchema)\n .describe(\n 'Applied in order, in the same transaction as every other pending migration. Empty is a MARKER: ' +\n 'the version moves and nothing runs — how an addition to a strict grammar tells older readers to refuse.',\n ),\n dependsOn: z\n .array(z.string().regex(MIGRATION_REF))\n .optional()\n .describe('Migrations of OTHER sequences that must be applied first, each as \"<sequence>/<n>\".'),\n })\n .strict();\n\nexport const SequenceSchema = z\n .object({\n id: z.string().regex(SEQUENCE_ID).describe('Namespaced and lowercase, e.g. \"nisc.vex.cache\" or \"midas.app\".'),\n documents: z\n .record(z.string().regex(KIND_NAME), DocumentKindSchema)\n .optional()\n .describe('The document kinds this sequence owns (a GRAMMAR sequence), each named \"<id>/<kind>\" elsewhere.'),\n migrations: z\n .array(MigrationSchema)\n .describe('Append-only. A migration is numbered by its position (from 1); the sequence\\'s version is its length.'),\n })\n .strict()\n // TWO KINDS OF OWNER. A table sequence (sql steps) is recorded per DATABASE,\n // in its ledger. A grammar sequence (document steps) is tracked per DOCUMENT,\n // by the stamp the document carries — because documents travel: an add-on\n // built on older code submits older documents to a newer host. One sequence\n // cannot be both; the two versions would mean different things.\n .superRefine((sequence, ctx) => {\n const kinds = new Set(sequence.migrations.flatMap((m) => m.steps.map((s) => s.kind)));\n if (kinds.has('sql') && (kinds.has('document') || sequence.documents !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: 'A sequence either owns tables (sql steps) or documents (document steps and `documents`), not both.',\n });\n }\n });\n\nexport type SqlStep = z.infer<typeof SqlStepSchema>;\nexport type DocumentStep = z.infer<typeof DocumentStepSchema>;\nexport type DocumentKind = z.infer<typeof DocumentKindSchema>;\nexport type Step = z.infer<typeof StepSchema>;\nexport type Migration = z.infer<typeof MigrationSchema>;\nexport type Sequence = z.infer<typeof SequenceSchema>;\n","import type { Migration } from './schema';\n\n// ═══════════════════════════════════════════════════════════════\n// What a migration DID, as a hash — the ledger's proof that the code still says\n// what the database ran.\n//\n// Over the steps only. The description is prose: fixing a typo in it must not\n// read as an edited migration. `dependsOn` orders, it does not act. The steps\n// are the effect, and changing an applied step is the one thing that has to\n// be refused — the database already holds the old effect.\n//\n// For the same reason a step's SQL is hashed without its full-line comments\n// (`-- …` on a line of its own) and without trailing whitespace: a migration\n// can carry its documentation verbatim, and rewording it is not an edit.\n//\n// WebCrypto (SHA-256), which Node ≥ 22 and every browser carry as\n// `crypto.subtle` — the same primitive Prism fingerprints with, so strata runs\n// unchanged in a server, a test and the showroom page.\n// ═══════════════════════════════════════════════════════════════\n\n// Sorted keys, recursively: the same value always serializes the same way,\n// whatever order its object literal was written in.\nconst canonical = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n};\n\nconst effectOf = (sql: string): string =>\n sql\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('--'))\n .map((line) => line.trimEnd())\n .join('\\n')\n .trim();\n\nexport const checksumOf = async (migration: Migration): Promise<string> => {\n const steps = migration.steps.map((step) => (step.kind === 'sql' ? { ...step, sql: effectOf(step.sql) } : step));\n const bytes = new TextEncoder().encode(canonical(steps));\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n};\n","// 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 { SequenceSchema, type DocumentKind, type Sequence, type Step } from './schema';\nimport { checksumOf } from './checksum';\nimport { StrataError, type StrataErrorCode } from './errors';\n\n// ═══════════════════════════════════════════════════════════════\n// The plan — what the code says, against what the database has run.\n//\n// Pure: sequences and ledger rows in, a plan out. No database, no clock. The\n// postgres runner reads the ledger, calls this, and applies what it says; a\n// showroom page or a CI check can call it with a ledger it made up.\n// ═══════════════════════════════════════════════════════════════\n\n// A migration the code declares, numbered and hashed.\nexport type PreparedMigration = {\n sequence: string;\n n: number;\n ref: string;\n description: string;\n checksum: string;\n steps: readonly Step[];\n dependsOn: readonly string[];\n};\n\nexport type PreparedSequence = {\n id: string;\n // A grammar sequence owns documents (tracked by stamps); otherwise it owns\n // tables (tracked by a database's ledger). See SequenceSchema.\n grammar: boolean;\n documents: Readonly<Record<string, DocumentKind>>;\n migrations: readonly PreparedMigration[];\n};\n\n// One row of the ledger, as a runner read it back.\nexport type LedgerRow = { sequence: string; n: number; checksum: string; description: string; appliedAt: string };\n\nexport type Problem = { code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>; detail: string };\n\nexport type Plan = {\n // Already run, per sequence this code knows: how far each one is.\n applied: Readonly<Record<string, number>>;\n // To run, in the order they must run.\n pending: readonly PreparedMigration[];\n // Anything that makes applying unsafe. A plan with problems is never applied.\n problems: readonly Problem[];\n};\n\nconst refOf = (sequence: string, n: number): string => `${sequence}/${n}`;\n\n// Parse, number and hash. Async only for the hash (WebCrypto).\nexport const prepare = async (sequences: readonly Sequence[]): Promise<readonly PreparedSequence[]> => {\n const seen = new Set<string>();\n const prepared: PreparedSequence[] = [];\n for (const input of sequences) {\n const parsed = SequenceSchema.safeParse(input);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);\n throw new StrataError('INVALID_SEQUENCE', `A sequence does not parse${typeof input.id === 'string' ? ` (\"${input.id}\")` : ''}.`, issues);\n }\n const sequence = parsed.data;\n if (seen.has(sequence.id)) {\n throw new StrataError('INVALID_SEQUENCE', `Two sequences are both called \"${sequence.id}\" — a sequence id names one owner.`);\n }\n seen.add(sequence.id);\n const migrations: PreparedMigration[] = [];\n for (const [index, migration] of sequence.migrations.entries()) {\n const n = index + 1;\n migrations.push({\n sequence: sequence.id,\n n,\n ref: refOf(sequence.id, n),\n description: migration.description,\n checksum: await checksumOf(migration),\n steps: migration.steps,\n dependsOn: migration.dependsOn ?? [],\n });\n }\n const grammar = sequence.documents !== undefined || sequence.migrations.some((m) => m.steps.some((s) => s.kind === 'document'));\n prepared.push({ id: sequence.id, grammar, documents: sequence.documents ?? {}, migrations });\n }\n return prepared;\n};\n\n// Order: walk the sequences in the order given, and let each run as far as its\n// dependencies allow before moving on; repeat until nothing moves. The same\n// input always yields the same order, and a sequence's own migrations stay\n// together unless a dependency splits them. Shared by the ledger's plan and a\n// document's upgrade, so both order the same migrations the same way.\nexport const orderPending = (\n queues: readonly { waiting: readonly PreparedMigration[] }[],\n alreadyDone: ReadonlySet<string>,\n): { pending: PreparedMigration[]; stuck: PreparedMigration[] } => {\n const done = new Set(alreadyDone);\n const waiting = queues.map((q) => [...q.waiting]);\n const pending: PreparedMigration[] = [];\n let moved = true;\n while (moved) {\n moved = false;\n for (const queue of waiting) {\n for (let head = queue[0]; head !== undefined; head = queue[0]) {\n if (!head.dependsOn.every((d) => done.has(d))) break;\n pending.push(head);\n done.add(head.ref);\n queue.shift();\n moved = true;\n }\n }\n }\n return { pending, stuck: waiting.flat() };\n};\n\nexport const planMigrations = (sequences: readonly PreparedSequence[], ledger: readonly LedgerRow[]): Plan => {\n const problems: Problem[] = [];\n const applied: Record<string, number> = {};\n const done = new Set(ledger.map((row) => refOf(row.sequence, row.n)));\n const byRef = new Map(ledger.map((row) => [refOf(row.sequence, row.n), row]));\n\n const queues: { id: string; waiting: PreparedMigration[] }[] = [];\n for (const sequence of sequences) {\n const rows = ledger.filter((row) => row.sequence === sequence.id);\n applied[sequence.id] = rows.length;\n\n // The database ran migrations this code has never seen: newer code migrated\n // it. Applying ours on top would be guessing — refuse.\n const beyond = rows.filter((row) => row.n > sequence.migrations.length);\n if (beyond.length > 0) {\n problems.push({\n code: 'TOO_NEW',\n detail: `${sequence.id}: the database is at ${Math.max(...rows.map((r) => r.n))}, this code knows ${sequence.migrations.length} — it was migrated by newer code.`,\n });\n }\n\n const waiting: PreparedMigration[] = [];\n for (const migration of sequence.migrations) {\n const row = byRef.get(migration.ref);\n if (row === undefined) {\n waiting.push(migration);\n } else if (row.checksum !== migration.checksum) {\n problems.push({\n code: 'EDITED',\n detail: `${migration.ref} (\"${migration.description}\") was applied ${row.appliedAt} and its steps have changed since. An applied migration is history — append a new one.`,\n });\n }\n }\n // A hole: something later ran, something earlier did not. The ledger was\n // written by hand, or by a different ordering of the same sequence.\n const firstWaiting = waiting[0];\n if (firstWaiting !== undefined && rows.some((row) => row.n > firstWaiting.n)) {\n problems.push({ code: 'EDITED', detail: `${sequence.id}: ${firstWaiting.ref} never ran, but a later migration of the sequence did.` });\n }\n queues.push({ id: sequence.id, waiting });\n }\n\n // Every dependency must be satisfiable by the ledger or by this plan.\n const provided = new Set(sequences.flatMap((s) => s.migrations.map((m) => m.ref)));\n for (const { waiting } of queues) {\n for (const migration of waiting) {\n for (const dependency of migration.dependsOn) {\n if (!done.has(dependency) && !provided.has(dependency)) {\n problems.push({ code: 'UNKNOWN_DEPENDENCY', detail: `${migration.ref} depends on ${dependency}, which nothing provides and the database has not run.` });\n }\n }\n }\n }\n\n const { pending, stuck } = orderPending(queues, done);\n if (stuck.length > 0 && !problems.some((p) => p.code === 'UNKNOWN_DEPENDENCY')) {\n problems.push({ code: 'CYCLE', detail: `These wait on each other and can never run: ${stuck.map((m) => m.ref).join(', ')}.` });\n }\n\n return { applied, pending, problems };\n};\n\n// Throw the plan's problems as one error, named by the first.\nexport const refuseProblems = (plan: Plan): void => {\n const first = plan.problems[0];\n if (first === undefined) return;\n throw new StrataError(first.code, 'The migrations cannot be applied safely.', plan.problems.map((p) => `${p.code}: ${p.detail}`));\n};\n","import { prepare, orderPending, type PreparedMigration, type PreparedSequence } from './plan';\nimport type { DocumentKind, Sequence } from './schema';\nimport { StrataError } from './errors';\n\n// ═══════════════════════════════════════════════════════════════\n// Documents — the JSON a grammar describes, wherever it is kept.\n//\n// A document carries a STAMP: for each grammar sequence, how far along that\n// sequence the writer was (`{ \"nisc.nova\": 3, \"nisc.prism\": 1 }`). Upgrading\n// runs every document migration the stamp has not seen, in the ledger's order,\n// and hands back the document with a current stamp. The same function serves a\n// row read at boot, a submission at intake and a file in an app's source tree:\n// the document does not care where it was kept.\n//\n// NESTING IS THE GRAMMAR'S, NOT THE MIGRATION'S. A kind declares where other\n// documents sit inside it (its embeddings: nova's layout holds layouts at\n// `children`, `children[]`, `then`, `else`, `do`; an action holds a layout and\n// Prism configs). The walker finds every document of a step's kind at any\n// depth and rewrites each on its own, deepest first. A transform only ever sees\n// ONE node — so migrations stay flat, and a Prism config can express them\n// without recursion of its own.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Stamp = Readonly<Record<string, number>>;\n\n// Where a document sits: the path from the root (keys and indexes) and its kind.\nexport type Location = { path: readonly (string | number)[]; kind: string; value: Record<string, unknown> };\n\n// The injected evaluator — nova's `transform` socket, the same shape: under moss\n// it is Prism's `evaluate`, and a migration runs exactly the way an endpoint does.\nexport type Transform = (config: unknown, source: unknown) => unknown;\n\nexport type UpgradeResult = {\n document: Record<string, unknown>;\n // What to store with the document: current on every grammar the upgrader was\n // given, and the document's entries for any other grammar kept as they were.\n stamp: Stamp;\n // What ran, in order — empty when the document was already current.\n applied: readonly string[];\n};\n\nexport type Upgrader = {\n // The stamp a document written NOW carries.\n stamp: Stamp;\n upgrade: (document: unknown, options: { kind: string; stamp?: Stamp | null }) => UpgradeResult;\n // Every document inside `document` (itself included), by kind — what the\n // walker sees. For a page that shows it, and for a check that asserts it.\n locate: (document: unknown, kind: string) => Location[];\n // Is a document at this stamp behind the code (true), current (false)? Throws\n // TOO_NEW if it is ahead.\n behind: (stamp: Stamp | null | undefined) => boolean;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst pathText = (path: readonly (string | number)[]): string =>\n path.reduce<string>((text, key) => (typeof key === 'number' ? `${text}[${key}]` : text === '' ? key : `${text}.${key}`), '');\n\n// One embedding pattern, applied to one value: every (relative path, value)\n// the pattern reaches. `key` descends, `*` crosses a record's values, and a\n// `[]` suffix crosses the array found there.\nconst reach = (value: unknown, pattern: string): { path: (string | number)[]; value: unknown }[] => {\n let frontier: { path: (string | number)[]; value: unknown }[] = [{ path: [], value }];\n for (const segment of pattern.split('.')) {\n const array = segment.endsWith('[]');\n const key = array ? segment.slice(0, -2) : segment;\n const next: { path: (string | number)[]; value: unknown }[] = [];\n for (const at of frontier) {\n if (!isRecord(at.value)) continue;\n const found: { path: (string | number)[]; value: unknown }[] =\n key === '*'\n ? Object.entries(at.value).map(([k, v]) => ({ path: [...at.path, k], value: v }))\n : key in at.value\n ? [{ path: [...at.path, key], value: at.value[key] }]\n : [];\n for (const f of found) {\n if (!array) next.push(f);\n else if (Array.isArray(f.value)) f.value.forEach((item, i) => next.push({ path: [...f.path, i], value: item }));\n }\n }\n frontier = next;\n }\n return frontier;\n};\n\nconst getAt = (root: unknown, path: readonly (string | number)[]): unknown =>\n path.reduce<unknown>((at, key) => {\n if (typeof key === 'number') return Array.isArray(at) ? at[key] : undefined;\n return isRecord(at) ? at[key] : undefined;\n }, root);\n\nconst setAt = (root: unknown, path: readonly (string | number)[], value: unknown): unknown => {\n const [head, ...rest] = path;\n if (head === undefined) return value;\n if (typeof head === 'number' && Array.isArray(root)) return root.map((item, i) => (i === head ? setAt(item, rest, value) : item));\n if (typeof head === 'string' && isRecord(root)) return { ...root, [head]: setAt(root[head], rest, value) };\n return root;\n};\n\nexport const createUpgrader = async (sequences: readonly Sequence[], options: { transform: Transform }): Promise<Upgrader> => {\n const prepared = await prepare(sequences);\n const tables = prepared.filter((s) => !s.grammar);\n if (tables.length > 0) {\n // A sequence is read as a grammar by what it declares (plan.ts). One with\n // nothing but markers and no `documents` reads as owning tables, so the\n // refusal says how a grammar says it is one — `migrate` alone would send a\n // kit's markers to a database's ledger.\n throw new StrataError(\n 'WRONG_OWNER',\n 'Documents are upgraded by grammar sequences; these own tables and belong to a database\\'s ledger (`migrate`). If one of them is a grammar, declare its `documents` — a sequence with no `documents` and no document step is read as owning tables.',\n tables.map((s) => s.id),\n );\n }\n const grammars: readonly PreparedSequence[] = prepared;\n\n const kinds = new Map<string, DocumentKind>();\n for (const sequence of grammars) {\n for (const [name, kind] of Object.entries(sequence.documents)) kinds.set(`${sequence.id}/${name}`, kind);\n }\n const unknown = [\n ...grammars.flatMap((s) => s.migrations.flatMap((m) => m.steps.flatMap((step) => (step.kind === 'document' && !kinds.has(step.at) ? [`${m.ref} rewrites ${step.at}`] : [])))),\n ...[...kinds].flatMap(([ref, kind]) => Object.entries(kind.embeds ?? {}).flatMap(([path, target]) => (kinds.has(target) ? [] : [`${ref} embeds ${target} at ${path}`]))),\n ];\n if (unknown.length > 0) throw new StrataError('UNKNOWN_KIND', 'A document kind is named that no sequence declares.', unknown);\n\n const stamp: Stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));\n\n // The stamp a document carries once this code has read it: this code's\n // position on every grammar it was given and — as they were — the document's\n // own entries for grammars it was not. Those record code this reader lacks (a\n // kit it does not have); dropping them would let code that does have the\n // grammar run its migrations over the document a second time.\n const ownIds = new Set(grammars.map((s) => s.id));\n const stampAfter = (given: Stamp | null | undefined): Stamp => {\n const others = Object.entries(given ?? {}).filter(([id]) => !ownIds.has(id));\n return others.length === 0 ? stamp : { ...stamp, ...Object.fromEntries(others) };\n };\n\n const locate = (document: unknown, kind: string): Location[] => {\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n const found: Location[] = [];\n const visit = (value: unknown, at: string, path: (string | number)[]): void => {\n if (!isRecord(value)) return;\n found.push({ path, kind: at, value });\n for (const [pattern, target] of Object.entries(kinds.get(at)?.embeds ?? {})) {\n for (const hit of reach(value, pattern)) visit(hit.value, target, [...path, ...hit.path]);\n }\n };\n visit(document, kind, []);\n return found;\n };\n\n const positionOf = (given: Stamp | null | undefined, id: string): number => given?.[id] ?? 0;\n\n const behind = (given: Stamp | null | undefined): boolean => {\n const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);\n if (ahead.length > 0) {\n throw new StrataError(\n 'TOO_NEW',\n 'This document was written by newer code than this — reading it would be guessing.',\n ahead.map((s) => `${s.id}: the document is at ${positionOf(given, s.id)}, this code knows ${s.migrations.length}`),\n );\n }\n return grammars.some((s) => positionOf(given, s.id) < s.migrations.length);\n };\n\n const upgrade = (document: unknown, { kind, stamp: given }: { kind: string; stamp?: Stamp | null }): UpgradeResult => {\n if (!isRecord(document)) throw new StrataError('STEP_FAILED', `A ${kind} document must be a JSON object.`);\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };\n\n // What this document has seen: everything up to its stamp, per sequence.\n // A sequence it has never heard of starts at 0 — a document written before\n // a grammar existed simply has none of its migrations yet.\n const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));\n const { pending, stuck } = orderPending(\n grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),\n done,\n );\n if (stuck.length > 0) throw new StrataError('CYCLE', 'Document migrations wait on each other and can never run.', stuck.map((m) => m.ref));\n\n let current: Record<string, unknown> = document;\n const applied: string[] = [];\n const runStep = (migration: PreparedMigration, at: string, transform: unknown): void => {\n // Deepest first: a parent's rewrite sees its children already rewritten,\n // and replacing a child never moves the path to its parent.\n const targets = locate(current, kind)\n .filter((l) => l.kind === at)\n .sort((a, b) => b.path.length - a.path.length);\n for (const target of targets) {\n // The value NOW, not when the targets were found: a child rewritten a\n // moment ago lives in `current`, and the parent must see — and keep — it.\n const value = getAt(current, target.path);\n let rewritten: unknown;\n try {\n rewritten = options.transform(transform, { document: value, path: pathText(target.path) });\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed on the ${at} at ${pathText(target.path) || '(root)'}.`,\n [cause instanceof Error ? cause.message : String(cause)],\n { cause },\n );\n }\n if (!isRecord(rewritten)) {\n throw new StrataError('STEP_FAILED', `${migration.ref} turned the ${at} at ${pathText(target.path) || '(root)'} into something that is not a document.`, [\n JSON.stringify(rewritten)?.slice(0, 200) ?? String(rewritten),\n ]);\n }\n const next = setAt(current, target.path, rewritten);\n if (isRecord(next)) current = next;\n }\n };\n for (const migration of pending) {\n for (const step of migration.steps) if (step.kind === 'document') runStep(migration, step.at, step.transform);\n applied.push(migration.ref);\n }\n return { document: current, stamp: stampAfter(given), applied };\n };\n\n return { stamp, upgrade, locate, behind };\n};\n","import type { SqlStep } from './schema';\n\n// ═══════════════════════════════════════════════════════════════\n// A DDL file as steps — one statement each, because a driver that prepares\n// statements refuses a string carrying several.\n//\n// Splitting on every `;` is wrong, and quietly: a comment that contains one\n// (\"-- each is a role; `remit` says…\") is cut in two, its tail becomes a line of\n// SQL, and the step fails on the database it was meant to set up. A statement\n// here ends only at a `;` that closes a line of SQL; comment lines never end\n// one. Comments stay in the steps (the checksum ignores full-line comments).\n//\n// Not a SQL parser: a `;` at the end of a line inside a string literal or a\n// function body would still end a statement. Write those as their own steps.\n// ═══════════════════════════════════════════════════════════════\n\nconst isComment = (line: string): boolean => line.trim().startsWith('--');\n\nexport const sqlSteps = (ddl: string): SqlStep[] => {\n const steps: SqlStep[] = [];\n let buffer: string[] = [];\n const flush = (): void => {\n const sql = buffer.join('\\n').trim().replace(/;\\s*$/, '').trim();\n if (sql.split('\\n').some((line) => line.trim() !== '' && !isComment(line))) steps.push({ kind: 'sql', sql });\n buffer = [];\n };\n for (const line of ddl.split('\\n')) {\n buffer.push(line);\n if (!isComment(line) && line.trimEnd().endsWith(';')) flush();\n }\n flush();\n return steps;\n};\n","// ═══════════════════════════════════════════════════════════\n// HOW DEEP A DOCUMENT MAY NEST, checked before a schema reads it. The\n// grammars are recursive (a layout's children, a Prism `$if`, a Vex `and`),\n// and a recursive schema recurses on the call stack: a document a few\n// thousand levels deep does not come back from `safeParse` refused, it throws\n// RangeError from inside the parser — at the one place meant to turn bad input\n// into a refusal. So every boundary that parses a document from outside asks\n// this first, and a document past the limit is refused like any other\n// invalid one.\n//\n// 256 levels of JSON. The deepest document in the lab apps is 25 (relay's\n// deal view: a layout's nodes, their props and bindings); a stranger's is\n// either near that or not a document anybody wrote. The walk is iterative, so\n// asking cannot overflow the stack either.\n// ═══════════════════════════════════════════════════════════\n\nexport const DOCUMENT_DEPTH_LIMIT = 256;\n\nexport const exceedsDepth = (value: unknown, limit: number = DOCUMENT_DEPTH_LIMIT): boolean => {\n const pending: { value: unknown; depth: number }[] = [{ value, depth: 0 }];\n for (let next = pending.pop(); next !== undefined; next = pending.pop()) {\n if (typeof next.value !== 'object' || next.value === null) continue;\n const depth = next.depth + 1;\n if (depth > limit) return true;\n for (const inner of Array.isArray(next.value) ? next.value : Object.values(next.value)) pending.push({ value: inner, depth });\n }\n return false;\n};\n\nexport const depthRefusal = (limit: number = DOCUMENT_DEPTH_LIMIT): string =>\n `the document nests deeper than ${limit} levels — no document is written that deep, and a schema reading one would overflow the stack`;\n","// @niscorp/strata — the core: the grammar of a migration, the plan, the errors.\n// Pure and storage-blind; `@niscorp/strata/postgres` applies a plan to a database.\n\nimport type { Sequence } from './schema';\n\nexport { SequenceSchema, MigrationSchema, StepSchema, SqlStepSchema, DocumentStepSchema, DocumentKindSchema, SEQUENCE_ID, MIGRATION_REF, KIND_NAME, KIND_REF, EMBED_PATH } from './schema';\nexport type { Sequence, Migration, Step, SqlStep, DocumentStep, DocumentKind } from './schema';\nexport { createUpgrader } from './documents';\nexport type { Stamp, Location, Transform, Upgrader, UpgradeResult } from './documents';\nexport { prepare, planMigrations, refuseProblems, orderPending } from './plan';\nexport type { Plan, Problem, PreparedMigration, PreparedSequence, LedgerRow } from './plan';\nexport { checksumOf } from './checksum';\nexport { sqlSteps } from './sql';\nexport { DOCUMENT_DEPTH_LIMIT, exceedsDepth, depthRefusal } from './depth';\nexport { StrataError } from './errors';\nexport type { StrataErrorCode } from './errors';\n\n// Authoring helper: a sequence, type-checked where it is written. Parsing\n// happens where it is applied (`prepare`), like every other artifact.\nexport const defineSequence = <const T extends Sequence>(sequence: T): T => sequence;\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createUpgrader } from './chunk-
|
|
1
|
+
export { createUpgrader } from './chunk-TWAEZHTB.js';
|
|
2
2
|
export { DocumentKindSchema, DocumentStepSchema, EMBED_PATH, KIND_NAME, KIND_REF, MIGRATION_REF, MigrationSchema, SEQUENCE_ID, SequenceSchema, SqlStepSchema, StepSchema, checksumOf, orderPending, planMigrations, prepare, refuseProblems } from './chunk-U5CPF4LQ.js';
|
|
3
3
|
export { StrataError } from './chunk-EGFF63GA.js';
|
|
4
4
|
|
package/dist/node/index.cjs
CHANGED
|
@@ -170,7 +170,7 @@ var createUpgrader = async (sequences, options) => {
|
|
|
170
170
|
if (tables.length > 0) {
|
|
171
171
|
throw new StrataError(
|
|
172
172
|
"WRONG_OWNER",
|
|
173
|
-
"Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`).",
|
|
173
|
+
"Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`). If one of them is a grammar, declare its `documents` \u2014 a sequence with no `documents` and no document step is read as owning tables.",
|
|
174
174
|
tables.map((s) => s.id)
|
|
175
175
|
);
|
|
176
176
|
}
|
|
@@ -185,6 +185,11 @@ var createUpgrader = async (sequences, options) => {
|
|
|
185
185
|
];
|
|
186
186
|
if (unknown.length > 0) throw new StrataError("UNKNOWN_KIND", "A document kind is named that no sequence declares.", unknown);
|
|
187
187
|
const stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));
|
|
188
|
+
const ownIds = new Set(grammars.map((s) => s.id));
|
|
189
|
+
const stampAfter = (given) => {
|
|
190
|
+
const others = Object.entries(given ?? {}).filter(([id]) => !ownIds.has(id));
|
|
191
|
+
return others.length === 0 ? stamp : { ...stamp, ...Object.fromEntries(others) };
|
|
192
|
+
};
|
|
188
193
|
const locate = (document, kind) => {
|
|
189
194
|
if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
|
|
190
195
|
const found = [];
|
|
@@ -213,7 +218,7 @@ var createUpgrader = async (sequences, options) => {
|
|
|
213
218
|
const upgrade = (document, { kind, stamp: given }) => {
|
|
214
219
|
if (!isRecord(document)) throw new StrataError("STEP_FAILED", `A ${kind} document must be a JSON object.`);
|
|
215
220
|
if (!kinds.has(kind)) throw new StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
|
|
216
|
-
if (!behind(given)) return { document, stamp, applied: [] };
|
|
221
|
+
if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };
|
|
217
222
|
const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));
|
|
218
223
|
const { pending, stuck } = orderPending(
|
|
219
224
|
grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),
|
|
@@ -250,7 +255,7 @@ var createUpgrader = async (sequences, options) => {
|
|
|
250
255
|
for (const step of migration.steps) if (step.kind === "document") runStep(migration, step.at, step.transform);
|
|
251
256
|
applied.push(migration.ref);
|
|
252
257
|
}
|
|
253
|
-
return { document: current, stamp, applied };
|
|
258
|
+
return { document: current, stamp: stampAfter(given), applied };
|
|
254
259
|
};
|
|
255
260
|
return { stamp, upgrade, locate, behind };
|
|
256
261
|
};
|
|
@@ -279,9 +284,12 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
|
|
|
279
284
|
if (isRecord2(a) && isRecord2(b)) {
|
|
280
285
|
for (const key of [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
|
|
281
286
|
const at = path === "" ? key : `${path}.${key}`;
|
|
287
|
+
const before = a[key];
|
|
288
|
+
const after = b[key];
|
|
282
289
|
if (!(key in a)) out.push(`+ ${at}`);
|
|
283
290
|
else if (!(key in b)) out.push(`- ${at}`);
|
|
284
|
-
else
|
|
291
|
+
else if (sets && key === "prefixItems" && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, out, limit, canon);
|
|
292
|
+
else diffLines(before, after, at, out, limit, canon, sets);
|
|
285
293
|
if (out.length >= limit) return;
|
|
286
294
|
}
|
|
287
295
|
return;
|
|
@@ -314,6 +322,14 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
|
|
|
314
322
|
}
|
|
315
323
|
out.push(`~ ${path || "(root)"}: ${JSON.stringify(a)?.slice(0, 60)} \u2192 ${JSON.stringify(b)?.slice(0, 60)}`);
|
|
316
324
|
};
|
|
325
|
+
var diffPositions = (a, b, path, out, limit, canon) => {
|
|
326
|
+
for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
|
|
327
|
+
if (out.length >= limit) return;
|
|
328
|
+
if (i >= a.length) out.push(`+ ${path}[${i}]`);
|
|
329
|
+
else if (i >= b.length) out.push(`- ${path}[${i}]`);
|
|
330
|
+
else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);
|
|
331
|
+
}
|
|
332
|
+
};
|
|
317
333
|
var diffJson = (a, b, limit = 20) => {
|
|
318
334
|
const out = [];
|
|
319
335
|
diffLines(a, b, "", out, limit, sortKeys, false);
|