@niscorp/strata 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/DESIGN.md +10 -3
  3. package/README.md +52 -12
  4. package/dist/check/index.cjs +6 -6
  5. package/dist/check/index.js +1 -1
  6. package/dist/{chunk-SH6BBA2X.js → chunk-2G3DFR6P.js} +13 -11
  7. package/dist/chunk-2G3DFR6P.js.map +1 -0
  8. package/dist/{chunk-FSEUYRLN.cjs → chunk-FMXFHYU2.cjs} +15 -6
  9. package/dist/chunk-FMXFHYU2.cjs.map +1 -0
  10. package/dist/{chunk-SYU7NKZR.cjs → chunk-HTW4IEBC.cjs} +13 -11
  11. package/dist/chunk-HTW4IEBC.cjs.map +1 -0
  12. package/dist/{chunk-564JCO6Q.cjs → chunk-I2CR5CBI.cjs} +17 -13
  13. package/dist/chunk-I2CR5CBI.cjs.map +1 -0
  14. package/dist/{chunk-FNMGVPSA.js → chunk-LJAB5G5Y.js} +13 -4
  15. package/dist/chunk-LJAB5G5Y.js.map +1 -0
  16. package/dist/{chunk-DGS4XJQQ.js → chunk-QDZYRBRP.js} +14 -11
  17. package/dist/chunk-QDZYRBRP.js.map +1 -0
  18. package/dist/{chunk-KYNER7UU.cjs → chunk-SJNHLIKR.cjs} +4 -3
  19. package/dist/chunk-SJNHLIKR.cjs.map +1 -0
  20. package/dist/{chunk-PAMQMFBK.js → chunk-YCQ6LS7X.js} +4 -3
  21. package/dist/chunk-YCQ6LS7X.js.map +1 -0
  22. package/dist/index.cjs +19 -19
  23. package/dist/index.js +2 -2
  24. package/dist/node/index.cjs +178 -89
  25. package/dist/node/index.cjs.map +1 -1
  26. package/dist/node/index.js +180 -91
  27. package/dist/node/index.js.map +1 -1
  28. package/dist/postgres/index.cjs +26 -11
  29. package/dist/postgres/index.cjs.map +1 -1
  30. package/dist/postgres/index.d.cts +1 -0
  31. package/dist/postgres/index.d.ts +1 -0
  32. package/dist/postgres/index.js +20 -5
  33. package/dist/postgres/index.js.map +1 -1
  34. package/dist/upgrade/index.cjs +6 -6
  35. package/dist/upgrade/index.js +2 -2
  36. package/package.json +1 -1
  37. package/dist/chunk-564JCO6Q.cjs.map +0 -1
  38. package/dist/chunk-DGS4XJQQ.js.map +0 -1
  39. package/dist/chunk-FNMGVPSA.js.map +0 -1
  40. package/dist/chunk-FSEUYRLN.cjs.map +0 -1
  41. package/dist/chunk-KYNER7UU.cjs.map +0 -1
  42. package/dist/chunk-PAMQMFBK.js.map +0 -1
  43. package/dist/chunk-SH6BBA2X.js.map +0 -1
  44. package/dist/chunk-SYU7NKZR.cjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # @niscorp/strata
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5c52ef5: BREAKING — approved by moccadroid (owner), 2026-11-22: nothing unless an app stores documents whose stamp has an entry, for a grammar it upgrades, that is not a number (`{ "acme.kit": "v0" }`), or keeps stamps in a column that is not jsonb. `upgrader.upgrade` and `upgrader.behind` now throw `INVALID_SEQUENCE` for such an entry, where `upgrade` returned the document unmigrated and stamped current; `upgradeStore` leaves such rows as they are and names them in a new `unread` list on its report, where it skipped them silently (jsonb) or ran every migration over them again (a `text` column).
8
+
9
+ A stamp entry is read with `Number`, as the comparisons always read it, so digits in a string and `null` read as before. An entry for a grammar the upgrader was given that reads as no number is refused with `INVALID_SEQUENCE`, naming the grammar and the entry.
10
+
11
+ `upgradeStore` still locks every row in one transaction, but reads only the keys and stamps under the lock, and then each behind row's document by its key, one at a time: a store whose rows are all current loads no document. A row it cannot read — a stamp that is neither null nor a JSON object, an entry for a given grammar that is no number, or a key the driver does not hand back exactly as stored (a `timestamptz` with microseconds) — is left as it is and named in `StoreReport.unread` (`id="e"`), present only when there is one; the pass goes on. `total` is still every row of the table.
12
+
13
+ - 66eb934: BREAKING — approved by moccadroid (owner), 2026-11-22: nothing unless an app runs `strata upgrade` with a `workDir` in which it keeps a `REPORT.md` or `plan.json` of its own (upgrade now exits 1 and leaves it, where it replaced and later deleted it), or relied on `strata verify` accepting a `plan.json` whose `from` differs from the committed `strata.lock.json` (it now refuses: plan again).
14
+
15
+ In a `workDir` the host names, strata treats a `REPORT.md` as its own only when it begins with `# strata upgrade` (a byte-order mark aside), and a `plan.json` only when it has a plan's shape. Given one that is not, `upgrade` leaves it as it is and exits 1 with "… is not one strata wrote — it is left as it is. Move it, or give strata a workDir of its own.", and `upgrade` and `verify` never remove it. In the default `.strata/upgrade`, which is strata's own, its files are replaced as before.
16
+
17
+ `verify` refuses a plan made from a lock other than the committed one, and so checks the untouched artifacts from the lock: an edited `plan.json` can no longer move the lock with the source never migrated. It compares stamps grammar by grammar, so grammars given in another order no longer refuse a valid plan. Two artifact ids that clean to one file name (`a/b`, `a_b`) each get an expected file of their own (`a_b.json`, `a_b~2.json`), where the second overwrote the first.
18
+
19
+ ### Patch Changes
20
+
21
+ - 61b15e4: `prepare` refuses a sequence that is `null` with `INVALID_SEQUENCE`, as it refuses any sequence that does not parse, instead of throwing a `TypeError`.
22
+
23
+ The README says that a line beginning with `--` is left out of a migration's checksum even inside a string literal or a dollar-quoted body, so an edit to such a line is not caught.
24
+
25
+ The README lists what `INVALID_SEQUENCE` is raised for, and where.
26
+
27
+ The README says that a statement Postgres will not run inside a transaction, such as `CREATE INDEX CONCURRENTLY`, always fails its run with `STEP_FAILED`.
28
+
29
+ - 7e8f6d4: `strata verify` fails, and leaves the lock where it is, when an edited artifact matches its migrated JSON but does not pass its kind's current schema.
30
+
31
+ `strata upgrade` and `strata verify` remove only the files a plan wrote (`plan.json`, `REPORT.md`, `expected/`), and a directory only once it is empty: a `workDir` that is the project itself, or lies outside it, no longer has its contents deleted, and `verify` keeps anything else in `.strata`.
32
+
33
+ The README says what to do when a migration renames the key a kind is embedded under: keep the old path in `embeds` beside the new one.
34
+
35
+ `strata.lock.json` is refused (`INVALID_SEQUENCE`, as for a lock that is not an object) when a grammar's entry is not a whole number of migrations, written as a number or as digits: `"x"`, `""`, `-1`, `null`, `true` and `1.5` no longer pass as current or re-run migrations.
36
+
37
+ ## 0.1.9
38
+
39
+ ### Patch Changes
40
+
41
+ - 2a44642: The docs say a run with nothing pending ends at its first read only without a `guard` or `dryRun`, that a pool without `transaction` is refused for those too, and that moss's boot now checks its sequences rather than running them.
42
+
43
+ **What to change:** nothing. Documentation only.
44
+
3
45
  ## 0.1.8
4
46
 
5
47
  ### Patch Changes
package/DESIGN.md CHANGED
@@ -43,7 +43,7 @@ production boot can require that a deploy step migrated first.
43
43
 
44
44
  **Read first, then one transaction, one lock.** A run reads the ledger before
45
45
  anything else; with problems it refuses, in verify mode or with nothing pending
46
- it ends there — a read that a role without DDL rights can make. Otherwise it
46
+ and no guard or dry run it ends there — a read that a role without DDL rights can make. Otherwise it
47
47
  opens one transaction, sets its own statement timeout, takes
48
48
  `pg_advisory_xact_lock` on the ledger's name, sets its lock timeout, creates
49
49
  the ledger if needed, reads it again, plans and applies. Postgres DDL is
@@ -71,7 +71,10 @@ caught in CI rather than by a refusing production boot.
71
71
  moss's server now runs `nisc.moss` (integrations, their actions, the generation
72
72
  pointer), `nisc.moss.sessions` (when the deployment uses moss's credential) and
73
73
  the vex cache's sequence in one run, **before** introspection — as the tables
74
- it replaced were. Two consequences, named rather than discovered later:
74
+ it replaced were. (Since then that run only checks them, refusing the boot
75
+ while anything is pending, unless the runtime sets `migrations: 'apply'`;
76
+ `nisc migrate` applies them.) Two consequences, named rather than discovered
77
+ later:
75
78
 
76
79
  - The generation table used to be created *after* introspection; it is now
77
80
  created before, and `strata_ledger` is a new table. Both enter the
@@ -88,7 +91,7 @@ it replaced were. Two consequences, named rather than discovered later:
88
91
  `initIntegrations` and `initSessions` have gone from what moss exports: the
89
92
  integration tables are part of `MOSS_SEQUENCE`, and the sessions table is
90
93
  made where a deployment keeps moss's stored sessions (`session:
91
- 'sessions'`); `createServer` and `migrateTables` run both. The other two
94
+ 'sessions'`); `migrateTables` applies both and `createServer` checks them. The other two
92
95
  are as they were, and the tide store is tide's own,
93
96
  `@niscorp/tide/postgres`.)
94
97
 
@@ -133,6 +136,10 @@ upgrades first. A stamp entry for a grammar the code was not given says nothing
133
136
  to it — the code cannot be ahead of or behind what it does not have — and an
134
137
  upgrade keeps the entry as it was: it is the document's record for code that
135
138
  does have that grammar, which would otherwise run its migrations a second time.
139
+ **⟲** An entry was read leniently: `"v0"` compared as neither behind nor ahead, so the
140
+ document came back unmigrated and stamped current, and a `text` stamp column read as no
141
+ stamp, so every migration ran again. An entry that is no number is now refused; a store
142
+ row strata cannot read is left as it is and named in the report.
136
143
 
137
144
  **Not every table of documents is a store.** `vex_cache` holds DSL and compiled
138
145
  Prism IR, but its protected rows are re-seeded from source on every boot and its
package/README.md CHANGED
@@ -44,7 +44,9 @@ ledgered run, and the server checks them at boot.
44
44
  ledger; change them and every database that ran it refuses to boot
45
45
  (`EDITED`). Append a new migration instead. Descriptions, `dependsOn` and
46
46
  full-line `--` comments are not part of the checksum — rewording is not
47
- editing.
47
+ editing. A line that begins with `--`, after any spaces, is left out even inside a string
48
+ literal or a dollar-quoted body, so an edit to such a line is not caught:
49
+ keep text like that off the start of a line, or in a migration of its own.
48
50
  - **One statement per step.** A driver that prepares statements (PGlite, `pg`
49
51
  with parameters) refuses a string carrying several. For a DDL file, use
50
52
  `sqlSteps(ddl)` — never split on every `;`: a comment containing one is cut
@@ -54,11 +56,15 @@ ledgered run, and the server checks them at boot.
54
56
  and two statements on one line, or a `;` followed by a trailing comment, stay
55
57
  one step. Write those as their own steps.
56
58
  - **A run reads before it writes.** The ledger is read first; a database with
57
- nothing pending is answered from that read — no lock, no DDL, no transaction —
58
- so an app whose database role cannot change tables can still check them.
59
+ nothing pending, run without `guard` or `dryRun`, is answered from that read
60
+ — no lock, no DDL, no transaction — so an app whose database role cannot
61
+ change tables can still check them.
59
62
  - **A run is one transaction** under an advisory lock. A step throws, nothing
60
63
  from the run happened — Postgres DDL is transactional. Two processes migrating
61
- at once serialize; the second finds the work done.
64
+ at once serialize; the second finds the work done. A statement Postgres will
65
+ not run inside a transaction (`CREATE INDEX CONCURRENTLY`) always
66
+ fails its run with `STEP_FAILED` ("cannot run inside a transaction block"):
67
+ write it without `CONCURRENTLY`, or run it outside strata.
62
68
  - **A run sets its own timeouts**, for its transaction only: a statement
63
69
  timeout (1 hour) that also bounds the wait for another run, then a lock
64
70
  timeout (10 s) so a step queued behind a busy table gives up instead of
@@ -102,8 +108,8 @@ ledgered run, and the server checks them at boot.
102
108
 
103
109
  The pool is structural — `{ query, transaction }`, the shape vex's PGlite pool
104
110
  and a wrapped `pg` pool already have. A pool without `transaction` is refused
105
- (`NO_TRANSACTION`) when it has something to apply: a run must land whole or
106
- not at all. `query` and
111
+ (`NO_TRANSACTION`) when it has something to apply, or a `guard` or `dryRun`:
112
+ a run must land whole or not at all. `query` and
107
113
  `transaction` are called on the object that has them, so a driver's own object
108
114
  whose methods reach for `this` — a PGlite, a `pg` client handed through as the
109
115
  transaction — works as it is.
@@ -182,6 +188,13 @@ const { document, stamp, applied } = upgrader.upgrade(storedAction, { kind: 'nis
182
188
  nova's `children` is a lone node or an array. Every document of a step's kind
183
189
  is found at any depth and rewritten on its own, deepest first; a transform
184
190
  only ever sees one node.
191
+ - **Embedding paths have no version.** Every migration finds nested documents
192
+ through the paths `embeds` declares now, whatever the document's stamp. A
193
+ migration that renames the key a kind is embedded under (`children` →
194
+ `items`) therefore keeps the old path in `embeds` beside the new one
195
+ (`{ 'children[]': …, 'items[]': … }`), for good: with the new path alone, the
196
+ nested documents of a document written before the rename are not found, are
197
+ not migrated, and are stamped current with their parent.
185
198
  - **The transform is injected** — `(config, source) => unknown`, nova's socket.
186
199
  Under moss it is Prism's `evaluate`; a migration runs exactly like an endpoint.
187
200
  The source is `{ document, path }`.
@@ -189,13 +202,17 @@ const { document, stamp, applied } = upgrader.upgrade(storedAction, { kind: 'nis
189
202
  the code** on any grammar the code was given is refused, `TOO_NEW`: the reader
190
203
  upgrades first. A stamp entry for a grammar the code was not given is neither
191
204
  ahead nor behind: it is kept on the stamp as it was, for code that has it.
205
+ - **An entry is a number of migrations.** It is read with `Number`, so digits
206
+ in a string and `null` (none) read too. An entry for a grammar the code was
207
+ given that reads as no number (`"v0"`) is refused, `INVALID_SEQUENCE`: read
208
+ as current, the document would come back unmigrated and stamped current.
192
209
 
193
210
  | | |
194
211
  |---|---|
195
212
  | `createUpgrader(grammars, { transform })` | `{ stamp, upgrade, locate, behind }` — the stamp a document written now carries; upgrade one; every document inside one, by kind; is a stamp behind (throws if ahead). A kind no sequence given declares is refused (`UNKNOWN_KIND`): a step's `at` or an embedding's target when the upgrader is created, the `kind` passed to `upgrade` or `locate` when it is called. |
196
213
  | `upgrader.upgrade(document, { kind, stamp })` | Returns `{ document, stamp, applied }`: `stamp` is what to store with the document, `applied` the refs of the migrations that ran, in order — empty when the document was already current. |
197
214
  | `upgrader.locate(document, kind)` | Given the root's kind, `{ path, kind, value }` for the root itself and every document embedded in it; `path` is the keys and indexes from the root. |
198
- | `upgradeStore(pool, store, upgrader)` | `@niscorp/strata/postgres`. Rewrites every row of a table holding documents that is behind, in one transaction; a row from newer code refuses the pass. `store` is `{ table, schema?, column, stamp, kind, key }`: `column` and `stamp` name the jsonb columns holding the document and its stamp, `kind` is the kind of every document in the store (`"nisc.nova/action"`), `key` lists the columns that identify a row. Returns `{ total, upgraded, applied }`: rows read, rows that were behind and rewritten, and per migration ref the number of rows it was applied to. |
215
+ | `upgradeStore(pool, store, upgrader)` | `@niscorp/strata/postgres`. Rewrites every row of a table of documents that is behind, in one transaction; a row from newer code refuses the pass. It locks every row and reads each one's key and stamp, then reads a behind row's document by its key, one at a time: a store whose rows are all current loads no document. `store` is `{ table, schema?, column, stamp, kind, key }`: `column` and `stamp` name the jsonb columns with the document and its stamp, `kind` is the kind of every document in the store (`"nisc.nova/action"`), `key` lists the columns that identify a row. Returns `{ total, upgraded, applied, unread? }`: rows read, rows that were behind and rewritten, per migration ref the number of rows it was applied to, and — only when there are any — the rows it could not read and left as they are, each named by its key (`id="e"`): a stamp that is neither null nor a JSON object (a `text` column), an entry for a given grammar that is no number, or a key the driver does not hand back exactly as stored (a `timestamptz` with microseconds). |
199
216
 
200
217
  ## The check
201
218
 
@@ -232,22 +249,45 @@ pnpm strata upgrade # .strata/upgrade/: expected JSON + REPORT.md (file
232
249
  pnpm strata verify # the edited source must equal it; then strata.lock.json moves
233
250
  ```
234
251
 
235
- `strata.lock.json` (committed) is the source's stamp. `upgrade` plans from it:
252
+ `strata.lock.json` (committed) is the source's stamp: each grammar's entry is
253
+ how many of its migrations the source is written at, a whole number (digits in
254
+ a string are read too); any other entry is refused (`INVALID_SEQUENCE`). `upgrade` plans from it:
236
255
  artifacts a migration changes get their expected JSON and a positional diff;
237
256
  the rest are recorded as untouched. `verify` passes only when every planned
238
- artifact equals its expected JSON (key order aside), every untouched one is
257
+ artifact equals its expected JSON (key order aside) and passes its kind's
258
+ current schema in `schemas`, every untouched one is
239
259
  still one no migration would change, and nothing was added or removed since
240
- the plan — then the lock moves and the work files go. A migration whose result
260
+ the plan — then the lock moves and the files the plan wrote go. The lock is the
261
+ source's stamp: `verify` refuses a plan made from any other ("plan again"),
262
+ whatever `plan.json` says, and compares stamps by grammar, not by the order
263
+ the grammars were given in. A migration whose result
241
264
  fails the current schema stops the plan: no edit could pass. `init` records a
242
265
  lock for a source that has never had one.
243
266
 
244
267
  | | |
245
268
  |---|---|
246
- | `@niscorp/strata/upgrade` | Pure: `planSourceUpgrade`, `verifySourceUpgrade`, `renderReport`, `changedStrings`. `planSourceUpgrade`'s `describe(ref)` returns the description of the migration `ref` names, for the report; it is asked for every migration between the source's stamp and the upgrader's. |
247
- | `@niscorp/strata/node` | `runSourceUpgrade(options, argv)` — the lock, the work directory, the report, "look in" hints from the source. `sources` is the directory under `root` that is searched for the files an artifact is written in (default `src`). |
269
+ | `@niscorp/strata/upgrade` | Pure: `planSourceUpgrade`, `verifySourceUpgrade`, `renderReport`, `changedStrings`. `verifySourceUpgrade` compares JSON only; `runSourceUpgrade` checks the schemas as well. `planSourceUpgrade`'s `describe(ref)` returns the description of the migration `ref` names, for the report; it is asked for every migration between the source's stamp and the upgrader's. |
270
+ | `@niscorp/strata/node` | `runSourceUpgrade(options, argv)` — the lock, the work directory, the report, "look in" hints from the source. `sources` is the directory under `root` that is searched for the files an artifact is written in (default `src`). `workDir` (default `.strata/upgrade`) is where `upgrade` writes `plan.json`, `REPORT.md` and `expected/`; `upgrade` and `verify` remove only those files, and a directory only once it is empty, so nothing else in it is touched. In a `workDir` the host names, a `REPORT.md` is strata's only when it begins with `# strata upgrade` (a byte-order mark aside) and a `plan.json` only when it has a plan's shape: given one that is not, `upgrade` leaves it as it is and exits 1 ("Move it, or give strata a workDir of its own."), and nothing removes it. An expected file is named after the artifact's kind and id; a second id that cleans to the same name (`a/b`, `a_b`) gets `~2`. |
248
271
 
249
272
  See [DESIGN.md](./DESIGN.md) and [the plan](../../docs/plans/versioning.md).
250
273
 
274
+ ## `INVALID_SEQUENCE`
275
+
276
+ One code covers input strata cannot read as what it was given for; the error's
277
+ sentence says which:
278
+
279
+ | Refused | Where |
280
+ |---|---|
281
+ | a sequence that does not parse, `null` included | `prepare` |
282
+ | two sequences with one id | `prepare` |
283
+ | a ledger `table` or `schema`, or a store's table, schema or column, that is not a plain identifier | `migrate`, `status`, `readLedger`, `ledgerDdl`, `upgradeStore` |
284
+ | a store whose `key` names no column | `upgradeStore` |
285
+ | a stamp entry, for a grammar the upgrader was given, that is no number | `upgrader.upgrade`, `upgrader.behind` (`upgradeStore` names such a row in `unread` instead) |
286
+ | a `strata.lock.json` that is JSON but not a lock, or has an entry that is not a whole number of migrations | `runSourceUpgrade` |
287
+ | two artifacts with one kind and id | `planSourceUpgrade`, `runSourceUpgrade` |
288
+
289
+ A `strata.lock.json` that is not JSON at all throws the parser's own `SyntaxError`.
290
+
251
291
  ## License
252
292
 
253
293
  Apache-2.0
@@ -1,29 +1,29 @@
1
1
  'use strict';
2
2
 
3
- var chunkSYU7NKZR_cjs = require('../chunk-SYU7NKZR.cjs');
3
+ var chunkHTW4IEBC_cjs = require('../chunk-HTW4IEBC.cjs');
4
4
  require('../chunk-7PBIGCLL.cjs');
5
5
 
6
6
 
7
7
 
8
8
  Object.defineProperty(exports, "checkCorpus", {
9
9
  enumerable: true,
10
- get: function () { return chunkSYU7NKZR_cjs.checkCorpus; }
10
+ get: function () { return chunkHTW4IEBC_cjs.checkCorpus; }
11
11
  });
12
12
  Object.defineProperty(exports, "compareSnapshot", {
13
13
  enumerable: true,
14
- get: function () { return chunkSYU7NKZR_cjs.compareSnapshot; }
14
+ get: function () { return chunkHTW4IEBC_cjs.compareSnapshot; }
15
15
  });
16
16
  Object.defineProperty(exports, "diffJson", {
17
17
  enumerable: true,
18
- get: function () { return chunkSYU7NKZR_cjs.diffJson; }
18
+ get: function () { return chunkHTW4IEBC_cjs.diffJson; }
19
19
  });
20
20
  Object.defineProperty(exports, "snapshotOf", {
21
21
  enumerable: true,
22
- get: function () { return chunkSYU7NKZR_cjs.snapshotOf; }
22
+ get: function () { return chunkHTW4IEBC_cjs.snapshotOf; }
23
23
  });
24
24
  Object.defineProperty(exports, "snapshotText", {
25
25
  enumerable: true,
26
- get: function () { return chunkSYU7NKZR_cjs.snapshotText; }
26
+ get: function () { return chunkHTW4IEBC_cjs.snapshotText; }
27
27
  });
28
28
  //# sourceMappingURL=index.cjs.map
29
29
  //# sourceMappingURL=index.cjs.map
@@ -1,4 +1,4 @@
1
- export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText } from '../chunk-SH6BBA2X.js';
1
+ export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText } from '../chunk-2G3DFR6P.js';
2
2
  import '../chunk-STNFHBNR.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
@@ -38,7 +38,8 @@ var snapshotOf = (sequence, schemas) => {
38
38
  };
39
39
  var snapshotText = (snapshot) => `${JSON.stringify(sortKeys(snapshot), null, 2)}
40
40
  `;
41
- var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
41
+ var diffLines = (a, b, path, run) => {
42
+ const { out, limit, canon, sets } = run;
42
43
  if (out.length >= limit) return;
43
44
  if (JSON.stringify(a) === JSON.stringify(b)) return;
44
45
  if (isRecord(a) && isRecord(b)) {
@@ -48,14 +49,14 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
48
49
  const after = b[key];
49
50
  if (!(key in a)) out.push(`+ ${at}`);
50
51
  else if (!(key in b)) out.push(`- ${at}`);
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);
52
+ else if (sets && key === "prefixItems" && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, run);
53
+ else diffLines(before, after, at, run);
53
54
  if (out.length >= limit) return;
54
55
  }
55
56
  return;
56
57
  }
57
58
  if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {
58
- a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));
59
+ a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, run));
59
60
  return;
60
61
  }
61
62
  if (Array.isArray(a) && Array.isArray(b)) {
@@ -67,7 +68,7 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
67
68
  for (const x of onlyA) {
68
69
  const partner = byLabel.get(label(x));
69
70
  if (partner !== void 0) {
70
- diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);
71
+ diffLines(x, partner, `${path}[${label(x)}]`, run);
71
72
  byLabel.delete(label(x));
72
73
  } else {
73
74
  out.push(`- ${path}[${label(x)}]`);
@@ -82,12 +83,13 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
82
83
  }
83
84
  out.push(`~ ${path || "(root)"}: ${JSON.stringify(a)?.slice(0, 60)} \u2192 ${JSON.stringify(b)?.slice(0, 60)}`);
84
85
  };
85
- var diffPositions = (a, b, path, out, limit, canon) => {
86
+ var diffPositions = (a, b, path, run) => {
87
+ const { out, limit } = run;
86
88
  for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
87
89
  if (out.length >= limit) return;
88
90
  if (i >= a.length) out.push(`+ ${path}[${i}]`);
89
91
  else if (i >= b.length) out.push(`- ${path}[${i}]`);
90
- else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);
92
+ else diffLines(a[i], b[i], `${path}[${i}]`, { ...run, sets: true });
91
93
  }
92
94
  };
93
95
  var REF_PREFIX = /^#\/(\$defs|definitions)\//;
@@ -172,7 +174,7 @@ var compareSnapshot = (recorded, current) => {
172
174
  const lines = [];
173
175
  if (!(kind in recorded.kinds)) lines.push("+ (a new kind)");
174
176
  else if (!(kind in current.kinds)) lines.push("- (the kind is gone)");
175
- else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), "", lines, 12);
177
+ else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), "", { out: lines, limit: 12, canon: normalize, sets: true });
176
178
  if (lines.length > 0) changes.push({ kind, lines });
177
179
  }
178
180
  return changes.length === 0 ? { status: "same" } : { status: "changed", changes };
@@ -183,7 +185,7 @@ var issueText = (issue) => {
183
185
  };
184
186
  var diffJson = (a, b, limit = 20) => {
185
187
  const out = [];
186
- diffLines(a, b, "", out, limit, sortKeys, false);
188
+ diffLines(a, b, "", { out, limit, canon: sortKeys, sets: false });
187
189
  return out;
188
190
  };
189
191
  var checkCorpus = async (upgrader, schemas, documents) => {
@@ -213,5 +215,5 @@ var checkCorpus = async (upgrader, schemas, documents) => {
213
215
  };
214
216
 
215
217
  export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText };
216
- //# sourceMappingURL=chunk-SH6BBA2X.js.map
217
- //# sourceMappingURL=chunk-SH6BBA2X.js.map
218
+ //# sourceMappingURL=chunk-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Sequence } from '../schema';\nimport type { Stamp, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\ntype Issue = { message: string; path?: readonly (PropertyKey | { key: PropertyKey })[] };\ntype StandardResult = { value: unknown; issues?: undefined } | { issues: readonly Issue[] };\n\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\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// Under NAMED the keys are names, not keywords: a field called `description` or\n// an op called `$ref` is grammar. Under DATA the values are instance data, not schemas.\nconst NAMED = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);\nconst DATA = new Set(['const', 'enum', 'default', 'examples']);\n\n// Applied when comparing, never to what is recorded: what the gate ignores can\n// then 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\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\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\nexport const snapshotText = (snapshot: Snapshot): string => `${JSON.stringify(sortKeys(snapshot), null, 2)}\n`;\n\ntype DiffRun = { out: string[]; limit: number; canon: (v: unknown) => unknown; sets: boolean };\n\nconst diffLines = (a: unknown, b: unknown, path: string, run: DiffRun): void => {\n const { out, limit, canon, sets } = run;\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 const before = a[key];\n const after = b[key];\n if (!(key in a)) out.push(`+ ${at}`);\n else if (!(key in b)) out.push(`- ${at}`);\n else if (sets && key === 'prefixItems' && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, run);\n else diffLines(before, after, at, run);\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}]`, run));\n return;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n // Schema arrays are sets more often than sequences (`anyOf`, `required`,\n // `enum`), and one added branch shifts every index after it: elements are\n // matched by what they describe, an object schema by its property names.\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)}]`, run);\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\nconst diffPositions = (a: readonly unknown[], b: readonly unknown[], path: string, run: DiffRun): void => {\n const { out, limit } = run;\n for (let i = 0; i < Math.max(a.length, b.length); i += 1) {\n if (out.length >= limit) return;\n if (i >= a.length) out.push(`+ ${path}[${i}]`);\n else if (i >= b.length) out.push(`- ${path}[${i}]`);\n else diffLines(a[i], b[i], `${path}[${i}]`, { ...run, sets: true });\n }\n};\n\n// Validators spell one schema many ways: they name and inline definitions as\n// they please, write a described reference as `allOf: [{ $ref }]` or as `$ref`,\n// and a union of bare types as `anyOf` or as `type: […]`. A comparison reads\n// both sides in one spelling.\nconst REF_PREFIX = /^#\\/(\\$defs|definitions)\\//;\n\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\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 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\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]), '', { out: lines, limit: 12, canon: normalize, sets: true });\n if (lines.length > 0) changes.push({ kind, lines });\n }\n return changes.length === 0 ? { status: 'same' } : { status: 'changed', changes };\n};\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\nexport const diffJson = (a: unknown, b: unknown, limit = 20): string[] => {\n const out: string[] = [];\n diffLines(a, b, '', { out, limit, canon: sortKeys, sets: false });\n return out;\n};\n\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,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkKYNER7UU_cjs = require('./chunk-KYNER7UU.cjs');
3
+ var chunkSJNHLIKR_cjs = require('./chunk-SJNHLIKR.cjs');
4
4
  var chunk7PBIGCLL_cjs = require('./chunk-7PBIGCLL.cjs');
5
5
 
6
6
  // src/documents.ts
@@ -36,7 +36,7 @@ var setAt = (root, path, value) => {
36
36
  return root;
37
37
  };
38
38
  var createUpgrader = async (sequences, options) => {
39
- const prepared = await chunkKYNER7UU_cjs.prepare(sequences);
39
+ const prepared = await chunkSJNHLIKR_cjs.prepare(sequences);
40
40
  const tables = prepared.filter((s) => !s.grammar);
41
41
  if (tables.length > 0) {
42
42
  throw new chunk7PBIGCLL_cjs.StrataError(
@@ -74,7 +74,16 @@ var createUpgrader = async (sequences, options) => {
74
74
  visit(document, kind, []);
75
75
  return found;
76
76
  };
77
- const positionOf = (given, id) => given?.[id] ?? 0;
77
+ const positionOf = (given, id) => {
78
+ const entry = given?.[id];
79
+ if (entry === void 0) return 0;
80
+ const position = Number(entry);
81
+ if (Number.isNaN(position)) {
82
+ const named = typeof entry === "number" ? String(entry) : JSON.stringify(entry);
83
+ throw new chunk7PBIGCLL_cjs.StrataError("INVALID_SEQUENCE", `The stamp's entry for ${id} is ${named}: not a number of migrations.`);
84
+ }
85
+ return position;
86
+ };
78
87
  const behind = (given) => {
79
88
  const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);
80
89
  if (ahead.length > 0) {
@@ -91,7 +100,7 @@ var createUpgrader = async (sequences, options) => {
91
100
  if (!kinds.has(kind)) throw new chunk7PBIGCLL_cjs.StrataError("UNKNOWN_KIND", `No sequence declares the document kind "${kind}".`, [...kinds.keys()]);
92
101
  if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };
93
102
  const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));
94
- const { pending, stuck } = chunkKYNER7UU_cjs.orderPending(
103
+ const { pending, stuck } = chunkSJNHLIKR_cjs.orderPending(
95
104
  grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),
96
105
  done
97
106
  );
@@ -132,5 +141,5 @@ var createUpgrader = async (sequences, options) => {
132
141
  };
133
142
 
134
143
  exports.createUpgrader = createUpgrader;
135
- //# sourceMappingURL=chunk-FSEUYRLN.cjs.map
136
- //# sourceMappingURL=chunk-FSEUYRLN.cjs.map
144
+ //# sourceMappingURL=chunk-FMXFHYU2.cjs.map
145
+ //# sourceMappingURL=chunk-FMXFHYU2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/documents.ts"],"names":["prepare","StrataError","orderPending"],"mappings":";;;;;;AAuBA,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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AAS;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-FMXFHYU2.cjs","sourcesContent":["import { prepare, orderPending, type PreparedMigration, type PreparedSequence } from './plan';\nimport type { DocumentKind, Sequence } from './schema';\nimport { StrataError } from './errors';\n\nexport type Stamp = Readonly<Record<string, number>>;\n\nexport type Location = { path: readonly (string | number)[]; kind: string; value: Record<string, unknown> };\n\nexport type Transform = (config: unknown, source: unknown) => unknown;\n\nexport type UpgradeResult = {\n document: Record<string, unknown>;\n stamp: Stamp;\n applied: readonly string[];\n};\n\nexport type Upgrader = {\n stamp: Stamp;\n upgrade: (document: unknown, options: { kind: string; stamp?: Stamp | null }) => UpgradeResult;\n locate: (document: unknown, kind: string) => Location[];\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\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`). 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 document's entries for grammars this code was not given are kept:\n // dropping them would let code that has the grammar run its migrations over\n // 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 // An entry is read with `Number`: digits and `null` read; one that reads as no number is refused rather\n // than read as current. A number is named as itself: JSON would print `NaN` as `null`.\n const positionOf = (given: Stamp | null | undefined, id: string): number => {\n const entry: unknown = given?.[id];\n if (entry === undefined) return 0;\n const position = Number(entry);\n if (Number.isNaN(position)) {\n const named = typeof entry === 'number' ? String(entry) : JSON.stringify(entry);\n throw new StrataError('INVALID_SEQUENCE', `The stamp's entry for ${id} is ${named}: not a number of migrations.`);\n }\n return position;\n };\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 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 // Read from `current`, not `target.value`: a child rewritten a moment\n // 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"]}
@@ -40,7 +40,8 @@ var snapshotOf = (sequence, schemas) => {
40
40
  };
41
41
  var snapshotText = (snapshot) => `${JSON.stringify(sortKeys(snapshot), null, 2)}
42
42
  `;
43
- var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
43
+ var diffLines = (a, b, path, run) => {
44
+ const { out, limit, canon, sets } = run;
44
45
  if (out.length >= limit) return;
45
46
  if (JSON.stringify(a) === JSON.stringify(b)) return;
46
47
  if (isRecord(a) && isRecord(b)) {
@@ -50,14 +51,14 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
50
51
  const after = b[key];
51
52
  if (!(key in a)) out.push(`+ ${at}`);
52
53
  else if (!(key in b)) out.push(`- ${at}`);
53
- else if (sets && key === "prefixItems" && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, out, limit, canon);
54
- else diffLines(before, after, at, out, limit, canon, sets);
54
+ else if (sets && key === "prefixItems" && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, run);
55
+ else diffLines(before, after, at, run);
55
56
  if (out.length >= limit) return;
56
57
  }
57
58
  return;
58
59
  }
59
60
  if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {
60
- a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));
61
+ a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, run));
61
62
  return;
62
63
  }
63
64
  if (Array.isArray(a) && Array.isArray(b)) {
@@ -69,7 +70,7 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
69
70
  for (const x of onlyA) {
70
71
  const partner = byLabel.get(label(x));
71
72
  if (partner !== void 0) {
72
- diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);
73
+ diffLines(x, partner, `${path}[${label(x)}]`, run);
73
74
  byLabel.delete(label(x));
74
75
  } else {
75
76
  out.push(`- ${path}[${label(x)}]`);
@@ -84,12 +85,13 @@ var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
84
85
  }
85
86
  out.push(`~ ${path || "(root)"}: ${JSON.stringify(a)?.slice(0, 60)} \u2192 ${JSON.stringify(b)?.slice(0, 60)}`);
86
87
  };
87
- var diffPositions = (a, b, path, out, limit, canon) => {
88
+ var diffPositions = (a, b, path, run) => {
89
+ const { out, limit } = run;
88
90
  for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
89
91
  if (out.length >= limit) return;
90
92
  if (i >= a.length) out.push(`+ ${path}[${i}]`);
91
93
  else if (i >= b.length) out.push(`- ${path}[${i}]`);
92
- else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);
94
+ else diffLines(a[i], b[i], `${path}[${i}]`, { ...run, sets: true });
93
95
  }
94
96
  };
95
97
  var REF_PREFIX = /^#\/(\$defs|definitions)\//;
@@ -174,7 +176,7 @@ var compareSnapshot = (recorded, current) => {
174
176
  const lines = [];
175
177
  if (!(kind in recorded.kinds)) lines.push("+ (a new kind)");
176
178
  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);
179
+ else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), "", { out: lines, limit: 12, canon: normalize, sets: true });
178
180
  if (lines.length > 0) changes.push({ kind, lines });
179
181
  }
180
182
  return changes.length === 0 ? { status: "same" } : { status: "changed", changes };
@@ -185,7 +187,7 @@ var issueText = (issue) => {
185
187
  };
186
188
  var diffJson = (a, b, limit = 20) => {
187
189
  const out = [];
188
- diffLines(a, b, "", out, limit, sortKeys, false);
190
+ diffLines(a, b, "", { out, limit, canon: sortKeys, sets: false });
189
191
  return out;
190
192
  };
191
193
  var checkCorpus = async (upgrader, schemas, documents) => {
@@ -219,5 +221,5 @@ exports.compareSnapshot = compareSnapshot;
219
221
  exports.diffJson = diffJson;
220
222
  exports.snapshotOf = snapshotOf;
221
223
  exports.snapshotText = snapshotText;
222
- //# sourceMappingURL=chunk-SYU7NKZR.cjs.map
223
- //# sourceMappingURL=chunk-SYU7NKZR.cjs.map
224
+ //# sourceMappingURL=chunk-HTW4IEBC.cjs.map
225
+ //# sourceMappingURL=chunk-HTW4IEBC.cjs.map