@niscorp/strata 0.1.3 → 0.1.5
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 +56 -0
- package/README.md +2 -2
- package/dist/check/index.cjs +23 -228
- package/dist/check/index.cjs.map +1 -1
- package/dist/check/index.js +2 -2
- package/dist/{chunk-274M232S.js → chunk-4BLHBVSC.js} +3 -3
- package/dist/{chunk-274M232S.js.map → chunk-4BLHBVSC.js.map} +1 -1
- package/dist/{chunk-U5CPF4LQ.js → chunk-5KTXEN43.js} +3 -3
- package/dist/{chunk-U5CPF4LQ.js.map → chunk-5KTXEN43.js.map} +1 -1
- package/dist/{chunk-EGFF63GA.js → chunk-AKKWEXO2.js} +2 -2
- package/dist/{chunk-EGFF63GA.js.map → chunk-AKKWEXO2.js.map} +1 -1
- package/dist/chunk-ATHZ7HT5.cjs +18 -0
- package/dist/chunk-ATHZ7HT5.cjs.map +1 -0
- package/dist/chunk-CL5DF2IQ.cjs +192 -0
- package/dist/chunk-CL5DF2IQ.cjs.map +1 -0
- package/dist/chunk-IHYBGLNW.cjs +161 -0
- package/dist/chunk-IHYBGLNW.cjs.map +1 -0
- package/dist/chunk-KNBS3AJZ.cjs +223 -0
- package/dist/chunk-KNBS3AJZ.cjs.map +1 -0
- package/dist/{chunk-TWAEZHTB.js → chunk-OLDORFOQ.js} +4 -4
- package/dist/{chunk-TWAEZHTB.js.map → chunk-OLDORFOQ.js.map} +1 -1
- package/dist/{chunk-2FIZEJXW.js → chunk-WU3OJHVZ.js} +4 -4
- package/dist/{chunk-2FIZEJXW.js.map → chunk-WU3OJHVZ.js.map} +1 -1
- package/dist/chunk-YXFEJJMC.cjs +136 -0
- package/dist/chunk-YXFEJJMC.cjs.map +1 -0
- package/dist/index.cjs +75 -330
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/node/index.cjs +14 -493
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.js +5 -5
- package/dist/{plan-BEIlXVUt.d.cts → plan-CxuteSH1.d.cts} +2 -2
- package/dist/{plan-BAewc8DG.d.ts → plan-mFmdh0qT.d.ts} +2 -2
- package/dist/postgres/index.cjs +30 -198
- package/dist/postgres/index.cjs.map +1 -1
- package/dist/postgres/index.d.cts +7 -2
- package/dist/postgres/index.d.ts +7 -2
- package/dist/postgres/index.js +17 -3
- package/dist/postgres/index.js.map +1 -1
- package/dist/upgrade/index.cjs +19 -240
- package/dist/upgrade/index.cjs.map +1 -1
- package/dist/upgrade/index.js +3 -3
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/postgres/index.ts"],"names":[],"mappings":";;;;AAqDA,IAAM,KAAA,GAAQ,0BAAA;AACd,IAAM,KAAA,GAAQ,CAAC,IAAA,EAAc,KAAA,KAA0B;AACrD,EAAA,IAAI,CAAC,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,EAAG,MAAM,IAAI,WAAA,CAAY,kBAAA,EAAoB,CAAA,WAAA,EAAc,KAAK,CAAA,EAAA,EAAK,IAAI,CAAA,4BAAA,CAA8B,CAAA;AAC3H,EAAA,OAAO,IAAI,IAAI,CAAA,CAAA,CAAA;AACjB,CAAA;AAEA,IAAM,YAAA,GAAe,CAAC,OAAA,KAA8E;AAClG,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,OAAA,CAAQ,KAAA,IAAS,iBAAiB,OAAO,CAAA;AAC7D,EAAA,MAAM,MAAA,GAAS,QAAQ,MAAA,KAAW,MAAA,GAAY,SAAY,KAAA,CAAM,OAAA,CAAQ,QAAQ,QAAQ,CAAA;AACxF,EAAA,OAAO,EAAE,SAAA,EAAW,MAAA,KAAW,MAAA,GAAY,KAAA,GAAQ,GAAG,MAAM,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,EAAI,MAAA,EAAO;AAClF,CAAA;AAEO,IAAM,SAAA,GAAY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AA,IAAK,CAAA,IAAK,CAAA;AAAA,IACzE;AACA,IAAA,OAAO,EAAE,KAAA,EAAO,IAAA,CAAK,MAAA,EAAQ,UAAU,OAAA,EAAQ;AAAA,EACjD,CAAC,CAAA;AACH","file":"index.js","sourcesContent":["import { prepare, planMigrations, refuseProblems, type LedgerRow, type Plan, type PreparedMigration, type PreparedSequence } from '../plan';\nimport type { Sequence } from '../schema';\nimport type { UpgradeResult, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/postgres — the ledger, and the one path DDL takes.\n//\n// A run is ONE TRANSACTION under an advisory lock: take the lock, make sure the\n// ledger exists, read it, plan against it, apply every pending step and record\n// each migration as it lands. Anything throws, nothing happened — Postgres DDL\n// is transactional, so a half-migrated database is not a state this can leave.\n// Two processes booting at once serialize on the lock; the second finds the\n// work done.\n//\n// The ledger's own table is the only statement strata runs outside a ledger —\n// the base case, the way every migration system has one.\n// ═══════════════════════════════════════════════════════════════\n\n// The pool shape nisc passes everywhere (vex's PgPool, a PGlite shim, a `pg`\n// pool wrapped to check a client out per transaction). Structural — strata\n// depends on no driver.\n//\n// `query` and `transaction` are called ON the object that has them, never\n// taken off it first. A driver's own object (a PGlite, a `pg` client handed\n// through as the transaction) has them as methods that reach for `this`; taken\n// off, they fail inside the driver on a property nobody here has heard of.\nexport type StrataQuery = (text: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;\nexport type StrataPool = {\n query: StrataQuery;\n transaction?: <T>(fn: (tx: { query: StrataQuery }) => Promise<T>) => Promise<T>;\n};\n\nexport type LedgerOptions = {\n // Default `strata_ledger`, in the connection's current schema — beside the\n // app's own tables.\n table?: string;\n schema?: string;\n};\n\nexport type MigrateOptions = LedgerOptions & {\n // `apply` (default): run what is pending. `verify`: refuse if anything is —\n // a production boot that expects a deploy step to have migrated already.\n mode?: 'apply' | 'verify';\n};\n\nexport type MigrateReport = {\n // What this run applied, in order.\n applied: readonly PreparedMigration[];\n // The plan it acted on (per-sequence positions before the run).\n plan: Plan;\n};\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst quote = (name: string, label: string): string => {\n if (!IDENT.test(name)) throw new StrataError('INVALID_SEQUENCE', `The ledger ${label} \"${name}\" is not a plain identifier.`);\n return `\"${name}\"`;\n};\n\nconst ledgerNameOf = (options: LedgerOptions): { qualified: string; schema: string | undefined } => {\n const table = quote(options.table ?? 'strata_ledger', 'table');\n const schema = options.schema === undefined ? undefined : quote(options.schema, 'schema');\n return { qualified: schema === undefined ? table : `${schema}.${table}`, schema };\n};\n\nexport const ledgerDdl = (options: LedgerOptions = {}): string => {\n const { qualified } = ledgerNameOf(options);\n return `CREATE TABLE IF NOT EXISTS ${qualified} (\n sequence text NOT NULL,\n n integer NOT NULL,\n description text NOT NULL,\n checksum text NOT NULL,\n applied_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (sequence, n)\n)`;\n};\n\nconst text = (value: unknown): string => (value instanceof Date ? value.toISOString() : String(value));\n\nconst readRows = async (on: { query: StrataQuery }, qualified: string): Promise<LedgerRow[]> => {\n const { rows } = await on.query(`SELECT sequence, n, checksum, description, applied_at FROM ${qualified} ORDER BY sequence, n`);\n return rows.map((row) => ({\n sequence: text(row['sequence']),\n n: Number(row['n']),\n checksum: text(row['checksum']),\n description: text(row['description']),\n appliedAt: text(row['applied_at']),\n }));\n};\n\n// The ledger as it stands — read-only, no lock, no table created. A database\n// that has never been migrated has an empty ledger.\nexport const readLedger = async (pool: StrataPool, options: LedgerOptions = {}): Promise<LedgerRow[]> => {\n const { qualified } = ledgerNameOf(options);\n const { rows } = await pool.query('SELECT to_regclass($1) IS NOT NULL AS present', [qualified]);\n if (rows[0]?.['present'] !== true) return [];\n return readRows(pool, qualified);\n};\n\n// What `migrate` would do, without doing it — for a boot report, a CI check, a\n// page that shows the ledger.\nexport const status = async (pool: StrataPool, sequences: readonly Sequence[], options: LedgerOptions = {}): Promise<Plan> =>\n planMigrations(await prepare(sequences), await readLedger(pool, options));\n\nconst refuseGrammars = (prepared: readonly PreparedSequence[]): void => {\n const grammars = prepared.filter((s) => s.grammar);\n if (grammars.length > 0) {\n throw new StrataError(\n 'WRONG_OWNER',\n 'These sequences own documents, not tables: a document carries its own stamp and is upgraded where it is read (`createUpgrader`, `upgradeStore`) — never recorded in a database\\'s ledger.',\n grammars.map((s) => s.id),\n );\n }\n};\n\nexport const migrate = async (pool: StrataPool, sequences: readonly Sequence[], options: MigrateOptions = {}): Promise<MigrateReport> => {\n const prepared = await prepare(sequences);\n refuseGrammars(prepared);\n if (pool.transaction === undefined) {\n throw new StrataError(\n 'NO_TRANSACTION',\n 'This pool cannot run a transaction, and a migration run must land whole or not at all. ' +\n 'Pass a pool with `transaction` (vex\\'s PGlite pool has one; wrap a `pg` Pool so it checks a client out per transaction).',\n );\n }\n const { qualified, schema } = ledgerNameOf(options);\n\n return pool.transaction(async (tx) => {\n // The lock first: two processes creating the ledger at once would race in\n // the catalog before either reached a row.\n await tx.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`strata:${qualified}`]);\n if (schema !== undefined) await tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);\n await tx.query(ledgerDdl(options));\n\n const plan = planMigrations(prepared, await readRows(tx, qualified));\n refuseProblems(plan);\n if (options.mode === 'verify' && plan.pending.length > 0) {\n throw new StrataError(\n 'PENDING',\n `${plan.pending.length} migration${plan.pending.length === 1 ? ' is' : 's are'} not applied, and this boot only verifies. Run the migrations first.`,\n plan.pending.map((m) => `${m.ref} ${m.description}`),\n );\n }\n\n const applied: PreparedMigration[] = [];\n for (const migration of plan.pending) {\n for (const [index, step] of migration.steps.entries()) {\n // Only table sequences reach the ledger (refuseGrammars above).\n if (step.kind !== 'sql') continue;\n try {\n await tx.query(step.sql);\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed at step ${index + 1} of ${migration.steps.length}. Nothing from this run was applied.`,\n [cause instanceof Error ? cause.message : String(cause), step.sql.length > 300 ? `${step.sql.slice(0, 300)}…` : step.sql],\n { cause },\n );\n }\n }\n await tx.query(`INSERT INTO ${qualified} (sequence, n, description, checksum) VALUES ($1, $2, $3, $4)`, [\n migration.sequence,\n migration.n,\n migration.description,\n migration.checksum,\n ]);\n applied.push(migration);\n }\n return { applied, plan };\n });\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Stores — tables whose rows hold documents.\n//\n// A store names where the documents live: the table, the jsonb column holding\n// each document, the jsonb column holding its stamp, the kind every document\n// in it is, and the key that identifies a row. The table itself (and its stamp\n// column) is its owner's, created by the owner's TABLE sequence; strata only\n// reads and rewrites rows.\n//\n// `upgradeStore` brings every row that is behind up to the code, in one\n// transaction, and writes each back with a current stamp. A row written by\n// newer code refuses the whole run (TOO_NEW) — the same answer the ledger\n// gives, one row at a time. Read paths that cannot wait for a boot upgrade the\n// row they read with the same upgrader; this is the pass that makes that rare.\n// ═══════════════════════════════════════════════════════════════\n\nexport type DocumentStore = {\n table: string;\n schema?: string;\n // The jsonb column holding the document.\n column: string;\n // The jsonb column holding the document's stamp (`{}` means \"before stamps\").\n stamp: string;\n // Every document in this store is of this kind, e.g. \"nisc.nova/action\".\n kind: string;\n // The columns that identify a row.\n key: readonly string[];\n};\n\nexport type StoreReport = {\n // Rows read, and rows that were behind and rewritten.\n total: number;\n upgraded: number;\n // Per migration ref, how many rows it rewrote.\n applied: Readonly<Record<string, number>>;\n};\n\nexport const upgradeStore = async (pool: StrataPool, store: DocumentStore, upgrader: Upgrader): Promise<StoreReport> => {\n if (pool.transaction === undefined) {\n throw new StrataError('NO_TRANSACTION', 'Rewriting a store must land whole or not at all; this pool cannot run a transaction.');\n }\n const table = store.schema === undefined ? quote(store.table, 'table') : `${quote(store.schema, 'schema')}.${quote(store.table, 'table')}`;\n const column = quote(store.column, 'column');\n const stamp = quote(store.stamp, 'column');\n const keys = store.key.map((k) => quote(k, 'column'));\n if (keys.length === 0) throw new StrataError('INVALID_SEQUENCE', `The store ${store.table} names no key columns.`);\n\n return pool.transaction(async (tx) => {\n const { rows } = await tx.query(`SELECT ${[...keys, column, stamp].join(', ')} FROM ${table} FOR UPDATE`);\n const applied: Record<string, number> = {};\n let upgraded = 0;\n for (const row of rows) {\n const given = row[store.stamp];\n const rowStamp = typeof given === 'object' && given !== null && !Array.isArray(given) ? Object.fromEntries(Object.entries(given).map(([k, v]) => [k, Number(v)])) : {};\n const where = store.key.map((k) => `${k}=${JSON.stringify(row[k])}`).join(', ');\n let result: UpgradeResult;\n try {\n if (!upgrader.behind(rowStamp)) continue;\n result = upgrader.upgrade(row[store.column], { kind: store.kind, stamp: rowStamp });\n } catch (cause) {\n if (cause instanceof StrataError) {\n throw new StrataError(cause.code, `${store.table} (${where}): ${cause.message.split('\\n')[0] ?? ''}`, cause.details, { cause });\n }\n throw cause;\n }\n await tx.query(\n `UPDATE ${table} SET ${column} = $1::jsonb, ${stamp} = $2::jsonb WHERE ${keys.map((k, i) => `${k} = $${i + 3}`).join(' AND ')}`,\n [JSON.stringify(result.document), JSON.stringify(result.stamp), ...store.key.map((k) => row[k])],\n );\n upgraded += 1;\n for (const ref of result.applied) applied[ref] = (applied[ref] ?? 0) + 1;\n }\n return { total: rows.length, upgraded, applied };\n });\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/postgres/index.ts"],"names":[],"mappings":";;;;AAgEA,IAAM,KAAA,GAAQ,0BAAA;AACd,IAAM,KAAA,GAAQ,CAAC,IAAA,EAAc,KAAA,KAA0B;AACrD,EAAA,IAAI,CAAC,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,EAAG,MAAM,IAAI,WAAA,CAAY,kBAAA,EAAoB,CAAA,WAAA,EAAc,KAAK,CAAA,EAAA,EAAK,IAAI,CAAA,4BAAA,CAA8B,CAAA;AAC3H,EAAA,OAAO,IAAI,IAAI,CAAA,CAAA,CAAA;AACjB,CAAA;AAEA,IAAM,YAAA,GAAe,CAAC,OAAA,KAA8E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Migrations, refuseProblems, type LedgerRow, type Plan, type PreparedMigration, type PreparedSequence } from '../plan';\nimport type { Sequence } from '../schema';\nimport type { UpgradeResult, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/postgres — the ledger, and the one path DDL takes.\n//\n// A run is ONE TRANSACTION under an advisory lock: take the lock, make sure the\n// ledger exists, read it, plan against it, apply every pending step and record\n// each migration as it lands. Anything throws, nothing happened — Postgres DDL\n// is transactional, so a half-migrated database is not a state this can leave.\n// Two processes booting at once serialize on the lock; the second finds the\n// work done.\n//\n// The ledger's own table is the only statement strata runs outside a ledger —\n// the base case, the way every migration system has one.\n// ═══════════════════════════════════════════════════════════════\n\n// The pool shape nisc passes everywhere (vex's PgPool, a PGlite shim, a `pg`\n// pool wrapped to check a client out per transaction). Structural — strata\n// depends on no driver.\n//\n// `query` and `transaction` are called ON the object that has them, never\n// taken off it first. A driver's own object (a PGlite, a `pg` client handed\n// through as the transaction) has them as methods that reach for `this`; taken\n// off, they fail inside the driver on a property nobody here has heard of.\nexport type StrataQuery = (text: string, values?: unknown[]) => Promise<{ rows: Record<string, unknown>[] }>;\nexport type StrataPool = {\n query: StrataQuery;\n transaction?: <T>(fn: (tx: { query: StrataQuery }) => Promise<T>) => Promise<T>;\n};\n\nexport type LedgerOptions = {\n // Default `strata_ledger`, in the connection's current schema — beside the\n // app's own tables.\n table?: string;\n schema?: string;\n};\n\n// What a host asks of a run before it may land: called inside the run's\n// transaction, after the last pending step — when nothing was pending too.\n// Every sentence it returns refuses the run (DOES_NOT_FIT) — and since\n// nothing has been committed, nothing happened. strata does not know what is\n// being asked; the host does.\nexport type MigrateGuard = (tx: { query: StrataQuery }) => Promise<readonly string[]>;\n\nexport type MigrateOptions = LedgerOptions & {\n // `apply` (default): run what is pending. `verify`: refuse if anything is —\n // a production boot that expects a deploy step to have migrated already.\n mode?: 'apply' | 'verify';\n guard?: MigrateGuard;\n // The whole run, guard included, then rolled back: the report says what\n // WOULD be applied. It takes the locks a real run takes, for as long.\n dryRun?: boolean;\n};\n\nexport type MigrateReport = {\n // What this run applied, in order.\n applied: readonly PreparedMigration[];\n // The plan it acted on (per-sequence positions before the run).\n plan: Plan;\n};\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst quote = (name: string, label: string): string => {\n if (!IDENT.test(name)) throw new StrataError('INVALID_SEQUENCE', `The ledger ${label} \"${name}\" is not a plain identifier.`);\n return `\"${name}\"`;\n};\n\nconst ledgerNameOf = (options: LedgerOptions): { qualified: string; schema: string | undefined } => {\n const table = quote(options.table ?? 'strata_ledger', 'table');\n const schema = options.schema === undefined ? undefined : quote(options.schema, 'schema');\n return { qualified: schema === undefined ? table : `${schema}.${table}`, schema };\n};\n\nexport const ledgerDdl = (options: LedgerOptions = {}): string => {\n const { qualified } = ledgerNameOf(options);\n return `CREATE TABLE IF NOT EXISTS ${qualified} (\n sequence text NOT NULL,\n n integer NOT NULL,\n description text NOT NULL,\n checksum text NOT NULL,\n applied_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY (sequence, n)\n)`;\n};\n\nconst text = (value: unknown): string => (value instanceof Date ? value.toISOString() : String(value));\n\nconst readRows = async (on: { query: StrataQuery }, qualified: string): Promise<LedgerRow[]> => {\n const { rows } = await on.query(`SELECT sequence, n, checksum, description, applied_at FROM ${qualified} ORDER BY sequence, n`);\n return rows.map((row) => ({\n sequence: text(row['sequence']),\n n: Number(row['n']),\n checksum: text(row['checksum']),\n description: text(row['description']),\n appliedAt: text(row['applied_at']),\n }));\n};\n\n// The ledger as it stands — read-only, no lock, no table created. A database\n// that has never been migrated has an empty ledger.\nexport const readLedger = async (pool: StrataPool, options: LedgerOptions = {}): Promise<LedgerRow[]> => {\n const { qualified } = ledgerNameOf(options);\n const { rows } = await pool.query('SELECT to_regclass($1) IS NOT NULL AS present', [qualified]);\n if (rows[0]?.['present'] !== true) return [];\n return readRows(pool, qualified);\n};\n\n// What `migrate` would do, without doing it — for a boot report, a CI check, a\n// page that shows the ledger.\nexport const status = async (pool: StrataPool, sequences: readonly Sequence[], options: LedgerOptions = {}): Promise<Plan> =>\n planMigrations(await prepare(sequences), await readLedger(pool, options));\n\nconst refuseGrammars = (prepared: readonly PreparedSequence[]): void => {\n const grammars = prepared.filter((s) => s.grammar);\n if (grammars.length > 0) {\n throw new StrataError(\n 'WRONG_OWNER',\n 'These sequences own documents, not tables: a document carries its own stamp and is upgraded where it is read (`createUpgrader`, `upgradeStore`) — never recorded in a database\\'s ledger.',\n grammars.map((s) => s.id),\n );\n }\n};\n\nexport const migrate = async (pool: StrataPool, sequences: readonly Sequence[], options: MigrateOptions = {}): Promise<MigrateReport> => {\n const prepared = await prepare(sequences);\n refuseGrammars(prepared);\n if (pool.transaction === undefined) {\n throw new StrataError(\n 'NO_TRANSACTION',\n 'This pool cannot run a transaction, and a migration run must land whole or not at all. ' +\n 'Pass a pool with `transaction` (vex\\'s PGlite pool has one; wrap a `pg` Pool so it checks a client out per transaction).',\n );\n }\n const { qualified, schema } = ledgerNameOf(options);\n // A dry run leaves by throwing: that is what rolls a transaction back in\n // every pool there is. This is the throw, told apart by being this object.\n const dryRunEnd = new Error('strata: dry run');\n let dryRunReport: MigrateReport | undefined;\n\n const run = pool.transaction(async (tx) => {\n // The lock first: two processes creating the ledger at once would race in\n // the catalog before either reached a row.\n await tx.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`strata:${qualified}`]);\n if (schema !== undefined) await tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);\n await tx.query(ledgerDdl(options));\n\n const plan = planMigrations(prepared, await readRows(tx, qualified));\n refuseProblems(plan);\n if (options.mode === 'verify' && plan.pending.length > 0) {\n throw new StrataError(\n 'PENDING',\n `${plan.pending.length} migration${plan.pending.length === 1 ? ' is' : 's are'} not applied, and this boot only verifies. Run the migrations first.`,\n plan.pending.map((m) => `${m.ref} ${m.description}`),\n );\n }\n\n const applied: PreparedMigration[] = [];\n for (const migration of plan.pending) {\n for (const [index, step] of migration.steps.entries()) {\n // Only table sequences reach the ledger (refuseGrammars above).\n if (step.kind !== 'sql') continue;\n try {\n await tx.query(step.sql);\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed at step ${index + 1} of ${migration.steps.length}. Nothing from this run was applied.`,\n [cause instanceof Error ? cause.message : String(cause), step.sql.length > 300 ? `${step.sql.slice(0, 300)}…` : step.sql],\n { cause },\n );\n }\n }\n await tx.query(`INSERT INTO ${qualified} (sequence, n, description, checksum) VALUES ($1, $2, $3, $4)`, [\n migration.sequence,\n migration.n,\n migration.description,\n migration.checksum,\n ]);\n applied.push(migration);\n }\n\n const reasons = options.guard === undefined ? [] : await options.guard(tx);\n if (reasons.length > 0) {\n throw new StrataError('DOES_NOT_FIT', 'What this run leaves does not fit what has to run on it. Nothing from this run was applied.', reasons);\n }\n if (options.dryRun === true) {\n dryRunReport = { applied, plan };\n throw dryRunEnd;\n }\n return { applied, plan };\n });\n\n return run.catch((error: unknown) => {\n if (error === dryRunEnd && dryRunReport !== undefined) return dryRunReport;\n throw error;\n });\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Stores — tables whose rows hold documents.\n//\n// A store names where the documents live: the table, the jsonb column holding\n// each document, the jsonb column holding its stamp, the kind every document\n// in it is, and the key that identifies a row. The table itself (and its stamp\n// column) is its owner's, created by the owner's TABLE sequence; strata only\n// reads and rewrites rows.\n//\n// `upgradeStore` brings every row that is behind up to the code, in one\n// transaction, and writes each back with a current stamp. A row written by\n// newer code refuses the whole run (TOO_NEW) — the same answer the ledger\n// gives, one row at a time. Read paths that cannot wait for a boot upgrade the\n// row they read with the same upgrader; this is the pass that makes that rare.\n// ═══════════════════════════════════════════════════════════════\n\nexport type DocumentStore = {\n table: string;\n schema?: string;\n // The jsonb column holding the document.\n column: string;\n // The jsonb column holding the document's stamp (`{}` means \"before stamps\").\n stamp: string;\n // Every document in this store is of this kind, e.g. \"nisc.nova/action\".\n kind: string;\n // The columns that identify a row.\n key: readonly string[];\n};\n\nexport type StoreReport = {\n // Rows read, and rows that were behind and rewritten.\n total: number;\n upgraded: number;\n // Per migration ref, how many rows it rewrote.\n applied: Readonly<Record<string, number>>;\n};\n\nexport const upgradeStore = async (pool: StrataPool, store: DocumentStore, upgrader: Upgrader): Promise<StoreReport> => {\n if (pool.transaction === undefined) {\n throw new StrataError('NO_TRANSACTION', 'Rewriting a store must land whole or not at all; this pool cannot run a transaction.');\n }\n const table = store.schema === undefined ? quote(store.table, 'table') : `${quote(store.schema, 'schema')}.${quote(store.table, 'table')}`;\n const column = quote(store.column, 'column');\n const stamp = quote(store.stamp, 'column');\n const keys = store.key.map((k) => quote(k, 'column'));\n if (keys.length === 0) throw new StrataError('INVALID_SEQUENCE', `The store ${store.table} names no key columns.`);\n\n return pool.transaction(async (tx) => {\n const { rows } = await tx.query(`SELECT ${[...keys, column, stamp].join(', ')} FROM ${table} FOR UPDATE`);\n const applied: Record<string, number> = {};\n let upgraded = 0;\n for (const row of rows) {\n const given = row[store.stamp];\n const rowStamp = typeof given === 'object' && given !== null && !Array.isArray(given) ? Object.fromEntries(Object.entries(given).map(([k, v]) => [k, Number(v)])) : {};\n const where = store.key.map((k) => `${k}=${JSON.stringify(row[k])}`).join(', ');\n let result: UpgradeResult;\n try {\n if (!upgrader.behind(rowStamp)) continue;\n result = upgrader.upgrade(row[store.column], { kind: store.kind, stamp: rowStamp });\n } catch (cause) {\n if (cause instanceof StrataError) {\n throw new StrataError(cause.code, `${store.table} (${where}): ${cause.message.split('\\n')[0] ?? ''}`, cause.details, { cause });\n }\n throw cause;\n }\n await tx.query(\n `UPDATE ${table} SET ${column} = $1::jsonb, ${stamp} = $2::jsonb WHERE ${keys.map((k, i) => `${k} = $${i + 3}`).join(' AND ')}`,\n [JSON.stringify(result.document), JSON.stringify(result.stamp), ...store.key.map((k) => row[k])],\n );\n upgraded += 1;\n for (const ref of result.applied) applied[ref] = (applied[ref] ?? 0) + 1;\n }\n return { total: rows.length, upgraded, applied };\n });\n};\n"]}
|
package/dist/upgrade/index.cjs
CHANGED
|
@@ -1,247 +1,26 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
details;
|
|
7
|
-
constructor(code, message, details = [], options) {
|
|
8
|
-
super(details.length > 0 ? `${message}
|
|
9
|
-
${details.map((d) => ` ${d}`).join("\n")}` : message, options);
|
|
10
|
-
this.name = "StrataError";
|
|
11
|
-
this.code = code;
|
|
12
|
-
this.details = details;
|
|
13
|
-
}
|
|
14
|
-
};
|
|
3
|
+
var chunkIHYBGLNW_cjs = require('../chunk-IHYBGLNW.cjs');
|
|
4
|
+
require('../chunk-KNBS3AJZ.cjs');
|
|
5
|
+
require('../chunk-ATHZ7HT5.cjs');
|
|
15
6
|
|
|
16
|
-
// src/check/index.ts
|
|
17
|
-
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
18
|
-
var byKey = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
|
|
19
|
-
var sortKeys = (value) => {
|
|
20
|
-
if (Array.isArray(value)) return value.map(sortKeys);
|
|
21
|
-
if (!isRecord(value)) return value;
|
|
22
|
-
return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));
|
|
23
|
-
};
|
|
24
|
-
var NAMED = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
|
|
25
|
-
var DATA = /* @__PURE__ */ new Set(["const", "enum", "default", "examples"]);
|
|
26
|
-
var normalize = (value) => {
|
|
27
|
-
if (Array.isArray(value)) return value.map(normalize);
|
|
28
|
-
if (!isRecord(value)) return value;
|
|
29
|
-
return Object.fromEntries(
|
|
30
|
-
Object.entries(value).filter(([key]) => key !== "description" && key !== "$schema").sort(byKey).map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)])
|
|
31
|
-
);
|
|
32
|
-
};
|
|
33
|
-
var namedSchemas = (map, each) => Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));
|
|
34
|
-
var diffLines = (a, b, path, out, limit, canon = normalize, sets = true) => {
|
|
35
|
-
if (out.length >= limit) return;
|
|
36
|
-
if (JSON.stringify(a) === JSON.stringify(b)) return;
|
|
37
|
-
if (isRecord(a) && isRecord(b)) {
|
|
38
|
-
for (const key of [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {
|
|
39
|
-
const at = path === "" ? key : `${path}.${key}`;
|
|
40
|
-
const before = a[key];
|
|
41
|
-
const after = b[key];
|
|
42
|
-
if (!(key in a)) out.push(`+ ${at}`);
|
|
43
|
-
else if (!(key in b)) out.push(`- ${at}`);
|
|
44
|
-
else if (sets && key === "prefixItems" && Array.isArray(before) && Array.isArray(after)) diffPositions(before, after, at, out, limit, canon);
|
|
45
|
-
else diffLines(before, after, at, out, limit, canon, sets);
|
|
46
|
-
if (out.length >= limit) return;
|
|
47
|
-
}
|
|
48
|
-
return;
|
|
49
|
-
}
|
|
50
|
-
if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {
|
|
51
|
-
a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
if (Array.isArray(a) && Array.isArray(b)) {
|
|
55
|
-
const text = (v) => JSON.stringify(canon(v));
|
|
56
|
-
const label = (v) => isRecord(v) && isRecord(v["properties"]) ? Object.keys(v["properties"]).join(",") : (text(v) ?? "").slice(0, 50);
|
|
57
|
-
const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));
|
|
58
|
-
const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));
|
|
59
|
-
const byLabel = new Map(onlyB.map((y) => [label(y), y]));
|
|
60
|
-
for (const x of onlyA) {
|
|
61
|
-
const partner = byLabel.get(label(x));
|
|
62
|
-
if (partner !== void 0) {
|
|
63
|
-
diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);
|
|
64
|
-
byLabel.delete(label(x));
|
|
65
|
-
} else {
|
|
66
|
-
out.push(`- ${path}[${label(x)}]`);
|
|
67
|
-
}
|
|
68
|
-
if (out.length >= limit) return;
|
|
69
|
-
}
|
|
70
|
-
for (const [name] of byLabel) {
|
|
71
|
-
out.push(`+ ${path}[${name}]`);
|
|
72
|
-
if (out.length >= limit) return;
|
|
73
|
-
}
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
out.push(`~ ${path || "(root)"}: ${JSON.stringify(a)?.slice(0, 60)} \u2192 ${JSON.stringify(b)?.slice(0, 60)}`);
|
|
77
|
-
};
|
|
78
|
-
var diffPositions = (a, b, path, out, limit, canon) => {
|
|
79
|
-
for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
|
|
80
|
-
if (out.length >= limit) return;
|
|
81
|
-
if (i >= a.length) out.push(`+ ${path}[${i}]`);
|
|
82
|
-
else if (i >= b.length) out.push(`- ${path}[${i}]`);
|
|
83
|
-
else diffLines(a[i], b[i], `${path}[${i}]`, out, limit, canon, true);
|
|
84
|
-
}
|
|
85
|
-
};
|
|
86
|
-
var diffJson = (a, b, limit = 20) => {
|
|
87
|
-
const out = [];
|
|
88
|
-
diffLines(a, b, "", out, limit, sortKeys, false);
|
|
89
|
-
return out;
|
|
90
|
-
};
|
|
91
7
|
|
|
92
|
-
// src/upgrade/index.ts
|
|
93
|
-
var keyOf = (doc) => `${doc.kind}:${doc.id}`;
|
|
94
|
-
var sortKeys2 = (value) => {
|
|
95
|
-
if (Array.isArray(value)) return value.map(sortKeys2);
|
|
96
|
-
if (typeof value !== "object" || value === null) return value;
|
|
97
|
-
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, sortKeys2(v)]));
|
|
98
|
-
};
|
|
99
|
-
var sameJson = (a, b) => JSON.stringify(sortKeys2(a)) === JSON.stringify(sortKeys2(b));
|
|
100
|
-
var changedStrings = (before, after) => {
|
|
101
|
-
const found = /* @__PURE__ */ new Set();
|
|
102
|
-
const visit = (a, b) => {
|
|
103
|
-
if (JSON.stringify(a) === JSON.stringify(b)) return;
|
|
104
|
-
if (typeof a === "string") {
|
|
105
|
-
found.add(a);
|
|
106
|
-
return;
|
|
107
|
-
}
|
|
108
|
-
if (Array.isArray(a)) {
|
|
109
|
-
a.forEach((item, i) => visit(item, Array.isArray(b) ? b[i] : void 0));
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
if (typeof a === "object" && a !== null) {
|
|
113
|
-
for (const [k, v] of Object.entries(a)) visit(v, typeof b === "object" && b !== null && !Array.isArray(b) ? Reflect.get(b, k) : void 0);
|
|
114
|
-
}
|
|
115
|
-
};
|
|
116
|
-
visit(before, after);
|
|
117
|
-
return [...found].filter((s) => s.length >= 4);
|
|
118
|
-
};
|
|
119
|
-
var planSourceUpgrade = async (options) => {
|
|
120
|
-
const { upgrader, stamp, documents, schemas, describe } = options;
|
|
121
|
-
const seen = /* @__PURE__ */ new Set();
|
|
122
|
-
const planned = [];
|
|
123
|
-
const untouched = [];
|
|
124
|
-
const problems = [];
|
|
125
|
-
for (const doc of documents) {
|
|
126
|
-
const key = keyOf(doc);
|
|
127
|
-
if (seen.has(key)) throw new StrataError("INVALID_SEQUENCE", `Two artifacts are both ${key} \u2014 an artifact needs one identity to be planned.`);
|
|
128
|
-
seen.add(key);
|
|
129
|
-
const result = upgrader.upgrade(doc.document, { kind: doc.kind, stamp });
|
|
130
|
-
if (sameJson(result.document, doc.document)) {
|
|
131
|
-
untouched.push(key);
|
|
132
|
-
continue;
|
|
133
|
-
}
|
|
134
|
-
planned.push({
|
|
135
|
-
kind: doc.kind,
|
|
136
|
-
id: doc.id,
|
|
137
|
-
...doc.file === void 0 ? {} : { file: doc.file },
|
|
138
|
-
applied: result.applied,
|
|
139
|
-
changes: diffJson(doc.document, result.document),
|
|
140
|
-
expected: result.document
|
|
141
|
-
});
|
|
142
|
-
const schema = schemas?.[doc.kind];
|
|
143
|
-
if (schema !== void 0) {
|
|
144
|
-
const checked = await schema["~standard"].validate(result.document);
|
|
145
|
-
if (checked.issues !== void 0) {
|
|
146
|
-
problems.push(`${key}: the migrated artifact does not pass ${doc.kind}'s current schema \u2014 ${checked.issues.slice(0, 2).map((i) => i.message).join("; ")}`);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
const from = stamp;
|
|
151
|
-
const to = upgrader.stamp;
|
|
152
|
-
const migrations = Object.entries(to).flatMap(
|
|
153
|
-
([id, n]) => Array.from({ length: Math.max(0, n - (from[id] ?? 0)) }, (_, i) => `${id}/${(from[id] ?? 0) + i + 1}`)
|
|
154
|
-
);
|
|
155
|
-
return {
|
|
156
|
-
from,
|
|
157
|
-
to,
|
|
158
|
-
migrations: migrations.map((ref) => ({ ref, description: describe(ref) })),
|
|
159
|
-
documents: planned.sort((a, b) => keyOf(a) < keyOf(b) ? -1 : 1),
|
|
160
|
-
untouched: untouched.sort(),
|
|
161
|
-
problems
|
|
162
|
-
};
|
|
163
|
-
};
|
|
164
|
-
var verifySourceUpgrade = (options) => {
|
|
165
|
-
const { plan, upgrader, documents } = options;
|
|
166
|
-
const now = new Map(documents.map((d) => [keyOf(d), d]));
|
|
167
|
-
const lines = [];
|
|
168
|
-
for (const want of plan.documents) {
|
|
169
|
-
const key = keyOf(want);
|
|
170
|
-
const got = now.get(key);
|
|
171
|
-
if (got === void 0) {
|
|
172
|
-
lines.push({ ok: false, text: `${key} is gone \u2014 the plan expected it rewritten, not removed` });
|
|
173
|
-
} else if (sameJson(got.document, want.expected)) {
|
|
174
|
-
lines.push({ ok: true, text: `${key} matches its migrated JSON` });
|
|
175
|
-
} else {
|
|
176
|
-
lines.push({ ok: false, text: `${key} does not match its migrated JSON yet`, detail: diffJson(got.document, want.expected, 12) });
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
for (const key of plan.untouched) {
|
|
180
|
-
const got = now.get(key);
|
|
181
|
-
if (got === void 0) {
|
|
182
|
-
lines.push({ ok: false, text: `${key} is gone \u2014 no migration asked for that` });
|
|
183
|
-
continue;
|
|
184
|
-
}
|
|
185
|
-
const again = upgrader.upgrade(got.document, { kind: got.kind, stamp: plan.from });
|
|
186
|
-
if (!sameJson(again.document, got.document)) {
|
|
187
|
-
lines.push({ ok: false, text: `${key} was not in the plan, but the migrations would change it now`, detail: diffJson(got.document, again.document, 12) });
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
const known = /* @__PURE__ */ new Set([...plan.documents.map(keyOf), ...plan.untouched]);
|
|
191
|
-
for (const key of now.keys()) {
|
|
192
|
-
if (!known.has(key)) lines.push({ ok: false, text: `${key} is new since the plan \u2014 plan again so it is checked too` });
|
|
193
|
-
}
|
|
194
|
-
const ok = lines.every((l) => l.ok);
|
|
195
|
-
if (ok) lines.push({ ok: true, text: `${plan.untouched.length} artifact(s) no migration touches, still untouched` });
|
|
196
|
-
return { ok, lines };
|
|
197
|
-
};
|
|
198
|
-
var renderReport = (plan, expectedPathOf) => {
|
|
199
|
-
const stamp = (s) => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(", ");
|
|
200
|
-
const out = [
|
|
201
|
-
"# strata upgrade",
|
|
202
|
-
"",
|
|
203
|
-
`The source is written at **${stamp(plan.from)}**; the installed grammars are at **${stamp(plan.to)}**.`,
|
|
204
|
-
"",
|
|
205
|
-
"## Migrations",
|
|
206
|
-
"",
|
|
207
|
-
...plan.migrations.map((m) => `- \`${m.ref}\` \u2014 ${m.description}`),
|
|
208
|
-
""
|
|
209
|
-
];
|
|
210
|
-
if (plan.problems.length > 0) {
|
|
211
|
-
out.push("## Stop: a migration is wrong", "", "These artifacts would not pass their current schema after migrating \u2014 no edit can make `verify` pass. Fix the migration, then plan again.", "", ...plan.problems.map((p) => `- ${p}`), "");
|
|
212
|
-
}
|
|
213
|
-
if (plan.documents.length === 0) {
|
|
214
|
-
out.push("## Nothing to edit", "", `No artifact changes (${plan.untouched.length} checked). Run \`verify\` to move the lock.`, "");
|
|
215
|
-
} else {
|
|
216
|
-
out.push(
|
|
217
|
-
`## ${plan.documents.length} artifact(s) to edit`,
|
|
218
|
-
"",
|
|
219
|
-
"Edit each so that it serialises to EXACTLY its expected JSON (key order aside) \u2014 then run `verify`. Only what is listed changes; every other artifact must stay as it is.",
|
|
220
|
-
""
|
|
221
|
-
);
|
|
222
|
-
for (const doc of plan.documents) {
|
|
223
|
-
out.push(
|
|
224
|
-
`### \`${doc.id}\` (${doc.kind})`,
|
|
225
|
-
"",
|
|
226
|
-
doc.file === void 0 ? "" : `- **File:** \`${doc.file}\``,
|
|
227
|
-
doc.lookIn === void 0 || doc.lookIn.length === 0 ? "" : `- **Look in:** ${doc.lookIn.map((f) => `\`${f}\``).join(", ")} \u2014 where the changing values are written`,
|
|
228
|
-
`- **Migrations:** ${doc.applied.map((r) => `\`${r}\``).join(", ")}`,
|
|
229
|
-
`- **Expected JSON:** \`${expectedPathOf(doc)}\``,
|
|
230
|
-
"- **Changes:**",
|
|
231
|
-
"",
|
|
232
|
-
"```",
|
|
233
|
-
...doc.changes,
|
|
234
|
-
"```",
|
|
235
|
-
""
|
|
236
|
-
);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
return out.filter((line, i, all) => !(line === "" && all[i - 1] === "")).join("\n");
|
|
240
|
-
};
|
|
241
8
|
|
|
242
|
-
exports
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
9
|
+
Object.defineProperty(exports, "changedStrings", {
|
|
10
|
+
enumerable: true,
|
|
11
|
+
get: function () { return chunkIHYBGLNW_cjs.changedStrings; }
|
|
12
|
+
});
|
|
13
|
+
Object.defineProperty(exports, "planSourceUpgrade", {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
get: function () { return chunkIHYBGLNW_cjs.planSourceUpgrade; }
|
|
16
|
+
});
|
|
17
|
+
Object.defineProperty(exports, "renderReport", {
|
|
18
|
+
enumerable: true,
|
|
19
|
+
get: function () { return chunkIHYBGLNW_cjs.renderReport; }
|
|
20
|
+
});
|
|
21
|
+
Object.defineProperty(exports, "verifySourceUpgrade", {
|
|
22
|
+
enumerable: true,
|
|
23
|
+
get: function () { return chunkIHYBGLNW_cjs.verifySourceUpgrade; }
|
|
24
|
+
});
|
|
246
25
|
//# sourceMappingURL=index.cjs.map
|
|
247
26
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/check/index.ts","../../src/upgrade/index.ts"],"names":["sortKeys"],"mappings":";;;AA0BO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EAC5B,IAAA;AAAA,EACA,OAAA;AAAA,EAET,YAAY,IAAA,EAAuB,OAAA,EAAiB,OAAA,GAA6B,IAAI,OAAA,EAA+B;AAClH,IAAA,KAAA,CAAM,OAAA,CAAQ,MAAA,GAAS,CAAA,GAAI,CAAA,EAAG,OAAO;AAAA,EAAK,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,GAAK,SAAS,OAAO,CAAA;AACtG,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF,CAAA;;;ACKA,IAAM,QAAA,GAAW,CAAC,KAAA,KAChB,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAErE,IAAM,KAAA,GAAQ,CAAC,CAAC,CAAC,CAAA,EAAsB,CAAC,CAAC,CAAA,KAAkC,CAAA,GAAI,CAAA,GAAI,EAAA,GAAK,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AAA,CAAO,CAAC,IAAA,EAAM,CAAA,EAAG,QAAQ,EAAE,IAAA,KAAS,EAAA,IAAM,GAAA,CAAI,IAAI,CAAC,CAAA,KAAM,EAAA,CAAG,CAAA,CAAE,KAAK,IAAI,CAAA;AACpF","file":"index.cjs","sourcesContent":["// Every refusal strata makes, by name. The message is a sentence for a person;\n// the code is for the program that has to decide what to do about it.\nexport type StrataErrorCode =\n // A sequence failed its schema, or two sequences share an id.\n | 'INVALID_SEQUENCE'\n // An applied migration's steps no longer match what the code says it ran.\n | 'EDITED'\n // The database has migrations of a sequence this code does not know yet —\n // it was migrated by newer code.\n | 'TOO_NEW'\n // A `dependsOn` names a migration nobody provides and the ledger lacks.\n | 'UNKNOWN_DEPENDENCY'\n // Pending migrations wait on each other.\n | 'CYCLE'\n // Verify mode found work to do.\n | 'PENDING'\n // A step threw; the whole run was rolled back.\n | 'STEP_FAILED'\n // The pool cannot hold one connection for a transaction.\n | 'NO_TRANSACTION'\n // A document kind nobody declares — as the root being upgraded, a step's\n // `at`, or an embedding's target.\n | 'UNKNOWN_KIND'\n // A grammar sequence handed to the ledger, or a table sequence to upgrade().\n | 'WRONG_OWNER';\n\nexport class StrataError extends Error {\n readonly code: StrataErrorCode;\n readonly details: readonly string[];\n\n constructor(code: StrataErrorCode, message: string, details: readonly string[] = [], options?: { cause?: unknown }) {\n super(details.length > 0 ? `${message}\\n${details.map((d) => ` ${d}`).join('\\n')}` : message, options);\n this.name = 'StrataError';\n this.code = code;\n this.details = details;\n }\n}\n","import type { Sequence } from '../schema';\nimport type { Stamp, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/check — the gate a grammar change has to pass.\n//\n// Two questions, both mechanical:\n//\n// 1. SNAPSHOT — did a kind's schema change without the grammar gaining a\n// migration? Each kind's JSON Schema, taken through the schema's OWN\n// Standard JSON Schema hook, is recorded per grammar version. Same version,\n// different schema: something changed that older readers were never told.\n// Append a migration (an empty marker is enough for an addition — strict\n// readers still have to refuse the newer documents), then record the new\n// version.\n//\n// 2. CORPUS — does every real document ever captured, at the stamp it was\n// captured at, still upgrade to the current grammar and pass the current\n// strict schema? This is the judge: a snapshot only says something moved,\n// the corpus says whether old documents survive it. No JSON Schema diff\n// tool is trusted to decide compatibility.\n//\n// Pure: no files, no process. A host reads and writes snapshots where it keeps\n// them (nisc's own live in the repo's `strata/` directory).\n// ═══════════════════════════════════════════════════════════════\n\ntype Issue = { message: string; path?: readonly (PropertyKey | { key: PropertyKey })[] };\ntype StandardResult = { value: unknown; issues?: undefined } | { issues: readonly Issue[] };\n\n// Any validator implementing Standard Schema + Standard JSON Schema (Zod ≥ 4.2,\n// Valibot, ArkType). Structural: strata depends on none of them.\nexport type GrammarSchema = {\n '~standard': {\n validate: (value: unknown) => StandardResult | Promise<StandardResult>;\n jsonSchema: { input: (options: { target: string }) => Record<string, unknown> };\n };\n};\n\nexport type Snapshot = { sequence: string; version: number; kinds: Readonly<Record<string, unknown>> };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst byKey = ([a]: [string, unknown], [b]: [string, unknown]): number => (a < b ? -1 : a > b ? 1 : 0);\n\n// Sorted keys, nothing else — for documents, where every key (a `description`\n// too) is content, and for a snapshot file, which keeps what the validator wrote.\nconst sortKeys = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (!isRecord(value)) return value;\n return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));\n};\n\n// Where a schema's keys are NAMES, not keywords — a field called `description`\n// or an op called `$ref` is grammar — and where its values are instance data\n// rather than schemas.\nconst NAMED = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);\nconst DATA = new Set(['const', 'enum', 'default', 'examples']);\n\n// A schema without its prose: the `description` KEYWORD is documentation, and\n// rewording a `.describe()` must not demand a migration. `$schema` is the same\n// everywhere. Applied when comparing, never to what is recorded — so what the\n// gate ignores can change without touching a snapshot file.\nconst normalize = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(normalize);\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => key !== 'description' && key !== '$schema')\n .sort(byKey)\n .map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)]),\n );\n};\n\n// A name → schema map, each schema through `each`, the names untouched.\nconst namedSchemas = (map: Record<string, unknown>, each: (schema: unknown) => unknown): Record<string, unknown> =>\n Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));\n\n// The grammar as it stands: every kind it declares, as JSON Schema — as the\n// validator wrote it, keys sorted. `schemas` must cover exactly the sequence's\n// kinds — a kind without a schema cannot be checked, and a schema without a\n// kind belongs to some other grammar.\nexport const snapshotOf = (sequence: Sequence, schemas: Readonly<Record<string, GrammarSchema>>): Snapshot => {\n const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);\n const given = Object.keys(schemas);\n const missing = declared.filter((k) => !given.includes(k));\n const extra = given.filter((k) => !declared.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new StrataError('UNKNOWN_KIND', `The schemas for ${sequence.id} do not match its kinds.`, [\n ...missing.map((k) => `no schema for ${k}`),\n ...extra.map((k) => `${k} is not a kind of ${sequence.id}`),\n ]);\n }\n const kinds: Record<string, unknown> = {};\n for (const kind of [...declared].sort()) {\n const schema = schemas[kind];\n if (schema !== undefined) kinds[kind] = sortKeys(schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }));\n }\n return { sequence: sequence.id, version: sequence.migrations.length, kinds };\n};\n\n// Stable text for a snapshot file: sorted keys, two-space indent, newline.\nexport const snapshotText = (snapshot: Snapshot): string => `${JSON.stringify(sortKeys(snapshot), null, 2)}\n`;\n\n// Schema arrays are compared as sets (`sets`) — all but a tuple's `prefixItems`,\n// see `diffPositions`; a document's arrays by position — `layout.children[1]` is\n// how a person finds the thing that changed.\nconst diffLines = (a: unknown, b: unknown, path: string, out: string[], limit: number, canon: (v: unknown) => unknown = normalize, sets = true): void => {\n if (out.length >= limit) return;\n if (JSON.stringify(a) === JSON.stringify(b)) return;\n if (isRecord(a) && isRecord(b)) {\n for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {\n const at = path === '' ? key : `${path}.${key}`;\n 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 — a union's `anyOf`, a\n // `required` list, an `enum` — and one added branch shifts every index\n // after it. Match elements by what they describe (an object schema by its\n // property names — for Prism's union, the op), report the ones on one side\n // only, and diff the ones that changed in place.\n const text = (v: unknown): string => JSON.stringify(canon(v));\n const label = (v: unknown): string =>\n isRecord(v) && isRecord(v['properties']) ? Object.keys(v['properties']).join(',') : (text(v) ?? '').slice(0, 50);\n const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));\n const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));\n const byLabel = new Map(onlyB.map((y) => [label(y), y]));\n for (const x of onlyA) {\n const partner = byLabel.get(label(x));\n if (partner !== undefined) {\n diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);\n byLabel.delete(label(x));\n } else {\n out.push(`- ${path}[${label(x)}]`);\n }\n if (out.length >= limit) return;\n }\n for (const [name] of byLabel) {\n out.push(`+ ${path}[${name}]`);\n if (out.length >= limit) return;\n }\n return;\n }\n out.push(`~ ${path || '(root)'}: ${JSON.stringify(a)?.slice(0, 60)} → ${JSON.stringify(b)?.slice(0, 60)}`);\n};\n\n// A tuple's `prefixItems` is the one schema array that is a SEQUENCE: position\n// is the grammar, so [string, number] and [number, string] are different tuples\n// and a document valid for one is not for the other. Compared place by place;\n// what sits IN a place is a schema again, its own arrays sets as ever.\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// ── canonical form ──────────────────────────────────────────────\n//\n// A snapshot records what the validator WROTE, and validators spell one schema\n// many ways: they name and inline definitions as they please (zod numbers them\n// in visit order, and 4.3 and 4.4 visit differently), write a described\n// reference as `allOf: [{ $ref }]` or as `$ref`, and a union of bare types as\n// `anyOf: [{ type }, …]` or `type: […]`. None of that is the grammar, so a\n// comparison reads both sides in one spelling: every definition inlined unless\n// it is recursive, the recursive ones renamed by first use, and every schema\n// identity above written one way. A snapshot FILE stays what the validator\n// wrote — only the comparison is canonical.\n\nconst REF_PREFIX = /^#\\/(\\$defs|definitions)\\//;\n\n// One spelling for the equivalences the node itself can show.\nconst respell = (value: Record<string, unknown>): Record<string, unknown> => {\n let node = value;\n const anyOf = node['anyOf'];\n if (!('type' in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m['type'] === 'string')) {\n const { anyOf: _union, ...rest } = node;\n node = { ...rest, type: anyOf.map((m) => (isRecord(m) ? m['type'] : undefined)) };\n }\n const type = node['type'];\n if (Array.isArray(type)) {\n const types = [...new Set(type.map(String))].sort();\n node = { ...node, type: types.length === 1 ? types[0] : types };\n }\n const allOf = node['allOf'];\n const only: unknown = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : undefined;\n if (!('$ref' in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only['$ref'] === 'string') {\n const { allOf: _wrapper, ...rest } = node;\n node = { ...rest, $ref: only['$ref'] };\n }\n return node;\n};\n\n// A schema node's own children — keyword values, and each schema of a name\n// map — but never the names, and never instance data.\nconst schemaChildren = (node: Record<string, unknown>): unknown[] =>\n Object.entries(node).flatMap(([key, child]) =>\n key === '$ref' || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child],\n );\n\nconst canonical = (recorded: unknown): unknown => {\n const schema = normalize(recorded);\n if (!isRecord(schema)) return schema;\n const defs: Record<string, unknown> = {\n ...(isRecord(schema['definitions']) ? schema['definitions'] : {}),\n ...(isRecord(schema['$defs']) ? schema['$defs'] : {}),\n };\n const { $defs: _defs, definitions: _definitions, ...body } = schema;\n const target = (ref: string): { key: string; node: unknown } =>\n ref === '#' ? { key: '#', node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, '')] };\n\n // Which targets are reached from inside their own expansion: those, and\n // only those, stay definitions.\n const recursive = new Set<string>();\n const findCycles = (value: unknown, stack: readonly string[]): void => {\n if (Array.isArray(value)) {\n for (const item of value) findCycles(item, stack);\n return;\n }\n if (!isRecord(value)) return;\n const node = respell(value);\n for (const child of schemaChildren(node)) findCycles(child, stack);\n const ref = node['$ref'];\n if (typeof ref !== 'string') return;\n const { key, node: next } = target(ref);\n if (stack.includes(key)) recursive.add(key);\n else findCycles(next, [...stack, key]);\n };\n findCycles(body, ['#']);\n\n const names = new Map<string, string>();\n const named: Record<string, unknown> = {};\n const nameOf = (key: string, node: unknown): string => {\n const known = names.get(key);\n if (known !== undefined) return known;\n const name = `d${names.size}`;\n names.set(key, name);\n named[name] = emit(node);\n return name;\n };\n const emit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(emit);\n if (!isRecord(value)) return value;\n const node = respell(value);\n const rest: Record<string, unknown> = Object.fromEntries(\n Object.entries(node)\n .filter(([key]) => key !== '$ref')\n .sort(byKey)\n .map(([key, child]) => [key, NAMED.has(key) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key) ? child : emit(child)]),\n );\n const ref = node['$ref'];\n if (typeof ref !== 'string') return rest;\n const { key, node: next } = target(ref);\n const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);\n return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;\n };\n\n const root = recursive.has('#') ? { $ref: `#/$defs/${nameOf('#', body)}` } : emit(body);\n return Object.keys(named).length === 0 ? root : sortKeys({ ...(isRecord(root) ? root : { allOf: [root] }), $defs: named });\n};\n\nexport type SnapshotComparison =\n | { status: 'same' }\n | { status: 'missing' }\n | { status: 'changed'; changes: readonly { kind: string; lines: readonly string[] }[] };\n\n// `recorded` is the snapshot kept for the grammar's CURRENT version (or\n// undefined if none was kept). Changed means: a migration is owed. Both sides\n// are read in canonical form, so a validator's respelling is not a change.\nexport const compareSnapshot = (recorded: Snapshot | undefined, current: Snapshot): SnapshotComparison => {\n if (recorded === undefined) return { status: 'missing' };\n const changes: { kind: string; lines: string[] }[] = [];\n for (const kind of [...new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {\n const lines: string[] = [];\n if (!(kind in recorded.kinds)) lines.push('+ (a new kind)');\n else if (!(kind in current.kinds)) lines.push('- (the kind is gone)');\n else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), '', lines, 12);\n if (lines.length > 0) changes.push({ kind, lines });\n }\n return changes.length === 0 ? { status: 'same' } : { status: 'changed', changes };\n};\n\n// ── the corpus ──────────────────────────────────────────────────\n\nexport type CorpusDocument = { id: string; kind: string; stamp: Stamp; document: unknown };\nexport type CorpusFailure = { id: string; kind: string; reason: string };\nexport type CorpusReport = { passed: number; failures: readonly CorpusFailure[] };\n\nconst issueText = (issue: Issue): string => {\n const path = (issue.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return `${path === '' ? '' : `${path}: `}${issue.message}`;\n};\n\n// What differs between two JSON values, as short lines (`+ a.b`, `- c`,\n// `~ d: 1 → 2`) — for a report a person or an agent acts on.\nexport const diffJson = (a: unknown, b: unknown, limit = 20): string[] => {\n const out: string[] = [];\n diffLines(a, b, '', out, limit, sortKeys, false);\n return out;\n};\n\n// Every document, upgraded from its stamp, must pass the current schema of its kind.\nexport const checkCorpus = async (\n upgrader: Upgrader,\n schemas: Readonly<Record<string, GrammarSchema>>,\n documents: readonly CorpusDocument[],\n): Promise<CorpusReport> => {\n const failures: CorpusFailure[] = [];\n let passed = 0;\n for (const doc of documents) {\n const schema = schemas[doc.kind];\n if (schema === undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });\n continue;\n }\n let upgraded: unknown;\n try {\n upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;\n } catch (error) {\n failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split('\\n')[0] ?? error.message : String(error) });\n continue;\n }\n const result = await schema['~standard'].validate(upgraded);\n if (result.issues !== undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join('; ') });\n } else {\n passed += 1;\n }\n }\n return { passed, failures };\n};\n","import type { Stamp, Upgrader } from '../documents';\nimport { diffJson, type GrammarSchema } from '../check';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/upgrade — artifacts in an app's SOURCE, brought forward.\n//\n// Rows and submissions are upgraded where they are read. Source files are\n// different: they are TypeScript, written by people, and rewriting them by\n// machine means a codemod that would have to understand every way a person\n// can write an object. So strata does not edit them. It works out, from the\n// migrations, EXACTLY what each artifact must become — and then checks that\n// whoever did the editing (a person, an agent) landed on it, byte for byte.\n//\n// plan the lock says the source is written at stamp S; the installed\n// grammars are ahead. Every artifact is upgraded from S: the ones\n// that change get their expected JSON and a diff; the rest are noted.\n// (edit) anyone — the report says which artifact, which migration, what\n// changes, and where the expected JSON is.\n// verify the edited source, read again: every planned artifact equals its\n// expected JSON; every other one is still one no migration touches.\n// Then — and only then — the lock moves.\n//\n// Pure: documents in, plans out. `@niscorp/strata/node` does the files.\n// ═══════════════════════════════════════════════════════════════\n\nexport type SourceDocument = { kind: string; id: string; document: unknown; file?: string };\n\nexport type PlannedDocument = {\n kind: string;\n id: string;\n file?: string;\n // Files that contain what changes — the artifact's own file names only where\n // its id is written; the layout it imports is often where the edit goes.\n lookIn?: readonly string[];\n applied: readonly string[];\n changes: readonly string[];\n expected: unknown;\n};\n\nexport type SourcePlan = {\n from: Stamp;\n to: Stamp;\n migrations: readonly { ref: string; description: string }[];\n // Artifacts the migrations change — the whole to-do list.\n documents: readonly PlannedDocument[];\n // Artifacts no pending migration touches (by kind:id) — verify checks they stay that way.\n untouched: readonly string[];\n // An expected document that does not pass its kind's current schema: the\n // MIGRATION is wrong, and no edit could make verify pass. Fix it first.\n problems: readonly string[];\n};\n\nconst keyOf = (doc: { kind: string; id: string }): string => `${doc.kind}:${doc.id}`;\n\nconst sortKeys = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (typeof value !== 'object' || value === null) return value;\n return Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([k, v]) => [k, sortKeys(v)]));\n};\n// Equal as JSON: key order is how a person happened to write the object, not content.\nconst sameJson = (a: unknown, b: unknown): boolean => JSON.stringify(sortKeys(a)) === JSON.stringify(sortKeys(b));\n\n// The string values a migration removes or rewrites — what to search the\n// source for to find where an edit goes.\nexport const changedStrings = (before: unknown, after: unknown): string[] => {\n const found = new Set<string>();\n const visit = (a: unknown, b: unknown): void => {\n if (JSON.stringify(a) === JSON.stringify(b)) return;\n if (typeof a === 'string') {\n found.add(a);\n return;\n }\n if (Array.isArray(a)) {\n a.forEach((item, i) => visit(item, Array.isArray(b) ? b[i] : undefined));\n return;\n }\n if (typeof a === 'object' && a !== null) {\n for (const [k, v] of Object.entries(a)) visit(v, typeof b === 'object' && b !== null && !Array.isArray(b) ? Reflect.get(b, k) : undefined);\n }\n };\n visit(before, after);\n return [...found].filter((s) => s.length >= 4);\n};\n\nexport const planSourceUpgrade = async (options: {\n upgrader: Upgrader;\n stamp: Stamp;\n documents: readonly SourceDocument[];\n schemas?: Readonly<Record<string, GrammarSchema>>;\n // Every migration the upgrader would run from `stamp`, for the report — the\n // host passes the grammar sequences' descriptions.\n describe: (ref: string) => string;\n}): Promise<SourcePlan> => {\n const { upgrader, stamp, documents, schemas, describe } = options;\n const seen = new Set<string>();\n const planned: PlannedDocument[] = [];\n const untouched: string[] = [];\n const problems: string[] = [];\n\n for (const doc of documents) {\n const key = keyOf(doc);\n if (seen.has(key)) throw new StrataError('INVALID_SEQUENCE', `Two artifacts are both ${key} — an artifact needs one identity to be planned.`);\n seen.add(key);\n const result = upgrader.upgrade(doc.document, { kind: doc.kind, stamp });\n if (sameJson(result.document, doc.document)) {\n untouched.push(key);\n continue;\n }\n planned.push({\n kind: doc.kind,\n id: doc.id,\n ...(doc.file === undefined ? {} : { file: doc.file }),\n applied: result.applied,\n changes: diffJson(doc.document, result.document),\n expected: result.document,\n });\n const schema = schemas?.[doc.kind];\n if (schema !== undefined) {\n const checked = await schema['~standard'].validate(result.document);\n if (checked.issues !== undefined) {\n problems.push(`${key}: the migrated artifact does not pass ${doc.kind}'s current schema — ${checked.issues.slice(0, 2).map((i) => i.message).join('; ')}`);\n }\n }\n }\n\n // Every migration between the lock and the installed grammars — markers\n // included, which change no artifact but still move the version.\n const from = stamp;\n const to = upgrader.stamp;\n const migrations = Object.entries(to).flatMap(([id, n]) =>\n Array.from({ length: Math.max(0, n - (from[id] ?? 0)) }, (_, i) => `${id}/${(from[id] ?? 0) + i + 1}`),\n );\n return {\n from,\n to,\n migrations: migrations.map((ref) => ({ ref, description: describe(ref) })),\n documents: planned.sort((a, b) => (keyOf(a) < keyOf(b) ? -1 : 1)),\n untouched: untouched.sort(),\n problems,\n };\n};\n\nexport type VerifyResult = {\n ok: boolean;\n lines: readonly { ok: boolean; text: string; detail?: readonly string[] }[];\n};\n\n// The edited source against the plan. `upgrader` still reads from the plan's\n// `from` stamp: an artifact the plan left untouched must still be one no\n// pending migration would change.\nexport const verifySourceUpgrade = (options: { plan: SourcePlan; upgrader: Upgrader; documents: readonly SourceDocument[] }): VerifyResult => {\n const { plan, upgrader, documents } = options;\n const now = new Map(documents.map((d) => [keyOf(d), d]));\n const lines: { ok: boolean; text: string; detail?: readonly string[] }[] = [];\n\n for (const want of plan.documents) {\n const key = keyOf(want);\n const got = now.get(key);\n if (got === undefined) {\n lines.push({ ok: false, text: `${key} is gone — the plan expected it rewritten, not removed` });\n } else if (sameJson(got.document, want.expected)) {\n lines.push({ ok: true, text: `${key} matches its migrated JSON` });\n } else {\n lines.push({ ok: false, text: `${key} does not match its migrated JSON yet`, detail: diffJson(got.document, want.expected, 12) });\n }\n }\n for (const key of plan.untouched) {\n const got = now.get(key);\n if (got === undefined) {\n lines.push({ ok: false, text: `${key} is gone — no migration asked for that` });\n continue;\n }\n const again = upgrader.upgrade(got.document, { kind: got.kind, stamp: plan.from });\n if (!sameJson(again.document, got.document)) {\n lines.push({ ok: false, text: `${key} was not in the plan, but the migrations would change it now`, detail: diffJson(got.document, again.document, 12) });\n }\n }\n const known = new Set([...plan.documents.map(keyOf), ...plan.untouched]);\n for (const key of now.keys()) {\n if (!known.has(key)) lines.push({ ok: false, text: `${key} is new since the plan — plan again so it is checked too` });\n }\n const ok = lines.every((l) => l.ok);\n if (ok) lines.push({ ok: true, text: `${plan.untouched.length} artifact(s) no migration touches, still untouched` });\n return { ok, lines };\n};\n\n// The report a person — or an agent — works from.\nexport const renderReport = (plan: SourcePlan, expectedPathOf: (doc: PlannedDocument) => string): string => {\n const stamp = (s: Stamp): string => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(', ');\n const out: string[] = [\n '# strata upgrade',\n '',\n `The source is written at **${stamp(plan.from)}**; the installed grammars are at **${stamp(plan.to)}**.`,\n '',\n '## Migrations',\n '',\n ...plan.migrations.map((m) => `- \\`${m.ref}\\` — ${m.description}`),\n '',\n ];\n if (plan.problems.length > 0) {\n out.push('## Stop: a migration is wrong', '', 'These artifacts would not pass their current schema after migrating — no edit can make `verify` pass. Fix the migration, then plan again.', '', ...plan.problems.map((p) => `- ${p}`), '');\n }\n if (plan.documents.length === 0) {\n out.push('## Nothing to edit', '', `No artifact changes (${plan.untouched.length} checked). Run \\`verify\\` to move the lock.`, '');\n } else {\n out.push(\n `## ${plan.documents.length} artifact(s) to edit`,\n '',\n 'Edit each so that it serialises to EXACTLY its expected JSON (key order aside) — then run `verify`. Only what is listed changes; every other artifact must stay as it is.',\n '',\n );\n for (const doc of plan.documents) {\n out.push(`### \\`${doc.id}\\` (${doc.kind})`, '', doc.file === undefined ? '' : `- **File:** \\`${doc.file}\\``,\n doc.lookIn === undefined || doc.lookIn.length === 0 ? '' : `- **Look in:** ${doc.lookIn.map((f) => `\\`${f}\\``).join(', ')} — where the changing values are written`, `- **Migrations:** ${doc.applied.map((r) => `\\`${r}\\``).join(', ')}`, `- **Expected JSON:** \\`${expectedPathOf(doc)}\\``, '- **Changes:**', '', '```', ...doc.changes, '```', '');\n }\n }\n return out.filter((line, i, all) => !(line === '' && all[i - 1] === '')).join('\\n');\n};\n"]}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"index.cjs"}
|
package/dist/upgrade/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import '../chunk-
|
|
1
|
+
export { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade } from '../chunk-WU3OJHVZ.js';
|
|
2
|
+
import '../chunk-4BLHBVSC.js';
|
|
3
|
+
import '../chunk-AKKWEXO2.js';
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
5
5
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niscorp/strata",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "Migrations for nisc — one ledger for the tables a database holds and the documents stored in them, applied in order, recorded once, refused when edited.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|