@niscorp/strata 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/DESIGN.md +8 -2
- package/README.md +23 -10
- package/dist/check/index.cjs +7 -7
- package/dist/check/index.js +2 -2
- package/dist/{chunk-KNBS3AJZ.cjs → chunk-3DPZS52U.cjs} +4 -4
- package/dist/chunk-3DPZS52U.cjs.map +1 -0
- package/dist/{chunk-ATHZ7HT5.cjs → chunk-BW4CKKGE.cjs} +2 -2
- package/dist/chunk-BW4CKKGE.cjs.map +1 -0
- package/dist/{chunk-5KTXEN43.js → chunk-CI652R5O.js} +3 -3
- package/dist/chunk-CI652R5O.js.map +1 -0
- package/dist/{chunk-OLDORFOQ.js → chunk-D42CQI2X.js} +4 -4
- package/dist/chunk-D42CQI2X.js.map +1 -0
- package/dist/{chunk-CL5DF2IQ.cjs → chunk-HW6ON3LT.cjs} +6 -6
- package/dist/chunk-HW6ON3LT.cjs.map +1 -0
- package/dist/{chunk-YXFEJJMC.cjs → chunk-IOS2DL6R.cjs} +15 -15
- package/dist/chunk-IOS2DL6R.cjs.map +1 -0
- package/dist/{chunk-4BLHBVSC.js → chunk-LIWVOCKP.js} +3 -3
- package/dist/chunk-LIWVOCKP.js.map +1 -0
- package/dist/{chunk-WU3OJHVZ.js → chunk-PODP3F5N.js} +4 -4
- package/dist/chunk-PODP3F5N.js.map +1 -0
- package/dist/{chunk-IHYBGLNW.cjs → chunk-QIXZZZE6.cjs} +8 -8
- package/dist/chunk-QIXZZZE6.cjs.map +1 -0
- package/dist/{chunk-AKKWEXO2.js → chunk-VNF4KPVN.js} +2 -2
- package/dist/chunk-VNF4KPVN.js.map +1 -0
- package/dist/index.cjs +21 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/node/index.cjs +11 -11
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.js +5 -5
- package/dist/node/index.js.map +1 -1
- package/dist/postgres/index.cjs +16 -16
- package/dist/postgres/index.cjs.map +1 -1
- package/dist/postgres/index.js +2 -2
- package/dist/postgres/index.js.map +1 -1
- package/dist/upgrade/index.cjs +7 -7
- package/dist/upgrade/index.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-4BLHBVSC.js.map +0 -1
- package/dist/chunk-5KTXEN43.js.map +0 -1
- package/dist/chunk-AKKWEXO2.js.map +0 -1
- package/dist/chunk-ATHZ7HT5.cjs.map +0 -1
- package/dist/chunk-CL5DF2IQ.cjs.map +0 -1
- package/dist/chunk-IHYBGLNW.cjs.map +0 -1
- package/dist/chunk-KNBS3AJZ.cjs.map +0 -1
- package/dist/chunk-OLDORFOQ.js.map +0 -1
- package/dist/chunk-WU3OJHVZ.js.map +0 -1
- package/dist/chunk-YXFEJJMC.cjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# @niscorp/strata
|
|
2
2
|
|
|
3
|
+
## 0.1.7
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 2e73b96: The README states what its API tables left to source comments.
|
|
8
|
+
|
|
9
|
+
It now gives the grammar of a sequence id and of a kind name, what `planMigrations` and `migrate` return, the refusals that had no name in the docs (`PENDING`, `STEP_FAILED`, `WRONG_OWNER` from `migrate`, `UNKNOWN_KIND`, a duplicate sequence id), what `upgrader.upgrade`, `upgrader.locate` and `upgradeStore` take and return, and rows for `refuseProblems` and `diffJson`.
|
|
10
|
+
|
|
11
|
+
No behaviour changed.
|
|
12
|
+
|
|
13
|
+
**What to change:** nothing.
|
|
14
|
+
|
|
15
|
+
## 0.1.6
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- de2a757: DESIGN.md no longer reads as if moss's `initIntegrations` and `initSessions` were still there to call. Moss stopped exporting both (see the moss changeset): its integration tables are part of `MOSS_SEQUENCE`, and the sessions table is made where a deployment keeps moss's stored sessions (`session: 'sessions'`); `createServer` and `migrateTables` run both. The paragraph that names it is the record of what moved when strata landed, and it now says what has changed since. No code changed.
|
|
20
|
+
|
|
21
|
+
**What to change:** nothing.
|
|
22
|
+
|
|
3
23
|
## 0.1.5
|
|
4
24
|
|
|
5
25
|
### Patch Changes
|
package/DESIGN.md
CHANGED
|
@@ -77,8 +77,14 @@ it replaced were. Two consequences, named rather than discovered later:
|
|
|
77
77
|
check builds the universe the way boot does, and `*.read` roles deny the
|
|
78
78
|
engine's tables. Any app granting a data wildcard should do the same.
|
|
79
79
|
- `initIntegrations`, `initSessions`, `cache.init()` and the tide store's
|
|
80
|
-
`migrate`
|
|
81
|
-
not moss's server gets the same guarantees.
|
|
80
|
+
`migrate` kept their names and went through the ledger from then on, so a
|
|
81
|
+
host that is not moss's server gets the same guarantees. (Since then
|
|
82
|
+
`initIntegrations` and `initSessions` have gone from what moss exports: the
|
|
83
|
+
integration tables are part of `MOSS_SEQUENCE`, and the sessions table is
|
|
84
|
+
made where a deployment keeps moss's stored sessions (`session:
|
|
85
|
+
'sessions'`); `createServer` and `migrateTables` run both. The other two
|
|
86
|
+
are as they were, and the tide store is tide's own,
|
|
87
|
+
`@niscorp/tide/postgres`.)
|
|
82
88
|
|
|
83
89
|
## Documents (S2)
|
|
84
90
|
|
package/README.md
CHANGED
|
@@ -57,6 +57,8 @@ own tables, the sessions table, the vex cache — in one ledgered run at boot.
|
|
|
57
57
|
at once serialize; the second finds the work done.
|
|
58
58
|
- **A database migrated by newer code is refused** (`TOO_NEW`), never guessed at.
|
|
59
59
|
- **Sequence ids are namespaced**: `nisc.vex.cache`, `nisc.moss`, `acme.app`.
|
|
60
|
+
An id is lowercase, in at least two dot-separated parts (`<owner>.<name>`),
|
|
61
|
+
each a letter followed by letters, digits or hyphens.
|
|
60
62
|
Order across sequences is the order you pass them, bent only by `dependsOn`
|
|
61
63
|
(`"nisc.moss/1"`) — deterministic, the same every time.
|
|
62
64
|
|
|
@@ -67,8 +69,9 @@ own tables, the sessions table, the vex cache — in one ledgered run at boot.
|
|
|
67
69
|
| | |
|
|
68
70
|
|---|---|
|
|
69
71
|
| `defineSequence(seq)` | Type-checks a sequence where it is written. |
|
|
70
|
-
| `prepare(sequences)` | Parses (Zod, at the boundary), numbers and checksums. Throws `INVALID_SEQUENCE`. |
|
|
71
|
-
| `planMigrations(prepared, ledger)` | Pure: what is pending, in order, and every problem (`EDITED`, `TOO_NEW`, `UNKNOWN_DEPENDENCY`, `CYCLE`). |
|
|
72
|
+
| `prepare(sequences)` | Parses (Zod, at the boundary), numbers and checksums. Throws `INVALID_SEQUENCE`. Two sequences with the same id are refused the same way. |
|
|
73
|
+
| `planMigrations(prepared, ledger)` | Pure: what is pending, in order, and every problem (`EDITED`, `TOO_NEW`, `UNKNOWN_DEPENDENCY`, `CYCLE`). Returns `{ applied, pending, problems }`; `applied` is, per sequence given, how many of its migrations the ledger records. `UNKNOWN_DEPENDENCY` is a `dependsOn` naming a migration that no sequence given provides and the ledger does not record. |
|
|
74
|
+
| `refuseProblems(plan)` | Throws a plan's problems as one `StrataError`: its `code` is the first problem's, its `details` list them all. Returns when the plan has none. `migrate` refuses a plan this way. |
|
|
72
75
|
| `checksumOf(migration)` | SHA-256 over the steps (WebCrypto — Node ≥ 22 and every browser). |
|
|
73
76
|
| `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. |
|
|
74
77
|
| `SequenceSchema`, `MigrationSchema`, `StepSchema` | The grammar, as Zod. |
|
|
@@ -78,14 +81,17 @@ own tables, the sessions table, the vex cache — in one ledgered run at boot.
|
|
|
78
81
|
|
|
79
82
|
| | |
|
|
80
83
|
|---|---|
|
|
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. |
|
|
84
|
+
| `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. `applied` is what this run applied, in order; `plan` is the plan it acted on, so `plan.applied` holds each sequence's position before the run. `'verify'` refuses with `PENDING` when anything is pending, and a step that throws refuses the run with `STEP_FAILED`. |
|
|
82
85
|
| `status(pool, sequences, options)` | The plan, read-only — creates nothing, not even the ledger. |
|
|
83
86
|
| `readLedger(pool, options)` | The ledger's rows; empty for a database never migrated. |
|
|
84
87
|
| `ledgerDdl(options)` | The ledger table's DDL — the one statement strata runs outside a ledger. |
|
|
85
88
|
|
|
86
89
|
The pool is structural — `{ query, transaction }`, the shape vex's PGlite pool
|
|
87
90
|
and a wrapped `pg` pool already have. A pool without `transaction` is refused
|
|
88
|
-
(`NO_TRANSACTION`): a run must land whole or not at all.
|
|
91
|
+
(`NO_TRANSACTION`): a run must land whole or not at all. `query` and
|
|
92
|
+
`transaction` are called on the object that has them, so a driver's own object
|
|
93
|
+
whose methods reach for `this` — a PGlite, a `pg` client handed through as the
|
|
94
|
+
transaction — works as it is.
|
|
89
95
|
|
|
90
96
|
The ledger defaults to `strata_ledger` in the connection's schema, beside the
|
|
91
97
|
app's tables; `table` and `schema` move it.
|
|
@@ -103,6 +109,9 @@ so it never runs again. From then on changes are plain appended migrations.
|
|
|
103
109
|
A **grammar** sequence owns document kinds instead of tables. It declares its
|
|
104
110
|
kinds and where other documents nest inside them (its **embeddings**), and its
|
|
105
111
|
migrations are **document steps** — a transform over one document of one kind.
|
|
112
|
+
A kind's name in `documents` is lowercase — a letter, then letters, digits or
|
|
113
|
+
hyphens — and everywhere else the kind is written `<sequence id>/<name>`
|
|
114
|
+
(`nisc.nova/layout`).
|
|
106
115
|
|
|
107
116
|
```ts
|
|
108
117
|
export const NOVA_SEQUENCE = {
|
|
@@ -131,7 +140,8 @@ const { document, stamp, applied } = upgrader.upgrade(storedAction, { kind: 'nis
|
|
|
131
140
|
along each grammar its writer was — and is upgraded where it is read. Grammars
|
|
132
141
|
are never recorded in a ledger: documents travel (an add-on built on older
|
|
133
142
|
code submits older documents), so their version travels with them. One
|
|
134
|
-
sequence owns tables or documents, never both.
|
|
143
|
+
sequence owns tables or documents, never both. `migrate` refuses a grammar
|
|
144
|
+
sequence (`WRONG_OWNER`).
|
|
135
145
|
- **A grammar declares `documents`**, from its first release — `{}` if it has
|
|
136
146
|
no kinds of its own. That is how strata tells the two owners apart: a sequence
|
|
137
147
|
is a grammar when it declares `documents` or has a document step, and anything
|
|
@@ -153,8 +163,10 @@ const { document, stamp, applied } = upgrader.upgrade(storedAction, { kind: 'nis
|
|
|
153
163
|
|
|
154
164
|
| | |
|
|
155
165
|
|---|---|
|
|
156
|
-
| `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). |
|
|
157
|
-
| `
|
|
166
|
+
| `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. |
|
|
167
|
+
| `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. |
|
|
168
|
+
| `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. |
|
|
169
|
+
| `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. |
|
|
158
170
|
|
|
159
171
|
## The check
|
|
160
172
|
|
|
@@ -164,9 +176,10 @@ host keeps the files.
|
|
|
164
176
|
| | |
|
|
165
177
|
|---|---|
|
|
166
178
|
| `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. |
|
|
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. |
|
|
179
|
+
| `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. `recorded` is the snapshot kept for the grammar's current version, `undefined` when none was kept (`missing`). |
|
|
168
180
|
| `snapshotText(snapshot)` | Stable file text: sorted keys. |
|
|
169
181
|
| `checkCorpus(upgrader, schemas, documents)` | Every captured document, upgraded from its stamp, must pass its kind's current schema. |
|
|
182
|
+
| `diffJson(a, b, limit)` | What differs between two JSON values, as short lines: `+ a.b` (added), `- c` (removed), `~ d: 1 → 2` (changed). At most `limit` lines, 20 by default. |
|
|
170
183
|
|
|
171
184
|
A snapshot only says *something moved*; the corpus of real documents is the
|
|
172
185
|
judge of whether old ones survive. nisc runs both on its own grammars in CI
|
|
@@ -201,8 +214,8 @@ lock for a source that has never had one.
|
|
|
201
214
|
|
|
202
215
|
| | |
|
|
203
216
|
|---|---|
|
|
204
|
-
| `@niscorp/strata/upgrade` | Pure: `planSourceUpgrade`, `verifySourceUpgrade`, `renderReport`, `changedStrings`. |
|
|
205
|
-
| `@niscorp/strata/node` | `runSourceUpgrade(options, argv)` — the lock, the work directory, the report, "look in" hints from the source. |
|
|
217
|
+
| `@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. |
|
|
218
|
+
| `@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`). |
|
|
206
219
|
|
|
207
220
|
See [DESIGN.md](./DESIGN.md) and [the plan](../../docs/plans/versioning.md).
|
|
208
221
|
|
package/dist/check/index.cjs
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
require('../chunk-
|
|
3
|
+
var chunk3DPZS52U_cjs = require('../chunk-3DPZS52U.cjs');
|
|
4
|
+
require('../chunk-BW4CKKGE.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
Object.defineProperty(exports, "checkCorpus", {
|
|
9
9
|
enumerable: true,
|
|
10
|
-
get: function () { return
|
|
10
|
+
get: function () { return chunk3DPZS52U_cjs.checkCorpus; }
|
|
11
11
|
});
|
|
12
12
|
Object.defineProperty(exports, "compareSnapshot", {
|
|
13
13
|
enumerable: true,
|
|
14
|
-
get: function () { return
|
|
14
|
+
get: function () { return chunk3DPZS52U_cjs.compareSnapshot; }
|
|
15
15
|
});
|
|
16
16
|
Object.defineProperty(exports, "diffJson", {
|
|
17
17
|
enumerable: true,
|
|
18
|
-
get: function () { return
|
|
18
|
+
get: function () { return chunk3DPZS52U_cjs.diffJson; }
|
|
19
19
|
});
|
|
20
20
|
Object.defineProperty(exports, "snapshotOf", {
|
|
21
21
|
enumerable: true,
|
|
22
|
-
get: function () { return
|
|
22
|
+
get: function () { return chunk3DPZS52U_cjs.snapshotOf; }
|
|
23
23
|
});
|
|
24
24
|
Object.defineProperty(exports, "snapshotText", {
|
|
25
25
|
enumerable: true,
|
|
26
|
-
get: function () { return
|
|
26
|
+
get: function () { return chunk3DPZS52U_cjs.snapshotText; }
|
|
27
27
|
});
|
|
28
28
|
//# sourceMappingURL=index.cjs.map
|
|
29
29
|
//# sourceMappingURL=index.cjs.map
|
package/dist/check/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
1
|
+
export { checkCorpus, compareSnapshot, diffJson, snapshotOf, snapshotText } from '../chunk-LIWVOCKP.js';
|
|
2
|
+
import '../chunk-VNF4KPVN.js';
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkBW4CKKGE_cjs = require('./chunk-BW4CKKGE.cjs');
|
|
4
4
|
|
|
5
5
|
// src/check/index.ts
|
|
6
6
|
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -26,7 +26,7 @@ var snapshotOf = (sequence, schemas) => {
|
|
|
26
26
|
const missing = declared.filter((k) => !given.includes(k));
|
|
27
27
|
const extra = given.filter((k) => !declared.includes(k));
|
|
28
28
|
if (missing.length > 0 || extra.length > 0) {
|
|
29
|
-
throw new
|
|
29
|
+
throw new chunkBW4CKKGE_cjs.StrataError("UNKNOWN_KIND", `The schemas for ${sequence.id} do not match its kinds.`, [
|
|
30
30
|
...missing.map((k) => `no schema for ${k}`),
|
|
31
31
|
...extra.map((k) => `${k} is not a kind of ${sequence.id}`)
|
|
32
32
|
]);
|
|
@@ -219,5 +219,5 @@ exports.compareSnapshot = compareSnapshot;
|
|
|
219
219
|
exports.diffJson = diffJson;
|
|
220
220
|
exports.snapshotOf = snapshotOf;
|
|
221
221
|
exports.snapshotText = snapshotText;
|
|
222
|
-
//# sourceMappingURL=chunk-
|
|
223
|
-
//# sourceMappingURL=chunk-
|
|
222
|
+
//# sourceMappingURL=chunk-3DPZS52U.cjs.map
|
|
223
|
+
//# sourceMappingURL=chunk-3DPZS52U.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/check/index.ts"],"names":["StrataError","key"],"mappings":";;;;;AAgBA,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;AAEpG,IAAM,QAAA,GAAW,CAAC,KAAA,KAA4B;AAC5C,EAAA,IAAI,MAAM,OAAA,CAAQ,KAAK,GAAG,OAAO,KAAA,CAAM,IAAI,QAAQ,CAAA;AACnD,EAAA,IAAI,CAAC,QAAA,CAAS,KAAK,CAAA,EAAG,OAAO,KAAA;AAC7B,EAAA,OAAO,MAAA,CAAO,YAAY,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,CAAE,IAAA,CAAK,KAAK,CAAA,CAAE,GAAA,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AA,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":"chunk-3DPZS52U.cjs","sourcesContent":["import type { 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\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 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, out, limit, canon);\n else diffLines(before, after, 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 (`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)}]`, 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\nconst diffPositions = (a: readonly unknown[], b: readonly unknown[], path: string, out: string[], limit: number, canon: (v: unknown) => unknown): void => {\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}]`, out, limit, canon, 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]), '', lines, 12);\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, sortKeys, 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"]}
|
|
@@ -14,5 +14,5 @@ ${details.map((d) => ` ${d}`).join("\n")}` : message, options);
|
|
|
14
14
|
};
|
|
15
15
|
|
|
16
16
|
exports.StrataError = StrataError;
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
18
|
-
//# sourceMappingURL=chunk-
|
|
17
|
+
//# sourceMappingURL=chunk-BW4CKKGE.cjs.map
|
|
18
|
+
//# sourceMappingURL=chunk-BW4CKKGE.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts"],"names":[],"mappings":";;;AAaO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAC5B,IAAA;AAAA,EACA,OAAA;AAAA,EAET,YAAY,IAAA,EAAuB,OAAA,EAAiB,OAAA,GAA6B,IAAI,OAAA,EAA+B;AAClH,IAAA,KAAA,CAAM,OAAA,CAAQ,MAAA,GAAS,CAAA,GAAI,CAAA,EAAG,OAAO;AAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,GAAK,SAAS,OAAO,CAAA;AACtG,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF","file":"chunk-BW4CKKGE.cjs","sourcesContent":["export type StrataErrorCode =\n | 'INVALID_SEQUENCE'\n | 'EDITED'\n | 'TOO_NEW'\n | 'UNKNOWN_DEPENDENCY'\n | 'CYCLE'\n | 'PENDING'\n | 'STEP_FAILED'\n | 'DOES_NOT_FIT'\n | 'NO_TRANSACTION'\n | 'UNKNOWN_KIND'\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"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { StrataError } from './chunk-
|
|
1
|
+
import { StrataError } from './chunk-VNF4KPVN.js';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
|
|
4
4
|
var SEQUENCE_ID = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
|
|
@@ -171,5 +171,5 @@ var refuseProblems = (plan) => {
|
|
|
171
171
|
};
|
|
172
172
|
|
|
173
173
|
export { DocumentKindSchema, DocumentStepSchema, EMBED_PATH, KIND_NAME, KIND_REF, MIGRATION_REF, MigrationSchema, SEQUENCE_ID, SequenceSchema, SqlStepSchema, StepSchema, checksumOf, orderPending, planMigrations, prepare, refuseProblems };
|
|
174
|
-
//# sourceMappingURL=chunk-
|
|
175
|
-
//# sourceMappingURL=chunk-
|
|
174
|
+
//# sourceMappingURL=chunk-CI652R5O.js.map
|
|
175
|
+
//# sourceMappingURL=chunk-CI652R5O.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts","../src/checksum.ts","../src/plan.ts"],"names":[],"mappings":";;;AAEO,IAAM,WAAA,GAAc;AAEpB,IAAM,aAAA,GAAgB;AAEtB,IAAM,SAAA,GAAY;AAClB,IAAM,QAAA,GAAW;AAKjB,IAAM,UAAA,GAAa;AAEnB,IAAM,aAAA,GAAgB,EAC1B,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,KAAK,CAAA,CACF,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,QAAA;AAAA,IACC;AAAA;AAGN,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,yEAAyE;AAE9E,IAAM,kBAAA,GAAqB,EAC/B,MAAA,CAAO;AAAA,EACN,IAAA,EAAM,CAAA,CAAE,OAAA,CAAQ,UAAU,CAAA;AAAA,EAC1B,EAAA,EAAI,EACD,MAAA,EAAO,CACP,MAAM,QAAQ,CAAA,CACd,SAAS,0GAAqG,CAAA;AAAA,EACjH,SAAA,EAAW,CAAA,CACR,OAAA,EAAQ,CACR,QAAA;AAAA,IAC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,EAAW;AACzB,EAAA,MAAM,IAAI,WAAA,CAAY,KAAA,CAAM,IAAA,EAAM,0CAAA,EAA4C,KAAK,QAAA,CAAS,GAAA,CAAI,CAAC,CAAA,KAAM,GAAG,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,MAAM,EAAE,CAAC,CAAA;AAClI","file":"chunk-CI652R5O.js","sourcesContent":["import { z } from 'zod';\n\nexport const SEQUENCE_ID = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+$/;\n\nexport const MIGRATION_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[1-9][0-9]*$/;\n\nexport const KIND_NAME = /^[a-z][a-z0-9-]*$/;\nexport const KIND_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[a-z][a-z0-9-]*$/;\n\n// `children[]` crosses the array at `children`, `endpoints.*` the record at\n// `endpoints`. Two wildcards, not one: nova's `children` is a single node or an\n// array, and one for both would read a lone node's `props` as layouts.\nexport const EMBED_PATH = /^([A-Za-z_$][\\w$]*|\\*)(\\[\\])?(\\.([A-Za-z_$][\\w$]*|\\*)(\\[\\])?)*$/;\n\nexport const SqlStepSchema = z\n .object({\n kind: z.literal('sql'),\n sql: z\n .string()\n .min(1)\n .describe(\n 'ONE SQL statement. A driver that prepares statements (PGlite, pg with parameters) refuses a string ' +\n 'carrying several — split them into steps rather than joining them with semicolons.',\n ),\n })\n .strict()\n .describe('A statement run against the database, inside the migration transaction.');\n\nexport const DocumentStepSchema = z\n .object({\n kind: z.literal('document'),\n at: z\n .string()\n .regex(KIND_REF)\n .describe('The kind of document this step rewrites, e.g. \"nisc.nova/layout\" — wherever one sits, at any depth.'),\n transform: z\n .unknown()\n .describe(\n 'A transform config (Prism) run by the injected evaluator over { document, path }: `document` is ONE document of ' +\n 'the `at` kind, `path` where it sits. It returns that document rewritten. Nested documents are found by the ' +\n 'grammar\\'s embeddings and rewritten on their own, deepest first — a transform only ever sees one flat node.',\n ),\n })\n .strict()\n .describe('A rewrite of stored JSON documents of one kind.');\n\nexport const StepSchema = z.discriminatedUnion('kind', [SqlStepSchema, DocumentStepSchema]);\n\nexport const DocumentKindSchema = z\n .object({\n embeds: z\n .record(z.string().regex(EMBED_PATH), z.string().regex(KIND_REF))\n .optional()\n .describe('Where other documents sit inside this one: path → the kind found there (possibly this kind itself).'),\n })\n .strict();\n\nexport const MigrationSchema = z\n .object({\n description: z\n .string()\n .min(1)\n .describe('One sentence: what this migration does. It is the changelog line and the ledger\\'s description.'),\n steps: z\n .array(StepSchema)\n .describe(\n 'Applied in order, in the same transaction as every other pending migration. Empty is a MARKER: ' +\n 'the version moves and nothing runs — how an addition to a strict grammar tells older readers to refuse.',\n ),\n dependsOn: z\n .array(z.string().regex(MIGRATION_REF))\n .optional()\n .describe('Migrations of OTHER sequences that must be applied first, each as \"<sequence>/<n>\".'),\n })\n .strict();\n\nexport const SequenceSchema = z\n .object({\n id: z.string().regex(SEQUENCE_ID).describe('Namespaced and lowercase, e.g. \"nisc.vex.cache\" or \"midas.app\".'),\n documents: z\n .record(z.string().regex(KIND_NAME), DocumentKindSchema)\n .optional()\n .describe('The document kinds this sequence owns (a GRAMMAR sequence), each named \"<id>/<kind>\" elsewhere.'),\n migrations: z\n .array(MigrationSchema)\n .describe('Append-only. A migration is numbered by its position (from 1); the sequence\\'s version is its length.'),\n })\n .strict()\n // Not both: a table sequence's version is recorded per database, a grammar\n // sequence's per document (its stamp), and one number cannot be both.\n .superRefine((sequence, ctx) => {\n const kinds = new Set(sequence.migrations.flatMap((m) => m.steps.map((s) => s.kind)));\n if (kinds.has('sql') && (kinds.has('document') || sequence.documents !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: 'A sequence either owns tables (sql steps) or documents (document steps and `documents`), not both.',\n });\n }\n });\n\nexport type SqlStep = z.infer<typeof SqlStepSchema>;\nexport type DocumentStep = z.infer<typeof DocumentStepSchema>;\nexport type DocumentKind = z.infer<typeof DocumentKindSchema>;\nexport type Step = z.infer<typeof StepSchema>;\nexport type Migration = z.infer<typeof MigrationSchema>;\nexport type Sequence = z.infer<typeof SequenceSchema>;\n","import type { Migration } from './schema';\n\nconst canonical = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n};\n\nconst effectOf = (sql: string): string =>\n sql\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('--'))\n .map((line) => line.trimEnd())\n .join('\\n')\n .trim();\n\nexport const checksumOf = async (migration: Migration): Promise<string> => {\n const steps = migration.steps.map((step) => (step.kind === 'sql' ? { ...step, sql: effectOf(step.sql) } : step));\n const bytes = new TextEncoder().encode(canonical(steps));\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n};\n","import { SequenceSchema, type DocumentKind, type Sequence, type Step } from './schema';\nimport { checksumOf } from './checksum';\nimport { StrataError, type StrataErrorCode } from './errors';\n\nexport type PreparedMigration = {\n sequence: string;\n n: number;\n ref: string;\n description: string;\n checksum: string;\n steps: readonly Step[];\n dependsOn: readonly string[];\n};\n\nexport type PreparedSequence = {\n id: string;\n grammar: boolean;\n documents: Readonly<Record<string, DocumentKind>>;\n migrations: readonly PreparedMigration[];\n};\n\nexport type LedgerRow = { sequence: string; n: number; checksum: string; description: string; appliedAt: string };\n\nexport type Problem = { code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>; detail: string };\n\nexport type Plan = {\n applied: Readonly<Record<string, number>>;\n pending: readonly PreparedMigration[];\n problems: readonly Problem[];\n};\n\nconst refOf = (sequence: string, n: number): string => `${sequence}/${n}`;\n\nexport const prepare = async (sequences: readonly Sequence[]): Promise<readonly PreparedSequence[]> => {\n const seen = new Set<string>();\n const prepared: PreparedSequence[] = [];\n for (const input of sequences) {\n const parsed = SequenceSchema.safeParse(input);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);\n throw new StrataError('INVALID_SEQUENCE', `A sequence does not parse${typeof input.id === 'string' ? ` (\"${input.id}\")` : ''}.`, issues);\n }\n const sequence = parsed.data;\n if (seen.has(sequence.id)) {\n throw new StrataError('INVALID_SEQUENCE', `Two sequences are both called \"${sequence.id}\" — a sequence id names one owner.`);\n }\n seen.add(sequence.id);\n const migrations: PreparedMigration[] = [];\n for (const [index, migration] of sequence.migrations.entries()) {\n const n = index + 1;\n migrations.push({\n sequence: sequence.id,\n n,\n ref: refOf(sequence.id, n),\n description: migration.description,\n checksum: await checksumOf(migration),\n steps: migration.steps,\n dependsOn: migration.dependsOn ?? [],\n });\n }\n const grammar = sequence.documents !== undefined || sequence.migrations.some((m) => m.steps.some((s) => s.kind === 'document'));\n prepared.push({ id: sequence.id, grammar, documents: sequence.documents ?? {}, migrations });\n }\n return prepared;\n};\n\nexport const orderPending = (\n queues: readonly { waiting: readonly PreparedMigration[] }[],\n alreadyDone: ReadonlySet<string>,\n): { pending: PreparedMigration[]; stuck: PreparedMigration[] } => {\n const done = new Set(alreadyDone);\n const waiting = queues.map((q) => [...q.waiting]);\n const pending: PreparedMigration[] = [];\n let moved = true;\n while (moved) {\n moved = false;\n for (const queue of waiting) {\n for (let head = queue[0]; head !== undefined; head = queue[0]) {\n if (!head.dependsOn.every((d) => done.has(d))) break;\n pending.push(head);\n done.add(head.ref);\n queue.shift();\n moved = true;\n }\n }\n }\n return { pending, stuck: waiting.flat() };\n};\n\nexport const planMigrations = (sequences: readonly PreparedSequence[], ledger: readonly LedgerRow[]): Plan => {\n const problems: Problem[] = [];\n const applied: Record<string, number> = {};\n const done = new Set(ledger.map((row) => refOf(row.sequence, row.n)));\n const byRef = new Map(ledger.map((row) => [refOf(row.sequence, row.n), row]));\n\n const queues: { id: string; waiting: PreparedMigration[] }[] = [];\n for (const sequence of sequences) {\n const rows = ledger.filter((row) => row.sequence === sequence.id);\n applied[sequence.id] = rows.length;\n\n const beyond = rows.filter((row) => row.n > sequence.migrations.length);\n if (beyond.length > 0) {\n problems.push({\n code: 'TOO_NEW',\n detail: `${sequence.id}: the database is at ${Math.max(...rows.map((r) => r.n))}, this code knows ${sequence.migrations.length} — it was migrated by newer code.`,\n });\n }\n\n const waiting: PreparedMigration[] = [];\n for (const migration of sequence.migrations) {\n const row = byRef.get(migration.ref);\n if (row === undefined) {\n waiting.push(migration);\n } else if (row.checksum !== migration.checksum) {\n problems.push({\n code: 'EDITED',\n detail: `${migration.ref} (\"${migration.description}\") was applied ${row.appliedAt} and its steps have changed since. An applied migration is history — append a new one.`,\n });\n }\n }\n const firstWaiting = waiting[0];\n if (firstWaiting !== undefined && rows.some((row) => row.n > firstWaiting.n)) {\n problems.push({ code: 'EDITED', detail: `${sequence.id}: ${firstWaiting.ref} never ran, but a later migration of the sequence did.` });\n }\n queues.push({ id: sequence.id, waiting });\n }\n\n const provided = new Set(sequences.flatMap((s) => s.migrations.map((m) => m.ref)));\n for (const { waiting } of queues) {\n for (const migration of waiting) {\n for (const dependency of migration.dependsOn) {\n if (!done.has(dependency) && !provided.has(dependency)) {\n problems.push({ code: 'UNKNOWN_DEPENDENCY', detail: `${migration.ref} depends on ${dependency}, which nothing provides and the database has not run.` });\n }\n }\n }\n }\n\n const { pending, stuck } = orderPending(queues, done);\n if (stuck.length > 0 && !problems.some((p) => p.code === 'UNKNOWN_DEPENDENCY')) {\n problems.push({ code: 'CYCLE', detail: `These wait on each other and can never run: ${stuck.map((m) => m.ref).join(', ')}.` });\n }\n\n return { applied, pending, problems };\n};\n\nexport const refuseProblems = (plan: Plan): void => {\n const first = plan.problems[0];\n if (first === undefined) return;\n throw new StrataError(first.code, 'The migrations cannot be applied safely.', plan.problems.map((p) => `${p.code}: ${p.detail}`));\n};\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { prepare, orderPending } from './chunk-
|
|
2
|
-
import { StrataError } from './chunk-
|
|
1
|
+
import { prepare, orderPending } from './chunk-CI652R5O.js';
|
|
2
|
+
import { StrataError } from './chunk-VNF4KPVN.js';
|
|
3
3
|
|
|
4
4
|
// src/documents.ts
|
|
5
5
|
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -130,5 +130,5 @@ var createUpgrader = async (sequences, options) => {
|
|
|
130
130
|
};
|
|
131
131
|
|
|
132
132
|
export { createUpgrader };
|
|
133
|
-
//# sourceMappingURL=chunk-
|
|
134
|
-
//# sourceMappingURL=chunk-
|
|
133
|
+
//# sourceMappingURL=chunk-D42CQI2X.js.map
|
|
134
|
+
//# sourceMappingURL=chunk-D42CQI2X.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/documents.ts"],"names":[],"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,GAAW,CAAC,IAAA,KAChB,IAAA,CAAK,MAAA,CAAe,CAAC,IAAA,EAAM,GAAA,KAAS,OAAO,GAAA,KAAQ,QAAA,GAAW,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,CAAA,GAAM,IAAA,KAAS,EAAA,GAAK,GAAA,GAAM,GAAG,IAAI,CAAA,CAAA,EAAI,GAAG,CAAA,CAAA,EAAK,EAAE,CAAA;AAE7H,IAAM,KAAA,GAAQ,CAAC,KAAA,EAAgB,OAAA,KAAqE;AAClG,EAAA,IAAI,WAA4D,CAAC,EAAE,MAAM,EAAC,EAAG,O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ACA,QAAA,IAAI,CAAC,QAAA,CAAS,SAAS,CAAA,EAAG;AACxB,UAAA,MAAM,IAAI,WAAA,CAAY,aAAA,EAAe,CAAA,EAAG,UAAU,GAAG,CAAA,YAAA,EAAe,EAAE,CAAA,IAAA,EAAO,QAAA,CAAS,MAAA,CAAO,IAAI,CAAA,IAAK,QAAQ,CAAA,uCAAA,CAAA,EAA2C;AAAA,YACvJ,IAAA,CAAK,UAAU,SAAS,CAAA,EAAG,MAAM,CAAA,EAAG,GAAG,CAAA,IAAK,MAAA,CAAO,SAAS;AAAA,WAC7D,CAAA;AAAA,QACH;AACA,QAAA,MAAM,IAAA,GAAO,KAAA,CAAM,OAAA,EAAS,MAAA,CAAO,MAAM,SAAS,CAAA;AAClD,QAAA,IAAI,QAAA,CAAS,IAAI,CAAA,EAAG,OAAA,GAAU,IAAA;AAAA,MAChC;AAAA,IACF,CAAA;AACA,IAAA,KAAA,MAAW,aAAa,OAAA,EAAS;AAC/B,MAAA,KAAA,MAAW,IAAA,IAAQ,SAAA,CAAU,KAAA,EAAO,IAAI,IAAA,CAAK,IAAA,KAAS,UAAA,EAAY,OAAA,CAAQ,SAAA,EAAW,IAAA,CAAK,EAAA,EAAI,IAAA,CAAK,SAAS,CAAA;AAC5G,MAAA,OAAA,CAAQ,IAAA,CAAK,UAAU,GAAG,CAAA;AAAA,IAC5B;AACA,IAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,OAAO,UAAA,CAAW,KAAK,GAAG,OAAA,EAAQ;AAAA,EAChE,CAAA;AAEA,EAAA,OAAO,EAAE,KAAA,EAAO,OAAA,EAAS,MAAA,EAAQ,MAAA,EAAO;AAC1C","file":"chunk-D42CQI2X.js","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 const positionOf = (given: Stamp | null | undefined, id: string): number => given?.[id] ?? 0;\n\n const behind = (given: Stamp | null | undefined): boolean => {\n const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);\n if (ahead.length > 0) {\n throw new StrataError(\n 'TOO_NEW',\n 'This document was written by newer code than this — reading it would be guessing.',\n ahead.map((s) => `${s.id}: the document is at ${positionOf(given, s.id)}, this code knows ${s.migrations.length}`),\n );\n }\n return grammars.some((s) => positionOf(given, s.id) < s.migrations.length);\n };\n\n const upgrade = (document: unknown, { kind, stamp: given }: { kind: string; stamp?: Stamp | null }): UpgradeResult => {\n if (!isRecord(document)) throw new StrataError('STEP_FAILED', `A ${kind} document must be a JSON object.`);\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n if (!behind(given)) return { document, stamp: stampAfter(given), applied: [] };\n\n 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"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkBW4CKKGE_cjs = require('./chunk-BW4CKKGE.cjs');
|
|
4
4
|
var zod = require('zod');
|
|
5
5
|
|
|
6
6
|
var SEQUENCE_ID = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
|
|
@@ -72,11 +72,11 @@ var prepare = async (sequences) => {
|
|
|
72
72
|
const parsed = SequenceSchema.safeParse(input);
|
|
73
73
|
if (!parsed.success) {
|
|
74
74
|
const issues = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`);
|
|
75
|
-
throw new
|
|
75
|
+
throw new chunkBW4CKKGE_cjs.StrataError("INVALID_SEQUENCE", `A sequence does not parse${typeof input.id === "string" ? ` ("${input.id}")` : ""}.`, issues);
|
|
76
76
|
}
|
|
77
77
|
const sequence = parsed.data;
|
|
78
78
|
if (seen.has(sequence.id)) {
|
|
79
|
-
throw new
|
|
79
|
+
throw new chunkBW4CKKGE_cjs.StrataError("INVALID_SEQUENCE", `Two sequences are both called "${sequence.id}" \u2014 a sequence id names one owner.`);
|
|
80
80
|
}
|
|
81
81
|
seen.add(sequence.id);
|
|
82
82
|
const migrations = [];
|
|
@@ -169,7 +169,7 @@ var planMigrations = (sequences, ledger) => {
|
|
|
169
169
|
var refuseProblems = (plan) => {
|
|
170
170
|
const first = plan.problems[0];
|
|
171
171
|
if (first === void 0) return;
|
|
172
|
-
throw new
|
|
172
|
+
throw new chunkBW4CKKGE_cjs.StrataError(first.code, "The migrations cannot be applied safely.", plan.problems.map((p) => `${p.code}: ${p.detail}`));
|
|
173
173
|
};
|
|
174
174
|
|
|
175
175
|
exports.DocumentKindSchema = DocumentKindSchema;
|
|
@@ -188,5 +188,5 @@ exports.orderPending = orderPending;
|
|
|
188
188
|
exports.planMigrations = planMigrations;
|
|
189
189
|
exports.prepare = prepare;
|
|
190
190
|
exports.refuseProblems = refuseProblems;
|
|
191
|
-
//# sourceMappingURL=chunk-
|
|
192
|
-
//# sourceMappingURL=chunk-
|
|
191
|
+
//# sourceMappingURL=chunk-HW6ON3LT.cjs.map
|
|
192
|
+
//# sourceMappingURL=chunk-HW6ON3LT.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts","../src/checksum.ts","../src/plan.ts"],"names":["z","StrataError"],"mappings":";;;;;AAEO,IAAM,WAAA,GAAc;AAEpB,IAAM,aAAA,GAAgB;AAEtB,IAAM,SAAA,GAAY;AAClB,IAAM,QAAA,GAAW;AAKjB,IAAM,UAAA,GAAa;AAEnB,IAAM,aAAA,GAAgBA,MAC1B,MAAA,CAAO;AAAA,EACN,IAAA,EAAMA,KAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,KAAKA,KAAA,CACF,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,QAAA;AAAA,IACC;AAAA;AAGN,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,yEAAyE;AAE9E,IAAM,kBAAA,GAAqBA,MAC/B,MAAA,CAAO;AAAA,EACN,IAAA,EAAM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;AAAA,EAC/H;AAEA,EAAA,OAAO,EAAE,OAAA,EAAS,OAAA,EAAS,QAAA,EAAS;AACtC;AAEO,IAAM,cAAA,GAAiB,CAAC,IAAA,KAAqB;AAClD,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,QAAA,CAAS,CAAC,CAAA;AAC7B,EAAA,IAAI,UAAU,MAAA,EAAW;AACzB,EAAA,MAAM,IAAIA,6BAAA,CAAY,KAAA,CAAM,IAAA,EAAM,0CAAA,EAA4C,KAAK,QAAA,CAAS,GAAA,CAAI,CAAC,CAAA,KAAM,GAAG,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,MAAM,EAAE,CAAC,CAAA;AAClI","file":"chunk-HW6ON3LT.cjs","sourcesContent":["import { z } from 'zod';\n\nexport const SEQUENCE_ID = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+$/;\n\nexport const MIGRATION_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[1-9][0-9]*$/;\n\nexport const KIND_NAME = /^[a-z][a-z0-9-]*$/;\nexport const KIND_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[a-z][a-z0-9-]*$/;\n\n// `children[]` crosses the array at `children`, `endpoints.*` the record at\n// `endpoints`. Two wildcards, not one: nova's `children` is a single node or an\n// array, and one for both would read a lone node's `props` as layouts.\nexport const EMBED_PATH = /^([A-Za-z_$][\\w$]*|\\*)(\\[\\])?(\\.([A-Za-z_$][\\w$]*|\\*)(\\[\\])?)*$/;\n\nexport const SqlStepSchema = z\n .object({\n kind: z.literal('sql'),\n sql: z\n .string()\n .min(1)\n .describe(\n 'ONE SQL statement. A driver that prepares statements (PGlite, pg with parameters) refuses a string ' +\n 'carrying several — split them into steps rather than joining them with semicolons.',\n ),\n })\n .strict()\n .describe('A statement run against the database, inside the migration transaction.');\n\nexport const DocumentStepSchema = z\n .object({\n kind: z.literal('document'),\n at: z\n .string()\n .regex(KIND_REF)\n .describe('The kind of document this step rewrites, e.g. \"nisc.nova/layout\" — wherever one sits, at any depth.'),\n transform: z\n .unknown()\n .describe(\n 'A transform config (Prism) run by the injected evaluator over { document, path }: `document` is ONE document of ' +\n 'the `at` kind, `path` where it sits. It returns that document rewritten. Nested documents are found by the ' +\n 'grammar\\'s embeddings and rewritten on their own, deepest first — a transform only ever sees one flat node.',\n ),\n })\n .strict()\n .describe('A rewrite of stored JSON documents of one kind.');\n\nexport const StepSchema = z.discriminatedUnion('kind', [SqlStepSchema, DocumentStepSchema]);\n\nexport const DocumentKindSchema = z\n .object({\n embeds: z\n .record(z.string().regex(EMBED_PATH), z.string().regex(KIND_REF))\n .optional()\n .describe('Where other documents sit inside this one: path → the kind found there (possibly this kind itself).'),\n })\n .strict();\n\nexport const MigrationSchema = z\n .object({\n description: z\n .string()\n .min(1)\n .describe('One sentence: what this migration does. It is the changelog line and the ledger\\'s description.'),\n steps: z\n .array(StepSchema)\n .describe(\n 'Applied in order, in the same transaction as every other pending migration. Empty is a MARKER: ' +\n 'the version moves and nothing runs — how an addition to a strict grammar tells older readers to refuse.',\n ),\n dependsOn: z\n .array(z.string().regex(MIGRATION_REF))\n .optional()\n .describe('Migrations of OTHER sequences that must be applied first, each as \"<sequence>/<n>\".'),\n })\n .strict();\n\nexport const SequenceSchema = z\n .object({\n id: z.string().regex(SEQUENCE_ID).describe('Namespaced and lowercase, e.g. \"nisc.vex.cache\" or \"midas.app\".'),\n documents: z\n .record(z.string().regex(KIND_NAME), DocumentKindSchema)\n .optional()\n .describe('The document kinds this sequence owns (a GRAMMAR sequence), each named \"<id>/<kind>\" elsewhere.'),\n migrations: z\n .array(MigrationSchema)\n .describe('Append-only. A migration is numbered by its position (from 1); the sequence\\'s version is its length.'),\n })\n .strict()\n // Not both: a table sequence's version is recorded per database, a grammar\n // sequence's per document (its stamp), and one number cannot be both.\n .superRefine((sequence, ctx) => {\n const kinds = new Set(sequence.migrations.flatMap((m) => m.steps.map((s) => s.kind)));\n if (kinds.has('sql') && (kinds.has('document') || sequence.documents !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: 'A sequence either owns tables (sql steps) or documents (document steps and `documents`), not both.',\n });\n }\n });\n\nexport type SqlStep = z.infer<typeof SqlStepSchema>;\nexport type DocumentStep = z.infer<typeof DocumentStepSchema>;\nexport type DocumentKind = z.infer<typeof DocumentKindSchema>;\nexport type Step = z.infer<typeof StepSchema>;\nexport type Migration = z.infer<typeof MigrationSchema>;\nexport type Sequence = z.infer<typeof SequenceSchema>;\n","import type { Migration } from './schema';\n\nconst canonical = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n};\n\nconst effectOf = (sql: string): string =>\n sql\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('--'))\n .map((line) => line.trimEnd())\n .join('\\n')\n .trim();\n\nexport const checksumOf = async (migration: Migration): Promise<string> => {\n const steps = migration.steps.map((step) => (step.kind === 'sql' ? { ...step, sql: effectOf(step.sql) } : step));\n const bytes = new TextEncoder().encode(canonical(steps));\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n};\n","import { SequenceSchema, type DocumentKind, type Sequence, type Step } from './schema';\nimport { checksumOf } from './checksum';\nimport { StrataError, type StrataErrorCode } from './errors';\n\nexport type PreparedMigration = {\n sequence: string;\n n: number;\n ref: string;\n description: string;\n checksum: string;\n steps: readonly Step[];\n dependsOn: readonly string[];\n};\n\nexport type PreparedSequence = {\n id: string;\n grammar: boolean;\n documents: Readonly<Record<string, DocumentKind>>;\n migrations: readonly PreparedMigration[];\n};\n\nexport type LedgerRow = { sequence: string; n: number; checksum: string; description: string; appliedAt: string };\n\nexport type Problem = { code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>; detail: string };\n\nexport type Plan = {\n applied: Readonly<Record<string, number>>;\n pending: readonly PreparedMigration[];\n problems: readonly Problem[];\n};\n\nconst refOf = (sequence: string, n: number): string => `${sequence}/${n}`;\n\nexport const prepare = async (sequences: readonly Sequence[]): Promise<readonly PreparedSequence[]> => {\n const seen = new Set<string>();\n const prepared: PreparedSequence[] = [];\n for (const input of sequences) {\n const parsed = SequenceSchema.safeParse(input);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);\n throw new StrataError('INVALID_SEQUENCE', `A sequence does not parse${typeof input.id === 'string' ? ` (\"${input.id}\")` : ''}.`, issues);\n }\n const sequence = parsed.data;\n if (seen.has(sequence.id)) {\n throw new StrataError('INVALID_SEQUENCE', `Two sequences are both called \"${sequence.id}\" — a sequence id names one owner.`);\n }\n seen.add(sequence.id);\n const migrations: PreparedMigration[] = [];\n for (const [index, migration] of sequence.migrations.entries()) {\n const n = index + 1;\n migrations.push({\n sequence: sequence.id,\n n,\n ref: refOf(sequence.id, n),\n description: migration.description,\n checksum: await checksumOf(migration),\n steps: migration.steps,\n dependsOn: migration.dependsOn ?? [],\n });\n }\n const grammar = sequence.documents !== undefined || sequence.migrations.some((m) => m.steps.some((s) => s.kind === 'document'));\n prepared.push({ id: sequence.id, grammar, documents: sequence.documents ?? {}, migrations });\n }\n return prepared;\n};\n\nexport const orderPending = (\n queues: readonly { waiting: readonly PreparedMigration[] }[],\n alreadyDone: ReadonlySet<string>,\n): { pending: PreparedMigration[]; stuck: PreparedMigration[] } => {\n const done = new Set(alreadyDone);\n const waiting = queues.map((q) => [...q.waiting]);\n const pending: PreparedMigration[] = [];\n let moved = true;\n while (moved) {\n moved = false;\n for (const queue of waiting) {\n for (let head = queue[0]; head !== undefined; head = queue[0]) {\n if (!head.dependsOn.every((d) => done.has(d))) break;\n pending.push(head);\n done.add(head.ref);\n queue.shift();\n moved = true;\n }\n }\n }\n return { pending, stuck: waiting.flat() };\n};\n\nexport const planMigrations = (sequences: readonly PreparedSequence[], ledger: readonly LedgerRow[]): Plan => {\n const problems: Problem[] = [];\n const applied: Record<string, number> = {};\n const done = new Set(ledger.map((row) => refOf(row.sequence, row.n)));\n const byRef = new Map(ledger.map((row) => [refOf(row.sequence, row.n), row]));\n\n const queues: { id: string; waiting: PreparedMigration[] }[] = [];\n for (const sequence of sequences) {\n const rows = ledger.filter((row) => row.sequence === sequence.id);\n applied[sequence.id] = rows.length;\n\n const beyond = rows.filter((row) => row.n > sequence.migrations.length);\n if (beyond.length > 0) {\n problems.push({\n code: 'TOO_NEW',\n detail: `${sequence.id}: the database is at ${Math.max(...rows.map((r) => r.n))}, this code knows ${sequence.migrations.length} — it was migrated by newer code.`,\n });\n }\n\n const waiting: PreparedMigration[] = [];\n for (const migration of sequence.migrations) {\n const row = byRef.get(migration.ref);\n if (row === undefined) {\n waiting.push(migration);\n } else if (row.checksum !== migration.checksum) {\n problems.push({\n code: 'EDITED',\n detail: `${migration.ref} (\"${migration.description}\") was applied ${row.appliedAt} and its steps have changed since. An applied migration is history — append a new one.`,\n });\n }\n }\n const firstWaiting = waiting[0];\n if (firstWaiting !== undefined && rows.some((row) => row.n > firstWaiting.n)) {\n problems.push({ code: 'EDITED', detail: `${sequence.id}: ${firstWaiting.ref} never ran, but a later migration of the sequence did.` });\n }\n queues.push({ id: sequence.id, waiting });\n }\n\n const provided = new Set(sequences.flatMap((s) => s.migrations.map((m) => m.ref)));\n for (const { waiting } of queues) {\n for (const migration of waiting) {\n for (const dependency of migration.dependsOn) {\n if (!done.has(dependency) && !provided.has(dependency)) {\n problems.push({ code: 'UNKNOWN_DEPENDENCY', detail: `${migration.ref} depends on ${dependency}, which nothing provides and the database has not run.` });\n }\n }\n }\n }\n\n const { pending, stuck } = orderPending(queues, done);\n if (stuck.length > 0 && !problems.some((p) => p.code === 'UNKNOWN_DEPENDENCY')) {\n problems.push({ code: 'CYCLE', detail: `These wait on each other and can never run: ${stuck.map((m) => m.ref).join(', ')}.` });\n }\n\n return { applied, pending, problems };\n};\n\nexport const refuseProblems = (plan: Plan): void => {\n const first = plan.problems[0];\n if (first === undefined) return;\n throw new StrataError(first.code, 'The migrations cannot be applied safely.', plan.problems.map((p) => `${p.code}: ${p.detail}`));\n};\n"]}
|