@niscorp/strata 0.1.1 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +83 -0
- package/DESIGN.md +7 -3
- package/README.md +19 -4
- package/dist/check/index.cjs +23 -217
- package/dist/check/index.cjs.map +1 -1
- package/dist/check/index.js +2 -2
- package/dist/{chunk-MY3TGSV3.js → chunk-4BLHBVSC.js} +15 -4
- package/dist/chunk-4BLHBVSC.js.map +1 -0
- 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-ICWKTTKN.js → chunk-OLDORFOQ.js} +12 -7
- package/dist/chunk-OLDORFOQ.js.map +1 -0
- package/dist/{chunk-HMT7HHFJ.js → chunk-WU3OJHVZ.js} +4 -4
- package/dist/{chunk-HMT7HHFJ.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 -325
- 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 -477
- 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 +36 -206
- 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 +24 -12
- package/dist/postgres/index.js.map +1 -1
- package/dist/upgrade/index.cjs +19 -229
- package/dist/upgrade/index.cjs.map +1 -1
- package/dist/upgrade/index.js +3 -3
- package/package.json +3 -2
- package/dist/chunk-ICWKTTKN.js.map +0 -1
- package/dist/chunk-MY3TGSV3.js.map +0 -1
package/dist/node/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/schema.ts","../../src/checksum.ts","../../src/errors.ts","../../src/plan.ts","../../src/documents.ts","../../src/check/index.ts","../../src/upgrade/index.ts","../../src/node/index.ts"],"names":["z","isRecord","sortKeys","existsSync","readdirSync","path","join","statSync","relative","sep","readFileSync","writeFileSync","byKey","rmSync","mkdirSync"],"mappings":";;;;;;;AAiBO,IAAM,WAAA,GAAc,uCAAA;AAIpB,IAAM,aAAA,GAAgB,oDAAA;AAItB,IAAM,SAAA,GAAY,mBAAA;AAClB,IAAM,QAAA,GAAW,wDAAA;AAOjB,IAAM,UAAA,GAAa,iEAAA;AAEnB,IAAM,aAAA,GAAgBA,MAC1B,MAAA,CAAO;AAAA,EACN,IAAA,EAAMA,KAAA,CAAE,OAAA,CAAQ,KAAK,CAAA;AAAA,EACrB,KAAKA,KAAA,CACF,MAAA,EAAO,CACP,GAAA,CAAI,CAAC,CAAA,CACL,QAAA;AAAA,IACC;AAAA;AAGN,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,yEAAyE,CAAA;AAE9E,IAAM,kBAAA,GAAqBA,MAC/B,MAAA,CAAO;AAAA,EACN,IAAA,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O,CAAA;AACvB,IAAA,SAAA,CAAU,KAAK,EAAE,CAAA;AACjB,IAAAY,SAAA,CAAOP,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 { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// The grammar of a migration.\n//\n// A SEQUENCE is an append-only list of migrations owned by one grammar owner —\n// a package's tables (`nisc.vex.cache`), a package's documents (`nisc.nova`,\n// later), an app's own (`midas.app`). A migration's number is its POSITION, so\n// the sequence's version is its length: nobody bumps a number, you append.\n//\n// Sequences are data. They are authored in TS for type-checking, but nothing\n// here is a function, so a sequence can be stored, shipped and inspected like\n// every other nisc artifact — and is parsed at the boundary like one.\n// ═══════════════════════════════════════════════════════════════\n\n// Namespaced, lowercase: `<owner>.<name>[.<name>…]`. The owner prefix keeps two\n// packages (or a package and an app) from ever claiming the same sequence.\nexport const SEQUENCE_ID = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+$/;\n\n// `<sequence>/<n>` — how a migration is named everywhere: the ledger, a\n// dependency, an error.\nexport const MIGRATION_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[1-9][0-9]*$/;\n\n// A document kind, named by its owner: `<sequence>/<kind>`, e.g.\n// \"nisc.nova/layout\". The kind part is a plain lowercase word.\nexport const KIND_NAME = /^[a-z][a-z0-9-]*$/;\nexport const KIND_REF = /^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*)+\\/[a-z][a-z0-9-]*$/;\n\n// Where, inside a document, another document sits. Dot-separated keys, with\n// two wildcards that say WHICH shape they cross — `children[]` is every item of\n// the array at `children`, `endpoints.*` every value of the record at\n// `endpoints`. Kept apart on purpose: nova's `children` is a single node OR an\n// array, and one wildcard for both would read a lone node's `props` as layouts.\nexport const EMBED_PATH = /^([A-Za-z_$][\\w$]*|\\*)(\\[\\])?(\\.([A-Za-z_$][\\w$]*|\\*)(\\[\\])?)*$/;\n\nexport const SqlStepSchema = z\n .object({\n kind: z.literal('sql'),\n sql: z\n .string()\n .min(1)\n .describe(\n 'ONE SQL statement. A driver that prepares statements (PGlite, pg with parameters) refuses a string ' +\n 'carrying several — split them into steps rather than joining them with semicolons.',\n ),\n })\n .strict()\n .describe('A statement run against the database, inside the migration transaction.');\n\nexport const DocumentStepSchema = z\n .object({\n kind: z.literal('document'),\n at: z\n .string()\n .regex(KIND_REF)\n .describe('The kind of document this step rewrites, e.g. \"nisc.nova/layout\" — wherever one sits, at any depth.'),\n transform: z\n .unknown()\n .describe(\n 'A transform config (Prism) run by the injected evaluator over { document, path }: `document` is ONE document of ' +\n 'the `at` kind, `path` where it sits. It returns that document rewritten. Nested documents are found by the ' +\n 'grammar\\'s embeddings and rewritten on their own, deepest first — a transform only ever sees one flat node.',\n ),\n })\n .strict()\n .describe('A rewrite of stored JSON documents of one kind.');\n\nexport const StepSchema = z.discriminatedUnion('kind', [SqlStepSchema, DocumentStepSchema]);\n\nexport const DocumentKindSchema = z\n .object({\n embeds: z\n .record(z.string().regex(EMBED_PATH), z.string().regex(KIND_REF))\n .optional()\n .describe('Where other documents sit inside this one: path → the kind found there (possibly this kind itself).'),\n })\n .strict();\n\nexport const MigrationSchema = z\n .object({\n description: z\n .string()\n .min(1)\n .describe('One sentence: what this migration does. It is the changelog line and the ledger\\'s description.'),\n steps: z\n .array(StepSchema)\n .describe(\n 'Applied in order, in the same transaction as every other pending migration. Empty is a MARKER: ' +\n 'the version moves and nothing runs — how an addition to a strict grammar tells older readers to refuse.',\n ),\n dependsOn: z\n .array(z.string().regex(MIGRATION_REF))\n .optional()\n .describe('Migrations of OTHER sequences that must be applied first, each as \"<sequence>/<n>\".'),\n })\n .strict();\n\nexport const SequenceSchema = z\n .object({\n id: z.string().regex(SEQUENCE_ID).describe('Namespaced and lowercase, e.g. \"nisc.vex.cache\" or \"midas.app\".'),\n documents: z\n .record(z.string().regex(KIND_NAME), DocumentKindSchema)\n .optional()\n .describe('The document kinds this sequence owns (a GRAMMAR sequence), each named \"<id>/<kind>\" elsewhere.'),\n migrations: z\n .array(MigrationSchema)\n .describe('Append-only. A migration is numbered by its position (from 1); the sequence\\'s version is its length.'),\n })\n .strict()\n // TWO KINDS OF OWNER. A table sequence (sql steps) is recorded per DATABASE,\n // in its ledger. A grammar sequence (document steps) is tracked per DOCUMENT,\n // by the stamp the document carries — because documents travel: an add-on\n // built on older code submits older documents to a newer host. One sequence\n // cannot be both; the two versions would mean different things.\n .superRefine((sequence, ctx) => {\n const kinds = new Set(sequence.migrations.flatMap((m) => m.steps.map((s) => s.kind)));\n if (kinds.has('sql') && (kinds.has('document') || sequence.documents !== undefined)) {\n ctx.addIssue({\n code: 'custom',\n message: 'A sequence either owns tables (sql steps) or documents (document steps and `documents`), not both.',\n });\n }\n });\n\nexport type SqlStep = z.infer<typeof SqlStepSchema>;\nexport type DocumentStep = z.infer<typeof DocumentStepSchema>;\nexport type DocumentKind = z.infer<typeof DocumentKindSchema>;\nexport type Step = z.infer<typeof StepSchema>;\nexport type Migration = z.infer<typeof MigrationSchema>;\nexport type Sequence = z.infer<typeof SequenceSchema>;\n","import type { Migration } from './schema';\n\n// ═══════════════════════════════════════════════════════════════\n// What a migration DID, as a hash — the ledger's proof that the code still says\n// what the database ran.\n//\n// Over the steps only. The description is prose: fixing a typo in it must not\n// read as an edited migration. `dependsOn` orders, it does not act. The steps\n// are the effect, and changing an applied step is the one thing that has to\n// be refused — the database already holds the old effect.\n//\n// For the same reason a step's SQL is hashed without its full-line comments\n// (`-- …` on a line of its own) and without trailing whitespace: a migration\n// can carry its documentation verbatim, and rewording it is not an edit.\n//\n// WebCrypto (SHA-256), which Node ≥ 22 and every browser carry as\n// `crypto.subtle` — the same primitive Prism fingerprints with, so strata runs\n// unchanged in a server, a test and the showroom page.\n// ═══════════════════════════════════════════════════════════════\n\n// Sorted keys, recursively: the same value always serializes the same way,\n// whatever order its object literal was written in.\nconst canonical = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;\n }\n return JSON.stringify(value);\n};\n\nconst effectOf = (sql: string): string =>\n sql\n .split('\\n')\n .filter((line) => !line.trimStart().startsWith('--'))\n .map((line) => line.trimEnd())\n .join('\\n')\n .trim();\n\nexport const checksumOf = async (migration: Migration): Promise<string> => {\n const steps = migration.steps.map((step) => (step.kind === 'sql' ? { ...step, sql: effectOf(step.sql) } : step));\n const bytes = new TextEncoder().encode(canonical(steps));\n const digest = await crypto.subtle.digest('SHA-256', bytes);\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n};\n","// 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 { SequenceSchema, type DocumentKind, type Sequence, type Step } from './schema';\nimport { checksumOf } from './checksum';\nimport { StrataError, type StrataErrorCode } from './errors';\n\n// ═══════════════════════════════════════════════════════════════\n// The plan — what the code says, against what the database has run.\n//\n// Pure: sequences and ledger rows in, a plan out. No database, no clock. The\n// postgres runner reads the ledger, calls this, and applies what it says; a\n// showroom page or a CI check can call it with a ledger it made up.\n// ═══════════════════════════════════════════════════════════════\n\n// A migration the code declares, numbered and hashed.\nexport type PreparedMigration = {\n sequence: string;\n n: number;\n ref: string;\n description: string;\n checksum: string;\n steps: readonly Step[];\n dependsOn: readonly string[];\n};\n\nexport type PreparedSequence = {\n id: string;\n // A grammar sequence owns documents (tracked by stamps); otherwise it owns\n // tables (tracked by a database's ledger). See SequenceSchema.\n grammar: boolean;\n documents: Readonly<Record<string, DocumentKind>>;\n migrations: readonly PreparedMigration[];\n};\n\n// One row of the ledger, as a runner read it back.\nexport type LedgerRow = { sequence: string; n: number; checksum: string; description: string; appliedAt: string };\n\nexport type Problem = { code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>; detail: string };\n\nexport type Plan = {\n // Already run, per sequence this code knows: how far each one is.\n applied: Readonly<Record<string, number>>;\n // To run, in the order they must run.\n pending: readonly PreparedMigration[];\n // Anything that makes applying unsafe. A plan with problems is never applied.\n problems: readonly Problem[];\n};\n\nconst refOf = (sequence: string, n: number): string => `${sequence}/${n}`;\n\n// Parse, number and hash. Async only for the hash (WebCrypto).\nexport const prepare = async (sequences: readonly Sequence[]): Promise<readonly PreparedSequence[]> => {\n const seen = new Set<string>();\n const prepared: PreparedSequence[] = [];\n for (const input of sequences) {\n const parsed = SequenceSchema.safeParse(input);\n if (!parsed.success) {\n const issues = parsed.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`);\n throw new StrataError('INVALID_SEQUENCE', `A sequence does not parse${typeof input.id === 'string' ? ` (\"${input.id}\")` : ''}.`, issues);\n }\n const sequence = parsed.data;\n if (seen.has(sequence.id)) {\n throw new StrataError('INVALID_SEQUENCE', `Two sequences are both called \"${sequence.id}\" — a sequence id names one owner.`);\n }\n seen.add(sequence.id);\n const migrations: PreparedMigration[] = [];\n for (const [index, migration] of sequence.migrations.entries()) {\n const n = index + 1;\n migrations.push({\n sequence: sequence.id,\n n,\n ref: refOf(sequence.id, n),\n description: migration.description,\n checksum: await checksumOf(migration),\n steps: migration.steps,\n dependsOn: migration.dependsOn ?? [],\n });\n }\n const grammar = sequence.documents !== undefined || sequence.migrations.some((m) => m.steps.some((s) => s.kind === 'document'));\n prepared.push({ id: sequence.id, grammar, documents: sequence.documents ?? {}, migrations });\n }\n return prepared;\n};\n\n// Order: walk the sequences in the order given, and let each run as far as its\n// dependencies allow before moving on; repeat until nothing moves. The same\n// input always yields the same order, and a sequence's own migrations stay\n// together unless a dependency splits them. Shared by the ledger's plan and a\n// document's upgrade, so both order the same migrations the same way.\nexport const orderPending = (\n queues: readonly { waiting: readonly PreparedMigration[] }[],\n alreadyDone: ReadonlySet<string>,\n): { pending: PreparedMigration[]; stuck: PreparedMigration[] } => {\n const done = new Set(alreadyDone);\n const waiting = queues.map((q) => [...q.waiting]);\n const pending: PreparedMigration[] = [];\n let moved = true;\n while (moved) {\n moved = false;\n for (const queue of waiting) {\n for (let head = queue[0]; head !== undefined; head = queue[0]) {\n if (!head.dependsOn.every((d) => done.has(d))) break;\n pending.push(head);\n done.add(head.ref);\n queue.shift();\n moved = true;\n }\n }\n }\n return { pending, stuck: waiting.flat() };\n};\n\nexport const planMigrations = (sequences: readonly PreparedSequence[], ledger: readonly LedgerRow[]): Plan => {\n const problems: Problem[] = [];\n const applied: Record<string, number> = {};\n const done = new Set(ledger.map((row) => refOf(row.sequence, row.n)));\n const byRef = new Map(ledger.map((row) => [refOf(row.sequence, row.n), row]));\n\n const queues: { id: string; waiting: PreparedMigration[] }[] = [];\n for (const sequence of sequences) {\n const rows = ledger.filter((row) => row.sequence === sequence.id);\n applied[sequence.id] = rows.length;\n\n // The database ran migrations this code has never seen: newer code migrated\n // it. Applying ours on top would be guessing — refuse.\n const beyond = rows.filter((row) => row.n > sequence.migrations.length);\n if (beyond.length > 0) {\n problems.push({\n code: 'TOO_NEW',\n detail: `${sequence.id}: the database is at ${Math.max(...rows.map((r) => r.n))}, this code knows ${sequence.migrations.length} — it was migrated by newer code.`,\n });\n }\n\n const waiting: PreparedMigration[] = [];\n for (const migration of sequence.migrations) {\n const row = byRef.get(migration.ref);\n if (row === undefined) {\n waiting.push(migration);\n } else if (row.checksum !== migration.checksum) {\n problems.push({\n code: 'EDITED',\n detail: `${migration.ref} (\"${migration.description}\") was applied ${row.appliedAt} and its steps have changed since. An applied migration is history — append a new one.`,\n });\n }\n }\n // A hole: something later ran, something earlier did not. The ledger was\n // written by hand, or by a different ordering of the same sequence.\n const firstWaiting = waiting[0];\n if (firstWaiting !== undefined && rows.some((row) => row.n > firstWaiting.n)) {\n problems.push({ code: 'EDITED', detail: `${sequence.id}: ${firstWaiting.ref} never ran, but a later migration of the sequence did.` });\n }\n queues.push({ id: sequence.id, waiting });\n }\n\n // Every dependency must be satisfiable by the ledger or by this plan.\n const provided = new Set(sequences.flatMap((s) => s.migrations.map((m) => m.ref)));\n for (const { waiting } of queues) {\n for (const migration of waiting) {\n for (const dependency of migration.dependsOn) {\n if (!done.has(dependency) && !provided.has(dependency)) {\n problems.push({ code: 'UNKNOWN_DEPENDENCY', detail: `${migration.ref} depends on ${dependency}, which nothing provides and the database has not run.` });\n }\n }\n }\n }\n\n const { pending, stuck } = orderPending(queues, done);\n if (stuck.length > 0 && !problems.some((p) => p.code === 'UNKNOWN_DEPENDENCY')) {\n problems.push({ code: 'CYCLE', detail: `These wait on each other and can never run: ${stuck.map((m) => m.ref).join(', ')}.` });\n }\n\n return { applied, pending, problems };\n};\n\n// Throw the plan's problems as one error, named by the first.\nexport const refuseProblems = (plan: Plan): void => {\n const first = plan.problems[0];\n if (first === undefined) return;\n throw new StrataError(first.code, 'The migrations cannot be applied safely.', plan.problems.map((p) => `${p.code}: ${p.detail}`));\n};\n","import { prepare, orderPending, type PreparedMigration, type PreparedSequence } from './plan';\nimport type { DocumentKind, Sequence } from './schema';\nimport { StrataError } from './errors';\n\n// ═══════════════════════════════════════════════════════════════\n// Documents — the JSON a grammar describes, wherever it is kept.\n//\n// A document carries a STAMP: for each grammar sequence, how far along that\n// sequence the writer was (`{ \"nisc.nova\": 3, \"nisc.prism\": 1 }`). Upgrading\n// runs every document migration the stamp has not seen, in the ledger's order,\n// and hands back the document with a current stamp. The same function serves a\n// row read at boot, a submission at intake and a file in an app's source tree:\n// the document does not care where it was kept.\n//\n// NESTING IS THE GRAMMAR'S, NOT THE MIGRATION'S. A kind declares where other\n// documents sit inside it (its embeddings: nova's layout holds layouts at\n// `children`, `children[]`, `then`, `else`, `do`; an action holds a layout and\n// Prism configs). The walker finds every document of a step's kind at any\n// depth and rewrites each on its own, deepest first. A transform only ever sees\n// ONE node — so migrations stay flat, and a Prism config can express them\n// without recursion of its own.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Stamp = Readonly<Record<string, number>>;\n\n// Where a document sits: the path from the root (keys and indexes) and its kind.\nexport type Location = { path: readonly (string | number)[]; kind: string; value: Record<string, unknown> };\n\n// The injected evaluator — nova's `transform` socket, the same shape: under moss\n// it is Prism's `evaluate`, and a migration runs exactly the way an endpoint does.\nexport type Transform = (config: unknown, source: unknown) => unknown;\n\nexport type UpgradeResult = {\n document: Record<string, unknown>;\n stamp: Stamp;\n // What ran, in order — empty when the document was already current.\n applied: readonly string[];\n};\n\nexport type Upgrader = {\n // The stamp a document written NOW carries.\n stamp: Stamp;\n upgrade: (document: unknown, options: { kind: string; stamp?: Stamp | null }) => UpgradeResult;\n // Every document inside `document` (itself included), by kind — what the\n // walker sees. For a page that shows it, and for a check that asserts it.\n locate: (document: unknown, kind: string) => Location[];\n // Is a document at this stamp behind the code (true), current (false)? Throws\n // TOO_NEW if it is ahead.\n behind: (stamp: Stamp | null | undefined) => boolean;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst pathText = (path: readonly (string | number)[]): string =>\n path.reduce<string>((text, key) => (typeof key === 'number' ? `${text}[${key}]` : text === '' ? key : `${text}.${key}`), '');\n\n// One embedding pattern, applied to one value: every (relative path, value)\n// the pattern reaches. `key` descends, `*` crosses a record's values, and a\n// `[]` suffix crosses the array found there.\nconst reach = (value: unknown, pattern: string): { path: (string | number)[]; value: unknown }[] => {\n let frontier: { path: (string | number)[]; value: unknown }[] = [{ path: [], value }];\n for (const segment of pattern.split('.')) {\n const array = segment.endsWith('[]');\n const key = array ? segment.slice(0, -2) : segment;\n const next: { path: (string | number)[]; value: unknown }[] = [];\n for (const at of frontier) {\n if (!isRecord(at.value)) continue;\n const found: { path: (string | number)[]; value: unknown }[] =\n key === '*'\n ? Object.entries(at.value).map(([k, v]) => ({ path: [...at.path, k], value: v }))\n : key in at.value\n ? [{ path: [...at.path, key], value: at.value[key] }]\n : [];\n for (const f of found) {\n if (!array) next.push(f);\n else if (Array.isArray(f.value)) f.value.forEach((item, i) => next.push({ path: [...f.path, i], value: item }));\n }\n }\n frontier = next;\n }\n return frontier;\n};\n\nconst getAt = (root: unknown, path: readonly (string | number)[]): unknown =>\n path.reduce<unknown>((at, key) => {\n if (typeof key === 'number') return Array.isArray(at) ? at[key] : undefined;\n return isRecord(at) ? at[key] : undefined;\n }, root);\n\nconst setAt = (root: unknown, path: readonly (string | number)[], value: unknown): unknown => {\n const [head, ...rest] = path;\n if (head === undefined) return value;\n if (typeof head === 'number' && Array.isArray(root)) return root.map((item, i) => (i === head ? setAt(item, rest, value) : item));\n if (typeof head === 'string' && isRecord(root)) return { ...root, [head]: setAt(root[head], rest, value) };\n return root;\n};\n\nexport const createUpgrader = async (sequences: readonly Sequence[], options: { transform: Transform }): Promise<Upgrader> => {\n const prepared = await prepare(sequences);\n const tables = prepared.filter((s) => !s.grammar);\n if (tables.length > 0) {\n throw new StrataError(\n 'WRONG_OWNER',\n 'Documents are upgraded by grammar sequences; these own tables and belong to a database\\'s ledger (`migrate`).',\n tables.map((s) => s.id),\n );\n }\n const grammars: readonly PreparedSequence[] = prepared;\n\n const kinds = new Map<string, DocumentKind>();\n for (const sequence of grammars) {\n for (const [name, kind] of Object.entries(sequence.documents)) kinds.set(`${sequence.id}/${name}`, kind);\n }\n const unknown = [\n ...grammars.flatMap((s) => s.migrations.flatMap((m) => m.steps.flatMap((step) => (step.kind === 'document' && !kinds.has(step.at) ? [`${m.ref} rewrites ${step.at}`] : [])))),\n ...[...kinds].flatMap(([ref, kind]) => Object.entries(kind.embeds ?? {}).flatMap(([path, target]) => (kinds.has(target) ? [] : [`${ref} embeds ${target} at ${path}`]))),\n ];\n if (unknown.length > 0) throw new StrataError('UNKNOWN_KIND', 'A document kind is named that no sequence declares.', unknown);\n\n const stamp: Stamp = Object.fromEntries(grammars.map((s) => [s.id, s.migrations.length]));\n\n const locate = (document: unknown, kind: string): Location[] => {\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n const found: Location[] = [];\n const visit = (value: unknown, at: string, path: (string | number)[]): void => {\n if (!isRecord(value)) return;\n found.push({ path, kind: at, value });\n for (const [pattern, target] of Object.entries(kinds.get(at)?.embeds ?? {})) {\n for (const hit of reach(value, pattern)) visit(hit.value, target, [...path, ...hit.path]);\n }\n };\n visit(document, kind, []);\n return found;\n };\n\n const positionOf = (given: Stamp | null | undefined, id: string): number => given?.[id] ?? 0;\n\n const behind = (given: Stamp | null | undefined): boolean => {\n const ahead = grammars.filter((s) => positionOf(given, s.id) > s.migrations.length);\n if (ahead.length > 0) {\n throw new StrataError(\n 'TOO_NEW',\n 'This document was written by newer code than this — reading it would be guessing.',\n ahead.map((s) => `${s.id}: the document is at ${positionOf(given, s.id)}, this code knows ${s.migrations.length}`),\n );\n }\n return grammars.some((s) => positionOf(given, s.id) < s.migrations.length);\n };\n\n const upgrade = (document: unknown, { kind, stamp: given }: { kind: string; stamp?: Stamp | null }): UpgradeResult => {\n if (!isRecord(document)) throw new StrataError('STEP_FAILED', `A ${kind} document must be a JSON object.`);\n if (!kinds.has(kind)) throw new StrataError('UNKNOWN_KIND', `No sequence declares the document kind \"${kind}\".`, [...kinds.keys()]);\n if (!behind(given)) return { document, stamp, applied: [] };\n\n // What this document has seen: everything up to its stamp, per sequence.\n // A sequence it has never heard of starts at 0 — a document written before\n // a grammar existed simply has none of its migrations yet.\n const done = new Set(grammars.flatMap((s) => s.migrations.filter((m) => m.n <= positionOf(given, s.id)).map((m) => m.ref)));\n const { pending, stuck } = orderPending(\n grammars.map((s) => ({ waiting: s.migrations.filter((m) => !done.has(m.ref)) })),\n done,\n );\n if (stuck.length > 0) throw new StrataError('CYCLE', 'Document migrations wait on each other and can never run.', stuck.map((m) => m.ref));\n\n let current: Record<string, unknown> = document;\n const applied: string[] = [];\n const runStep = (migration: PreparedMigration, at: string, transform: unknown): void => {\n // Deepest first: a parent's rewrite sees its children already rewritten,\n // and replacing a child never moves the path to its parent.\n const targets = locate(current, kind)\n .filter((l) => l.kind === at)\n .sort((a, b) => b.path.length - a.path.length);\n for (const target of targets) {\n // The value NOW, not when the targets were found: a child rewritten a\n // moment ago lives in `current`, and the parent must see — and keep — it.\n const value = getAt(current, target.path);\n let rewritten: unknown;\n try {\n rewritten = options.transform(transform, { document: value, path: pathText(target.path) });\n } catch (cause) {\n throw new StrataError(\n 'STEP_FAILED',\n `${migration.ref} (\"${migration.description}\") failed on the ${at} at ${pathText(target.path) || '(root)'}.`,\n [cause instanceof Error ? cause.message : String(cause)],\n { cause },\n );\n }\n if (!isRecord(rewritten)) {\n throw new StrataError('STEP_FAILED', `${migration.ref} turned the ${at} at ${pathText(target.path) || '(root)'} into something that is not a document.`, [\n JSON.stringify(rewritten)?.slice(0, 200) ?? String(rewritten),\n ]);\n }\n const next = setAt(current, target.path, rewritten);\n if (isRecord(next)) current = next;\n }\n };\n for (const migration of pending) {\n for (const step of migration.steps) if (step.kind === 'document') runStep(migration, step.at, step.transform);\n applied.push(migration.ref);\n }\n return { document: current, stamp, applied };\n };\n\n return { stamp, upgrade, locate, behind };\n};\n","import type { Sequence } from '../schema';\nimport type { Stamp, Upgrader } from '../documents';\nimport { StrataError } from '../errors';\n\n// ═══════════════════════════════════════════════════════════════\n// @niscorp/strata/check — the gate a grammar change has to pass.\n//\n// Two questions, both mechanical:\n//\n// 1. SNAPSHOT — did a kind's schema change without the grammar gaining a\n// migration? Each kind's JSON Schema, taken through the schema's OWN\n// Standard JSON Schema hook, is recorded per grammar version. Same version,\n// different schema: something changed that older readers were never told.\n// Append a migration (an empty marker is enough for an addition — strict\n// readers still have to refuse the newer documents), then record the new\n// version.\n//\n// 2. CORPUS — does every real document ever captured, at the stamp it was\n// captured at, still upgrade to the current grammar and pass the current\n// strict schema? This is the judge: a snapshot only says something moved,\n// the corpus says whether old documents survive it. No JSON Schema diff\n// tool is trusted to decide compatibility.\n//\n// Pure: no files, no process. A host reads and writes snapshots where it keeps\n// them (nisc's own live in the repo's `strata/` directory).\n// ═══════════════════════════════════════════════════════════════\n\ntype Issue = { message: string; path?: readonly (PropertyKey | { key: PropertyKey })[] };\ntype StandardResult = { value: unknown; issues?: undefined } | { issues: readonly Issue[] };\n\n// Any validator implementing Standard Schema + Standard JSON Schema (Zod ≥ 4.2,\n// Valibot, ArkType). Structural: strata depends on none of them.\nexport type GrammarSchema = {\n '~standard': {\n validate: (value: unknown) => StandardResult | Promise<StandardResult>;\n jsonSchema: { input: (options: { target: string }) => Record<string, unknown> };\n };\n};\n\nexport type Snapshot = { sequence: string; version: number; kinds: Readonly<Record<string, unknown>> };\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst byKey = ([a]: [string, unknown], [b]: [string, unknown]): number => (a < b ? -1 : a > b ? 1 : 0);\n\n// Sorted keys, nothing else — for documents, where every key (a `description`\n// too) is content, and for a snapshot file, which keeps what the validator wrote.\nconst sortKeys = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (!isRecord(value)) return value;\n return Object.fromEntries(Object.entries(value).sort(byKey).map(([k, v]) => [k, sortKeys(v)]));\n};\n\n// Where a schema's keys are NAMES, not keywords — a field called `description`\n// or an op called `$ref` is grammar — and where its values are instance data\n// rather than schemas.\nconst NAMED = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);\nconst DATA = new Set(['const', 'enum', 'default', 'examples']);\n\n// A schema without its prose: the `description` KEYWORD is documentation, and\n// rewording a `.describe()` must not demand a migration. `$schema` is the same\n// everywhere. Applied when comparing, never to what is recorded — so what the\n// gate ignores can change without touching a snapshot file.\nconst normalize = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(normalize);\n if (!isRecord(value)) return value;\n return Object.fromEntries(\n Object.entries(value)\n .filter(([key]) => key !== 'description' && key !== '$schema')\n .sort(byKey)\n .map(([key, v]) => [key, NAMED.has(key) && isRecord(v) ? namedSchemas(v, normalize) : DATA.has(key) ? sortKeys(v) : normalize(v)]),\n );\n};\n\n// A name → schema map, each schema through `each`, the names untouched.\nconst namedSchemas = (map: Record<string, unknown>, each: (schema: unknown) => unknown): Record<string, unknown> =>\n Object.fromEntries(Object.entries(map).sort(byKey).map(([name, schema]) => [name, each(schema)]));\n\n// The grammar as it stands: every kind it declares, as JSON Schema — as the\n// validator wrote it, keys sorted. `schemas` must cover exactly the sequence's\n// kinds — a kind without a schema cannot be checked, and a schema without a\n// kind belongs to some other grammar.\nexport const snapshotOf = (sequence: Sequence, schemas: Readonly<Record<string, GrammarSchema>>): Snapshot => {\n const declared = Object.keys(sequence.documents ?? {}).map((k) => `${sequence.id}/${k}`);\n const given = Object.keys(schemas);\n const missing = declared.filter((k) => !given.includes(k));\n const extra = given.filter((k) => !declared.includes(k));\n if (missing.length > 0 || extra.length > 0) {\n throw new StrataError('UNKNOWN_KIND', `The schemas for ${sequence.id} do not match its kinds.`, [\n ...missing.map((k) => `no schema for ${k}`),\n ...extra.map((k) => `${k} is not a kind of ${sequence.id}`),\n ]);\n }\n const kinds: Record<string, unknown> = {};\n for (const kind of [...declared].sort()) {\n const schema = schemas[kind];\n if (schema !== undefined) kinds[kind] = sortKeys(schema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }));\n }\n return { sequence: sequence.id, version: sequence.migrations.length, kinds };\n};\n\n// Stable text for a snapshot file: sorted keys, two-space indent, newline.\nexport const snapshotText = (snapshot: Snapshot): string => `${JSON.stringify(sortKeys(snapshot), null, 2)}\n`;\n\n// Schema arrays are compared as sets (`sets`); a document's arrays by position —\n// `layout.children[1]` is how a person finds the thing that changed.\nconst diffLines = (a: unknown, b: unknown, path: string, out: string[], limit: number, canon: (v: unknown) => unknown = normalize, sets = true): void => {\n if (out.length >= limit) return;\n if (JSON.stringify(a) === JSON.stringify(b)) return;\n if (isRecord(a) && isRecord(b)) {\n for (const key of [...new Set([...Object.keys(a), ...Object.keys(b)])].sort()) {\n const at = path === '' ? key : `${path}.${key}`;\n if (!(key in a)) out.push(`+ ${at}`);\n else if (!(key in b)) out.push(`- ${at}`);\n else diffLines(a[key], b[key], at, out, limit, canon, sets);\n if (out.length >= limit) return;\n }\n return;\n }\n if (Array.isArray(a) && Array.isArray(b) && !sets && a.length === b.length) {\n a.forEach((item, i) => diffLines(item, b[i], `${path}[${i}]`, out, limit, canon, sets));\n return;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n // Schema arrays are SETS more often than sequences — a union's `anyOf`, a\n // `required` list, an `enum` — and one added branch shifts every index\n // after it. Match elements by what they describe (an object schema by its\n // property names — for Prism's union, the op), report the ones on one side\n // only, and diff the ones that changed in place.\n const text = (v: unknown): string => JSON.stringify(canon(v));\n const label = (v: unknown): string =>\n isRecord(v) && isRecord(v['properties']) ? Object.keys(v['properties']).join(',') : (text(v) ?? '').slice(0, 50);\n const onlyA = a.filter((x) => !b.some((y) => text(y) === text(x)));\n const onlyB = b.filter((y) => !a.some((x) => text(x) === text(y)));\n const byLabel = new Map(onlyB.map((y) => [label(y), y]));\n for (const x of onlyA) {\n const partner = byLabel.get(label(x));\n if (partner !== undefined) {\n diffLines(x, partner, `${path}[${label(x)}]`, out, limit, canon, sets);\n byLabel.delete(label(x));\n } else {\n out.push(`- ${path}[${label(x)}]`);\n }\n if (out.length >= limit) return;\n }\n for (const [name] of byLabel) {\n out.push(`+ ${path}[${name}]`);\n if (out.length >= limit) return;\n }\n return;\n }\n out.push(`~ ${path || '(root)'}: ${JSON.stringify(a)?.slice(0, 60)} → ${JSON.stringify(b)?.slice(0, 60)}`);\n};\n\n// ── canonical form ──────────────────────────────────────────────\n//\n// A snapshot records what the validator WROTE, and validators spell one schema\n// many ways: they name and inline definitions as they please (zod numbers them\n// in visit order, and 4.3 and 4.4 visit differently), write a described\n// reference as `allOf: [{ $ref }]` or as `$ref`, and a union of bare types as\n// `anyOf: [{ type }, …]` or `type: […]`. None of that is the grammar, so a\n// comparison reads both sides in one spelling: every definition inlined unless\n// it is recursive, the recursive ones renamed by first use, and every schema\n// identity above written one way. A snapshot FILE stays what the validator\n// wrote — only the comparison is canonical.\n\nconst REF_PREFIX = /^#\\/(\\$defs|definitions)\\//;\n\n// One spelling for the equivalences the node itself can show.\nconst respell = (value: Record<string, unknown>): Record<string, unknown> => {\n let node = value;\n const anyOf = node['anyOf'];\n if (!('type' in node) && Array.isArray(anyOf) && anyOf.length > 0 && anyOf.every((m) => isRecord(m) && Object.keys(m).length === 1 && typeof m['type'] === 'string')) {\n const { anyOf: _union, ...rest } = node;\n node = { ...rest, type: anyOf.map((m) => (isRecord(m) ? m['type'] : undefined)) };\n }\n const type = node['type'];\n if (Array.isArray(type)) {\n const types = [...new Set(type.map(String))].sort();\n node = { ...node, type: types.length === 1 ? types[0] : types };\n }\n const allOf = node['allOf'];\n const only: unknown = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : undefined;\n if (!('$ref' in node) && isRecord(only) && Object.keys(only).length === 1 && typeof only['$ref'] === 'string') {\n const { allOf: _wrapper, ...rest } = node;\n node = { ...rest, $ref: only['$ref'] };\n }\n return node;\n};\n\n// A schema node's own children — keyword values, and each schema of a name\n// map — but never the names, and never instance data.\nconst schemaChildren = (node: Record<string, unknown>): unknown[] =>\n Object.entries(node).flatMap(([key, child]) =>\n key === '$ref' || DATA.has(key) ? [] : NAMED.has(key) && isRecord(child) ? Object.values(child) : [child],\n );\n\nconst canonical = (recorded: unknown): unknown => {\n const schema = normalize(recorded);\n if (!isRecord(schema)) return schema;\n const defs: Record<string, unknown> = {\n ...(isRecord(schema['definitions']) ? schema['definitions'] : {}),\n ...(isRecord(schema['$defs']) ? schema['$defs'] : {}),\n };\n const { $defs: _defs, definitions: _definitions, ...body } = schema;\n const target = (ref: string): { key: string; node: unknown } =>\n ref === '#' ? { key: '#', node: body } : { key: ref, node: defs[ref.replace(REF_PREFIX, '')] };\n\n // Which targets are reached from inside their own expansion: those, and\n // only those, stay definitions.\n const recursive = new Set<string>();\n const findCycles = (value: unknown, stack: readonly string[]): void => {\n if (Array.isArray(value)) {\n for (const item of value) findCycles(item, stack);\n return;\n }\n if (!isRecord(value)) return;\n const node = respell(value);\n for (const child of schemaChildren(node)) findCycles(child, stack);\n const ref = node['$ref'];\n if (typeof ref !== 'string') return;\n const { key, node: next } = target(ref);\n if (stack.includes(key)) recursive.add(key);\n else findCycles(next, [...stack, key]);\n };\n findCycles(body, ['#']);\n\n const names = new Map<string, string>();\n const named: Record<string, unknown> = {};\n const nameOf = (key: string, node: unknown): string => {\n const known = names.get(key);\n if (known !== undefined) return known;\n const name = `d${names.size}`;\n names.set(key, name);\n named[name] = emit(node);\n return name;\n };\n const emit = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(emit);\n if (!isRecord(value)) return value;\n const node = respell(value);\n const rest: Record<string, unknown> = Object.fromEntries(\n Object.entries(node)\n .filter(([key]) => key !== '$ref')\n .sort(byKey)\n .map(([key, child]) => [key, NAMED.has(key) && isRecord(child) ? namedSchemas(child, emit) : DATA.has(key) ? child : emit(child)]),\n );\n const ref = node['$ref'];\n if (typeof ref !== 'string') return rest;\n const { key, node: next } = target(ref);\n const referred = recursive.has(key) ? { $ref: `#/$defs/${nameOf(key, next)}` } : emit(next);\n return Object.keys(rest).length > 0 ? { ...rest, allOf: [referred] } : referred;\n };\n\n const root = recursive.has('#') ? { $ref: `#/$defs/${nameOf('#', body)}` } : emit(body);\n return Object.keys(named).length === 0 ? root : sortKeys({ ...(isRecord(root) ? root : { allOf: [root] }), $defs: named });\n};\n\nexport type SnapshotComparison =\n | { status: 'same' }\n | { status: 'missing' }\n | { status: 'changed'; changes: readonly { kind: string; lines: readonly string[] }[] };\n\n// `recorded` is the snapshot kept for the grammar's CURRENT version (or\n// undefined if none was kept). Changed means: a migration is owed. Both sides\n// are read in canonical form, so a validator's respelling is not a change.\nexport const compareSnapshot = (recorded: Snapshot | undefined, current: Snapshot): SnapshotComparison => {\n if (recorded === undefined) return { status: 'missing' };\n const changes: { kind: string; lines: string[] }[] = [];\n for (const kind of [...new Set([...Object.keys(recorded.kinds), ...Object.keys(current.kinds)])].sort()) {\n const lines: string[] = [];\n if (!(kind in recorded.kinds)) lines.push('+ (a new kind)');\n else if (!(kind in current.kinds)) lines.push('- (the kind is gone)');\n else diffLines(canonical(recorded.kinds[kind]), canonical(current.kinds[kind]), '', lines, 12);\n if (lines.length > 0) changes.push({ kind, lines });\n }\n return changes.length === 0 ? { status: 'same' } : { status: 'changed', changes };\n};\n\n// ── the corpus ──────────────────────────────────────────────────\n\nexport type CorpusDocument = { id: string; kind: string; stamp: Stamp; document: unknown };\nexport type CorpusFailure = { id: string; kind: string; reason: string };\nexport type CorpusReport = { passed: number; failures: readonly CorpusFailure[] };\n\nconst issueText = (issue: Issue): string => {\n const path = (issue.path ?? []).map((p) => (typeof p === 'object' ? String(p.key) : String(p))).join('.');\n return `${path === '' ? '' : `${path}: `}${issue.message}`;\n};\n\n// What differs between two JSON values, as short lines (`+ a.b`, `- c`,\n// `~ d: 1 → 2`) — for a report a person or an agent acts on.\nexport const diffJson = (a: unknown, b: unknown, limit = 20): string[] => {\n const out: string[] = [];\n diffLines(a, b, '', out, limit, sortKeys, false);\n return out;\n};\n\n// Every document, upgraded from its stamp, must pass the current schema of its kind.\nexport const checkCorpus = async (\n upgrader: Upgrader,\n schemas: Readonly<Record<string, GrammarSchema>>,\n documents: readonly CorpusDocument[],\n): Promise<CorpusReport> => {\n const failures: CorpusFailure[] = [];\n let passed = 0;\n for (const doc of documents) {\n const schema = schemas[doc.kind];\n if (schema === undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: `no schema for ${doc.kind}` });\n continue;\n }\n let upgraded: unknown;\n try {\n upgraded = upgrader.upgrade(doc.document, { kind: doc.kind, stamp: doc.stamp }).document;\n } catch (error) {\n failures.push({ id: doc.id, kind: doc.kind, reason: error instanceof Error ? error.message.split('\\n')[0] ?? error.message : String(error) });\n continue;\n }\n const result = await schema['~standard'].validate(upgraded);\n if (result.issues !== undefined) {\n failures.push({ id: doc.id, kind: doc.kind, reason: result.issues.slice(0, 3).map(issueText).join('; ') });\n } else {\n passed += 1;\n }\n }\n return { passed, failures };\n};\n","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","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":";;;;;;;;;;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,KAClBA,aAAA,CAAW,GAAG,C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A,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\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"]}
|
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-OLDORFOQ.js';
|
|
2
|
+
import '../chunk-5KTXEN43.js';
|
|
3
|
+
import { planSourceUpgrade, changedStrings, renderReport, verifySourceUpgrade } from '../chunk-WU3OJHVZ.js';
|
|
4
|
+
import '../chunk-4BLHBVSC.js';
|
|
5
|
+
import { StrataError } from '../chunk-AKKWEXO2.js';
|
|
6
6
|
import { rmSync, mkdirSync, writeFileSync, existsSync, readFileSync, readdirSync, statSync } from 'fs';
|
|
7
7
|
import { join, relative, sep } from 'path';
|
|
8
8
|
|
|
@@ -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' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER';
|
|
3
|
+
type StrataErrorCode = 'INVALID_SEQUENCE' | 'EDITED' | 'TOO_NEW' | '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[];
|
|
@@ -32,7 +32,7 @@ type LedgerRow = {
|
|
|
32
32
|
appliedAt: string;
|
|
33
33
|
};
|
|
34
34
|
type Problem = {
|
|
35
|
-
code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>;
|
|
35
|
+
code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>;
|
|
36
36
|
detail: string;
|
|
37
37
|
};
|
|
38
38
|
type Plan = {
|
|
@@ -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' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER';
|
|
3
|
+
type StrataErrorCode = 'INVALID_SEQUENCE' | 'EDITED' | 'TOO_NEW' | '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[];
|
|
@@ -32,7 +32,7 @@ type LedgerRow = {
|
|
|
32
32
|
appliedAt: string;
|
|
33
33
|
};
|
|
34
34
|
type Problem = {
|
|
35
|
-
code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>;
|
|
35
|
+
code: Exclude<StrataErrorCode, 'PENDING' | 'STEP_FAILED' | 'DOES_NOT_FIT' | 'NO_TRANSACTION' | 'UNKNOWN_KIND' | 'WRONG_OWNER'>;
|
|
36
36
|
detail: string;
|
|
37
37
|
};
|
|
38
38
|
type Plan = {
|