@niscorp/strata 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/DESIGN.md +7 -3
  3. package/README.md +19 -4
  4. package/dist/check/index.cjs +23 -217
  5. package/dist/check/index.cjs.map +1 -1
  6. package/dist/check/index.js +2 -2
  7. package/dist/{chunk-MY3TGSV3.js → chunk-4BLHBVSC.js} +15 -4
  8. package/dist/chunk-4BLHBVSC.js.map +1 -0
  9. package/dist/{chunk-U5CPF4LQ.js → chunk-5KTXEN43.js} +3 -3
  10. package/dist/{chunk-U5CPF4LQ.js.map → chunk-5KTXEN43.js.map} +1 -1
  11. package/dist/{chunk-EGFF63GA.js → chunk-AKKWEXO2.js} +2 -2
  12. package/dist/{chunk-EGFF63GA.js.map → chunk-AKKWEXO2.js.map} +1 -1
  13. package/dist/chunk-ATHZ7HT5.cjs +18 -0
  14. package/dist/chunk-ATHZ7HT5.cjs.map +1 -0
  15. package/dist/chunk-CL5DF2IQ.cjs +192 -0
  16. package/dist/chunk-CL5DF2IQ.cjs.map +1 -0
  17. package/dist/chunk-IHYBGLNW.cjs +161 -0
  18. package/dist/chunk-IHYBGLNW.cjs.map +1 -0
  19. package/dist/chunk-KNBS3AJZ.cjs +223 -0
  20. package/dist/chunk-KNBS3AJZ.cjs.map +1 -0
  21. package/dist/{chunk-ICWKTTKN.js → chunk-OLDORFOQ.js} +12 -7
  22. package/dist/chunk-OLDORFOQ.js.map +1 -0
  23. package/dist/{chunk-HMT7HHFJ.js → chunk-WU3OJHVZ.js} +4 -4
  24. package/dist/{chunk-HMT7HHFJ.js.map → chunk-WU3OJHVZ.js.map} +1 -1
  25. package/dist/chunk-YXFEJJMC.cjs +136 -0
  26. package/dist/chunk-YXFEJJMC.cjs.map +1 -0
  27. package/dist/index.cjs +75 -325
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +1 -1
  30. package/dist/index.d.ts +1 -1
  31. package/dist/index.js +3 -3
  32. package/dist/node/index.cjs +14 -477
  33. package/dist/node/index.cjs.map +1 -1
  34. package/dist/node/index.js +5 -5
  35. package/dist/{plan-BEIlXVUt.d.cts → plan-CxuteSH1.d.cts} +2 -2
  36. package/dist/{plan-BAewc8DG.d.ts → plan-mFmdh0qT.d.ts} +2 -2
  37. package/dist/postgres/index.cjs +36 -206
  38. package/dist/postgres/index.cjs.map +1 -1
  39. package/dist/postgres/index.d.cts +7 -2
  40. package/dist/postgres/index.d.ts +7 -2
  41. package/dist/postgres/index.js +24 -12
  42. package/dist/postgres/index.js.map +1 -1
  43. package/dist/upgrade/index.cjs +19 -229
  44. package/dist/upgrade/index.cjs.map +1 -1
  45. package/dist/upgrade/index.js +3 -3
  46. package/package.json +3 -2
  47. package/dist/chunk-ICWKTTKN.js.map +0 -1
  48. package/dist/chunk-MY3TGSV3.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,88 @@
1
1
  # @niscorp/strata
2
2
 
3
+ ## 0.1.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 7f8d202: Under `require`, the entry points of nova, prism and strata share one copy of their code, as they always have under `import`.
8
+
9
+ The CommonJS build was not split, so every entry point carried its own copy of each class and of each React context. The ESM build is byte for byte what it was. Under `require`:
10
+ - an error from `@niscorp/strata/postgres`, `/check`, `/upgrade` or `/node` is an `instanceof` the `StrataError` that `@niscorp/strata` exports; one from `prismTransform` of `@niscorp/prism/migrations` is an `instanceof PrismError`; one from `<Nova.Layout>` is an `instanceof NovaError` and of its own class. None of them was.
11
+ - `upgradeStore` names the row it refused — `integration_actions (integration_id="…", action_id="…"): …`, with the upgrader's error as its `cause` — and so does a moss boot that meets a stored row it cannot read. Both gave the upgrader's sentence alone.
12
+ - a kit registered from `@niscorp/nova/adapters/react/components` renders under `<Nova.Shell>`. It threw `useShell must be used inside <NovaShellProvider>`.
13
+
14
+ **What to change:** nothing in an ESM app. A CommonJS app that had built on any of the above — a branch that ran because `instanceof` failed, a match on the whole text of an `upgradeStore` refusal — now sees what an ESM app sees. An app that loads both builds of one package in one process still has two copies of it.
15
+
16
+ - 2b5fd83: `migrate` takes a `guard` and a `dryRun`.
17
+
18
+ A host could run a table migration and could not ask anything of the result before it landed, or see what a run would do without doing it.
19
+
20
+ `guard(tx)` is asked inside the run's transaction, after the last pending step — when nothing was pending too. Every sentence it returns refuses the run with `DOES_NOT_FIT`, and nothing was applied. `dryRun` does all of it, guard included, then rolls it back: the report says what would be applied, and it takes the locks a real run takes.
21
+
22
+ **What to change:** nothing. A run given neither behaves exactly as before. `StrataErrorCode` gains one member, `DOES_NOT_FIT`.
23
+
24
+ ## 0.1.3
25
+
26
+ ### Patch Changes
27
+
28
+ - 18182d7: README corrections. `sqlSteps` cuts at each line that ends in `;`, full-line `--` comments excepted. It is not a SQL parser: a `;` that ends a line inside a string, a function body, a `/* */` comment or a trailing `--` comment cuts there too, and two statements on one line, or a `;` followed by a trailing comment, stay one step. The `compareSnapshot` example shows the lines it prints (`- required["id"]`, `+ required["key"]`). No code changed.
29
+
30
+ **What to change:** nothing.
31
+
32
+ - bd3184d: An upgrade keeps a document's stamp entries for grammars the upgrader was not given.
33
+
34
+ `upgrade` handed back the upgrader's own stamp, and `upgradeStore` wrote it over the row's. A row stamped `{ "acme.forms": 0, "acme.prices": 1 }`, upgraded by code that was given `acme.forms` only, was written back stamped `{ "acme.forms": 1 }`: its record of `acme.prices` was gone. Code that has that grammar then read the row as never migrated and ran `acme.prices/1` over it a second time — a price already in cents, multiplied again.
35
+
36
+ The stamp now handed back, and written, is the upgrader's own plus the document's entries for any grammar it was not given, as they were. Nothing new is refused, and nothing else is written differently: for a document whose stamp names only the upgrader's grammars, `upgrade` returns `upgrader.stamp` itself, as before. `upgrader.stamp`, `behind`, the lock file and every ledger checksum are untouched.
37
+
38
+ `TOO_NEW` is, as it always was, about the grammars the code was given — a stamp entry for one it was not given is neither ahead nor behind. The README, DESIGN and rule 19 of `@niscorp/nisc`'s `AGENTS.md` said "on any grammar"; they now say "on any grammar the code was given".
39
+
40
+ **What to change:** nothing.
41
+
42
+ - bab7b2c: `compareSnapshot` reads a tuple by position: swapped positions are a change.
43
+
44
+ Every array in a schema was compared as a set — right for a union's members, a `required` list, an `enum` — and that included a tuple's `prefixItems`, where position is the grammar. `z.tuple([z.string(), z.number()])` changed to `z.tuple([z.number(), z.string()])` read as `{ status: 'same' }` while a document valid before (`["a", 1]`) was no longer valid, so the gate asked for no migration.
45
+
46
+ A tuple's positions are now compared place by place: the swap above is `changed`, with `~ …prefixItems[0].type: "string" → "number"`, and a position added or removed is named (`+ …prefixItems[1]`). What sits inside a position is compared as before, a union there still as a set. A recorded snapshot is read as it was and none needs re-recording: nisc's own grammars, Prism's with its ten tuples among them, answer `same` as before.
47
+
48
+ **What to change:** nothing, unless a grammar of yours had a tuple's positions reordered at a version that was already recorded. That was a change the gate missed; it now says so, and the answer is the migration the change owed — append it, then record the new version.
49
+
50
+ - eef9cd9: The `WRONG_OWNER` refusal from `createUpgrader` says what to do when the sequence is a grammar: declare its `documents`.
51
+
52
+ strata tells a grammar from a table sequence by what the sequence declares: `documents`, or a document step. A kit that declares neither and has no migrations yet — or only empty markers, the migration an addition to a grammar is recorded with — reads as owning tables, and `createUpgrader` refuses it. The refusal named one way out, `migrate`, which for a kit is the wrong one: it records the kit's markers in a database's ledger.
53
+
54
+ Which sequences are refused has not changed, and neither has how a sequence is read. The message has a second sentence:
55
+ - before: ``Documents are upgraded by grammar sequences; these own tables and belong to a database's ledger (`migrate`).``
56
+ - now: ``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.``
57
+
58
+ The README states the rule, and its kit example declares `documents: {}`.
59
+
60
+ **What to change:** nothing in an app. Code or a stored expectation that compares this error's full message text needs the new text; `code` (`WRONG_OWNER`) and `details` are as they were.
61
+
62
+ ## 0.1.2
63
+
64
+ ### Patch Changes
65
+
66
+ - fe30458: Every package exports its `package.json`, so an app can say which version of a package it runs by reading it from the package:
67
+
68
+ ```ts
69
+ import prism from '@niscorp/prism/package.json' with { type: 'json' };
70
+ prism.version; // the version that is installed, not the range that asked for it
71
+ ```
72
+
73
+ Until now the `exports` map hid it, and the only way to the version was a path into `node_modules`. `check:packages` installs the tarballs and reads every package's version this way.
74
+
75
+ **What to change:** nothing. An app that read a version by path can read it by name.
76
+
77
+ - 1e6d55d: A pool's `query` and `transaction` are called on the pool, and a transaction's `query` on the transaction — never taken off the object first. A driver's own object has them as methods that need their receiver, and taken off they failed inside the driver, on a property nothing in nisc names:
78
+ - **strata** — `migrate` and `upgradeStore` over a `PGlite` threw `Cannot read properties of undefined (reading '_checkReady')`; `status` and `readLedger` did too, once a ledger existed. A pool whose `transaction` hands a checked-out `pg` client through as the transaction failed in `migrate` the same way.
79
+ - **moss** — `createTideStore` took `query` off the transaction. Over a pool that hands its client through, every transaction of the store failed inside the driver, and tide recorded the run as deferred: nothing threw, and the effect never ran.
80
+ - **vex** — `createPostgresAdapter` with a read limit set (`limitReads`) threw on a pool whose `transaction` is a method.
81
+
82
+ A `PGlite` now works as a pool as it is, and so does a `pg` wrapper that passes its client through. A pool built from closures (`createPglitePool`, a wrapper that builds its own `query`) behaves as before.
83
+
84
+ **What to change:** nothing.
85
+
3
86
  ## 0.1.1
4
87
 
5
88
  ### Patch Changes
package/DESIGN.md CHANGED
@@ -114,9 +114,13 @@ migration runs through the engine that runs endpoints, with the same guarantee
114
114
  that no code executes. That is what makes a third party's migration safe to run.
115
115
 
116
116
  **Refuse ahead, upgrade behind.** Strict grammars make every addition break
117
- older readers, so a document ahead of the code on any grammar is `TOO_NEW` — at
118
- boot a refusal to start, at intake "the host must be updated first", on a read
119
- path the one action left out with a sentence. The reader upgrades first.
117
+ older readers, so a document ahead of the code on any grammar the code was given
118
+ is `TOO_NEW` — at boot a refusal to start, at intake "the host must be updated
119
+ first", on a read path the one action left out with a sentence. The reader
120
+ upgrades first. A stamp entry for a grammar the code was not given says nothing
121
+ to it — the code cannot be ahead of or behind what it does not have — and an
122
+ upgrade keeps the entry as it was: it is the document's record for code that
123
+ does have that grammar, which would otherwise run its migrations a second time.
120
124
 
121
125
  **Not every table of documents is a store.** `vex_cache` holds DSL and compiled
122
126
  Prism IR, but its protected rows are re-seeded from source on every boot and its
package/README.md CHANGED
@@ -48,6 +48,10 @@ own tables, the sessions table, the vex cache — in one ledgered run at boot.
48
48
  with parameters) refuses a string carrying several. For a DDL file, use
49
49
  `sqlSteps(ddl)` — never split on every `;`: a comment containing one is cut
50
50
  in two and its tail becomes SQL (lyceum's schema would have failed at boot).
51
+ `sqlSteps` is not a SQL parser: a `;` that ends a line inside a string, a
52
+ function body, a `/* */` comment or a trailing `--` comment cuts there too,
53
+ and two statements on one line, or a `;` followed by a trailing comment, stay
54
+ one step. Write those as their own steps.
51
55
  - **A run is one transaction** under an advisory lock. A step throws, nothing
52
56
  from the run happened — Postgres DDL is transactional. Two processes booting
53
57
  at once serialize; the second finds the work done.
@@ -66,7 +70,7 @@ own tables, the sessions table, the vex cache — in one ledgered run at boot.
66
70
  | `prepare(sequences)` | Parses (Zod, at the boundary), numbers and checksums. Throws `INVALID_SEQUENCE`. |
67
71
  | `planMigrations(prepared, ledger)` | Pure: what is pending, in order, and every problem (`EDITED`, `TOO_NEW`, `UNKNOWN_DEPENDENCY`, `CYCLE`). |
68
72
  | `checksumOf(migration)` | SHA-256 over the steps (WebCrypto — Node ≥ 22 and every browser). |
69
- | `sqlSteps(ddl)` | A DDL file as one step per statement — splits only at a `;` that ends a line of SQL, never inside a comment. |
73
+ | `sqlSteps(ddl)` | A DDL file as one step per statement, for a file where every statement ends its line with `;`. Cuts at each line that ends in `;`, full-line `--` comments excepted. Not a SQL parser. |
70
74
  | `SequenceSchema`, `MigrationSchema`, `StepSchema` | The grammar, as Zod. |
71
75
  | `StrataError` | `code` + a sentence + `details`. |
72
76
 
@@ -74,7 +78,7 @@ own tables, the sessions table, the vex cache — in one ledgered run at boot.
74
78
 
75
79
  | | |
76
80
  |---|---|
77
- | `migrate(pool, sequences, { mode, table, schema })` | The run. `mode: 'apply'` (default) or `'verify'`. Returns `{ applied, plan }`. |
81
+ | `migrate(pool, sequences, { mode, guard, dryRun, table, schema })` | The run. `mode: 'apply'` (default) or `'verify'`. Returns `{ applied, plan }`. `guard(tx)` is asked inside the run, after the last pending step — when nothing was pending too: every sentence it returns refuses the run (`DOES_NOT_FIT`), and nothing was applied. `dryRun` does all of it, guard included, then rolls it back — the report says what would be applied, and it takes the locks a real run takes. |
78
82
  | `status(pool, sequences, options)` | The plan, read-only — creates nothing, not even the ledger. |
79
83
  | `readLedger(pool, options)` | The ledger's rows; empty for a database never migrated. |
80
84
  | `ledgerDdl(options)` | The ledger table's DDL — the one statement strata runs outside a ledger. |
@@ -111,8 +115,11 @@ export const NOVA_SEQUENCE = {
111
115
  };
112
116
 
113
117
  // An app's kit: Button's `label` prop is now `text` — one flat node at a time.
118
+ // `documents` is what says this sequence is a grammar; the kit has no kinds of
119
+ // its own (it rewrites nova's layouts), so it declares none.
114
120
  export const kit = {
115
121
  id: 'acme.kit',
122
+ documents: {},
116
123
  migrations: [{ description: 'Button: label → text', steps: [{ kind: 'document', at: 'nisc.nova/layout', transform: renameLabelPrismConfig }] }],
117
124
  };
118
125
 
@@ -125,6 +132,12 @@ const { document, stamp, applied } = upgrader.upgrade(storedAction, { kind: 'nis
125
132
  are never recorded in a ledger: documents travel (an add-on built on older
126
133
  code submits older documents), so their version travels with them. One
127
134
  sequence owns tables or documents, never both.
135
+ - **A grammar declares `documents`**, from its first release — `{}` if it has
136
+ no kinds of its own. That is how strata tells the two owners apart: a sequence
137
+ is a grammar when it declares `documents` or has a document step, and anything
138
+ else owns tables. A kit with no migrations yet, or with only empty markers,
139
+ and no `documents` therefore reads as owning tables, and `createUpgrader`
140
+ refuses it (`WRONG_OWNER`). Declare `documents`; do not hand it to `migrate`.
128
141
  - **The walker does the recursion.** Embedding paths use `key`, `*` (every
129
142
  value of a record) and `[]` (every item of an array) — kept apart because
130
143
  nova's `children` is a lone node or an array. Every document of a step's kind
@@ -134,7 +147,9 @@ const { document, stamp, applied } = upgrader.upgrade(storedAction, { kind: 'nis
134
147
  Under moss it is Prism's `evaluate`; a migration runs exactly like an endpoint.
135
148
  The source is `{ document, path }`.
136
149
  - **No stamp** (`{}`, `null`) reads as the start of every grammar. **Ahead of
137
- the code** on any grammar is refused, `TOO_NEW`: the reader upgrades first.
150
+ the code** on any grammar the code was given is refused, `TOO_NEW`: the reader
151
+ upgrades first. A stamp entry for a grammar the code was not given is neither
152
+ ahead nor behind: it is kept on the stamp as it was, for code that has it.
138
153
 
139
154
  | | |
140
155
  |---|---|
@@ -149,7 +164,7 @@ host keeps the files.
149
164
  | | |
150
165
  |---|---|
151
166
  | `snapshotOf(sequence, schemas)` | Each kind's JSON Schema, through the schema's own Standard JSON Schema hook (Zod ≥ 4.2, Valibot, ArkType), as the validator wrote it — keys sorted, nothing removed. `schemas` must cover exactly the grammar's kinds. |
152
- | `compareSnapshot(recorded, current)` | `same`, `missing`, or `changed` with short diff lines (`+ properties.retry`, `~ required[0]: "id" → "key"`). Changed at the same version = a migration is owed. Both sides are compared without prose (the `description` keyword — a field named `description` is grammar) and in one spelling (definitions inlined unless recursive, `allOf: [{ $ref }]` as `$ref`, a union of bare types as a type list), so a reworded `.describe()` or a validator's respelling is not a change. |
167
+ | `compareSnapshot(recorded, current)` | `same`, `missing`, or `changed` with short diff lines (`+ properties.retry`, `- required["id"]`, `+ required["key"]`). Changed at the same version = a migration is owed. Both sides are compared without prose (the `description` keyword — a field named `description` is grammar) and in one spelling (definitions inlined unless recursive, `allOf: [{ $ref }]` as `$ref`, a union of bare types as a type list), so a reworded `.describe()` or a validator's respelling is not a change. |
153
168
  | `snapshotText(snapshot)` | Stable file text: sorted keys. |
154
169
  | `checkCorpus(upgrader, schemas, documents)` | Every captured document, upgraded from its stamp, must pass its kind's current schema. |
155
170
 
@@ -1,223 +1,29 @@
1
1
  'use strict';
2
2
 
3
- // src/errors.ts
4
- var StrataError = class extends Error {
5
- code;
6
- details;
7
- constructor(code, message, details = [], options) {
8
- super(details.length > 0 ? `${message}
9
- ${details.map((d) => ` ${d}`).join("\n")}` : message, options);
10
- this.name = "StrataError";
11
- this.code = code;
12
- this.details = details;
13
- }
14
- };
3
+ var chunkKNBS3AJZ_cjs = require('../chunk-KNBS3AJZ.cjs');
4
+ require('../chunk-ATHZ7HT5.cjs');
15
5
 
16
- // src/check/index.ts
17
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18
- var byKey = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
19
- var sortKeys = (value) => {
20
- if (Array.isArray(value)) return value.map(sortKeys);
21
- if (!isRecord(value)) return value;
22
- return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));
23
- };
24
- var NAMED = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
25
- var DATA = /* @__PURE__ */ new Set(["const", "enum", "default", "examples"]);
26
- var normalize = (value) => {
27
- if (Array.isArray(value)) return value.map(normalize);
28
- if (!isRecord(value)) return value;
29
- return Object.fromEntries(
30
- Object.entries(value).filter(([key]) => key !== "description" && key !== "$schema").sort(byKey).map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)])
31
- );
32
- };
33
- var namedSchemas = (map, each) => Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));
34
- var snapshotOf = (sequence, schemas) => {
35
- const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);
36
- const given = Object.keys(schemas);
37
- const missing = declared.filter((k) => !given.includes(k));
38
- const extra = given.filter((k) => !declared.includes(k));
39
- if (missing.length > 0 || extra.length > 0) {
40
- throw new StrataError("UNKNOWN_KIND", `The schemas for ${sequence.id} do not match its kinds.`, [
41
- ...missing.map((k) => `no schema for ${k}`),
42
- ...extra.map((k) => `${k} is not a kind of ${sequence.id}`)
43
- ]);
44
- }
45
- const kinds = {};
46
- for (const kind of [...declared].sort()) {
47
- const schema = schemas[kind];
48
- if (schema !== void 0) kinds[kind] = sortKeys(schema["~standard"].jsonSchema.input({ target: "draft-2020-12" }));
49
- }
50
- return { sequence: sequence.id, version: sequence.migrations.length, kinds };
51
- };
52
- var snapshotText = (snapshot) => `${JSON.stringify(sortKeys(snapshot), null, 2)}
53
- `;
54
- var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
55
- if (out.length >= limit) return;
56
- if (JSON.stringify(a) === JSON.stringify(b)) return;
57
- if (isRecord(a) && isRecord(b)) {
58
- for (const key of [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
59
- const at = path === "" ? key : `${path}.${key}`;
60
- if (!(key in a)) out.push(`+ ${at}`);
61
- else if (!(key in b)) out.push(`- ${at}`);
62
- else diffLines(a[key], b[key], at, out, limit, canon, sets);
63
- if (out.length >= limit) return;
64
- }
65
- return;
66
- }
67
- if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {
68
- a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));
69
- return;
70
- }
71
- if (Array.isArray(a) && Array.isArray(b)) {
72
- const text = (v) => JSON.stringify(canon(v));
73
- const label = (v) => isRecord(v) && isRecord(v["properties"]) ? Object.keys(v["properties"]).join(",") : (text(v) ?? "").slice(0, 50);
74
- const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));
75
- const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));
76
- const byLabel = new Map(onlyB.map((y) => [label(y), y]));
77
- for (const x of onlyA) {
78
- const partner = byLabel.get(label(x));
79
- if (partner !== void 0) {
80
- diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);
81
- byLabel.delete(label(x));
82
- } else {
83
- out.push(`- ${path}[${label(x)}]`);
84
- }
85
- if (out.length >= limit) return;
86
- }
87
- for (const [name] of byLabel) {
88
- out.push(`+ ${path}[${name}]`);
89
- if (out.length >= limit) return;
90
- }
91
- return;
92
- }
93
- out.push(`~ ${path || "(root)"}: ${JSON.stringify(a)?.slice(0, 60)} \u2192 ${JSON.stringify(b)?.slice(0, 60)}`);
94
- };
95
- var REF_PREFIX = /^#\/(\$defs|definitions)\//;
96
- var respell = (value) => {
97
- let node = value;
98
- const anyOf = node["anyOf"];
99
- if (!("type" in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m["type"] === "string")) {
100
- const { anyOf: _union, ...rest } = node;
101
- node = { ...rest, type: anyOf.map((m) => isRecord(m) ? m["type"] : void 0) };
102
- }
103
- const type = node["type"];
104
- if (Array.isArray(type)) {
105
- const types = [...new Set(type.map(String))].sort();
106
- node = { ...node, type: types.length === 1 ? types[0] : types };
107
- }
108
- const allOf = node["allOf"];
109
- const only = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : void 0;
110
- if (!("$ref" in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only["$ref"] === "string") {
111
- const { allOf: _wrapper, ...rest } = node;
112
- node = { ...rest, $ref: only["$ref"] };
113
- }
114
- return node;
115
- };
116
- var schemaChildren = (node) => Object.entries(node).flatMap(
117
- ([key, child]) => key === "$ref" || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child]
118
- );
119
- var canonical = (recorded) => {
120
- const schema = normalize(recorded);
121
- if (!isRecord(schema)) return schema;
122
- const defs = {
123
- ...isRecord(schema["definitions"]) ? schema["definitions"] : {},
124
- ...isRecord(schema["$defs"]) ? schema["$defs"] : {}
125
- };
126
- const { $defs: _defs, definitions: _definitions, ...body } = schema;
127
- const target = (ref) => ref === "#" ? { key: "#", node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, "")] };
128
- const recursive = /* @__PURE__ */ new Set();
129
- const findCycles = (value, stack) => {
130
- if (Array.isArray(value)) {
131
- for (const item of value) findCycles(item, stack);
132
- return;
133
- }
134
- if (!isRecord(value)) return;
135
- const node = respell(value);
136
- for (const child of schemaChildren(node)) findCycles(child, stack);
137
- const ref = node["$ref"];
138
- if (typeof ref !== "string") return;
139
- const { key, node: next } = target(ref);
140
- if (stack.includes(key)) recursive.add(key);
141
- else findCycles(next, [...stack, key]);
142
- };
143
- findCycles(body, ["#"]);
144
- const names = /* @__PURE__ */ new Map();
145
- const named = {};
146
- const nameOf = (key, node) => {
147
- const known = names.get(key);
148
- if (known !== void 0) return known;
149
- const name = `d${names.size}`;
150
- names.set(key, name);
151
- named[name] = emit(node);
152
- return name;
153
- };
154
- const emit = (value) => {
155
- if (Array.isArray(value)) return value.map(emit);
156
- if (!isRecord(value)) return value;
157
- const node = respell(value);
158
- const rest = Object.fromEntries(
159
- Object.entries(node).filter(([key2]) => key2 !== "$ref").sort(byKey).map(([key2, child]) => [key2, NAMED.has(key2) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key2) ? child : emit(child)])
160
- );
161
- const ref = node["$ref"];
162
- if (typeof ref !== "string") return rest;
163
- const { key, node: next } = target(ref);
164
- const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);
165
- return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;
166
- };
167
- const root = recursive.has("#") ? { $ref: `#/$defs/${nameOf("#", body)}` } : emit(body);
168
- return Object.keys(named).length === 0 ? root : sortKeys({ ...isRecord(root) ? root : { allOf: [root] }, $defs: named });
169
- };
170
- var compareSnapshot = (recorded, current) => {
171
- if (recorded === void 0) return { status: "missing" };
172
- const changes = [];
173
- for (const kind of [.../* @__PURE__ */ new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {
174
- const lines = [];
175
- if (!(kind in recorded.kinds)) lines.push("+ (a new kind)");
176
- else if (!(kind in current.kinds)) lines.push("- (the kind is gone)");
177
- else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), "", lines, 12);
178
- if (lines.length > 0) changes.push({ kind, lines });
179
- }
180
- return changes.length === 0 ? { status: "same" } : { status: "changed", changes };
181
- };
182
- var issueText = (issue) => {
183
- const path = (issue.path ?? []).map((p) => typeof p === "object" ? String(p.key) : String(p)).join(".");
184
- return `${path === "" ? "" : `${path}: `}${issue.message}`;
185
- };
186
- var diffJson = (a, b, limit = 20) => {
187
- const out = [];
188
- diffLines(a, b, "", out, limit, sortKeys, false);
189
- return out;
190
- };
191
- var checkCorpus = async (upgrader, schemas, documents) => {
192
- const failures = [];
193
- let passed = 0;
194
- for (const doc of documents) {
195
- const schema = schemas[doc.kind];
196
- if (schema === void 0) {
197
- failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });
198
- continue;
199
- }
200
- let upgraded;
201
- try {
202
- upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;
203
- } catch (error) {
204
- failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split("\n")[0] ?? error.message : String(error) });
205
- continue;
206
- }
207
- const result = await schema["~standard"].validate(upgraded);
208
- if (result.issues !== void 0) {
209
- failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join("; ") });
210
- } else {
211
- passed += 1;
212
- }
213
- }
214
- return { passed, failures };
215
- };
216
6
 
217
- exports.checkCorpus = checkCorpus;
218
- exports.compareSnapshot = compareSnapshot;
219
- exports.diffJson = diffJson;
220
- exports.snapshotOf = snapshotOf;
221
- exports.snapshotText = snapshotText;
7
+
8
+ Object.defineProperty(exports, "checkCorpus", {
9
+ enumerable: true,
10
+ get: function () { return chunkKNBS3AJZ_cjs.checkCorpus; }
11
+ });
12
+ Object.defineProperty(exports, "compareSnapshot", {
13
+ enumerable: true,
14
+ get: function () { return chunkKNBS3AJZ_cjs.compareSnapshot; }
15
+ });
16
+ Object.defineProperty(exports, "diffJson", {
17
+ enumerable: true,
18
+ get: function () { return chunkKNBS3AJZ_cjs.diffJson; }
19
+ });
20
+ Object.defineProperty(exports, "snapshotOf", {
21
+ enumerable: true,
22
+ get: function () { return chunkKNBS3AJZ_cjs.snapshotOf; }
23
+ });
24
+ Object.defineProperty(exports, "snapshotText", {
25
+ enumerable: true,
26
+ get: function () { return chunkKNBS3AJZ_cjs.snapshotText; }
27
+ });
222
28
  //# sourceMappingURL=index.cjs.map
223
29
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors.ts","../../src/check/index.ts"],"names":["key"],"mappings":";;;AA0BO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAC5B,IAAA;AAAA,EACA,OAAA;AAAA,EAET,YAAY,IAAA,EAAuB,OAAA,EAAiB,OAAA,GAA6B,IAAI,OAAA,EAA+B;AAClH,IAAA,KAAA,CAAM,OAAA,CAAQ,MAAA,GAAS,CAAA,GAAI,CAAA,EAAG,OAAO;AAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,GAAK,SAAS,OAAO,CAAA;AACtG,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF,CAAA;;;ACKA,IAAM,QAAA,GAAW,CAAC,KAAA,KAChB,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAErE,IAAM,KAAA,GAAQ,CAAC,CAAC,CAAC,CAAA,EAAsB,CAAC,CAAC,CAAA,KAAkC,CAAA,GAAI,CAAA,GAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAA;AAIpG,IA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EAAO,GAAA,CAAI,KAAA,EAAO,CAAA,CAAE,QAAA;AAAA,IAClF,SAAS,KAAA,EAAO;AACd,MAAA,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,GAAA,CAAI,IAAI,IAAA,EAAM,GAAA,CAAI,IAAA,EAAM,MAAA,EAAQ,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,CAAE,CAAC,CAAA,IAAK,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAA,EAAG,CAAA;AAC5I,MAAA;AAAA,IACF;AACA,IAAA,MAAM,SAAS,MAAM,MAAA,CAAO,WAAW,CAAA,CAAE,SAAS,QAAQ,CAAA;AAC1D,IAAA,IAAI,MAAA,CAAO,WAAW,MAAA,EAAW;AAC/B,MAAA,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,GAAA,CAAI,IAAI,IAAA,EAAM,GAAA,CAAI,MAAM,MAAA,EAAQ,MAAA,CAAO,OAAO,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA,CAAE,GAAA,CAAI,SAAS,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA,EAAG,CAAA;AAAA,IAC3G,CAAA,MAAO;AACL,MAAA,MAAA,IAAU,CAAA;AAAA,IACZ;AAAA,EACF;AACA,EAAA,OAAO,EAAE,QAAQ,QAAA,EAAS;AAC5B","file":"index.cjs","sourcesContent":["// Every refusal strata makes, by name. The message is a sentence for a person;\n// the code is for the program that has to decide what to do about it.\nexport type StrataErrorCode =\n // A sequence failed its schema, or two sequences share an id.\n | 'INVALID_SEQUENCE'\n // An applied migration's steps no longer match what the code says it ran.\n | 'EDITED'\n // The database has migrations of a sequence this code does not know yet —\n // it was migrated by newer code.\n | 'TOO_NEW'\n // A `dependsOn` names a migration nobody provides and the ledger lacks.\n | 'UNKNOWN_DEPENDENCY'\n // Pending migrations wait on each other.\n | 'CYCLE'\n // Verify mode found work to do.\n | 'PENDING'\n // A step threw; the whole run was rolled back.\n | 'STEP_FAILED'\n // The pool cannot hold one connection for a transaction.\n | 'NO_TRANSACTION'\n // A document kind nobody declares — as the root being upgraded, a step's\n // `at`, or an embedding's target.\n | 'UNKNOWN_KIND'\n // A grammar sequence handed to the ledger, or a table sequence to upgrade().\n | 'WRONG_OWNER';\n\nexport class StrataError extends Error {\n readonly code: StrataErrorCode;\n readonly details: readonly string[];\n\n constructor(code: StrataErrorCode, message: string, details: readonly string[] = [], options?: { cause?: unknown }) {\n super(details.length > 0 ? `${message}\\n${details.map((d) => ` ${d}`).join('\\n')}` : message, options);\n this.name = 'StrataError';\n this.code = code;\n this.details = details;\n }\n}\n","import type { Sequence } from '../schema';\nimport type { Stamp, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/check — the gate a grammar change has to pass.\n//\n// Two questions, both mechanical:\n//\n// 1. SNAPSHOT — did a kind's schema change without the grammar gaining a\n// migration? Each kind's JSON Schema, taken through the schema's OWN\n// Standard JSON Schema hook, is recorded per grammar version. Same version,\n// different schema: something changed that older readers were never told.\n// Append a migration (an empty marker is enough for an addition — strict\n// readers still have to refuse the newer documents), then record the new\n// version.\n//\n// 2. CORPUS — does every real document ever captured, at the stamp it was\n// captured at, still upgrade to the current grammar and pass the current\n// strict schema? This is the judge: a snapshot only says something moved,\n// the corpus says whether old documents survive it. No JSON Schema diff\n// tool is trusted to decide compatibility.\n//\n// Pure: no files, no process. A host reads and writes snapshots where it keeps\n// them (nisc's own live in the repo's `strata/` directory).\n// ═══════════════════════════════════════════════════════════════\n\ntype Issue = { message: string; path?: readonly (PropertyKey | { key: PropertyKey })[] };\ntype StandardResult = { value: unknown; issues?: undefined } | { issues: readonly Issue[] };\n\n// Any validator implementing Standard Schema + Standard JSON Schema (Zod ≥ 4.2,\n// Valibot, ArkType). Structural: strata depends on none of them.\nexport type GrammarSchema = {\n '~standard': {\n validate: (value: unknown) => StandardResult | Promise<StandardResult>;\n jsonSchema: { input: (options: { target: string }) => Record<string, unknown> };\n };\n};\n\nexport type Snapshot = { sequence: string; version: number; kinds: Readonly<Record<string, unknown>> };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst byKey = ([a]: [string, unknown], [b]: [string, unknown]): number => (a < b ? -1 : a > b ? 1 : 0);\n\n// Sorted keys, nothing else — for documents, where every key (a `description`\n// too) is content, and for a snapshot file, which keeps what the validator wrote.\nconst sortKeys = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (!isRecord(value)) return value;\n return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));\n};\n\n// Where a schema's keys are NAMES, not keywords — a field called `description`\n// or an op called `$ref` is grammar — and where its values are instance data\n// rather than schemas.\nconst NAMED = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);\nconst DATA = new Set(['const', 'enum', 'default', 'examples']);\n\n// A schema without its prose: the `description` KEYWORD is documentation, and\n// rewording a `.describe()` must not demand a migration. `$schema` is the same\n// everywhere. Applied when comparing, never to what is recorded — so what the\n// gate ignores can change without touching a snapshot file.\nconst normalize = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(normalize);\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => key !== 'description' && key !== '$schema')\n .sort(byKey)\n .map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)]),\n );\n};\n\n// A name → schema map, each schema through `each`, the names untouched.\nconst namedSchemas = (map: Record<string, unknown>, each: (schema: unknown) => unknown): Record<string, unknown> =>\n Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));\n\n// The grammar as it stands: every kind it declares, as JSON Schema — as the\n// validator wrote it, keys sorted. `schemas` must cover exactly the sequence's\n// kinds — a kind without a schema cannot be checked, and a schema without a\n// kind belongs to some other grammar.\nexport const snapshotOf = (sequence: Sequence, schemas: Readonly<Record<string, GrammarSchema>>): Snapshot => {\n const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);\n const given = Object.keys(schemas);\n const missing = declared.filter((k) => !given.includes(k));\n const extra = given.filter((k) => !declared.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new StrataError('UNKNOWN_KIND', `The schemas for ${sequence.id} do not match its kinds.`, [\n ...missing.map((k) => `no schema for ${k}`),\n ...extra.map((k) => `${k} is not a kind of ${sequence.id}`),\n ]);\n }\n const kinds: Record<string, unknown> = {};\n for (const kind of [...declared].sort()) {\n const schema = schemas[kind];\n if (schema !== undefined) kinds[kind] = sortKeys(schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }));\n }\n return { sequence: sequence.id, version: sequence.migrations.length, kinds };\n};\n\n// Stable text for a snapshot file: sorted keys, two-space indent, newline.\nexport const snapshotText = (snapshot: Snapshot): string => `${JSON.stringify(sortKeys(snapshot), null, 2)}\n`;\n\n// Schema arrays are compared as sets (`sets`); a document's arrays by position —\n// `layout.children[1]` is how a person finds the thing that changed.\nconst diffLines = (a: unknown, b: unknown, path: string, out: string[], limit: number, canon: (v: unknown) => unknown = normalize, sets = true): void => {\n if (out.length >= limit) return;\n if (JSON.stringify(a) === JSON.stringify(b)) return;\n if (isRecord(a) && isRecord(b)) {\n for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {\n const at = path === '' ? key : `${path}.${key}`;\n if (!(key in a)) out.push(`+ ${at}`);\n else if (!(key in b)) out.push(`- ${at}`);\n else diffLines(a[key], b[key], at, out, limit, canon, sets);\n if (out.length >= limit) return;\n }\n return;\n }\n if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {\n a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));\n return;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n // Schema arrays are SETS more often than sequences — a union's `anyOf`, a\n // `required` list, an `enum` — and one added branch shifts every index\n // after it. Match elements by what they describe (an object schema by its\n // property names — for Prism's union, the op), report the ones on one side\n // only, and diff the ones that changed in place.\n const text = (v: unknown): string => JSON.stringify(canon(v));\n const label = (v: unknown): string =>\n isRecord(v) && isRecord(v['properties']) ? Object.keys(v['properties']).join(',') : (text(v) ?? '').slice(0, 50);\n const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));\n const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));\n const byLabel = new Map(onlyB.map((y) => [label(y), y]));\n for (const x of onlyA) {\n const partner = byLabel.get(label(x));\n if (partner !== undefined) {\n diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);\n byLabel.delete(label(x));\n } else {\n out.push(`- ${path}[${label(x)}]`);\n }\n if (out.length >= limit) return;\n }\n for (const [name] of byLabel) {\n out.push(`+ ${path}[${name}]`);\n if (out.length >= limit) return;\n }\n return;\n }\n out.push(`~ ${path || '(root)'}: ${JSON.stringify(a)?.slice(0, 60)} → ${JSON.stringify(b)?.slice(0, 60)}`);\n};\n\n// ── canonical form ──────────────────────────────────────────────\n//\n// A snapshot records what the validator WROTE, and validators spell one schema\n// many ways: they name and inline definitions as they please (zod numbers them\n// in visit order, and 4.3 and 4.4 visit differently), write a described\n// reference as `allOf: [{ $ref }]` or as `$ref`, and a union of bare types as\n// `anyOf: [{ type }, …]` or `type: […]`. None of that is the grammar, so a\n// comparison reads both sides in one spelling: every definition inlined unless\n// it is recursive, the recursive ones renamed by first use, and every schema\n// identity above written one way. A snapshot FILE stays what the validator\n// wrote — only the comparison is canonical.\n\nconst REF_PREFIX = /^#\\/(\\$defs|definitions)\\//;\n\n// One spelling for the equivalences the node itself can show.\nconst respell = (value: Record<string, unknown>): Record<string, unknown> => {\n let node = value;\n const anyOf = node['anyOf'];\n if (!('type' in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m['type'] === 'string')) {\n const { anyOf: _union, ...rest } = node;\n node = { ...rest, type: anyOf.map((m) => (isRecord(m) ? m['type'] : undefined)) };\n }\n const type = node['type'];\n if (Array.isArray(type)) {\n const types = [...new Set(type.map(String))].sort();\n node = { ...node, type: types.length === 1 ? types[0] : types };\n }\n const allOf = node['allOf'];\n const only: unknown = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : undefined;\n if (!('$ref' in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only['$ref'] === 'string') {\n const { allOf: _wrapper, ...rest } = node;\n node = { ...rest, $ref: only['$ref'] };\n }\n return node;\n};\n\n// A schema node's own children — keyword values, and each schema of a name\n// map — but never the names, and never instance data.\nconst schemaChildren = (node: Record<string, unknown>): unknown[] =>\n Object.entries(node).flatMap(([key, child]) =>\n key === '$ref' || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child],\n );\n\nconst canonical = (recorded: unknown): unknown => {\n const schema = normalize(recorded);\n if (!isRecord(schema)) return schema;\n const defs: Record<string, unknown> = {\n ...(isRecord(schema['definitions']) ? schema['definitions'] : {}),\n ...(isRecord(schema['$defs']) ? schema['$defs'] : {}),\n };\n const { $defs: _defs, definitions: _definitions, ...body } = schema;\n const target = (ref: string): { key: string; node: unknown } =>\n ref === '#' ? { key: '#', node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, '')] };\n\n // Which targets are reached from inside their own expansion: those, and\n // only those, stay definitions.\n const recursive = new Set<string>();\n const findCycles = (value: unknown, stack: readonly string[]): void => {\n if (Array.isArray(value)) {\n for (const item of value) findCycles(item, stack);\n return;\n }\n if (!isRecord(value)) return;\n const node = respell(value);\n for (const child of schemaChildren(node)) findCycles(child, stack);\n const ref = node['$ref'];\n if (typeof ref !== 'string') return;\n const { key, node: next } = target(ref);\n if (stack.includes(key)) recursive.add(key);\n else findCycles(next, [...stack, key]);\n };\n findCycles(body, ['#']);\n\n const names = new Map<string, string>();\n const named: Record<string, unknown> = {};\n const nameOf = (key: string, node: unknown): string => {\n const known = names.get(key);\n if (known !== undefined) return known;\n const name = `d${names.size}`;\n names.set(key, name);\n named[name] = emit(node);\n return name;\n };\n const emit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(emit);\n if (!isRecord(value)) return value;\n const node = respell(value);\n const rest: Record<string, unknown> = Object.fromEntries(\n Object.entries(node)\n .filter(([key]) => key !== '$ref')\n .sort(byKey)\n .map(([key, child]) => [key, NAMED.has(key) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key) ? child : emit(child)]),\n );\n const ref = node['$ref'];\n if (typeof ref !== 'string') return rest;\n const { key, node: next } = target(ref);\n const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);\n return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;\n };\n\n const root = recursive.has('#') ? { $ref: `#/$defs/${nameOf('#', body)}` } : emit(body);\n return Object.keys(named).length === 0 ? root : sortKeys({ ...(isRecord(root) ? root : { allOf: [root] }), $defs: named });\n};\n\nexport type SnapshotComparison =\n | { status: 'same' }\n | { status: 'missing' }\n | { status: 'changed'; changes: readonly { kind: string; lines: readonly string[] }[] };\n\n// `recorded` is the snapshot kept for the grammar's CURRENT version (or\n// undefined if none was kept). Changed means: a migration is owed. Both sides\n// are read in canonical form, so a validator's respelling is not a change.\nexport const compareSnapshot = (recorded: Snapshot | undefined, current: Snapshot): SnapshotComparison => {\n if (recorded === undefined) return { status: 'missing' };\n const changes: { kind: string; lines: string[] }[] = [];\n for (const kind of [...new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {\n const lines: string[] = [];\n if (!(kind in recorded.kinds)) lines.push('+ (a new kind)');\n else if (!(kind in current.kinds)) lines.push('- (the kind is gone)');\n else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), '', lines, 12);\n if (lines.length > 0) changes.push({ kind, lines });\n }\n return changes.length === 0 ? { status: 'same' } : { status: 'changed', changes };\n};\n\n// ── the corpus ──────────────────────────────────────────────────\n\nexport type CorpusDocument = { id: string; kind: string; stamp: Stamp; document: unknown };\nexport type CorpusFailure = { id: string; kind: string; reason: string };\nexport type CorpusReport = { passed: number; failures: readonly CorpusFailure[] };\n\nconst issueText = (issue: Issue): string => {\n const path = (issue.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return `${path === '' ? '' : `${path}: `}${issue.message}`;\n};\n\n// What differs between two JSON values, as short lines (`+ a.b`, `- c`,\n// `~ d: 1 → 2`) — for a report a person or an agent acts on.\nexport const diffJson = (a: unknown, b: unknown, limit = 20): string[] => {\n const out: string[] = [];\n diffLines(a, b, '', out, limit, sortKeys, false);\n return out;\n};\n\n// Every document, upgraded from its stamp, must pass the current schema of its kind.\nexport const checkCorpus = async (\n upgrader: Upgrader,\n schemas: Readonly<Record<string, GrammarSchema>>,\n documents: readonly CorpusDocument[],\n): Promise<CorpusReport> => {\n const failures: CorpusFailure[] = [];\n let passed = 0;\n for (const doc of documents) {\n const schema = schemas[doc.kind];\n if (schema === undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });\n continue;\n }\n let upgraded: unknown;\n try {\n upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;\n } catch (error) {\n failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split('\\n')[0] ?? error.message : String(error) });\n continue;\n }\n const result = await schema['~standard'].validate(upgraded);\n if (result.issues !== undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join('; ') });\n } else {\n passed += 1;\n }\n }\n return { passed, failures };\n};\n"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.cjs"}
@@ -1,4 +1,4 @@
1
- export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText } from '../chunk-MY3TGSV3.js';
2
- import '../chunk-EGFF63GA.js';
1
+ export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText } from '../chunk-4BLHBVSC.js';
2
+ import '../chunk-AKKWEXO2.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { StrataError } from './chunk-EGFF63GA.js';
1
+ import { StrataError } from './chunk-AKKWEXO2.js';
2
2
 
3
3
  // src/check/index.ts
4
4
  var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -44,9 +44,12 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
44
44
  if (isRecord(a) && isRecord(b)) {
45
45
  for (const key of [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
46
46
  const at = path === "" ? key : `${path}.${key}`;
47
+ const before = a[key];
48
+ const after = b[key];
47
49
  if (!(key in a)) out.push(`+ ${at}`);
48
50
  else if (!(key in b)) out.push(`- ${at}`);
49
- else diffLines(a[key], b[key], at, out, limit, canon, sets);
51
+ else if (sets && key === "prefixItems" && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, out, limit, canon);
52
+ else diffLines(before, after, at, out, limit, canon, sets);
50
53
  if (out.length >= limit) return;
51
54
  }
52
55
  return;
@@ -79,6 +82,14 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
79
82
  }
80
83
  out.push(`~ ${path || "(root)"}: ${JSON.stringify(a)?.slice(0, 60)} \u2192 ${JSON.stringify(b)?.slice(0, 60)}`);
81
84
  };
85
+ var diffPositions = (a, b, path, out, limit, canon) => {
86
+ for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
87
+ if (out.length >= limit) return;
88
+ if (i >= a.length) out.push(`+ ${path}[${i}]`);
89
+ else if (i >= b.length) out.push(`- ${path}[${i}]`);
90
+ else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);
91
+ }
92
+ };
82
93
  var REF_PREFIX = /^#\/(\$defs|definitions)\//;
83
94
  var respell = (value) => {
84
95
  let node = value;
@@ -202,5 +213,5 @@ var checkCorpus = async (upgrader, schemas, documents) => {
202
213
  };
203
214
 
204
215
  export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText };
205
- //# sourceMappingURL=chunk-MY3TGSV3.js.map
206
- //# sourceMappingURL=chunk-MY3TGSV3.js.map
216
+ //# sourceMappingURL=chunk-4BLHBVSC.js.map
217
+ //# sourceMappingURL=chunk-4BLHBVSC.js.map