@prisma-next/migration-tools 0.5.0-dev.1 → 0.5.0-dev.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +34 -22
  2. package/dist/{constants-BRi0X7B_.mjs → constants-WVGVMOdu.mjs} +1 -1
  3. package/dist/{constants-BRi0X7B_.mjs.map → constants-WVGVMOdu.mjs.map} +1 -1
  4. package/dist/{errors-BKbRGCJM.mjs → errors-CZ9JD4sd.mjs} +50 -21
  5. package/dist/errors-CZ9JD4sd.mjs.map +1 -0
  6. package/dist/exports/constants.mjs +1 -1
  7. package/dist/exports/{types.d.mts → errors.d.mts} +6 -8
  8. package/dist/exports/errors.d.mts.map +1 -0
  9. package/dist/exports/errors.mjs +3 -0
  10. package/dist/exports/graph.d.mts +2 -0
  11. package/dist/exports/graph.mjs +1 -0
  12. package/dist/exports/hash.d.mts +52 -0
  13. package/dist/exports/hash.d.mts.map +1 -0
  14. package/dist/exports/hash.mjs +3 -0
  15. package/dist/exports/io.d.mts +7 -6
  16. package/dist/exports/io.d.mts.map +1 -1
  17. package/dist/exports/io.mjs +156 -2
  18. package/dist/exports/io.mjs.map +1 -0
  19. package/dist/exports/metadata.d.mts +2 -0
  20. package/dist/exports/metadata.mjs +1 -0
  21. package/dist/exports/{dag.d.mts → migration-graph.d.mts} +10 -9
  22. package/dist/exports/migration-graph.d.mts.map +1 -0
  23. package/dist/exports/{dag.mjs → migration-graph.mjs} +17 -17
  24. package/dist/exports/migration-graph.mjs.map +1 -0
  25. package/dist/exports/migration-ts.mjs +1 -1
  26. package/dist/exports/migration.d.mts +13 -10
  27. package/dist/exports/migration.d.mts.map +1 -1
  28. package/dist/exports/migration.mjs +20 -21
  29. package/dist/exports/migration.mjs.map +1 -1
  30. package/dist/exports/package.d.mts +2 -0
  31. package/dist/exports/package.mjs +1 -0
  32. package/dist/exports/refs.d.mts +11 -5
  33. package/dist/exports/refs.d.mts.map +1 -1
  34. package/dist/exports/refs.mjs +106 -30
  35. package/dist/exports/refs.mjs.map +1 -1
  36. package/dist/graph-B5wbCSna.d.mts +22 -0
  37. package/dist/graph-B5wbCSna.d.mts.map +1 -0
  38. package/dist/hash-BNWumjn7.mjs +76 -0
  39. package/dist/hash-BNWumjn7.mjs.map +1 -0
  40. package/dist/metadata-DDa5L-uD.d.mts +45 -0
  41. package/dist/metadata-DDa5L-uD.d.mts.map +1 -0
  42. package/dist/package-BJ5KAEcD.d.mts +21 -0
  43. package/dist/package-BJ5KAEcD.d.mts.map +1 -0
  44. package/package.json +26 -14
  45. package/src/errors.ts +57 -15
  46. package/src/exports/errors.ts +1 -0
  47. package/src/exports/graph.ts +1 -0
  48. package/src/exports/hash.ts +2 -0
  49. package/src/exports/io.ts +1 -1
  50. package/src/exports/metadata.ts +1 -0
  51. package/src/exports/{dag.ts → migration-graph.ts} +2 -2
  52. package/src/exports/package.ts +1 -0
  53. package/src/exports/refs.ts +10 -2
  54. package/src/graph.ts +19 -0
  55. package/src/hash.ts +91 -0
  56. package/src/io.ts +32 -20
  57. package/src/metadata.ts +36 -0
  58. package/src/migration-base.ts +32 -28
  59. package/src/{dag.ts → migration-graph.ts} +35 -38
  60. package/src/package.ts +18 -0
  61. package/src/refs.ts +148 -37
  62. package/dist/attestation-DtF8tEOM.mjs +0 -65
  63. package/dist/attestation-DtF8tEOM.mjs.map +0 -1
  64. package/dist/errors-BKbRGCJM.mjs.map +0 -1
  65. package/dist/exports/attestation.d.mts +0 -37
  66. package/dist/exports/attestation.d.mts.map +0 -1
  67. package/dist/exports/attestation.mjs +0 -4
  68. package/dist/exports/dag.d.mts.map +0 -1
  69. package/dist/exports/dag.mjs.map +0 -1
  70. package/dist/exports/types.d.mts.map +0 -1
  71. package/dist/exports/types.mjs +0 -3
  72. package/dist/io-CCnYsUHU.mjs +0 -153
  73. package/dist/io-CCnYsUHU.mjs.map +0 -1
  74. package/dist/types-DyGXcWWp.d.mts +0 -71
  75. package/dist/types-DyGXcWWp.d.mts.map +0 -1
  76. package/src/attestation.ts +0 -81
  77. package/src/exports/attestation.ts +0 -2
  78. package/src/exports/types.ts +0 -10
  79. package/src/types.ts +0 -66
@@ -1 +1 @@
1
- {"version":3,"file":"refs.mjs","names":["raw: string","parsed: unknown"],"sources":["../../src/refs.ts"],"sourcesContent":["import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { type } from 'arktype';\nimport { dirname, join } from 'pathe';\nimport {\n errorInvalidRefName,\n errorInvalidRefs,\n errorInvalidRefValue,\n MigrationToolsError,\n} from './errors';\n\nexport type Refs = Readonly<Record<string, string>>;\n\nconst REF_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\/[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\nconst REF_VALUE_PATTERN = /^sha256:(empty|[0-9a-f]{64})$/;\n\nexport function validateRefName(name: string): boolean {\n if (name.length === 0) return false;\n if (name.includes('..')) return false;\n if (name.includes('//')) return false;\n if (name.startsWith('.')) return false;\n return REF_NAME_PATTERN.test(name);\n}\n\nexport function validateRefValue(value: string): boolean {\n return REF_VALUE_PATTERN.test(value);\n}\n\nconst RefsSchema = type('Record<string, string>').narrow((refs, ctx) => {\n for (const [key, value] of Object.entries(refs)) {\n if (!validateRefName(key)) return ctx.mustBe(`valid ref names (invalid: \"${key}\")`);\n if (!validateRefValue(value))\n return ctx.mustBe(`valid contract hashes (invalid value for \"${key}\": \"${value}\")`);\n }\n return true;\n});\n\nexport async function readRefs(refsPath: string): Promise<Refs> {\n let raw: string;\n try {\n raw = await readFile(refsPath, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return {};\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw errorInvalidRefs(refsPath, 'Failed to parse as JSON');\n }\n\n const result = RefsSchema(parsed);\n if (result instanceof type.errors) {\n throw errorInvalidRefs(refsPath, result.summary);\n }\n\n return result;\n}\n\nexport async function writeRefs(refsPath: string, refs: Refs): Promise<void> {\n for (const [key, value] of Object.entries(refs)) {\n if (!validateRefName(key)) {\n throw errorInvalidRefName(key);\n }\n if (!validateRefValue(value)) {\n throw errorInvalidRefValue(value);\n }\n }\n\n const sorted = Object.fromEntries(Object.entries(refs).sort(([a], [b]) => a.localeCompare(b)));\n\n const dir = dirname(refsPath);\n await mkdir(dir, { recursive: true });\n\n const tmpPath = join(dir, `.refs.json.${Date.now()}.tmp`);\n await writeFile(tmpPath, `${JSON.stringify(sorted, null, 2)}\\n`);\n await rename(tmpPath, refsPath);\n}\n\nexport function resolveRef(refs: Refs, name: string): string {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const hash = refs[name];\n if (hash === undefined) {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref named \"${name}\" exists in refs.json.`,\n fix: `Available refs: ${Object.keys(refs).join(', ') || '(none)'}. Create a ref with: set the \"${name}\" key in migrations/refs.json.`,\n details: { refName: name, availableRefs: Object.keys(refs) },\n });\n }\n\n if (!validateRefValue(hash)) {\n throw errorInvalidRefValue(hash);\n }\n\n return hash;\n}\n"],"mappings":";;;;;;AAYA,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAE1B,SAAgB,gBAAgB,MAAuB;AACrD,KAAI,KAAK,WAAW,EAAG,QAAO;AAC9B,KAAI,KAAK,SAAS,KAAK,CAAE,QAAO;AAChC,KAAI,KAAK,SAAS,KAAK,CAAE,QAAO;AAChC,KAAI,KAAK,WAAW,IAAI,CAAE,QAAO;AACjC,QAAO,iBAAiB,KAAK,KAAK;;AAGpC,SAAgB,iBAAiB,OAAwB;AACvD,QAAO,kBAAkB,KAAK,MAAM;;AAGtC,MAAM,aAAa,KAAK,yBAAyB,CAAC,QAAQ,MAAM,QAAQ;AACtE,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,EAAE;AAC/C,MA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CAGjC,MAAM,OAAO,KAAK;AAClB,KAAI,SAAS,OACX,OAAM,IAAI,oBAAoB,yBAAyB,gBAAgB,KAAK,IAAI;EAC9E,KAAK,iBAAiB,KAAK;EAC3B,KAAK,mBAAmB,OAAO,KAAK,KAAK,CAAC,KAAK,KAAK,IAAI,SAAS,gCAAgC,KAAK;EACtG,SAAS;GAAE,SAAS;GAAM,eAAe,OAAO,KAAK,KAAK;GAAE;EAC7D,CAAC;AAGJ,KAAI,CAAC,iBAAiB,KAAK,CACzB,OAAM,qBAAqB,KAAK;AAGlC,QAAO"}
1
+ {"version":3,"file":"refs.mjs","names":["raw: string","parsed: unknown","entries: string[]","refs: Record<string, RefEntry>"],"sources":["../../src/refs.ts"],"sourcesContent":["import { mkdir, readdir, readFile, rename, rmdir, unlink, writeFile } from 'node:fs/promises';\nimport { type } from 'arktype';\nimport { dirname, join, relative } from 'pathe';\nimport {\n errorInvalidRefFile,\n errorInvalidRefName,\n errorInvalidRefValue,\n MigrationToolsError,\n} from './errors';\n\nexport interface RefEntry {\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\nexport type Refs = Readonly<Record<string, RefEntry>>;\n\nconst REF_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\/[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\nconst REF_VALUE_PATTERN = /^sha256:(empty|[0-9a-f]{64})$/;\n\nexport function validateRefName(name: string): boolean {\n if (name.length === 0) return false;\n if (name.includes('..')) return false;\n if (name.includes('//')) return false;\n if (name.startsWith('.')) return false;\n return REF_NAME_PATTERN.test(name);\n}\n\nexport function validateRefValue(value: string): boolean {\n return REF_VALUE_PATTERN.test(value);\n}\n\nconst RefEntrySchema = type({\n hash: 'string',\n invariants: 'string[]',\n}).narrow((entry, ctx) => {\n if (!validateRefValue(entry.hash))\n return ctx.mustBe(`a valid contract hash (got \"${entry.hash}\")`);\n return true;\n});\n\nfunction refFilePath(refsDir: string, name: string): string {\n return join(refsDir, `${name}.json`);\n}\n\nfunction refNameFromPath(refsDir: string, filePath: string): string {\n const rel = relative(refsDir, filePath);\n return rel.replace(/\\.json$/, '');\n}\n\nexport async function readRef(refsDir: string, name: string): Promise<RefEntry> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const filePath = refFilePath(refsDir, name);\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref file found at \"${filePath}\".`,\n fix: `Create the ref with: prisma-next migration ref set ${name} <hash>`,\n details: { refName: name, filePath },\n });\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');\n }\n\n const result = RefEntrySchema(parsed);\n if (result instanceof type.errors) {\n throw errorInvalidRefFile(filePath, result.summary);\n }\n\n return result;\n}\n\nexport async function readRefs(refsDir: string): Promise<Refs> {\n let entries: string[];\n try {\n entries = await readdir(refsDir, { recursive: true, encoding: 'utf-8' });\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return {};\n }\n throw error;\n }\n\n const jsonFiles = entries.filter((entry) => entry.endsWith('.json'));\n const refs: Record<string, RefEntry> = {};\n\n for (const jsonFile of jsonFiles) {\n const filePath = join(refsDir, jsonFile);\n const name = refNameFromPath(refsDir, filePath);\n\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n // Tolerate the TOCTOU race between `readdir` and `readFile` (ENOENT) and\n // benign EISDIR if a directory happens to end in `.json`. Anything else\n // (EACCES, EIO, EMFILE, …) is a real failure and propagates so the CLI\n // surfaces it rather than silently dropping the ref.\n const code = error instanceof Error ? (error as { code?: string }).code : undefined;\n if (code === 'ENOENT' || code === 'EISDIR') {\n continue;\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');\n }\n\n const result = RefEntrySchema(parsed);\n if (result instanceof type.errors) {\n throw errorInvalidRefFile(filePath, result.summary);\n }\n\n refs[name] = result;\n }\n\n return refs;\n}\n\nexport async function writeRef(refsDir: string, name: string, entry: RefEntry): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n if (!validateRefValue(entry.hash)) {\n throw errorInvalidRefValue(entry.hash);\n }\n\n const filePath = refFilePath(refsDir, name);\n const dir = dirname(filePath);\n await mkdir(dir, { recursive: true });\n\n const tmpPath = join(dir, `.${name.split('/').pop()}.json.${Date.now()}.tmp`);\n await writeFile(\n tmpPath,\n `${JSON.stringify({ hash: entry.hash, invariants: [...entry.invariants] }, null, 2)}\\n`,\n );\n await rename(tmpPath, filePath);\n}\n\nexport async function deleteRef(refsDir: string, name: string): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const filePath = refFilePath(refsDir, name);\n try {\n await unlink(filePath);\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref file found at \"${filePath}\".`,\n fix: 'Run `prisma-next migration ref list` to see available refs.',\n details: { refName: name, filePath },\n });\n }\n throw error;\n }\n\n // Clean empty parent directories up to refsDir. Stop walking on the expected\n // \"directory has siblings\" signal (ENOTEMPTY on Linux, EEXIST on some BSDs)\n // and on ENOENT (concurrent removal). Anything else (EACCES, EIO, …) is a\n // real failure and propagates.\n let dir = dirname(filePath);\n while (dir !== refsDir && dir.startsWith(refsDir)) {\n try {\n await rmdir(dir);\n dir = dirname(dir);\n } catch (error) {\n const code = error instanceof Error ? (error as { code?: string }).code : undefined;\n if (code === 'ENOTEMPTY' || code === 'EEXIST' || code === 'ENOENT') {\n break;\n }\n throw error;\n }\n }\n}\n\nexport function resolveRef(refs: Refs, name: string): RefEntry {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n // Object.hasOwn gate: plain-object `refs` would otherwise let\n // `refs['constructor']` return Object.prototype.constructor and bypass the\n // UNKNOWN_REF throw. validateRefName accepts `\"constructor\"` as a name shape.\n if (!Object.hasOwn(refs, name)) {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref named \"${name}\" exists.`,\n fix: `Available refs: ${Object.keys(refs).join(', ') || '(none)'}. Create a ref with: prisma-next migration ref set ${name} <hash>`,\n details: { refName: name, availableRefs: Object.keys(refs) },\n });\n }\n\n // biome-ignore lint/style/noNonNullAssertion: Object.hasOwn gate above guarantees this is defined\n return refs[name]!;\n}\n"],"mappings":";;;;;;AAiBA,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAE1B,SAAgB,gBAAgB,MAAuB;AACrD,KAAI,KAAK,WAAW,EAAG,QAAO;AAC9B,KAAI,KAAK,SAAS,KAAK,CAAE,QAAO;AAChC,KAAI,KAAK,SAAS,KAAK,CAAE,QAAO;AAChC,KAAI,KAAK,WAAW,IAAI,CAAE,QAAO;AACjC,QAAO,iBAAiB,KAAK,KAAK;;AAGpC,SAAgB,iBAAiB,OAAwB;AACvD,QAAO,kBAAkB,KAAK,MAAM;;AAGtC,MAAM,iBAAiB,KAAK;CAC1B,MAAM;CACN,YAAY;CACb,CAAC,CAAC,QAAQ,OAAO,QAAQ;AACxB,KAAI,CAAC,iBAAiB,MAAM,KAAK,CAC/B,QAAO,IAAI,OAAO,+BAA+B,MAAM,KAAK,IAAI;AAClE,QAAO;EACP;AAEF,SAAS,YAAY,SAAiB,MAAsB;AAC1D,QAAO,KAAK,SAAS,GAAG,KAAK,OAAO;;AAGtC,SAAS,gBAAgB,SAAiB,UAA0B;AAElE,QADY,SAAS,SAAS,SAAS,CAC5B,QAAQ,WAAW,GAAG;;AAGnC,eAAsB,QAAQ,SAAiB,MAAiC;AA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EACd,MAAM,OAAO,iBAAiB,QAAS,MAA4B,OAAO;AAC1E,MAAI,SAAS,eAAe,SAAS,YAAY,SAAS,SACxD;AAEF,QAAM;;;AAKZ,SAAgB,WAAW,MAAY,MAAwB;AAC7D,KAAI,CAAC,gBAAgB,KAAK,CACxB,OAAM,oBAAoB,KAAK;AAMjC,KAAI,CAAC,OAAO,OAAO,MAAM,KAAK,CAC5B,OAAM,IAAI,oBAAoB,yBAAyB,gBAAgB,KAAK,IAAI;EAC9E,KAAK,iBAAiB,KAAK;EAC3B,KAAK,mBAAmB,OAAO,KAAK,KAAK,CAAC,KAAK,KAAK,IAAI,SAAS,qDAAqD,KAAK;EAC3H,SAAS;GAAE,SAAS;GAAM,eAAe,OAAO,KAAK,KAAK;GAAE;EAC7D,CAAC;AAIJ,QAAO,KAAK"}
@@ -0,0 +1,22 @@
1
+ //#region src/graph.d.ts
2
+ /**
3
+ * An entry in the migration graph. All on-disk migrations are attested,
4
+ * so `migrationHash` is always a string.
5
+ */
6
+ interface MigrationEdge {
7
+ readonly from: string;
8
+ readonly to: string;
9
+ readonly migrationHash: string;
10
+ readonly dirName: string;
11
+ readonly createdAt: string;
12
+ readonly labels: readonly string[];
13
+ }
14
+ interface MigrationGraph {
15
+ readonly nodes: ReadonlySet<string>;
16
+ readonly forwardChain: ReadonlyMap<string, readonly MigrationEdge[]>;
17
+ readonly reverseChain: ReadonlyMap<string, readonly MigrationEdge[]>;
18
+ readonly migrationByHash: ReadonlyMap<string, MigrationEdge>;
19
+ }
20
+ //#endregion
21
+ export { MigrationGraph as n, MigrationEdge as t };
22
+ //# sourceMappingURL=graph-B5wbCSna.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-B5wbCSna.d.mts","names":[],"sources":["../src/graph.ts"],"sourcesContent":[],"mappings":";;AAIA;AASA;;AAEsD,UAXrC,aAAA,CAWqC;EAA7B,SAAA,IAAA,EAAA,MAAA;EAC6B,SAAA,EAAA,EAAA,MAAA;EAA7B,SAAA,aAAA,EAAA,MAAA;EACuB,SAAA,OAAA,EAAA,MAAA;EAApB,SAAA,SAAA,EAAA,MAAA;EAAW,SAAA,MAAA,EAAA,SAAA,MAAA,EAAA;;UAJtB,cAAA;kBACC;yBACO,6BAA6B;yBAC7B,6BAA6B;4BAC1B,oBAAoB"}
@@ -0,0 +1,76 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ //#region src/canonicalize-json.ts
4
+ function sortKeys(value) {
5
+ if (value === null || typeof value !== "object") return value;
6
+ if (Array.isArray(value)) return value.map(sortKeys);
7
+ const sorted = {};
8
+ for (const key of Object.keys(value).sort()) sorted[key] = sortKeys(value[key]);
9
+ return sorted;
10
+ }
11
+ function canonicalizeJson(value) {
12
+ return JSON.stringify(sortKeys(value));
13
+ }
14
+
15
+ //#endregion
16
+ //#region src/hash.ts
17
+ function sha256Hex(input) {
18
+ return createHash("sha256").update(input).digest("hex");
19
+ }
20
+ /**
21
+ * Content-addressed migration hash over (metadata envelope sans
22
+ * contracts/hints/signature, ops). See ADR 199 — Storage-only migration
23
+ * identity for the rationale: contracts are anchored separately by the
24
+ * storage-hash bookends inside the envelope; planner hints are advisory
25
+ * and must not affect identity.
26
+ *
27
+ * The integrity check is purely structural, not semantic. The function
28
+ * canonicalizes its inputs via `sortKeys` (recursive) + `JSON.stringify`
29
+ * and hashes the result. Target-specific operation payloads (`step.sql`,
30
+ * Mongo's pipeline AST, …) are hashed verbatim — no per-target
31
+ * normalization is required, because what's being verified is "do the
32
+ * on-disk bytes still produce their recorded hash", not "do two
33
+ * semantically-equivalent migrations hash the same". The latter is an
34
+ * emit-drift concern (ADR 192 step 2).
35
+ *
36
+ * The symmetry across write and read holds because `JSON.parse(
37
+ * JSON.stringify(x))` round-trips JSON-safe values losslessly and
38
+ * `sortKeys` is idempotent and deterministic — write-time and read-time
39
+ * canonicalization produce the same canonical bytes regardless of
40
+ * source-side key ordering or whitespace.
41
+ *
42
+ * The `migrationHash` field on the metadata is stripped before hashing
43
+ * so the function can be used both at write time (when no hash exists
44
+ * yet) and at verify time (rehashing an already-attested record).
45
+ */
46
+ function computeMigrationHash(metadata, ops) {
47
+ const { migrationHash: _migrationHash, signature: _signature, fromContract: _fromContract, toContract: _toContract, hints: _hints, ...strippedMeta } = metadata;
48
+ return `sha256:${sha256Hex(canonicalizeJson([canonicalizeJson(strippedMeta), canonicalizeJson(ops)].map(sha256Hex)))}`;
49
+ }
50
+ /**
51
+ * Re-hash an in-memory migration package and compare against the stored
52
+ * `migrationHash`. See `computeMigrationHash` for the canonicalization rules.
53
+ *
54
+ * Returns `{ ok: true }` when the package is internally consistent, or
55
+ * `{ ok: false, reason: 'mismatch', storedHash, computedHash }` when it is
56
+ * not — typically a sign of FS corruption, partial writes, or a post-emit
57
+ * hand edit.
58
+ */
59
+ function verifyMigrationHash(pkg) {
60
+ const computed = computeMigrationHash(pkg.metadata, pkg.ops);
61
+ if (pkg.metadata.migrationHash === computed) return {
62
+ ok: true,
63
+ storedHash: pkg.metadata.migrationHash,
64
+ computedHash: computed
65
+ };
66
+ return {
67
+ ok: false,
68
+ reason: "mismatch",
69
+ storedHash: pkg.metadata.migrationHash,
70
+ computedHash: computed
71
+ };
72
+ }
73
+
74
+ //#endregion
75
+ export { verifyMigrationHash as n, computeMigrationHash as t };
76
+ //# sourceMappingURL=hash-BNWumjn7.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash-BNWumjn7.mjs","names":["sorted: Record<string, unknown>"],"sources":["../src/canonicalize-json.ts","../src/hash.ts"],"sourcesContent":["function sortKeys(value: unknown): unknown {\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(sortKeys);\n }\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeys((value as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\nexport function canonicalizeJson(value: unknown): string {\n return JSON.stringify(sortKeys(value));\n}\n","import { createHash } from 'node:crypto';\nimport { canonicalizeJson } from './canonicalize-json';\nimport type { MigrationMetadata } from './metadata';\nimport type { MigrationOps, MigrationPackage } from './package';\n\nexport interface VerifyResult {\n readonly ok: boolean;\n readonly reason?: 'mismatch';\n readonly storedHash: string;\n readonly computedHash: string;\n}\n\nfunction sha256Hex(input: string): string {\n return createHash('sha256').update(input).digest('hex');\n}\n\n/**\n * Content-addressed migration hash over (metadata envelope sans\n * contracts/hints/signature, ops). See ADR 199 — Storage-only migration\n * identity for the rationale: contracts are anchored separately by the\n * storage-hash bookends inside the envelope; planner hints are advisory\n * and must not affect identity.\n *\n * The integrity check is purely structural, not semantic. The function\n * canonicalizes its inputs via `sortKeys` (recursive) + `JSON.stringify`\n * and hashes the result. Target-specific operation payloads (`step.sql`,\n * Mongo's pipeline AST, …) are hashed verbatim — no per-target\n * normalization is required, because what's being verified is \"do the\n * on-disk bytes still produce their recorded hash\", not \"do two\n * semantically-equivalent migrations hash the same\". The latter is an\n * emit-drift concern (ADR 192 step 2).\n *\n * The symmetry across write and read holds because `JSON.parse(\n * JSON.stringify(x))` round-trips JSON-safe values losslessly and\n * `sortKeys` is idempotent and deterministic — write-time and read-time\n * canonicalization produce the same canonical bytes regardless of\n * source-side key ordering or whitespace.\n *\n * The `migrationHash` field on the metadata is stripped before hashing\n * so the function can be used both at write time (when no hash exists\n * yet) and at verify time (rehashing an already-attested record).\n */\nexport function computeMigrationHash(\n metadata: Omit<MigrationMetadata, 'migrationHash'> & { readonly migrationHash?: string },\n ops: MigrationOps,\n): string {\n const {\n migrationHash: _migrationHash,\n signature: _signature,\n fromContract: _fromContract,\n toContract: _toContract,\n hints: _hints,\n ...strippedMeta\n } = metadata;\n\n const canonicalMetadata = canonicalizeJson(strippedMeta);\n const canonicalOps = canonicalizeJson(ops);\n\n const partHashes = [canonicalMetadata, canonicalOps].map(sha256Hex);\n const hash = sha256Hex(canonicalizeJson(partHashes));\n\n return `sha256:${hash}`;\n}\n\n/**\n * Re-hash an in-memory migration package and compare against the stored\n * `migrationHash`. See `computeMigrationHash` for the canonicalization rules.\n *\n * Returns `{ ok: true }` when the package is internally consistent, or\n * `{ ok: false, reason: 'mismatch', storedHash, computedHash }` when it is\n * not — typically a sign of FS corruption, partial writes, or a post-emit\n * hand edit.\n */\nexport function verifyMigrationHash(pkg: MigrationPackage): VerifyResult {\n const computed = computeMigrationHash(pkg.metadata, pkg.ops);\n\n if (pkg.metadata.migrationHash === computed) {\n return {\n ok: true,\n storedHash: pkg.metadata.migrationHash,\n computedHash: computed,\n };\n }\n\n return {\n ok: false,\n reason: 'mismatch',\n storedHash: pkg.metadata.migrationHash,\n computedHash: computed,\n };\n}\n"],"mappings":";;;AAAA,SAAS,SAAS,OAAyB;AACzC,KAAI,UAAU,QAAQ,OAAO,UAAU,SACrC,QAAO;AAET,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,IAAI,SAAS;CAE5B,MAAMA,SAAkC,EAAE;AAC1C,MAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAAC,MAAM,CACzC,QAAO,OAAO,SAAU,MAAkC,KAAK;AAEjE,QAAO;;AAGT,SAAgB,iBAAiB,OAAwB;AACvD,QAAO,KAAK,UAAU,SAAS,MAAM,CAAC;;;;;ACHxC,SAAS,UAAU,OAAuB;AACxC,QAAO,WAAW,SAAS,CAAC,OAAO,MAAM,CAAC,OAAO,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BzD,SAAgB,qBACd,UACA,KACQ;CACR,MAAM,EACJ,eAAe,gBACf,WAAW,YACX,cAAc,eACd,YAAY,aACZ,OAAO,QACP,GAAG,iBACD;AAQJ,QAAO,UAFM,UAAU,iBADJ,CAHO,iBAAiB,aAAa,EACnC,iBAAiB,IAAI,CAEU,CAAC,IAAI,UAAU,CAChB,CAAC;;;;;;;;;;;AActD,SAAgB,oBAAoB,KAAqC;CACvE,MAAM,WAAW,qBAAqB,IAAI,UAAU,IAAI,IAAI;AAE5D,KAAI,IAAI,SAAS,kBAAkB,SACjC,QAAO;EACL,IAAI;EACJ,YAAY,IAAI,SAAS;EACzB,cAAc;EACf;AAGH,QAAO;EACL,IAAI;EACJ,QAAQ;EACR,YAAY,IAAI,SAAS;EACzB,cAAc;EACf"}
@@ -0,0 +1,45 @@
1
+ import { Contract } from "@prisma-next/contract/types";
2
+
3
+ //#region src/metadata.d.ts
4
+ interface MigrationHints {
5
+ readonly used: readonly string[];
6
+ readonly applied: readonly string[];
7
+ readonly plannerVersion: string;
8
+ }
9
+ /**
10
+ * In-memory migration metadata envelope. Every migration is content-addressed:
11
+ * the `migrationHash` is a hash over the metadata envelope plus the operations
12
+ * list, computed at write time. There is no draft state — a migration
13
+ * directory either exists with fully attested metadata or it does not.
14
+ *
15
+ * When the planner cannot lower an operation because of an unfilled
16
+ * `placeholder(...)` slot, the migration is still written with `migrationHash`
17
+ * hashed over `ops: []`. Re-running self-emit after the user fills the
18
+ * placeholder produces a *different* `migrationHash` (committed to the real
19
+ * ops); this is intentional.
20
+ *
21
+ * The on-disk JSON shape in `migration.json` matches this type field-for-field
22
+ * — `JSON.stringify(metadata, null, 2)` is the canonical writer output.
23
+ */
24
+ interface MigrationMetadata {
25
+ readonly migrationHash: string;
26
+ readonly from: string;
27
+ readonly to: string;
28
+ readonly kind: 'regular' | 'baseline';
29
+ readonly fromContract: Contract | null;
30
+ readonly toContract: Contract;
31
+ readonly hints: MigrationHints;
32
+ readonly labels: readonly string[];
33
+ readonly authorship?: {
34
+ readonly author?: string;
35
+ readonly email?: string;
36
+ };
37
+ readonly signature?: {
38
+ readonly keyId: string;
39
+ readonly value: string;
40
+ } | null;
41
+ readonly createdAt: string;
42
+ }
43
+ //#endregion
44
+ export { MigrationMetadata as n, MigrationHints as t };
45
+ //# sourceMappingURL=metadata-DDa5L-uD.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metadata-DDa5L-uD.d.mts","names":[],"sources":["../src/metadata.ts"],"sourcesContent":[],"mappings":";;;UAEiB,cAAA;;EAAA,SAAA,OAAA,EAAc,SAAA,MAAA,EAAA;EAqBd,SAAA,cAAiB,EAAA,MAAA;;;;;;;;;;;;;;;;;UAAjB,iBAAA;;;;;yBAKQ;uBACF;kBACL"}
@@ -0,0 +1,21 @@
1
+ import { n as MigrationMetadata } from "./metadata-DDa5L-uD.mjs";
2
+ import { MigrationPlanOperation } from "@prisma-next/framework-components/control";
3
+
4
+ //#region src/package.d.ts
5
+ type MigrationOps = readonly MigrationPlanOperation[];
6
+ /**
7
+ * An on-disk migration directory (a "package") with its parsed metadata and
8
+ * operations. Returned from `readMigrationPackage` / `readMigrationsDir` only
9
+ * after the loader has verified the package's integrity (hash recomputation
10
+ * against the stored `migrationHash`); holding a `MigrationPackage` value
11
+ * therefore implies the package is internally consistent.
12
+ */
13
+ interface MigrationPackage {
14
+ readonly dirName: string;
15
+ readonly dirPath: string;
16
+ readonly metadata: MigrationMetadata;
17
+ readonly ops: MigrationOps;
18
+ }
19
+ //#endregion
20
+ export { MigrationPackage as n, MigrationOps as t };
21
+ //# sourceMappingURL=package-BJ5KAEcD.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"package-BJ5KAEcD.d.mts","names":[],"sources":["../src/package.ts"],"sourcesContent":[],"mappings":";;;;KAGY,YAAA,YAAwB;;AAApC;AASA;;;;;UAAiB,gBAAA;;;qBAGI;gBACL"}
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@prisma-next/migration-tools",
3
- "version": "0.5.0-dev.1",
3
+ "version": "0.5.0-dev.11",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
- "description": "On-disk migration persistence, attestation, and chain reconstruction for Prisma Next",
6
+ "description": "On-disk migration persistence, hash verification, and chain reconstruction for Prisma Next",
7
7
  "dependencies": {
8
8
  "arktype": "^2.1.29",
9
9
  "pathe": "^2.0.3",
10
10
  "prettier": "^3.6.2",
11
- "@prisma-next/contract": "0.5.0-dev.1",
12
- "@prisma-next/utils": "0.5.0-dev.1",
13
- "@prisma-next/framework-components": "0.5.0-dev.1"
11
+ "@prisma-next/contract": "0.5.0-dev.11",
12
+ "@prisma-next/framework-components": "0.5.0-dev.11",
13
+ "@prisma-next/utils": "0.5.0-dev.11"
14
14
  },
15
15
  "devDependencies": {
16
16
  "tsdown": "0.18.4",
@@ -27,21 +27,33 @@
27
27
  "node": ">=20"
28
28
  },
29
29
  "exports": {
30
- "./types": {
31
- "types": "./dist/exports/types.d.mts",
32
- "import": "./dist/exports/types.mjs"
30
+ "./metadata": {
31
+ "types": "./dist/exports/metadata.d.mts",
32
+ "import": "./dist/exports/metadata.mjs"
33
+ },
34
+ "./package": {
35
+ "types": "./dist/exports/package.d.mts",
36
+ "import": "./dist/exports/package.mjs"
37
+ },
38
+ "./graph": {
39
+ "types": "./dist/exports/graph.d.mts",
40
+ "import": "./dist/exports/graph.mjs"
41
+ },
42
+ "./errors": {
43
+ "types": "./dist/exports/errors.d.mts",
44
+ "import": "./dist/exports/errors.mjs"
33
45
  },
34
46
  "./io": {
35
47
  "types": "./dist/exports/io.d.mts",
36
48
  "import": "./dist/exports/io.mjs"
37
49
  },
38
- "./attestation": {
39
- "types": "./dist/exports/attestation.d.mts",
40
- "import": "./dist/exports/attestation.mjs"
50
+ "./hash": {
51
+ "types": "./dist/exports/hash.d.mts",
52
+ "import": "./dist/exports/hash.mjs"
41
53
  },
42
- "./dag": {
43
- "types": "./dist/exports/dag.d.mts",
44
- "import": "./dist/exports/dag.mjs"
54
+ "./migration-graph": {
55
+ "types": "./dist/exports/migration-graph.d.mts",
56
+ "import": "./dist/exports/migration-graph.mjs"
45
57
  },
46
58
  "./refs": {
47
59
  "types": "./dist/exports/refs.d.mts",
package/src/errors.ts CHANGED
@@ -1,10 +1,29 @@
1
+ import { basename, dirname, relative } from 'pathe';
2
+
3
+ /**
4
+ * Build the canonical "re-emit this package" remediation hint.
5
+ *
6
+ * Every on-disk migration package ships its own `migration.ts` author-time
7
+ * file. Running it regenerates `migration.json` and `ops.json` with the
8
+ * correct hash + metadata, so it is the right primitive whenever a single
9
+ * package's on-disk artifacts are missing, malformed, or otherwise corrupt.
10
+ * Pointing users at `migration plan` would emit a *new* package rather than
11
+ * heal the broken one.
12
+ */
13
+ function reemitHint(dir: string, fallback?: string): string {
14
+ const relativeDir = relative(process.cwd(), dir);
15
+ const reemit = `Re-emit the package by running \`node "${relativeDir}/migration.ts"\``;
16
+ return fallback ? `${reemit}, ${fallback}` : `${reemit}.`;
17
+ }
18
+
1
19
  /**
2
20
  * Structured error for migration tooling operations.
3
21
  *
4
22
  * Follows the NAMESPACE.SUBCODE convention from ADR 027. All codes live under
5
- * the MIGRATION namespace. These are tooling-time errors (file I/O, attestation,
6
- * migration history reconstruction), distinct from the runtime MIGRATION.* codes for apply-time
7
- * failures (PRECHECK_FAILED, POSTCHECK_FAILED, etc.).
23
+ * the MIGRATION namespace. These are tooling-time errors (file I/O, hash
24
+ * verification, migration history reconstruction), distinct from the runtime
25
+ * MIGRATION.* codes for apply-time failures (PRECHECK_FAILED, POSTCHECK_FAILED,
26
+ * etc.).
8
27
  *
9
28
  * Fields:
10
29
  * - code: Stable machine-readable code (MIGRATION.SUBCODE)
@@ -55,7 +74,10 @@ export function errorDirectoryExists(dir: string): MigrationToolsError {
55
74
  export function errorMissingFile(file: string, dir: string): MigrationToolsError {
56
75
  return new MigrationToolsError('MIGRATION.FILE_MISSING', `Missing ${file}`, {
57
76
  why: `Expected "${file}" in "${dir}" but the file does not exist.`,
58
- fix: 'Ensure the migration directory contains both migration.json and ops.json. If the directory is corrupt, delete it and re-run migration plan.',
77
+ fix: reemitHint(
78
+ dir,
79
+ 'or delete the directory if the migration is unwanted and the source TypeScript is gone.',
80
+ ),
59
81
  details: { file, dir },
60
82
  });
61
83
  }
@@ -63,15 +85,15 @@ export function errorMissingFile(file: string, dir: string): MigrationToolsError
63
85
  export function errorInvalidJson(filePath: string, parseError: string): MigrationToolsError {
64
86
  return new MigrationToolsError('MIGRATION.INVALID_JSON', 'Invalid JSON in migration file', {
65
87
  why: `Failed to parse "${filePath}": ${parseError}`,
66
- fix: 'Fix the JSON syntax error, or delete the migration directory and re-run migration plan.',
88
+ fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),
67
89
  details: { filePath, parseError },
68
90
  });
69
91
  }
70
92
 
71
93
  export function errorInvalidManifest(filePath: string, reason: string): MigrationToolsError {
72
94
  return new MigrationToolsError('MIGRATION.INVALID_MANIFEST', 'Invalid migration manifest', {
73
- why: `Manifest at "${filePath}" is invalid: ${reason}`,
74
- fix: 'Ensure the manifest has all required fields (from, to, kind, toContract). If corrupt, delete and re-plan.',
95
+ why: `Migration manifest at "${filePath}" is invalid: ${reason}`,
96
+ fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),
75
97
  details: { filePath, reason },
76
98
  });
77
99
  }
@@ -92,13 +114,17 @@ export function errorInvalidDestName(destName: string): MigrationToolsError {
92
114
  });
93
115
  }
94
116
 
95
- export function errorSameSourceAndTarget(dirName: string, hash: string): MigrationToolsError {
117
+ export function errorSameSourceAndTarget(dir: string, hash: string): MigrationToolsError {
118
+ const dirName = basename(dir);
96
119
  return new MigrationToolsError(
97
120
  'MIGRATION.SAME_SOURCE_AND_TARGET',
98
121
  'Migration has same source and target',
99
122
  {
100
123
  why: `Migration "${dirName}" has from === to === "${hash}". A migration must transition between two different contract states.`,
101
- fix: 'Delete the invalid migration directory and re-run migration plan.',
124
+ fix: reemitHint(
125
+ dir,
126
+ 'or delete the directory if the migration is unwanted and the source TypeScript is gone.',
127
+ ),
102
128
  details: { dirName, hash },
103
129
  },
104
130
  );
@@ -175,14 +201,30 @@ export function errorInvalidRefValue(value: string): MigrationToolsError {
175
201
  });
176
202
  }
177
203
 
178
- export function errorDuplicateMigrationId(migrationId: string): MigrationToolsError {
204
+ export function errorDuplicateMigrationHash(migrationHash: string): MigrationToolsError {
179
205
  return new MigrationToolsError(
180
- 'MIGRATION.DUPLICATE_MIGRATION_ID',
181
- 'Duplicate migrationId in migration graph',
206
+ 'MIGRATION.DUPLICATE_MIGRATION_HASH',
207
+ 'Duplicate migrationHash in migration graph',
182
208
  {
183
- why: `Multiple migrations share migrationId "${migrationId}". Each migration must have a unique content-addressed identity.`,
184
- fix: 'Regenerate one of the conflicting migrations so each migrationId is unique, then re-run migration commands.',
185
- details: { migrationId },
209
+ why: `Multiple migrations share migrationHash "${migrationHash}". Each migration must have a unique content-addressed identity.`,
210
+ fix: 'Regenerate one of the conflicting migrations so each migrationHash is unique, then re-run migration commands.',
211
+ details: { migrationHash },
186
212
  },
187
213
  );
188
214
  }
215
+
216
+ export function errorMigrationHashMismatch(
217
+ dir: string,
218
+ storedHash: string,
219
+ computedHash: string,
220
+ ): MigrationToolsError {
221
+ // Render a cwd-relative path in the human-readable diagnostic so users
222
+ // running CLI commands from the project root see a familiar short path.
223
+ // Keep the absolute path in `details.dir` for machine consumers.
224
+ const relativeDir = relative(process.cwd(), dir);
225
+ return new MigrationToolsError('MIGRATION.HASH_MISMATCH', 'Migration package is corrupt', {
226
+ why: `Stored migrationHash "${storedHash}" does not match the recomputed hash "${computedHash}" for "${relativeDir}". The migration.json or ops.json has been edited or partially written since emit.`,
227
+ fix: reemitHint(dir, 'or restore the directory from version control.'),
228
+ details: { dir, storedHash, computedHash },
229
+ });
230
+ }
@@ -0,0 +1 @@
1
+ export { MigrationToolsError } from '../errors';
@@ -0,0 +1 @@
1
+ export type { MigrationEdge, MigrationGraph } from '../graph';
@@ -0,0 +1,2 @@
1
+ export type { VerifyResult } from '../hash';
2
+ export { computeMigrationHash, verifyMigrationHash } from '../hash';
package/src/exports/io.ts CHANGED
@@ -3,7 +3,7 @@ export {
3
3
  formatMigrationDirName,
4
4
  readMigrationPackage,
5
5
  readMigrationsDir,
6
- writeMigrationManifest,
6
+ writeMigrationMetadata,
7
7
  writeMigrationOps,
8
8
  writeMigrationPackage,
9
9
  } from '../io';
@@ -0,0 +1 @@
1
+ export type { MigrationHints, MigrationMetadata } from '../metadata';
@@ -1,4 +1,4 @@
1
- export type { PathDecision } from '../dag';
1
+ export type { PathDecision } from '../migration-graph';
2
2
  export {
3
3
  detectCycles,
4
4
  detectOrphans,
@@ -8,4 +8,4 @@ export {
8
8
  findPathWithDecision,
9
9
  findReachableLeaves,
10
10
  reconstructGraph,
11
- } from '../dag';
11
+ } from '../migration-graph';
@@ -0,0 +1 @@
1
+ export type { MigrationOps, MigrationPackage } from '../package';
@@ -1,2 +1,10 @@
1
- export type { Refs } from '../refs';
2
- export { readRefs, resolveRef, validateRefName, validateRefValue, writeRefs } from '../refs';
1
+ export type { RefEntry, Refs } from '../refs';
2
+ export {
3
+ deleteRef,
4
+ readRef,
5
+ readRefs,
6
+ resolveRef,
7
+ validateRefName,
8
+ validateRefValue,
9
+ writeRef,
10
+ } from '../refs';
package/src/graph.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * An entry in the migration graph. All on-disk migrations are attested,
3
+ * so `migrationHash` is always a string.
4
+ */
5
+ export interface MigrationEdge {
6
+ readonly from: string;
7
+ readonly to: string;
8
+ readonly migrationHash: string;
9
+ readonly dirName: string;
10
+ readonly createdAt: string;
11
+ readonly labels: readonly string[];
12
+ }
13
+
14
+ export interface MigrationGraph {
15
+ readonly nodes: ReadonlySet<string>;
16
+ readonly forwardChain: ReadonlyMap<string, readonly MigrationEdge[]>;
17
+ readonly reverseChain: ReadonlyMap<string, readonly MigrationEdge[]>;
18
+ readonly migrationByHash: ReadonlyMap<string, MigrationEdge>;
19
+ }
package/src/hash.ts ADDED
@@ -0,0 +1,91 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { canonicalizeJson } from './canonicalize-json';
3
+ import type { MigrationMetadata } from './metadata';
4
+ import type { MigrationOps, MigrationPackage } from './package';
5
+
6
+ export interface VerifyResult {
7
+ readonly ok: boolean;
8
+ readonly reason?: 'mismatch';
9
+ readonly storedHash: string;
10
+ readonly computedHash: string;
11
+ }
12
+
13
+ function sha256Hex(input: string): string {
14
+ return createHash('sha256').update(input).digest('hex');
15
+ }
16
+
17
+ /**
18
+ * Content-addressed migration hash over (metadata envelope sans
19
+ * contracts/hints/signature, ops). See ADR 199 — Storage-only migration
20
+ * identity for the rationale: contracts are anchored separately by the
21
+ * storage-hash bookends inside the envelope; planner hints are advisory
22
+ * and must not affect identity.
23
+ *
24
+ * The integrity check is purely structural, not semantic. The function
25
+ * canonicalizes its inputs via `sortKeys` (recursive) + `JSON.stringify`
26
+ * and hashes the result. Target-specific operation payloads (`step.sql`,
27
+ * Mongo's pipeline AST, …) are hashed verbatim — no per-target
28
+ * normalization is required, because what's being verified is "do the
29
+ * on-disk bytes still produce their recorded hash", not "do two
30
+ * semantically-equivalent migrations hash the same". The latter is an
31
+ * emit-drift concern (ADR 192 step 2).
32
+ *
33
+ * The symmetry across write and read holds because `JSON.parse(
34
+ * JSON.stringify(x))` round-trips JSON-safe values losslessly and
35
+ * `sortKeys` is idempotent and deterministic — write-time and read-time
36
+ * canonicalization produce the same canonical bytes regardless of
37
+ * source-side key ordering or whitespace.
38
+ *
39
+ * The `migrationHash` field on the metadata is stripped before hashing
40
+ * so the function can be used both at write time (when no hash exists
41
+ * yet) and at verify time (rehashing an already-attested record).
42
+ */
43
+ export function computeMigrationHash(
44
+ metadata: Omit<MigrationMetadata, 'migrationHash'> & { readonly migrationHash?: string },
45
+ ops: MigrationOps,
46
+ ): string {
47
+ const {
48
+ migrationHash: _migrationHash,
49
+ signature: _signature,
50
+ fromContract: _fromContract,
51
+ toContract: _toContract,
52
+ hints: _hints,
53
+ ...strippedMeta
54
+ } = metadata;
55
+
56
+ const canonicalMetadata = canonicalizeJson(strippedMeta);
57
+ const canonicalOps = canonicalizeJson(ops);
58
+
59
+ const partHashes = [canonicalMetadata, canonicalOps].map(sha256Hex);
60
+ const hash = sha256Hex(canonicalizeJson(partHashes));
61
+
62
+ return `sha256:${hash}`;
63
+ }
64
+
65
+ /**
66
+ * Re-hash an in-memory migration package and compare against the stored
67
+ * `migrationHash`. See `computeMigrationHash` for the canonicalization rules.
68
+ *
69
+ * Returns `{ ok: true }` when the package is internally consistent, or
70
+ * `{ ok: false, reason: 'mismatch', storedHash, computedHash }` when it is
71
+ * not — typically a sign of FS corruption, partial writes, or a post-emit
72
+ * hand edit.
73
+ */
74
+ export function verifyMigrationHash(pkg: MigrationPackage): VerifyResult {
75
+ const computed = computeMigrationHash(pkg.metadata, pkg.ops);
76
+
77
+ if (pkg.metadata.migrationHash === computed) {
78
+ return {
79
+ ok: true,
80
+ storedHash: pkg.metadata.migrationHash,
81
+ computedHash: computed,
82
+ };
83
+ }
84
+
85
+ return {
86
+ ok: false,
87
+ reason: 'mismatch',
88
+ storedHash: pkg.metadata.migrationHash,
89
+ computedHash: computed,
90
+ };
91
+ }