@niscorp/strata 0.1.6 → 0.1.8
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 +26 -0
- package/DESIGN.md +11 -5
- package/README.md +56 -14
- package/dist/check/index.cjs +7 -7
- package/dist/check/index.js +2 -2
- package/dist/{chunk-IHYBGLNW.cjs → chunk-564JCO6Q.cjs} +8 -8
- package/dist/chunk-564JCO6Q.cjs.map +1 -0
- package/dist/{chunk-ATHZ7HT5.cjs → chunk-7PBIGCLL.cjs} +2 -2
- package/dist/chunk-7PBIGCLL.cjs.map +1 -0
- package/dist/{chunk-WU3OJHVZ.js → chunk-DGS4XJQQ.js} +4 -4
- package/dist/chunk-DGS4XJQQ.js.map +1 -0
- package/dist/{chunk-OLDORFOQ.js → chunk-FNMGVPSA.js} +4 -4
- package/dist/chunk-FNMGVPSA.js.map +1 -0
- package/dist/{chunk-YXFEJJMC.cjs → chunk-FSEUYRLN.cjs} +15 -15
- package/dist/chunk-FSEUYRLN.cjs.map +1 -0
- package/dist/{chunk-CL5DF2IQ.cjs → chunk-KYNER7UU.cjs} +18 -7
- package/dist/chunk-KYNER7UU.cjs.map +1 -0
- package/dist/{chunk-5KTXEN43.js → chunk-PAMQMFBK.js} +15 -4
- package/dist/chunk-PAMQMFBK.js.map +1 -0
- package/dist/{chunk-4BLHBVSC.js → chunk-SH6BBA2X.js} +3 -3
- package/dist/chunk-SH6BBA2X.js.map +1 -0
- package/dist/{chunk-AKKWEXO2.js → chunk-STNFHBNR.js} +2 -2
- package/dist/chunk-STNFHBNR.js.map +1 -0
- package/dist/{chunk-KNBS3AJZ.cjs → chunk-SYU7NKZR.cjs} +4 -4
- package/dist/chunk-SYU7NKZR.cjs.map +1 -0
- package/dist/index.cjs +21 -21
- 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/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/{plan-mFmdh0qT.d.ts → plan-BMZJUCZ1.d.ts} +6 -3
- package/dist/{plan-CxuteSH1.d.cts → plan-Bq_Q2x5r.d.cts} +6 -3
- package/dist/postgres/index.cjs +36 -23
- package/dist/postgres/index.cjs.map +1 -1
- package/dist/postgres/index.d.cts +7 -3
- package/dist/postgres/index.d.ts +7 -3
- package/dist/postgres/index.js +25 -12
- 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/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { M as Migration, S as SqlStep, a as Sequence } from './documents-BjlM94Ea.js';
|
|
2
2
|
export { D as DocumentKind, b as DocumentKindSchema, c as DocumentStep, d as DocumentStepSchema, E as EMBED_PATH, K as KIND_NAME, e as KIND_REF, L as Location, f as MIGRATION_REF, g as MigrationSchema, h as SEQUENCE_ID, i as SequenceSchema, j as SqlStepSchema, k as Stamp, l as Step, m as StepSchema, T as Transform, U as UpgradeResult, n as Upgrader, o as createUpgrader } from './documents-BjlM94Ea.js';
|
|
3
|
-
export { L as LedgerRow, P as Plan, a as
|
|
3
|
+
export { L as LedgerRow, P as Plan, a as PlanOptions, b as PreparedMigration, c as PreparedSequence, d as Problem, S as StrataError, e as StrataErrorCode, o as orderPending, p as planMigrations, f as prepare, r as refuseProblems } from './plan-BMZJUCZ1.js';
|
|
4
4
|
import 'zod';
|
|
5
5
|
|
|
6
6
|
declare const checksumOf: (migration: Migration) => Promise<string>;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { createUpgrader } from './chunk-
|
|
2
|
-
export { DocumentKindSchema, DocumentStepSchema, EMBED_PATH, KIND_NAME, KIND_REF, MIGRATION_REF, MigrationSchema, SEQUENCE_ID, SequenceSchema, SqlStepSchema, StepSchema, checksumOf, orderPending, planMigrations, prepare, refuseProblems } from './chunk-
|
|
3
|
-
export { StrataError } from './chunk-
|
|
1
|
+
export { createUpgrader } from './chunk-FNMGVPSA.js';
|
|
2
|
+
export { DocumentKindSchema, DocumentStepSchema, EMBED_PATH, KIND_NAME, KIND_REF, MIGRATION_REF, MigrationSchema, SEQUENCE_ID, SequenceSchema, SqlStepSchema, StepSchema, checksumOf, orderPending, planMigrations, prepare, refuseProblems } from './chunk-PAMQMFBK.js';
|
|
3
|
+
export { StrataError } from './chunk-STNFHBNR.js';
|
|
4
4
|
|
|
5
5
|
// src/sql.ts
|
|
6
6
|
var isComment = (line) => line.trim().startsWith("--");
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sql.ts","../src/depth.ts","../src/index.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"sources":["../src/sql.ts","../src/depth.ts","../src/index.ts"],"names":[],"mappings":";;;;;AAMA,IAAM,YAAY,CAAC,IAAA,KAA0B,KAAK,IAAA,EAAK,CAAE,WAAW,IAAI,CAAA;AAEjE,IAAM,QAAA,GAAW,CAAC,GAAA,KAA2B;AAClD,EAAA,MAAM,QAAmB,EAAC;AAC1B,EAAA,IAAI,SAAmB,EAAC;AACxB,EAAA,MAAM,QAAQ,MAAY;AACxB,IAAA,MAAM,GAAA,GAAM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AAA,CAAM,OAAA,CAAQ,KAAK,KAAK,CAAA,GAAI,KAAK,KAAA,GAAQ,MAAA,CAAO,OAAO,IAAA,CAAK,KAAK,GAAG,OAAA,CAAQ,IAAA,CAAK,EAAE,KAAA,EAAO,KAAA,EAAO,OAAO,CAAA;AAAA,EAC9H;AACA,EAAA,OAAO,KAAA;AACT;AAEO,IAAM,YAAA,GAAe,CAAC,KAAA,GAAgB,oBAAA,KAC3C,kCAAkC,KAAK,CAAA,kGAAA;;;ACAlC,IAAM,cAAA,GAAiB,CAA2B,QAAA,KAAmB","file":"index.js","sourcesContent":["import type { SqlStep } from './schema';\n\n// A statement ends only at a `;` that closes a line of SQL: splitting on every\n// `;` would cut a comment that contains one in two. Not a SQL parser: a `;`\n// ending a line inside a string literal or a function body still ends a statement.\n\nconst isComment = (line: string): boolean => line.trim().startsWith('--');\n\nexport const sqlSteps = (ddl: string): SqlStep[] => {\n const steps: SqlStep[] = [];\n let buffer: string[] = [];\n const flush = (): void => {\n const sql = buffer.join('\\n').trim().replace(/;\\s*$/, '').trim();\n if (sql.split('\\n').some((line) => line.trim() !== '' && !isComment(line))) steps.push({ kind: 'sql', sql });\n buffer = [];\n };\n for (const line of ddl.split('\\n')) {\n buffer.push(line);\n if (!isComment(line) && line.trimEnd().endsWith(';')) flush();\n }\n flush();\n return steps;\n};\n","export const DOCUMENT_DEPTH_LIMIT = 256;\n\nexport const exceedsDepth = (value: unknown, limit: number = DOCUMENT_DEPTH_LIMIT): boolean => {\n const pending: { value: unknown; depth: number }[] = [{ value, depth: 0 }];\n for (let next = pending.pop(); next !== undefined; next = pending.pop()) {\n if (typeof next.value !== 'object' || next.value === null) continue;\n const depth = next.depth + 1;\n if (depth > limit) return true;\n for (const inner of Array.isArray(next.value) ? next.value : Object.values(next.value)) pending.push({ value: inner, depth });\n }\n return false;\n};\n\nexport const depthRefusal = (limit: number = DOCUMENT_DEPTH_LIMIT): string =>\n `the document nests deeper than ${limit} levels — no document is written that deep, and a schema reading one would overflow the stack`;\n","import type { Sequence } from './schema';\n\nexport { SequenceSchema, MigrationSchema, StepSchema, SqlStepSchema, DocumentStepSchema, DocumentKindSchema, SEQUENCE_ID, MIGRATION_REF, KIND_NAME, KIND_REF, EMBED_PATH } from './schema';\nexport type { Sequence, Migration, Step, SqlStep, DocumentStep, DocumentKind } from './schema';\nexport { createUpgrader } from './documents';\nexport type { Stamp, Location, Transform, Upgrader, UpgradeResult } from './documents';\nexport { prepare, planMigrations, refuseProblems, orderPending } from './plan';\nexport type { Plan, PlanOptions, Problem, PreparedMigration, PreparedSequence, LedgerRow } from './plan';\nexport { checksumOf } from './checksum';\nexport { sqlSteps } from './sql';\nexport { DOCUMENT_DEPTH_LIMIT, exceedsDepth, depthRefusal } from './depth';\nexport { StrataError } from './errors';\nexport type { StrataErrorCode } from './errors';\n\nexport const defineSequence = <const T extends Sequence>(sequence: T): T => sequence;\n"]}
|
package/dist/node/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
require('../chunk-
|
|
5
|
-
var
|
|
6
|
-
require('../chunk-
|
|
7
|
-
var
|
|
3
|
+
var chunkFSEUYRLN_cjs = require('../chunk-FSEUYRLN.cjs');
|
|
4
|
+
require('../chunk-KYNER7UU.cjs');
|
|
5
|
+
var chunk564JCO6Q_cjs = require('../chunk-564JCO6Q.cjs');
|
|
6
|
+
require('../chunk-SYU7NKZR.cjs');
|
|
7
|
+
var chunk7PBIGCLL_cjs = require('../chunk-7PBIGCLL.cjs');
|
|
8
8
|
var fs = require('fs');
|
|
9
9
|
var path = require('path');
|
|
10
10
|
|
|
@@ -21,12 +21,12 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
21
21
|
const lockPath = path.join(options.root, options.lock ?? "strata.lock.json");
|
|
22
22
|
const work = path.join(options.root, options.workDir ?? path.join(".strata", "upgrade"));
|
|
23
23
|
const rel = (path$1) => path.relative(options.root, path$1).split(path.sep).join("/");
|
|
24
|
-
const upgrader = await
|
|
24
|
+
const upgrader = await chunkFSEUYRLN_cjs.createUpgrader(options.grammars, { transform: options.transform });
|
|
25
25
|
const descriptions = new Map(options.grammars.flatMap((g) => g.migrations.map((m, i) => [`${g.id}/${i + 1}`, m.description])));
|
|
26
26
|
const readLock = () => {
|
|
27
27
|
if (!fs.existsSync(lockPath)) return void 0;
|
|
28
28
|
const raw = JSON.parse(fs.readFileSync(lockPath, "utf8"));
|
|
29
|
-
if (!isRecord(raw) || !isRecord(raw["grammar"])) throw new
|
|
29
|
+
if (!isRecord(raw) || !isRecord(raw["grammar"])) throw new chunk7PBIGCLL_cjs.StrataError("INVALID_SEQUENCE", `${rel(lockPath)} is not a lock: expected { "grammar": { \u2026 } }.`);
|
|
30
30
|
return Object.fromEntries(Object.entries(raw["grammar"]).map(([k, v]) => [k, Number(v)]));
|
|
31
31
|
};
|
|
32
32
|
const writeLock = (stamp) => fs.writeFileSync(lockPath, `${JSON.stringify({ grammar: Object.fromEntries(Object.entries(stamp).sort(([a], [b]) => a < b ? -1 : 1)) }, null, 2)}
|
|
@@ -83,7 +83,7 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
83
83
|
return 0;
|
|
84
84
|
}
|
|
85
85
|
const documents = await loadDocuments();
|
|
86
|
-
const drafted = await
|
|
86
|
+
const drafted = await chunk564JCO6Q_cjs.planSourceUpgrade({
|
|
87
87
|
upgrader,
|
|
88
88
|
stamp: lock,
|
|
89
89
|
documents,
|
|
@@ -95,7 +95,7 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
95
95
|
const plan = {
|
|
96
96
|
...drafted,
|
|
97
97
|
documents: drafted.documents.map((doc) => {
|
|
98
|
-
const needles =
|
|
98
|
+
const needles = chunk564JCO6Q_cjs.changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `"${s}"`]);
|
|
99
99
|
const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));
|
|
100
100
|
return { ...doc, lookIn };
|
|
101
101
|
})
|
|
@@ -111,7 +111,7 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
111
111
|
}
|
|
112
112
|
fs.writeFileSync(path.join(work, "plan.json"), `${JSON.stringify(plan, null, 2)}
|
|
113
113
|
`);
|
|
114
|
-
fs.writeFileSync(path.join(work, "REPORT.md"), `${
|
|
114
|
+
fs.writeFileSync(path.join(work, "REPORT.md"), `${chunk564JCO6Q_cjs.renderReport(plan, (d) => rel(expectedPathOf(d)))}
|
|
115
115
|
`);
|
|
116
116
|
log(`[plan] ${stampText(plan.from)} \u2192 ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);
|
|
117
117
|
for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);
|
|
@@ -146,7 +146,7 @@ var runSourceUpgrade = async (options, argv) => {
|
|
|
146
146
|
log(`[fail] the plan was made for ${stampText(plan.to)}, but the installed grammars are at ${stampText(upgrader.stamp)} \u2014 plan again: strata upgrade`);
|
|
147
147
|
return 1;
|
|
148
148
|
}
|
|
149
|
-
const result =
|
|
149
|
+
const result = chunk564JCO6Q_cjs.verifySourceUpgrade({ plan, upgrader, documents: await loadDocuments() });
|
|
150
150
|
for (const line of result.lines) {
|
|
151
151
|
log(`[${line.ok ? "pass" : "fail"}] ${line.text}`);
|
|
152
152
|
for (const d of line.detail ?? []) log(` ${d}`);
|
package/dist/node/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/node/index.ts"],"names":["existsSync","readdirSync","path","join","statSync","relative","sep","createUpgrader","readFileSync","StrataError","writeFileSync","planSourceUpgrade","changedStrings","rmSync","mkdirSync","renderReport","verifySourceUpgrade"],"mappings":";;;;;;;;;;AAuCA,IAAM,QAAA,GAAW,CAAC,KAAA,KAAqD,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KA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AAA,CAAI,CAAA,wBAAA,EAA2B,OAAO,CAAA,mDAAA,CAAgD,CAAA;AACtF,EAAA,OAAO,CAAA;AACT","file":"index.cjs","sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\nimport { createUpgrader, type Stamp, type Transform } from '../documents';\nimport type { Sequence } from '../schema';\nimport type { GrammarSchema } from '../check';\nimport { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade, type SourceDocument, type SourcePlan } from '../upgrade';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/node — `strata upgrade` for an app's source.\n//\n// An app runs this from a script of its own (it knows how to list its\n// artifacts; strata does not), e.g. `src/dev/strata.ts`:\n//\n// process.exit(await runSourceUpgrade({ root, grammars, transform, documents }, process.argv.slice(2)));\n//\n// status [--check] where the source stands against the installed grammars\n// init record that the source is written at the CURRENT grammars\n// upgrade plan: expected JSON + REPORT.md in .strata/upgrade/\n// verify the edited source against the plan; moves the lock\n//\n// The lock — strata.lock.json, committed — is the source's stamp: which\n// version of every grammar its artifacts are written in. It moves only when\n// verify passes.\n// ═══════════════════════════════════════════════════════════════\n\nexport type SourceUpgradeOptions = {\n root: string;\n grammars: readonly Sequence[];\n transform: Transform;\n documents: () => readonly SourceDocument[] | Promise<readonly SourceDocument[]>;\n schemas?: Readonly<Record<string, GrammarSchema>>;\n lock?: string;\n workDir?: string;\n // Where to look for the file an artifact is written in (default \"src\").\n sources?: string;\n log?: (line: string) => void;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst stampText = (s: Stamp): string => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(', ') || '(nothing)';\n\nconst filesUnder = (dir: string): string[] =>\n existsSync(dir)\n ? readdirSync(dir).flatMap((name) => {\n const path = join(dir, name);\n if (name === 'node_modules' || name.startsWith('.')) return [];\n return statSync(path).isDirectory() ? filesUnder(path) : /\\.(ts|tsx|js|mjs)$/.test(name) ? [path] : [];\n })\n : [];\n\nexport const runSourceUpgrade = async (options: SourceUpgradeOptions, argv: readonly string[]): Promise<number> => {\n const log = options.log ?? ((line: string) => console.log(line));\n const command = argv.find((a) => !a.startsWith('-')) ?? 'status';\n const lockPath = join(options.root, options.lock ?? 'strata.lock.json');\n const work = join(options.root, options.workDir ?? join('.strata', 'upgrade'));\n // POSIX separators on every platform: these paths land in REPORT.md,\n // plan.json and the log, which agents and committed tooling read.\n const rel = (path: string): string => relative(options.root, path).split(sep).join('/');\n\n const upgrader = await createUpgrader(options.grammars, { transform: options.transform });\n const descriptions = new Map<string, string>(options.grammars.flatMap((g) => g.migrations.map((m, i): [string, string] => [`${g.id}/${i + 1}`, m.description])));\n\n const readLock = (): Stamp | undefined => {\n if (!existsSync(lockPath)) return undefined;\n const raw: unknown = JSON.parse(readFileSync(lockPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['grammar'])) throw new StrataError('INVALID_SEQUENCE', `${rel(lockPath)} is not a lock: expected { \"grammar\": { … } }.`);\n return Object.fromEntries(Object.entries(raw['grammar']).map(([k, v]) => [k, Number(v)]));\n };\n const writeLock = (stamp: Stamp): void =>\n writeFileSync(lockPath, `${JSON.stringify({ grammar: Object.fromEntries(Object.entries(stamp).sort(([a], [b]) => (a < b ? -1 : 1))) }, null, 2)}\\n`);\n\n const sourceText = (): Map<string, string> => new Map(filesUnder(join(options.root, options.sources ?? 'src')).map((f) => [f, readFileSync(f, 'utf8')]));\n\n const loadDocuments = async (): Promise<SourceDocument[]> => {\n const text = sourceText();\n const fileOf = (id: string): string | undefined => {\n const needles = [`id: '${id}'`, `id: \"${id}\"`, `\"id\": \"${id}\"`];\n for (const [path, body] of text) if (needles.some((n) => body.includes(n))) return rel(path);\n return undefined;\n };\n return (await options.documents()).map((d) => {\n // Pure JSON, as it would be stored: no undefined, no functions.\n const document: unknown = JSON.parse(JSON.stringify(d.document));\n const file = d.file ?? fileOf(d.id);\n return { kind: d.kind, id: d.id, document, ...(file === undefined ? {} : { file }) };\n });\n };\n\n const lock = readLock();\n\n if (command === 'init') {\n if (lock !== undefined) {\n log(`[fail] ${rel(lockPath)} already records ${stampText(lock)} — init only records a source that has never had a lock.`);\n return 1;\n }\n writeLock(upgrader.stamp);\n log(`[pass] recorded: the source is written at ${stampText(upgrader.stamp)} (${rel(lockPath)}). Only true if it is — commit it.`);\n return 0;\n }\n\n if (lock === undefined) {\n log(`[fail] no ${rel(lockPath)} — nothing records which grammars this source is written in.`);\n log(` If it is written at the installed ones (${stampText(upgrader.stamp)}), run: strata init`);\n return 1;\n }\n\n let behind: boolean;\n try {\n behind = upgrader.behind(lock);\n } catch (error) {\n log(`[fail] ${error instanceof Error ? error.message.split('\\n').join('\\n ') : String(error)}`);\n log(' The lock is ahead of the installed grammars — install the newer packages, or the lock is wrong.');\n return 1;\n }\n\n if (command === 'status') {\n if (!behind) {\n log(`[pass] the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n log(`[${argv.includes('--check') ? 'fail' : 'info'}] the source is written at ${stampText(lock)}; the installed grammars are at ${stampText(upgrader.stamp)}.`);\n log(' Run: strata upgrade — then edit what REPORT.md lists — then: strata verify');\n return argv.includes('--check') ? 1 : 0;\n }\n\n if (command === 'upgrade') {\n if (!behind) {\n log(`[pass] nothing to upgrade — the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n const documents = await loadDocuments();\n const drafted = await planSourceUpgrade({\n upgrader,\n stamp: lock,\n documents,\n ...(options.schemas === undefined ? {} : { schemas: options.schemas }),\n describe: (ref) => descriptions.get(ref) ?? '(no description)',\n });\n // Where each change is written: the files holding the values it rewrites.\n const text = sourceText();\n const byKey = new Map(documents.map((d) => [`${d.kind}:${d.id}`, d]));\n const plan: SourcePlan = {\n ...drafted,\n documents: drafted.documents.map((doc) => {\n const needles = changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `\"${s}\"`]);\n const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));\n return { ...doc, lookIn };\n }),\n };\n rmSync(work, { recursive: true, force: true });\n mkdirSync(work, { recursive: true });\n const expectedPathOf = (doc: { kind: string; id: string }): string => join(work, 'expected', doc.kind.replace(/[^a-z0-9.-]/gi, '_'), `${doc.id.replace(/[^A-Za-z0-9._-]/g, '_')}.json`);\n for (const doc of plan.documents) {\n const path = expectedPathOf(doc);\n mkdirSync(join(path, '..'), { recursive: true });\n writeFileSync(path, `${JSON.stringify(doc.expected, null, 2)}\\n`);\n }\n writeFileSync(join(work, 'plan.json'), `${JSON.stringify(plan, null, 2)}\\n`);\n writeFileSync(join(work, 'REPORT.md'), `${renderReport(plan, (d) => rel(expectedPathOf(d)))}\\n`);\n log(`[plan] ${stampText(plan.from)} → ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);\n for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);\n log(` ${plan.documents.length} artifact(s) to edit, ${plan.untouched.length} untouched.`);\n for (const d of plan.documents) log(` ${d.file ?? '(file not found)'} ${d.id}`);\n log(` Report: ${rel(join(work, 'REPORT.md'))} — edit, then: strata verify`);\n for (const p of plan.problems) log(`[fail] ${p}`);\n return plan.problems.length > 0 ? 1 : 0;\n }\n\n if (command === 'verify') {\n const planPath = join(work, 'plan.json');\n if (!existsSync(planPath)) {\n log(`[fail] no plan at ${rel(planPath)} — run: strata upgrade`);\n return 1;\n }\n const raw: unknown = JSON.parse(readFileSync(planPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['to']) || !isRecord(raw['from']) || !Array.isArray(raw['documents']) || !Array.isArray(raw['untouched'])) {\n log(`[fail] ${rel(planPath)} is not a plan — run: strata upgrade`);\n return 1;\n }\n // The plan was made by strata and read back as it wrote it.\n const plan: SourcePlan = {\n from: Object.fromEntries(Object.entries(raw['from']).map(([k, v]) => [k, Number(v)])),\n to: Object.fromEntries(Object.entries(raw['to']).map(([k, v]) => [k, Number(v)])),\n migrations: [],\n documents: raw['documents'].flatMap((d: unknown) =>\n isRecord(d) && typeof d['kind'] === 'string' && typeof d['id'] === 'string' ? [{ kind: d['kind'], id: d['id'], applied: [], changes: [], expected: d['expected'] }] : [],\n ),\n untouched: raw['untouched'].map(String),\n problems: [],\n };\n if (JSON.stringify(plan.to) !== JSON.stringify(upgrader.stamp)) {\n log(`[fail] the plan was made for ${stampText(plan.to)}, but the installed grammars are at ${stampText(upgrader.stamp)} — plan again: strata upgrade`);\n return 1;\n }\n const result = verifySourceUpgrade({ plan, upgrader, documents: await loadDocuments() });\n for (const line of result.lines) {\n log(`[${line.ok ? 'pass' : 'fail'}] ${line.text}`);\n for (const d of line.detail ?? []) log(` ${d}`);\n }\n if (!result.ok) return 1;\n writeLock(plan.to);\n rmSync(join(options.root, options.workDir ?? '.strata'), { recursive: true, force: true });\n log(`[pass] the source is now written at ${stampText(plan.to)} — ${rel(lockPath)} updated. Commit it with the edits.`);\n return 0;\n }\n\n log(`[fail] unknown command \"${command}\" — status [--check] | init | upgrade | verify`);\n return 1;\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/node/index.ts"],"names":["existsSync","readdirSync","path","join","statSync","relative","sep","createUpgrader","readFileSync","StrataError","writeFileSync","planSourceUpgrade","changedStrings","rmSync","mkdirSync","renderReport","verifySourceUpgrade"],"mappings":";;;;;;;;;;AAoBA,IAAM,QAAA,GAAW,CAAC,KAAA,KAAqD,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAE1I,IAAM,SAAA,GAAY,CAAC,CAAA,KAAqB,MAAA,CAAO,QAAQ,CAAC,CAAA,CAAE,IAAI,CAAC,CAAC,GAAG,CAAC,CAAA,KAAM,GAAG,CAAC,CAAA,CAAA,EAAI,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAA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AU,IAAA,CAAK,EAAE,CAAC,uCAAuC,SAAA,CAAU,QAAA,CAAS,KAAK,CAAC,CAAA,kCAAA,CAA+B,CAAA;AACrJ,MAAA,OAAO,CAAA;AAAA,IACT;AACA,IAAA,MAAM,MAAA,GAASQ,sCAAoB,EAAE,IAAA,EAAM,UAAU,SAAA,EAAW,MAAM,aAAA,EAAc,EAAG,CAAA;AACvF,IAAA,KAAA,MAAW,IAAA,IAAQ,OAAO,KAAA,EAAO;AAC/B,MAAA,GAAA,CAAI,CAAA,CAAA,EAAI,KAAK,EAAA,GAAK,MAAA,GAAS,MAAM,CAAA,EAAA,EAAK,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AACjD,MAAA,KAAA,MAAW,CAAA,IAAK,KAAK,MAAA,IAAU,IAAI,GAAA,CAAI,CAAA,SAAA,EAAY,CAAC,CAAA,CAAE,CAAA;AAAA,IACxD;AACA,IAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,OAAO,CAAA;AACvB,IAAA,SAAA,CAAU,KAAK,EAAE,CAAA;AACjB,IAAAH,SAAA,CAAOV,SAAA,CAAK,OAAA,CAAQ,IAAA,EAAM,OAAA,CAAQ,OAAA,IAAW,SAAS,CAAA,EAAG,EAAE,SAAA,EAAW,IAAA,EAAM,KAAA,EAAO,IAAA,EAAM,CAAA;AACzF,IAAA,GAAA,CAAI,CAAA,oCAAA,EAAuC,UAAU,IAAA,CAAK,EAAE,CAAC,CAAA,QAAA,EAAM,GAAA,CAAI,QAAQ,CAAC,CAAA,mCAAA,CAAqC,CAAA;AACrH,IAAA,OAAO,CAAA;AAAA,EACT;AAEA,EAAA,GAAA,CAAI,CAAA,wBAAA,EAA2B,OAAO,CAAA,mDAAA,CAAgD,CAAA;AACtF,EAAA,OAAO,CAAA;AACT","file":"index.cjs","sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\nimport { createUpgrader, type Stamp, type Transform } from '../documents';\nimport type { Sequence } from '../schema';\nimport type { GrammarSchema } from '../check';\nimport { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade, type SourceDocument, type SourcePlan } from '../upgrade';\nimport { StrataError } from '../errors';\n\nexport type SourceUpgradeOptions = {\n root: string;\n grammars: readonly Sequence[];\n transform: Transform;\n documents: () => readonly SourceDocument[] | Promise<readonly SourceDocument[]>;\n schemas?: Readonly<Record<string, GrammarSchema>>;\n lock?: string;\n workDir?: string;\n sources?: string;\n log?: (line: string) => void;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst stampText = (s: Stamp): string => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(', ') || '(nothing)';\n\nconst filesUnder = (dir: string): string[] =>\n existsSync(dir)\n ? readdirSync(dir).flatMap((name) => {\n const path = join(dir, name);\n if (name === 'node_modules' || name.startsWith('.')) return [];\n return statSync(path).isDirectory() ? filesUnder(path) : /\\.(ts|tsx|js|mjs)$/.test(name) ? [path] : [];\n })\n : [];\n\nexport const runSourceUpgrade = async (options: SourceUpgradeOptions, argv: readonly string[]): Promise<number> => {\n const log = options.log ?? ((line: string) => console.log(line));\n const command = argv.find((a) => !a.startsWith('-')) ?? 'status';\n const lockPath = join(options.root, options.lock ?? 'strata.lock.json');\n const work = join(options.root, options.workDir ?? join('.strata', 'upgrade'));\n // POSIX separators on every platform: these paths land in REPORT.md, plan.json and the log.\n const rel = (path: string): string => relative(options.root, path).split(sep).join('/');\n\n const upgrader = await createUpgrader(options.grammars, { transform: options.transform });\n const descriptions = new Map<string, string>(options.grammars.flatMap((g) => g.migrations.map((m, i): [string, string] => [`${g.id}/${i + 1}`, m.description])));\n\n const readLock = (): Stamp | undefined => {\n if (!existsSync(lockPath)) return undefined;\n const raw: unknown = JSON.parse(readFileSync(lockPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['grammar'])) throw new StrataError('INVALID_SEQUENCE', `${rel(lockPath)} is not a lock: expected { \"grammar\": { … } }.`);\n return Object.fromEntries(Object.entries(raw['grammar']).map(([k, v]) => [k, Number(v)]));\n };\n const writeLock = (stamp: Stamp): void =>\n writeFileSync(lockPath, `${JSON.stringify({ grammar: Object.fromEntries(Object.entries(stamp).sort(([a], [b]) => (a < b ? -1 : 1))) }, null, 2)}\\n`);\n\n const sourceText = (): Map<string, string> => new Map(filesUnder(join(options.root, options.sources ?? 'src')).map((f) => [f, readFileSync(f, 'utf8')]));\n\n const loadDocuments = async (): Promise<SourceDocument[]> => {\n const text = sourceText();\n const fileOf = (id: string): string | undefined => {\n const needles = [`id: '${id}'`, `id: \"${id}\"`, `\"id\": \"${id}\"`];\n for (const [path, body] of text) if (needles.some((n) => body.includes(n))) return rel(path);\n return undefined;\n };\n return (await options.documents()).map((d) => {\n // As it would be stored: no undefined, no functions.\n const document: unknown = JSON.parse(JSON.stringify(d.document));\n const file = d.file ?? fileOf(d.id);\n return { kind: d.kind, id: d.id, document, ...(file === undefined ? {} : { file }) };\n });\n };\n\n const lock = readLock();\n\n if (command === 'init') {\n if (lock !== undefined) {\n log(`[fail] ${rel(lockPath)} already records ${stampText(lock)} — init only records a source that has never had a lock.`);\n return 1;\n }\n writeLock(upgrader.stamp);\n log(`[pass] recorded: the source is written at ${stampText(upgrader.stamp)} (${rel(lockPath)}). Only true if it is — commit it.`);\n return 0;\n }\n\n if (lock === undefined) {\n log(`[fail] no ${rel(lockPath)} — nothing records which grammars this source is written in.`);\n log(` If it is written at the installed ones (${stampText(upgrader.stamp)}), run: strata init`);\n return 1;\n }\n\n let behind: boolean;\n try {\n behind = upgrader.behind(lock);\n } catch (error) {\n log(`[fail] ${error instanceof Error ? error.message.split('\\n').join('\\n ') : String(error)}`);\n log(' The lock is ahead of the installed grammars — install the newer packages, or the lock is wrong.');\n return 1;\n }\n\n if (command === 'status') {\n if (!behind) {\n log(`[pass] the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n log(`[${argv.includes('--check') ? 'fail' : 'info'}] the source is written at ${stampText(lock)}; the installed grammars are at ${stampText(upgrader.stamp)}.`);\n log(' Run: strata upgrade — then edit what REPORT.md lists — then: strata verify');\n return argv.includes('--check') ? 1 : 0;\n }\n\n if (command === 'upgrade') {\n if (!behind) {\n log(`[pass] nothing to upgrade — the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n const documents = await loadDocuments();\n const drafted = await planSourceUpgrade({\n upgrader,\n stamp: lock,\n documents,\n ...(options.schemas === undefined ? {} : { schemas: options.schemas }),\n describe: (ref) => descriptions.get(ref) ?? '(no description)',\n });\n const text = sourceText();\n const byKey = new Map(documents.map((d) => [`${d.kind}:${d.id}`, d]));\n const plan: SourcePlan = {\n ...drafted,\n documents: drafted.documents.map((doc) => {\n const needles = changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `\"${s}\"`]);\n const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));\n return { ...doc, lookIn };\n }),\n };\n rmSync(work, { recursive: true, force: true });\n mkdirSync(work, { recursive: true });\n const expectedPathOf = (doc: { kind: string; id: string }): string => join(work, 'expected', doc.kind.replace(/[^a-z0-9.-]/gi, '_'), `${doc.id.replace(/[^A-Za-z0-9._-]/g, '_')}.json`);\n for (const doc of plan.documents) {\n const path = expectedPathOf(doc);\n mkdirSync(join(path, '..'), { recursive: true });\n writeFileSync(path, `${JSON.stringify(doc.expected, null, 2)}\\n`);\n }\n writeFileSync(join(work, 'plan.json'), `${JSON.stringify(plan, null, 2)}\\n`);\n writeFileSync(join(work, 'REPORT.md'), `${renderReport(plan, (d) => rel(expectedPathOf(d)))}\\n`);\n log(`[plan] ${stampText(plan.from)} → ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);\n for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);\n log(` ${plan.documents.length} artifact(s) to edit, ${plan.untouched.length} untouched.`);\n for (const d of plan.documents) log(` ${d.file ?? '(file not found)'} ${d.id}`);\n log(` Report: ${rel(join(work, 'REPORT.md'))} — edit, then: strata verify`);\n for (const p of plan.problems) log(`[fail] ${p}`);\n return plan.problems.length > 0 ? 1 : 0;\n }\n\n if (command === 'verify') {\n const planPath = join(work, 'plan.json');\n if (!existsSync(planPath)) {\n log(`[fail] no plan at ${rel(planPath)} — run: strata upgrade`);\n return 1;\n }\n const raw: unknown = JSON.parse(readFileSync(planPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['to']) || !isRecord(raw['from']) || !Array.isArray(raw['documents']) || !Array.isArray(raw['untouched'])) {\n log(`[fail] ${rel(planPath)} is not a plan — run: strata upgrade`);\n return 1;\n }\n const plan: SourcePlan = {\n from: Object.fromEntries(Object.entries(raw['from']).map(([k, v]) => [k, Number(v)])),\n to: Object.fromEntries(Object.entries(raw['to']).map(([k, v]) => [k, Number(v)])),\n migrations: [],\n documents: raw['documents'].flatMap((d: unknown) =>\n isRecord(d) && typeof d['kind'] === 'string' && typeof d['id'] === 'string' ? [{ kind: d['kind'], id: d['id'], applied: [], changes: [], expected: d['expected'] }] : [],\n ),\n untouched: raw['untouched'].map(String),\n problems: [],\n };\n if (JSON.stringify(plan.to) !== JSON.stringify(upgrader.stamp)) {\n log(`[fail] the plan was made for ${stampText(plan.to)}, but the installed grammars are at ${stampText(upgrader.stamp)} — plan again: strata upgrade`);\n return 1;\n }\n const result = verifySourceUpgrade({ plan, upgrader, documents: await loadDocuments() });\n for (const line of result.lines) {\n log(`[${line.ok ? 'pass' : 'fail'}] ${line.text}`);\n for (const d of line.detail ?? []) log(` ${d}`);\n }\n if (!result.ok) return 1;\n writeLock(plan.to);\n rmSync(join(options.root, options.workDir ?? '.strata'), { recursive: true, force: true });\n log(`[pass] the source is now written at ${stampText(plan.to)} — ${rel(lockPath)} updated. Commit it with the edits.`);\n return 0;\n }\n\n log(`[fail] unknown command \"${command}\" — status [--check] | init | upgrade | verify`);\n return 1;\n};\n"]}
|
package/dist/node/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { createUpgrader } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import { planSourceUpgrade, changedStrings, renderReport, verifySourceUpgrade } from '../chunk-
|
|
4
|
-
import '../chunk-
|
|
5
|
-
import { StrataError } from '../chunk-
|
|
1
|
+
import { createUpgrader } from '../chunk-FNMGVPSA.js';
|
|
2
|
+
import '../chunk-PAMQMFBK.js';
|
|
3
|
+
import { planSourceUpgrade, changedStrings, renderReport, verifySourceUpgrade } from '../chunk-DGS4XJQQ.js';
|
|
4
|
+
import '../chunk-SH6BBA2X.js';
|
|
5
|
+
import { StrataError } from '../chunk-STNFHBNR.js';
|
|
6
6
|
import { rmSync, mkdirSync, writeFileSync, existsSync, readFileSync, readdirSync, statSync } from 'fs';
|
|
7
7
|
import { join, relative, sep } from 'path';
|
|
8
8
|
|
package/dist/node/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/node/index.ts"],"names":[],"mappings":";;;;;;;;AAuCA,IAAM,QAAA,GAAW,CAAC,KAAA,KAAqD,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAE1I,IAAM,SAAA,GAAY,CAAC,CAAA,KAAqB,MAAA,CAAO,QAAQ,CAAC,CAAA,CAAE,IAAI,CAAC,CAAC,GAAG,CAAC,CAAA,KAAM,GAAG,CAAC,CAAA,CAAA,EAAI,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA,IAAK,WAAA;AAErG,IAAM,UAAA,GAAa,CAAC,GAAA,KAClB,UAAA,CAAW,GAAG,CAAA,GACV,WAAA,CAAY,GAAG,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACjC,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,GAAA,EAAK,IAAI,CAAA;AAC3B,EAAA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A,EAAO;AAC/B,MAAA,GAAA,CAAI,CAAA,CAAA,EAAI,KAAK,EAAA,GAAK,MAAA,GAAS,MAAM,CAAA,EAAA,EAAK,IAAA,CAAK,IAAI,CAAA,CAAE,CAAA;AACjD,MAAA,KAAA,MAAW,CAAA,IAAK,KAAK,MAAA,IAAU,IAAI,GAAA,CAAI,CAAA,SAAA,EAAY,CAAC,CAAA,CAAE,CAAA;AAAA,IACxD;AACA,IAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,OAAO,CAAA;AACvB,IAAA,SAAA,CAAU,KAAK,EAAE,CAAA;AACjB,IAAA,MAAA,CAAO,IAAA,CAAK,OAAA,CAAQ,IAAA,EAAM,OAAA,CAAQ,OAAA,IAAW,SAAS,CAAA,EAAG,EAAE,SAAA,EAAW,IAAA,EAAM,KAAA,EAAO,IAAA,EAAM,CAAA;AACzF,IAAA,GAAA,CAAI,CAAA,oCAAA,EAAuC,UAAU,IAAA,CAAK,EAAE,CAAC,CAAA,QAAA,EAAM,GAAA,CAAI,QAAQ,CAAC,CAAA,mCAAA,CAAqC,CAAA;AACrH,IAAA,OAAO,CAAA;AAAA,EACT;AAEA,EAAA,GAAA,CAAI,CAAA,wBAAA,EAA2B,OAAO,CAAA,mDAAA,CAAgD,CAAA;AACtF,EAAA,OAAO,CAAA;AACT","file":"index.js","sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\nimport { createUpgrader, type Stamp, type Transform } from '../documents';\nimport type { Sequence } from '../schema';\nimport type { GrammarSchema } from '../check';\nimport { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade, type SourceDocument, type SourcePlan } from '../upgrade';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/node — `strata upgrade` for an app's source.\n//\n// An app runs this from a script of its own (it knows how to list its\n// artifacts; strata does not), e.g. `src/dev/strata.ts`:\n//\n// process.exit(await runSourceUpgrade({ root, grammars, transform, documents }, process.argv.slice(2)));\n//\n// status [--check] where the source stands against the installed grammars\n// init record that the source is written at the CURRENT grammars\n// upgrade plan: expected JSON + REPORT.md in .strata/upgrade/\n// verify the edited source against the plan; moves the lock\n//\n// The lock — strata.lock.json, committed — is the source's stamp: which\n// version of every grammar its artifacts are written in. It moves only when\n// verify passes.\n// ═══════════════════════════════════════════════════════════════\n\nexport type SourceUpgradeOptions = {\n root: string;\n grammars: readonly Sequence[];\n transform: Transform;\n documents: () => readonly SourceDocument[] | Promise<readonly SourceDocument[]>;\n schemas?: Readonly<Record<string, GrammarSchema>>;\n lock?: string;\n workDir?: string;\n // Where to look for the file an artifact is written in (default \"src\").\n sources?: string;\n log?: (line: string) => void;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst stampText = (s: Stamp): string => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(', ') || '(nothing)';\n\nconst filesUnder = (dir: string): string[] =>\n existsSync(dir)\n ? readdirSync(dir).flatMap((name) => {\n const path = join(dir, name);\n if (name === 'node_modules' || name.startsWith('.')) return [];\n return statSync(path).isDirectory() ? filesUnder(path) : /\\.(ts|tsx|js|mjs)$/.test(name) ? [path] : [];\n })\n : [];\n\nexport const runSourceUpgrade = async (options: SourceUpgradeOptions, argv: readonly string[]): Promise<number> => {\n const log = options.log ?? ((line: string) => console.log(line));\n const command = argv.find((a) => !a.startsWith('-')) ?? 'status';\n const lockPath = join(options.root, options.lock ?? 'strata.lock.json');\n const work = join(options.root, options.workDir ?? join('.strata', 'upgrade'));\n // POSIX separators on every platform: these paths land in REPORT.md,\n // plan.json and the log, which agents and committed tooling read.\n const rel = (path: string): string => relative(options.root, path).split(sep).join('/');\n\n const upgrader = await createUpgrader(options.grammars, { transform: options.transform });\n const descriptions = new Map<string, string>(options.grammars.flatMap((g) => g.migrations.map((m, i): [string, string] => [`${g.id}/${i + 1}`, m.description])));\n\n const readLock = (): Stamp | undefined => {\n if (!existsSync(lockPath)) return undefined;\n const raw: unknown = JSON.parse(readFileSync(lockPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['grammar'])) throw new StrataError('INVALID_SEQUENCE', `${rel(lockPath)} is not a lock: expected { \"grammar\": { … } }.`);\n return Object.fromEntries(Object.entries(raw['grammar']).map(([k, v]) => [k, Number(v)]));\n };\n const writeLock = (stamp: Stamp): void =>\n writeFileSync(lockPath, `${JSON.stringify({ grammar: Object.fromEntries(Object.entries(stamp).sort(([a], [b]) => (a < b ? -1 : 1))) }, null, 2)}\\n`);\n\n const sourceText = (): Map<string, string> => new Map(filesUnder(join(options.root, options.sources ?? 'src')).map((f) => [f, readFileSync(f, 'utf8')]));\n\n const loadDocuments = async (): Promise<SourceDocument[]> => {\n const text = sourceText();\n const fileOf = (id: string): string | undefined => {\n const needles = [`id: '${id}'`, `id: \"${id}\"`, `\"id\": \"${id}\"`];\n for (const [path, body] of text) if (needles.some((n) => body.includes(n))) return rel(path);\n return undefined;\n };\n return (await options.documents()).map((d) => {\n // Pure JSON, as it would be stored: no undefined, no functions.\n const document: unknown = JSON.parse(JSON.stringify(d.document));\n const file = d.file ?? fileOf(d.id);\n return { kind: d.kind, id: d.id, document, ...(file === undefined ? {} : { file }) };\n });\n };\n\n const lock = readLock();\n\n if (command === 'init') {\n if (lock !== undefined) {\n log(`[fail] ${rel(lockPath)} already records ${stampText(lock)} — init only records a source that has never had a lock.`);\n return 1;\n }\n writeLock(upgrader.stamp);\n log(`[pass] recorded: the source is written at ${stampText(upgrader.stamp)} (${rel(lockPath)}). Only true if it is — commit it.`);\n return 0;\n }\n\n if (lock === undefined) {\n log(`[fail] no ${rel(lockPath)} — nothing records which grammars this source is written in.`);\n log(` If it is written at the installed ones (${stampText(upgrader.stamp)}), run: strata init`);\n return 1;\n }\n\n let behind: boolean;\n try {\n behind = upgrader.behind(lock);\n } catch (error) {\n log(`[fail] ${error instanceof Error ? error.message.split('\\n').join('\\n ') : String(error)}`);\n log(' The lock is ahead of the installed grammars — install the newer packages, or the lock is wrong.');\n return 1;\n }\n\n if (command === 'status') {\n if (!behind) {\n log(`[pass] the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n log(`[${argv.includes('--check') ? 'fail' : 'info'}] the source is written at ${stampText(lock)}; the installed grammars are at ${stampText(upgrader.stamp)}.`);\n log(' Run: strata upgrade — then edit what REPORT.md lists — then: strata verify');\n return argv.includes('--check') ? 1 : 0;\n }\n\n if (command === 'upgrade') {\n if (!behind) {\n log(`[pass] nothing to upgrade — the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n const documents = await loadDocuments();\n const drafted = await planSourceUpgrade({\n upgrader,\n stamp: lock,\n documents,\n ...(options.schemas === undefined ? {} : { schemas: options.schemas }),\n describe: (ref) => descriptions.get(ref) ?? '(no description)',\n });\n // Where each change is written: the files holding the values it rewrites.\n const text = sourceText();\n const byKey = new Map(documents.map((d) => [`${d.kind}:${d.id}`, d]));\n const plan: SourcePlan = {\n ...drafted,\n documents: drafted.documents.map((doc) => {\n const needles = changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `\"${s}\"`]);\n const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));\n return { ...doc, lookIn };\n }),\n };\n rmSync(work, { recursive: true, force: true });\n mkdirSync(work, { recursive: true });\n const expectedPathOf = (doc: { kind: string; id: string }): string => join(work, 'expected', doc.kind.replace(/[^a-z0-9.-]/gi, '_'), `${doc.id.replace(/[^A-Za-z0-9._-]/g, '_')}.json`);\n for (const doc of plan.documents) {\n const path = expectedPathOf(doc);\n mkdirSync(join(path, '..'), { recursive: true });\n writeFileSync(path, `${JSON.stringify(doc.expected, null, 2)}\\n`);\n }\n writeFileSync(join(work, 'plan.json'), `${JSON.stringify(plan, null, 2)}\\n`);\n writeFileSync(join(work, 'REPORT.md'), `${renderReport(plan, (d) => rel(expectedPathOf(d)))}\\n`);\n log(`[plan] ${stampText(plan.from)} → ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);\n for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);\n log(` ${plan.documents.length} artifact(s) to edit, ${plan.untouched.length} untouched.`);\n for (const d of plan.documents) log(` ${d.file ?? '(file not found)'} ${d.id}`);\n log(` Report: ${rel(join(work, 'REPORT.md'))} — edit, then: strata verify`);\n for (const p of plan.problems) log(`[fail] ${p}`);\n return plan.problems.length > 0 ? 1 : 0;\n }\n\n if (command === 'verify') {\n const planPath = join(work, 'plan.json');\n if (!existsSync(planPath)) {\n log(`[fail] no plan at ${rel(planPath)} — run: strata upgrade`);\n return 1;\n }\n const raw: unknown = JSON.parse(readFileSync(planPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['to']) || !isRecord(raw['from']) || !Array.isArray(raw['documents']) || !Array.isArray(raw['untouched'])) {\n log(`[fail] ${rel(planPath)} is not a plan — run: strata upgrade`);\n return 1;\n }\n // The plan was made by strata and read back as it wrote it.\n const plan: SourcePlan = {\n from: Object.fromEntries(Object.entries(raw['from']).map(([k, v]) => [k, Number(v)])),\n to: Object.fromEntries(Object.entries(raw['to']).map(([k, v]) => [k, Number(v)])),\n migrations: [],\n documents: raw['documents'].flatMap((d: unknown) =>\n isRecord(d) && typeof d['kind'] === 'string' && typeof d['id'] === 'string' ? [{ kind: d['kind'], id: d['id'], applied: [], changes: [], expected: d['expected'] }] : [],\n ),\n untouched: raw['untouched'].map(String),\n problems: [],\n };\n if (JSON.stringify(plan.to) !== JSON.stringify(upgrader.stamp)) {\n log(`[fail] the plan was made for ${stampText(plan.to)}, but the installed grammars are at ${stampText(upgrader.stamp)} — plan again: strata upgrade`);\n return 1;\n }\n const result = verifySourceUpgrade({ plan, upgrader, documents: await loadDocuments() });\n for (const line of result.lines) {\n log(`[${line.ok ? 'pass' : 'fail'}] ${line.text}`);\n for (const d of line.detail ?? []) log(` ${d}`);\n }\n if (!result.ok) return 1;\n writeLock(plan.to);\n rmSync(join(options.root, options.workDir ?? '.strata'), { recursive: true, force: true });\n log(`[pass] the source is now written at ${stampText(plan.to)} — ${rel(lockPath)} updated. Commit it with the edits.`);\n return 0;\n }\n\n log(`[fail] unknown command \"${command}\" — status [--check] | init | upgrade | verify`);\n return 1;\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/node/index.ts"],"names":[],"mappings":";;;;;;;;AAoBA,IAAM,QAAA,GAAW,CAAC,KAAA,KAAqD,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAQ,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AAE1I,IAAM,SAAA,GAAY,CAAC,CAAA,KAAqB,MAAA,CAAO,QAAQ,CAAC,CAAA,CAAE,IAAI,CAAC,CAAC,GAAG,CAAC,CAAA,KAAM,GAAG,CAAC,CAAA,CAAA,EAAI,CAAC,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA,IAAK,WAAA;AAErG,IAAM,UAAA,GAAa,CAAC,GAAA,KAClB,UAAA,CAAW,GAAG,CAAA,GACV,WAAA,CAAY,GAAG,CAAA,CAAE,OAAA,CAAQ,CAAC,IAAA,KAAS;AACjC,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,GAAA,EAAK,IAAI,CAAA;AAC3B,EAAA,IAAI,SAAS,cAAA,IAAkB,IAAA,CAAK,WAAW,GAAG,CAAA,SAAU,EAAC;AAC7D,EAAA,OAAO,QAAA,CAAS,IAAI,CAAA,CAAE,WAAA,KAAgB,UAAA,CAAW,IAAI,CAAA,GAAI,oBAAA,CAAqB,KAAK,IAAI,CAAA,GAAI,CAAC,IAAI,IAAI,EAAC;AACvG,CAAC,IACD,EAAC;AAEA,IAAM,gBAAA,GAAmB,OAAO,OAAA,EAA+B,IAAA,KAA6C;AACjH,EAAA,MAAM,MAAM,OAAA,CAAQ,GAAA,KAAQ,CAAC,IAAA,KAAiB,OAAA,CAAQ,IAAI,IAA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CAAK,OAAA,CAAQ,IAAA,EAAM,OAAA,CAAQ,OAAA,IAAW,SAAS,CAAA,EAAG,EAAE,SAAA,EAAW,IAAA,EAAM,KAAA,EAAO,IAAA,EAAM,CAAA;AACzF,IAAA,GAAA,CAAI,CAAA,oCAAA,EAAuC,UAAU,IAAA,CAAK,EAAE,CAAC,CAAA,QAAA,EAAM,GAAA,CAAI,QAAQ,CAAC,CAAA,mCAAA,CAAqC,CAAA;AACrH,IAAA,OAAO,CAAA;AAAA,EACT;AAEA,EAAA,GAAA,CAAI,CAAA,wBAAA,EAA2B,OAAO,CAAA,mDAAA,CAAgD,CAAA;AACtF,EAAA,OAAO,CAAA;AACT","file":"index.js","sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\nimport { createUpgrader, type Stamp, type Transform } from '../documents';\nimport type { Sequence } from '../schema';\nimport type { GrammarSchema } from '../check';\nimport { changedStrings, planSourceUpgrade, renderReport, verifySourceUpgrade, type SourceDocument, type SourcePlan } from '../upgrade';\nimport { StrataError } from '../errors';\n\nexport type SourceUpgradeOptions = {\n root: string;\n grammars: readonly Sequence[];\n transform: Transform;\n documents: () => readonly SourceDocument[] | Promise<readonly SourceDocument[]>;\n schemas?: Readonly<Record<string, GrammarSchema>>;\n lock?: string;\n workDir?: string;\n sources?: string;\n log?: (line: string) => void;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst stampText = (s: Stamp): string => Object.entries(s).map(([k, v]) => `${k} ${v}`).join(', ') || '(nothing)';\n\nconst filesUnder = (dir: string): string[] =>\n existsSync(dir)\n ? readdirSync(dir).flatMap((name) => {\n const path = join(dir, name);\n if (name === 'node_modules' || name.startsWith('.')) return [];\n return statSync(path).isDirectory() ? filesUnder(path) : /\\.(ts|tsx|js|mjs)$/.test(name) ? [path] : [];\n })\n : [];\n\nexport const runSourceUpgrade = async (options: SourceUpgradeOptions, argv: readonly string[]): Promise<number> => {\n const log = options.log ?? ((line: string) => console.log(line));\n const command = argv.find((a) => !a.startsWith('-')) ?? 'status';\n const lockPath = join(options.root, options.lock ?? 'strata.lock.json');\n const work = join(options.root, options.workDir ?? join('.strata', 'upgrade'));\n // POSIX separators on every platform: these paths land in REPORT.md, plan.json and the log.\n const rel = (path: string): string => relative(options.root, path).split(sep).join('/');\n\n const upgrader = await createUpgrader(options.grammars, { transform: options.transform });\n const descriptions = new Map<string, string>(options.grammars.flatMap((g) => g.migrations.map((m, i): [string, string] => [`${g.id}/${i + 1}`, m.description])));\n\n const readLock = (): Stamp | undefined => {\n if (!existsSync(lockPath)) return undefined;\n const raw: unknown = JSON.parse(readFileSync(lockPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['grammar'])) throw new StrataError('INVALID_SEQUENCE', `${rel(lockPath)} is not a lock: expected { \"grammar\": { … } }.`);\n return Object.fromEntries(Object.entries(raw['grammar']).map(([k, v]) => [k, Number(v)]));\n };\n const writeLock = (stamp: Stamp): void =>\n writeFileSync(lockPath, `${JSON.stringify({ grammar: Object.fromEntries(Object.entries(stamp).sort(([a], [b]) => (a < b ? -1 : 1))) }, null, 2)}\\n`);\n\n const sourceText = (): Map<string, string> => new Map(filesUnder(join(options.root, options.sources ?? 'src')).map((f) => [f, readFileSync(f, 'utf8')]));\n\n const loadDocuments = async (): Promise<SourceDocument[]> => {\n const text = sourceText();\n const fileOf = (id: string): string | undefined => {\n const needles = [`id: '${id}'`, `id: \"${id}\"`, `\"id\": \"${id}\"`];\n for (const [path, body] of text) if (needles.some((n) => body.includes(n))) return rel(path);\n return undefined;\n };\n return (await options.documents()).map((d) => {\n // As it would be stored: no undefined, no functions.\n const document: unknown = JSON.parse(JSON.stringify(d.document));\n const file = d.file ?? fileOf(d.id);\n return { kind: d.kind, id: d.id, document, ...(file === undefined ? {} : { file }) };\n });\n };\n\n const lock = readLock();\n\n if (command === 'init') {\n if (lock !== undefined) {\n log(`[fail] ${rel(lockPath)} already records ${stampText(lock)} — init only records a source that has never had a lock.`);\n return 1;\n }\n writeLock(upgrader.stamp);\n log(`[pass] recorded: the source is written at ${stampText(upgrader.stamp)} (${rel(lockPath)}). Only true if it is — commit it.`);\n return 0;\n }\n\n if (lock === undefined) {\n log(`[fail] no ${rel(lockPath)} — nothing records which grammars this source is written in.`);\n log(` If it is written at the installed ones (${stampText(upgrader.stamp)}), run: strata init`);\n return 1;\n }\n\n let behind: boolean;\n try {\n behind = upgrader.behind(lock);\n } catch (error) {\n log(`[fail] ${error instanceof Error ? error.message.split('\\n').join('\\n ') : String(error)}`);\n log(' The lock is ahead of the installed grammars — install the newer packages, or the lock is wrong.');\n return 1;\n }\n\n if (command === 'status') {\n if (!behind) {\n log(`[pass] the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n log(`[${argv.includes('--check') ? 'fail' : 'info'}] the source is written at ${stampText(lock)}; the installed grammars are at ${stampText(upgrader.stamp)}.`);\n log(' Run: strata upgrade — then edit what REPORT.md lists — then: strata verify');\n return argv.includes('--check') ? 1 : 0;\n }\n\n if (command === 'upgrade') {\n if (!behind) {\n log(`[pass] nothing to upgrade — the source is written at the installed grammars (${stampText(lock)})`);\n return 0;\n }\n const documents = await loadDocuments();\n const drafted = await planSourceUpgrade({\n upgrader,\n stamp: lock,\n documents,\n ...(options.schemas === undefined ? {} : { schemas: options.schemas }),\n describe: (ref) => descriptions.get(ref) ?? '(no description)',\n });\n const text = sourceText();\n const byKey = new Map(documents.map((d) => [`${d.kind}:${d.id}`, d]));\n const plan: SourcePlan = {\n ...drafted,\n documents: drafted.documents.map((doc) => {\n const needles = changedStrings(byKey.get(`${doc.kind}:${doc.id}`)?.document, doc.expected).flatMap((s) => [`'${s}'`, `\"${s}\"`]);\n const lookIn = [...text].filter(([, body]) => needles.some((n) => body.includes(n))).map(([path]) => rel(path));\n return { ...doc, lookIn };\n }),\n };\n rmSync(work, { recursive: true, force: true });\n mkdirSync(work, { recursive: true });\n const expectedPathOf = (doc: { kind: string; id: string }): string => join(work, 'expected', doc.kind.replace(/[^a-z0-9.-]/gi, '_'), `${doc.id.replace(/[^A-Za-z0-9._-]/g, '_')}.json`);\n for (const doc of plan.documents) {\n const path = expectedPathOf(doc);\n mkdirSync(join(path, '..'), { recursive: true });\n writeFileSync(path, `${JSON.stringify(doc.expected, null, 2)}\\n`);\n }\n writeFileSync(join(work, 'plan.json'), `${JSON.stringify(plan, null, 2)}\\n`);\n writeFileSync(join(work, 'REPORT.md'), `${renderReport(plan, (d) => rel(expectedPathOf(d)))}\\n`);\n log(`[plan] ${stampText(plan.from)} → ${stampText(plan.to)}: ${plan.migrations.length} migration(s)`);\n for (const m of plan.migrations) log(` ${m.ref} ${m.description}`);\n log(` ${plan.documents.length} artifact(s) to edit, ${plan.untouched.length} untouched.`);\n for (const d of plan.documents) log(` ${d.file ?? '(file not found)'} ${d.id}`);\n log(` Report: ${rel(join(work, 'REPORT.md'))} — edit, then: strata verify`);\n for (const p of plan.problems) log(`[fail] ${p}`);\n return plan.problems.length > 0 ? 1 : 0;\n }\n\n if (command === 'verify') {\n const planPath = join(work, 'plan.json');\n if (!existsSync(planPath)) {\n log(`[fail] no plan at ${rel(planPath)} — run: strata upgrade`);\n return 1;\n }\n const raw: unknown = JSON.parse(readFileSync(planPath, 'utf8'));\n if (!isRecord(raw) || !isRecord(raw['to']) || !isRecord(raw['from']) || !Array.isArray(raw['documents']) || !Array.isArray(raw['untouched'])) {\n log(`[fail] ${rel(planPath)} is not a plan — run: strata upgrade`);\n return 1;\n }\n const plan: SourcePlan = {\n from: Object.fromEntries(Object.entries(raw['from']).map(([k, v]) => [k, Number(v)])),\n to: Object.fromEntries(Object.entries(raw['to']).map(([k, v]) => [k, Number(v)])),\n migrations: [],\n documents: raw['documents'].flatMap((d: unknown) =>\n isRecord(d) && typeof d['kind'] === 'string' && typeof d['id'] === 'string' ? [{ kind: d['kind'], id: d['id'], applied: [], changes: [], expected: d['expected'] }] : [],\n ),\n untouched: raw['untouched'].map(String),\n problems: [],\n };\n if (JSON.stringify(plan.to) !== JSON.stringify(upgrader.stamp)) {\n log(`[fail] the plan was made for ${stampText(plan.to)}, but the installed grammars are at ${stampText(upgrader.stamp)} — plan again: strata upgrade`);\n return 1;\n }\n const result = verifySourceUpgrade({ plan, upgrader, documents: await loadDocuments() });\n for (const line of result.lines) {\n log(`[${line.ok ? 'pass' : 'fail'}] ${line.text}`);\n for (const d of line.detail ?? []) log(` ${d}`);\n }\n if (!result.ok) return 1;\n writeLock(plan.to);\n rmSync(join(options.root, options.workDir ?? '.strata'), { recursive: true, force: true });\n log(`[pass] the source is now written at ${stampText(plan.to)} — ${rel(lockPath)} updated. Commit it with the edits.`);\n return 0;\n }\n\n log(`[fail] unknown command \"${command}\" — status [--check] | init | upgrade | verify`);\n return 1;\n};\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { l as Step, D as DocumentKind, a as Sequence } from './documents-BjlM94Ea.js';
|
|
2
2
|
|
|
3
|
-
type StrataErrorCode = 'INVALID_SEQUENCE' | 'EDITED' | 'TOO_NEW' | 'UNKNOWN_DEPENDENCY' | 'CYCLE' | 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER';
|
|
3
|
+
type StrataErrorCode = 'INVALID_SEQUENCE' | 'EDITED' | 'TOO_NEW' | 'UNKNOWN_SEQUENCE' | 'UNKNOWN_DEPENDENCY' | 'CYCLE' | 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER';
|
|
4
4
|
declare class StrataError extends Error {
|
|
5
5
|
readonly code: StrataErrorCode;
|
|
6
6
|
readonly details: readonly string[];
|
|
@@ -47,7 +47,10 @@ declare const orderPending: (queues: readonly {
|
|
|
47
47
|
pending: PreparedMigration[];
|
|
48
48
|
stuck: PreparedMigration[];
|
|
49
49
|
};
|
|
50
|
-
|
|
50
|
+
type PlanOptions = {
|
|
51
|
+
complete?: boolean;
|
|
52
|
+
};
|
|
53
|
+
declare const planMigrations: (sequences: readonly PreparedSequence[], ledger: readonly LedgerRow[], options?: PlanOptions) => Plan;
|
|
51
54
|
declare const refuseProblems: (plan: Plan) => void;
|
|
52
55
|
|
|
53
|
-
export { type LedgerRow as L, type Plan as P, StrataError as S, type
|
|
56
|
+
export { type LedgerRow as L, type Plan as P, StrataError as S, type PlanOptions as a, type PreparedMigration as b, type PreparedSequence as c, type Problem as d, type StrataErrorCode as e, prepare as f, orderPending as o, planMigrations as p, refuseProblems as r };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { l as Step, D as DocumentKind, a as Sequence } from './documents-BjlM94Ea.cjs';
|
|
2
2
|
|
|
3
|
-
type StrataErrorCode = 'INVALID_SEQUENCE' | 'EDITED' | 'TOO_NEW' | 'UNKNOWN_DEPENDENCY' | 'CYCLE' | 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER';
|
|
3
|
+
type StrataErrorCode = 'INVALID_SEQUENCE' | 'EDITED' | 'TOO_NEW' | 'UNKNOWN_SEQUENCE' | 'UNKNOWN_DEPENDENCY' | 'CYCLE' | 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER';
|
|
4
4
|
declare class StrataError extends Error {
|
|
5
5
|
readonly code: StrataErrorCode;
|
|
6
6
|
readonly details: readonly string[];
|
|
@@ -47,7 +47,10 @@ declare const orderPending: (queues: readonly {
|
|
|
47
47
|
pending: PreparedMigration[];
|
|
48
48
|
stuck: PreparedMigration[];
|
|
49
49
|
};
|
|
50
|
-
|
|
50
|
+
type PlanOptions = {
|
|
51
|
+
complete?: boolean;
|
|
52
|
+
};
|
|
53
|
+
declare const planMigrations: (sequences: readonly PreparedSequence[], ledger: readonly LedgerRow[], options?: PlanOptions) => Plan;
|
|
51
54
|
declare const refuseProblems: (plan: Plan) => void;
|
|
52
55
|
|
|
53
|
-
export { type LedgerRow as L, type Plan as P, StrataError as S, type
|
|
56
|
+
export { type LedgerRow as L, type Plan as P, StrataError as S, type PlanOptions as a, type PreparedMigration as b, type PreparedSequence as c, type Problem as d, type StrataErrorCode as e, prepare as f, orderPending as o, planMigrations as p, refuseProblems as r };
|
package/dist/postgres/index.cjs
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunkKYNER7UU_cjs = require('../chunk-KYNER7UU.cjs');
|
|
4
|
+
var chunk7PBIGCLL_cjs = require('../chunk-7PBIGCLL.cjs');
|
|
5
5
|
|
|
6
6
|
// src/postgres/index.ts
|
|
7
|
+
var LOCK_TIMEOUT_MS = 1e4;
|
|
8
|
+
var STATEMENT_TIMEOUT_MS = 36e5;
|
|
7
9
|
var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
8
10
|
var quote = (name, label) => {
|
|
9
|
-
if (!IDENT.test(name)) throw new
|
|
11
|
+
if (!IDENT.test(name)) throw new chunk7PBIGCLL_cjs.StrataError("INVALID_SEQUENCE", `The ledger ${label} "${name}" is not a plain identifier.`);
|
|
10
12
|
return `"${name}"`;
|
|
11
13
|
};
|
|
12
14
|
var ledgerNameOf = (options) => {
|
|
@@ -42,22 +44,37 @@ var readLedger = async (pool, options = {}) => {
|
|
|
42
44
|
if (rows[0]?.["present"] !== true) return [];
|
|
43
45
|
return readRows(pool, qualified);
|
|
44
46
|
};
|
|
45
|
-
var status = async (pool, sequences, options = {}) =>
|
|
47
|
+
var status = async (pool, sequences, options = {}) => chunkKYNER7UU_cjs.planMigrations(await chunkKYNER7UU_cjs.prepare(sequences), await readLedger(pool, options), options);
|
|
46
48
|
var refuseGrammars = (prepared) => {
|
|
47
49
|
const grammars = prepared.filter((s) => s.grammar);
|
|
48
50
|
if (grammars.length > 0) {
|
|
49
|
-
throw new
|
|
51
|
+
throw new chunk7PBIGCLL_cjs.StrataError(
|
|
50
52
|
"WRONG_OWNER",
|
|
51
53
|
"These sequences own documents, not tables: a document carries its own stamp and is upgraded where it is read (`createUpgrader`, `upgradeStore`) \u2014 never recorded in a database's ledger.",
|
|
52
54
|
grammars.map((s) => s.id)
|
|
53
55
|
);
|
|
54
56
|
}
|
|
55
57
|
};
|
|
58
|
+
var refusePending = (plan) => {
|
|
59
|
+
if (plan.pending.length === 0) return;
|
|
60
|
+
throw new chunk7PBIGCLL_cjs.StrataError(
|
|
61
|
+
"PENDING",
|
|
62
|
+
`${plan.pending.length} migration${plan.pending.length === 1 ? " is" : "s are"} not applied, and this boot only verifies. Run the migrations first.`,
|
|
63
|
+
plan.pending.map((m) => `${m.ref} ${m.description}`)
|
|
64
|
+
);
|
|
65
|
+
};
|
|
56
66
|
var migrate = async (pool, sequences, options = {}) => {
|
|
57
|
-
const prepared = await
|
|
67
|
+
const prepared = await chunkKYNER7UU_cjs.prepare(sequences);
|
|
58
68
|
refuseGrammars(prepared);
|
|
69
|
+
const read = chunkKYNER7UU_cjs.planMigrations(prepared, await readLedger(pool, options), options);
|
|
70
|
+
chunkKYNER7UU_cjs.refuseProblems(read);
|
|
71
|
+
if (options.mode === "verify") {
|
|
72
|
+
refusePending(read);
|
|
73
|
+
return { applied: [], plan: read };
|
|
74
|
+
}
|
|
75
|
+
if (read.pending.length === 0 && options.guard === void 0 && options.dryRun !== true) return { applied: [], plan: read };
|
|
59
76
|
if (pool.transaction === void 0) {
|
|
60
|
-
throw new
|
|
77
|
+
throw new chunk7PBIGCLL_cjs.StrataError(
|
|
61
78
|
"NO_TRANSACTION",
|
|
62
79
|
"This pool cannot run a transaction, and a migration run must land whole or not at all. Pass a pool with `transaction` (vex's PGlite pool has one; wrap a `pg` Pool so it checks a client out per transaction)."
|
|
63
80
|
);
|
|
@@ -66,18 +83,14 @@ var migrate = async (pool, sequences, options = {}) => {
|
|
|
66
83
|
const dryRunEnd = new Error("strata: dry run");
|
|
67
84
|
let dryRunReport;
|
|
68
85
|
const run = pool.transaction(async (tx) => {
|
|
86
|
+
await tx.query("SELECT set_config('statement_timeout', $1, true)", [`${options.statementTimeoutMs ?? STATEMENT_TIMEOUT_MS}ms`]);
|
|
87
|
+
await tx.query("SELECT set_config('lock_timeout', '0', true)");
|
|
69
88
|
await tx.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`strata:${qualified}`]);
|
|
89
|
+
await tx.query("SELECT set_config('lock_timeout', $1, true)", [`${options.lockTimeoutMs ?? LOCK_TIMEOUT_MS}ms`]);
|
|
70
90
|
if (schema !== void 0) await tx.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);
|
|
71
91
|
await tx.query(ledgerDdl(options));
|
|
72
|
-
const plan =
|
|
73
|
-
|
|
74
|
-
if (options.mode === "verify" && plan.pending.length > 0) {
|
|
75
|
-
throw new chunkATHZ7HT5_cjs.StrataError(
|
|
76
|
-
"PENDING",
|
|
77
|
-
`${plan.pending.length} migration${plan.pending.length === 1 ? " is" : "s are"} not applied, and this boot only verifies. Run the migrations first.`,
|
|
78
|
-
plan.pending.map((m) => `${m.ref} ${m.description}`)
|
|
79
|
-
);
|
|
80
|
-
}
|
|
92
|
+
const plan = chunkKYNER7UU_cjs.planMigrations(prepared, await readRows(tx, qualified), options);
|
|
93
|
+
chunkKYNER7UU_cjs.refuseProblems(plan);
|
|
81
94
|
const applied = [];
|
|
82
95
|
for (const migration of plan.pending) {
|
|
83
96
|
for (const [index, step] of migration.steps.entries()) {
|
|
@@ -85,7 +98,7 @@ var migrate = async (pool, sequences, options = {}) => {
|
|
|
85
98
|
try {
|
|
86
99
|
await tx.query(step.sql);
|
|
87
100
|
} catch (cause) {
|
|
88
|
-
throw new
|
|
101
|
+
throw new chunk7PBIGCLL_cjs.StrataError(
|
|
89
102
|
"STEP_FAILED",
|
|
90
103
|
`${migration.ref} ("${migration.description}") failed at step ${index + 1} of ${migration.steps.length}. Nothing from this run was applied.`,
|
|
91
104
|
[cause instanceof Error ? cause.message : String(cause), step.sql.length > 300 ? `${step.sql.slice(0, 300)}\u2026` : step.sql],
|
|
@@ -101,9 +114,9 @@ var migrate = async (pool, sequences, options = {}) => {
|
|
|
101
114
|
]);
|
|
102
115
|
applied.push(migration);
|
|
103
116
|
}
|
|
104
|
-
const reasons = options.guard === void 0 ? [] : await options.guard(tx);
|
|
117
|
+
const reasons = options.guard === void 0 ? [] : await options.guard(tx, { applied });
|
|
105
118
|
if (reasons.length > 0) {
|
|
106
|
-
throw new
|
|
119
|
+
throw new chunk7PBIGCLL_cjs.StrataError("DOES_NOT_FIT", "What this run leaves does not fit what has to run on it. Nothing from this run was applied.", reasons);
|
|
107
120
|
}
|
|
108
121
|
if (options.dryRun === true) {
|
|
109
122
|
dryRunReport = { applied, plan };
|
|
@@ -118,13 +131,13 @@ var migrate = async (pool, sequences, options = {}) => {
|
|
|
118
131
|
};
|
|
119
132
|
var upgradeStore = async (pool, store, upgrader) => {
|
|
120
133
|
if (pool.transaction === void 0) {
|
|
121
|
-
throw new
|
|
134
|
+
throw new chunk7PBIGCLL_cjs.StrataError("NO_TRANSACTION", "Rewriting a store must land whole or not at all; this pool cannot run a transaction.");
|
|
122
135
|
}
|
|
123
136
|
const table = store.schema === void 0 ? quote(store.table, "table") : `${quote(store.schema, "schema")}.${quote(store.table, "table")}`;
|
|
124
137
|
const column = quote(store.column, "column");
|
|
125
138
|
const stamp = quote(store.stamp, "column");
|
|
126
139
|
const keys = store.key.map((k) => quote(k, "column"));
|
|
127
|
-
if (keys.length === 0) throw new
|
|
140
|
+
if (keys.length === 0) throw new chunk7PBIGCLL_cjs.StrataError("INVALID_SEQUENCE", `The store ${store.table} names no key columns.`);
|
|
128
141
|
return pool.transaction(async (tx) => {
|
|
129
142
|
const { rows } = await tx.query(`SELECT ${[...keys, column, stamp].join(", ")} FROM ${table} FOR UPDATE`);
|
|
130
143
|
const applied = {};
|
|
@@ -138,8 +151,8 @@ var upgradeStore = async (pool, store, upgrader) => {
|
|
|
138
151
|
if (!upgrader.behind(rowStamp)) continue;
|
|
139
152
|
result = upgrader.upgrade(row[store.column], { kind: store.kind, stamp: rowStamp });
|
|
140
153
|
} catch (cause) {
|
|
141
|
-
if (cause instanceof
|
|
142
|
-
throw new
|
|
154
|
+
if (cause instanceof chunk7PBIGCLL_cjs.StrataError) {
|
|
155
|
+
throw new chunk7PBIGCLL_cjs.StrataError(cause.code, `${store.table} (${where}): ${cause.message.split("\n")[0] ?? ""}`, cause.details, { cause });
|
|
143
156
|
}
|
|
144
157
|
throw cause;
|
|
145
158
|
}
|