@prisma-next/migration-tools 0.5.0-dev.3 → 0.5.0-dev.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.
@@ -1,4 +1,4 @@
1
- import { r as readMigrationPackage } from "./io-CCnYsUHU.mjs";
1
+ import { r as readMigrationPackage } from "./io-Cd6GLyjK.mjs";
2
2
  import { createHash } from "node:crypto";
3
3
 
4
4
  //#region src/canonicalize-json.ts
@@ -62,4 +62,4 @@ async function verifyMigration(dir) {
62
62
 
63
63
  //#endregion
64
64
  export { verifyMigration as n, verifyMigrationBundle as r, computeMigrationId as t };
65
- //# sourceMappingURL=attestation-DtF8tEOM.mjs.map
65
+ //# sourceMappingURL=attestation-BnzTb0Qp.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"attestation-DtF8tEOM.mjs","names":["sorted: Record<string, unknown>"],"sources":["../src/canonicalize-json.ts","../src/attestation.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 { readMigrationPackage } from './io';\nimport type { MigrationBundle, MigrationManifest, MigrationOps } from './types';\n\nexport interface VerifyResult {\n readonly ok: boolean;\n readonly reason?: 'mismatch';\n readonly storedMigrationId?: string;\n readonly computedMigrationId?: string;\n}\n\nfunction sha256Hex(input: string): string {\n return createHash('sha256').update(input).digest('hex');\n}\n\n/**\n * Content-addressed migration identity over (manifest envelope sans\n * contracts/hints, ops). See ADR 199 \"Storage-only migration identity\"\n * 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 `migrationId` field on the manifest is stripped before hashing so\n * the function can be used both at write time (when no id exists yet)\n * and at verify time (rehashing an already-attested manifest).\n */\nexport function computeMigrationId(\n manifest: Omit<MigrationManifest, 'migrationId'> & { readonly migrationId?: string },\n ops: MigrationOps,\n): string {\n const {\n migrationId: _migrationId,\n signature: _signature,\n fromContract: _fromContract,\n toContract: _toContract,\n hints: _hints,\n ...strippedMeta\n } = manifest;\n\n const canonicalManifest = canonicalizeJson(strippedMeta);\n const canonicalOps = canonicalizeJson(ops);\n\n const partHashes = [canonicalManifest, canonicalOps].map(sha256Hex);\n const hash = sha256Hex(canonicalizeJson(partHashes));\n\n return `sha256:${hash}`;\n}\n\n/**\n * Re-hash an on-disk migration bundle and compare against the stored\n * `migrationId`. Returns `{ ok: true }` when the package is internally\n * consistent (manifest + ops still produce the recorded id), or\n * `{ ok: false, reason: 'mismatch', stored, computed }` when they do\n * not — typically a sign of FS corruption, partial writes, or a\n * post-emit hand edit.\n */\nexport function verifyMigrationBundle(bundle: MigrationBundle): VerifyResult {\n const computed = computeMigrationId(bundle.manifest, bundle.ops);\n\n if (bundle.manifest.migrationId === computed) {\n return {\n ok: true,\n storedMigrationId: bundle.manifest.migrationId,\n computedMigrationId: computed,\n };\n }\n\n return {\n ok: false,\n reason: 'mismatch',\n storedMigrationId: bundle.manifest.migrationId,\n computedMigrationId: computed,\n };\n}\n\n/** Convenience wrapper: read the package from disk then verify it. */\nexport async function verifyMigration(dir: string): Promise<VerifyResult> {\n const pkg = await readMigrationPackage(dir);\n return verifyMigrationBundle(pkg);\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;;;;;;;;;;;;;AAczD,SAAgB,mBACd,UACA,KACQ;CACR,MAAM,EACJ,aAAa,cACb,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;;;;;;;;;;AAatD,SAAgB,sBAAsB,QAAuC;CAC3E,MAAM,WAAW,mBAAmB,OAAO,UAAU,OAAO,IAAI;AAEhE,KAAI,OAAO,SAAS,gBAAgB,SAClC,QAAO;EACL,IAAI;EACJ,mBAAmB,OAAO,SAAS;EACnC,qBAAqB;EACtB;AAGH,QAAO;EACL,IAAI;EACJ,QAAQ;EACR,mBAAmB,OAAO,SAAS;EACnC,qBAAqB;EACtB;;;AAIH,eAAsB,gBAAgB,KAAoC;AAExE,QAAO,sBADK,MAAM,qBAAqB,IAAI,CACV"}
1
+ {"version":3,"file":"attestation-BnzTb0Qp.mjs","names":["sorted: Record<string, unknown>"],"sources":["../src/canonicalize-json.ts","../src/attestation.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 { readMigrationPackage } from './io';\nimport type { MigrationBundle, MigrationManifest, MigrationOps } from './types';\n\nexport interface VerifyResult {\n readonly ok: boolean;\n readonly reason?: 'mismatch';\n readonly storedMigrationId?: string;\n readonly computedMigrationId?: string;\n}\n\nfunction sha256Hex(input: string): string {\n return createHash('sha256').update(input).digest('hex');\n}\n\n/**\n * Content-addressed migration identity over (manifest envelope sans\n * contracts/hints, ops). See ADR 199 \"Storage-only migration identity\"\n * 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 `migrationId` field on the manifest is stripped before hashing so\n * the function can be used both at write time (when no id exists yet)\n * and at verify time (rehashing an already-attested manifest).\n */\nexport function computeMigrationId(\n manifest: Omit<MigrationManifest, 'migrationId'> & { readonly migrationId?: string },\n ops: MigrationOps,\n): string {\n const {\n migrationId: _migrationId,\n signature: _signature,\n fromContract: _fromContract,\n toContract: _toContract,\n hints: _hints,\n ...strippedMeta\n } = manifest;\n\n const canonicalManifest = canonicalizeJson(strippedMeta);\n const canonicalOps = canonicalizeJson(ops);\n\n const partHashes = [canonicalManifest, canonicalOps].map(sha256Hex);\n const hash = sha256Hex(canonicalizeJson(partHashes));\n\n return `sha256:${hash}`;\n}\n\n/**\n * Re-hash an on-disk migration bundle and compare against the stored\n * `migrationId`. Returns `{ ok: true }` when the package is internally\n * consistent (manifest + ops still produce the recorded id), or\n * `{ ok: false, reason: 'mismatch', stored, computed }` when they do\n * not — typically a sign of FS corruption, partial writes, or a\n * post-emit hand edit.\n */\nexport function verifyMigrationBundle(bundle: MigrationBundle): VerifyResult {\n const computed = computeMigrationId(bundle.manifest, bundle.ops);\n\n if (bundle.manifest.migrationId === computed) {\n return {\n ok: true,\n storedMigrationId: bundle.manifest.migrationId,\n computedMigrationId: computed,\n };\n }\n\n return {\n ok: false,\n reason: 'mismatch',\n storedMigrationId: bundle.manifest.migrationId,\n computedMigrationId: computed,\n };\n}\n\n/** Convenience wrapper: read the package from disk then verify it. */\nexport async function verifyMigration(dir: string): Promise<VerifyResult> {\n const pkg = await readMigrationPackage(dir);\n return verifyMigrationBundle(pkg);\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;;;;;;;;;;;;;AAczD,SAAgB,mBACd,UACA,KACQ;CACR,MAAM,EACJ,aAAa,cACb,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;;;;;;;;;;AAatD,SAAgB,sBAAsB,QAAuC;CAC3E,MAAM,WAAW,mBAAmB,OAAO,UAAU,OAAO,IAAI;AAEhE,KAAI,OAAO,SAAS,gBAAgB,SAClC,QAAO;EACL,IAAI;EACJ,mBAAmB,OAAO,SAAS;EACnC,qBAAqB;EACtB;AAGH,QAAO;EACL,IAAI;EACJ,QAAQ;EACR,mBAAmB,OAAO,SAAS;EACnC,qBAAqB;EACtB;;;AAIH,eAAsB,gBAAgB,KAAoC;AAExE,QAAO,sBADK,MAAM,qBAAqB,IAAI,CACV"}
@@ -116,12 +116,12 @@ function errorNoInitialMigration(nodes) {
116
116
  details: { nodes }
117
117
  });
118
118
  }
119
- function errorInvalidRefs(refsPath, reason) {
120
- return new MigrationToolsError("MIGRATION.INVALID_REFS", "Invalid refs.json", {
121
- why: `refs.json at "${refsPath}" is invalid: ${reason}`,
122
- fix: "Ensure refs.json is a flat object mapping valid ref names to contract hash strings.",
119
+ function errorInvalidRefFile(filePath, reason) {
120
+ return new MigrationToolsError("MIGRATION.INVALID_REF_FILE", "Invalid ref file", {
121
+ why: `Ref file at "${filePath}" is invalid: ${reason}`,
122
+ fix: "Ensure the ref file contains valid JSON with { \"hash\": \"sha256:<64 hex chars>\", \"invariants\": [\"...\"] }.",
123
123
  details: {
124
- path: refsPath,
124
+ path: filePath,
125
125
  reason
126
126
  }
127
127
  });
@@ -156,5 +156,5 @@ function errorDuplicateMigrationId(migrationId) {
156
156
  }
157
157
 
158
158
  //#endregion
159
- export { errorInvalidDestName as a, errorInvalidRefName as c, errorInvalidSlug as d, errorMissingFile as f, errorSameSourceAndTarget as h, errorDuplicateMigrationId as i, errorInvalidRefValue as l, errorNoTarget as m, errorAmbiguousTarget as n, errorInvalidJson as o, errorNoInitialMigration as p, errorDirectoryExists as r, errorInvalidManifest as s, MigrationToolsError as t, errorInvalidRefs as u };
160
- //# sourceMappingURL=errors-BKbRGCJM.mjs.map
159
+ export { errorInvalidDestName as a, errorInvalidRefFile as c, errorInvalidSlug as d, errorMissingFile as f, errorSameSourceAndTarget as h, errorDuplicateMigrationId as i, errorInvalidRefName as l, errorNoTarget as m, errorAmbiguousTarget as n, errorInvalidJson as o, errorNoInitialMigration as p, errorDirectoryExists as r, errorInvalidManifest as s, MigrationToolsError as t, errorInvalidRefValue as u };
160
+ //# sourceMappingURL=errors-BmiSgz1j.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-BKbRGCJM.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Structured error for migration tooling operations.\n *\n * Follows the NAMESPACE.SUBCODE convention from ADR 027. All codes live under\n * the MIGRATION namespace. These are tooling-time errors (file I/O, attestation,\n * migration history reconstruction), distinct from the runtime MIGRATION.* codes for apply-time\n * failures (PRECHECK_FAILED, POSTCHECK_FAILED, etc.).\n *\n * Fields:\n * - code: Stable machine-readable code (MIGRATION.SUBCODE)\n * - category: Always 'MIGRATION'\n * - why: Explains the cause in plain language\n * - fix: Actionable remediation step\n * - details: Machine-readable structured data for agents\n */\nexport class MigrationToolsError extends Error {\n readonly code: string;\n readonly category = 'MIGRATION' as const;\n readonly why: string;\n readonly fix: string;\n readonly details: Record<string, unknown> | undefined;\n\n constructor(\n code: string,\n summary: string,\n options: {\n readonly why: string;\n readonly fix: string;\n readonly details?: Record<string, unknown>;\n },\n ) {\n super(summary);\n this.name = 'MigrationToolsError';\n this.code = code;\n this.why = options.why;\n this.fix = options.fix;\n this.details = options.details;\n }\n\n static is(error: unknown): error is MigrationToolsError {\n if (!(error instanceof Error)) return false;\n const candidate = error as MigrationToolsError;\n return candidate.name === 'MigrationToolsError' && typeof candidate.code === 'string';\n }\n}\n\nexport function errorDirectoryExists(dir: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.DIR_EXISTS', 'Migration directory already exists', {\n why: `The directory \"${dir}\" already exists. Each migration must have a unique directory.`,\n fix: 'Use --name to pick a different name, or delete the existing directory and re-run.',\n details: { dir },\n });\n}\n\nexport function errorMissingFile(file: string, dir: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.FILE_MISSING', `Missing ${file}`, {\n why: `Expected \"${file}\" in \"${dir}\" but the file does not exist.`,\n fix: 'Ensure the migration directory contains both migration.json and ops.json. If the directory is corrupt, delete it and re-run migration plan.',\n details: { file, dir },\n });\n}\n\nexport function errorInvalidJson(filePath: string, parseError: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_JSON', 'Invalid JSON in migration file', {\n why: `Failed to parse \"${filePath}\": ${parseError}`,\n fix: 'Fix the JSON syntax error, or delete the migration directory and re-run migration plan.',\n details: { filePath, parseError },\n });\n}\n\nexport function errorInvalidManifest(filePath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_MANIFEST', 'Invalid migration manifest', {\n why: `Manifest at \"${filePath}\" is invalid: ${reason}`,\n fix: 'Ensure the manifest has all required fields (from, to, kind, toContract). If corrupt, delete and re-plan.',\n details: { filePath, reason },\n });\n}\n\nexport function errorInvalidSlug(slug: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_NAME', 'Invalid migration name', {\n why: `The slug \"${slug}\" contains no valid characters after sanitization (only a-z, 0-9 are kept).`,\n fix: 'Provide a name with at least one alphanumeric character, e.g. --name add_users.',\n details: { slug },\n });\n}\n\nexport function errorInvalidDestName(destName: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_DEST_NAME', 'Invalid copy destination name', {\n why: `The destination name \"${destName}\" must be a single path segment (no \"..\" or directory separators).`,\n fix: 'Use a simple file name such as \"contract.json\" for each destination in the copy list.',\n details: { destName },\n });\n}\n\nexport function errorSameSourceAndTarget(dirName: string, hash: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.SAME_SOURCE_AND_TARGET',\n 'Migration has same source and target',\n {\n why: `Migration \"${dirName}\" has from === to === \"${hash}\". A migration must transition between two different contract states.`,\n fix: 'Delete the invalid migration directory and re-run migration plan.',\n details: { dirName, hash },\n },\n );\n}\n\nexport function errorAmbiguousTarget(\n branchTips: readonly string[],\n context?: {\n divergencePoint: string;\n branches: readonly {\n tip: string;\n edges: readonly { dirName: string; from: string; to: string }[];\n }[];\n },\n): MigrationToolsError {\n const divergenceInfo = context\n ? `\\nDivergence point: ${context.divergencePoint}\\nBranches:\\n${context.branches.map((b) => ` → ${b.tip} (${b.edges.length} edge(s): ${b.edges.map((e) => e.dirName).join(' → ') || 'direct'})`).join('\\n')}`\n : '';\n return new MigrationToolsError('MIGRATION.AMBIGUOUS_TARGET', 'Ambiguous migration target', {\n why: `The migration history has diverged into multiple branches: ${branchTips.join(', ')}. This typically happens when two developers plan migrations from the same starting point.${divergenceInfo}`,\n fix: 'Use `migration ref set <name> <hash>` to target a specific branch, delete one of the conflicting migration directories and re-run `migration plan`, or use --from <hash> to explicitly select a starting point.',\n details: {\n branchTips,\n ...(context ? { divergencePoint: context.divergencePoint, branches: context.branches } : {}),\n },\n });\n}\n\nexport function errorNoInitialMigration(nodes: readonly string[]): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.NO_INITIAL_MIGRATION', 'No initial migration found', {\n why: `No migration starts from the empty contract state (known hashes: ${nodes.join(', ')}). At least one migration must originate from the empty state.`,\n fix: 'Inspect the migrations directory for corrupted migration.json files. At least one migration must start from the empty contract hash.',\n details: { nodes },\n });\n}\n\nexport function errorInvalidRefs(refsPath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REFS', 'Invalid refs.json', {\n why: `refs.json at \"${refsPath}\" is invalid: ${reason}`,\n fix: 'Ensure refs.json is a flat object mapping valid ref names to contract hash strings.',\n details: { path: refsPath, reason },\n });\n}\n\nexport function errorInvalidRefFile(filePath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_FILE', 'Invalid ref file', {\n why: `Ref file at \"${filePath}\" is invalid: ${reason}`,\n fix: 'Ensure the ref file contains valid JSON with { \"hash\": \"sha256:<64 hex chars>\", \"invariants\": [\"...\"] }.',\n details: { path: filePath, reason },\n });\n}\n\nexport function errorInvalidRefName(refName: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_NAME', 'Invalid ref name', {\n why: `Ref name \"${refName}\" is invalid. Names must be lowercase alphanumeric with hyphens or forward slashes (no \".\" or \"..\" segments).`,\n fix: `Use a valid ref name (e.g., \"staging\", \"envs/production\").`,\n details: { refName },\n });\n}\n\nexport function errorNoTarget(reachableHashes: readonly string[]): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.NO_TARGET', 'No migration target could be resolved', {\n why: `The migration history contains cycles and no target can be resolved automatically (reachable hashes: ${reachableHashes.join(', ')}). This typically happens after rollback migrations (e.g., C1→C2→C1).`,\n fix: 'Use --from <hash> to specify the planning origin explicitly.',\n details: { reachableHashes },\n });\n}\n\nexport function errorInvalidRefValue(value: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_VALUE', 'Invalid ref value', {\n why: `Ref value \"${value}\" is not a valid contract hash. Values must be in the format \"sha256:<64 hex chars>\" or \"sha256:empty\".`,\n fix: 'Use a valid storage hash from `prisma-next contract emit` output or an existing migration.',\n details: { value },\n });\n}\n\nexport function errorDuplicateMigrationId(migrationId: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.DUPLICATE_MIGRATION_ID',\n 'Duplicate migrationId in migration graph',\n {\n why: `Multiple migrations share migrationId \"${migrationId}\". Each migration must have a unique content-addressed identity.`,\n fix: 'Regenerate one of the conflicting migrations so each migrationId is unique, then re-run migration commands.',\n details: { migrationId },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,AAAS;CACT,AAAS,WAAW;CACpB,AAAS;CACT,AAAS;CACT,AAAS;CAET,YACE,MACA,SACA,SAKA;AACA,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,OAAK,MAAM,QAAQ;AACnB,OAAK,MAAM,QAAQ;AACnB,OAAK,UAAU,QAAQ;;CAGzB,OAAO,GAAG,OAA8C;AACtD,MAAI,EAAE,iBAAiB,OAAQ,QAAO;EACtC,MAAM,YAAY;AAClB,SAAO,UAAU,SAAS,yBAAyB,OAAO,UAAU,SAAS;;;AAIjF,SAAgB,qBAAqB,KAAkC;AACrE,QAAO,IAAI,oBAAoB,wBAAwB,sCAAsC;EAC3F,KAAK,kBAAkB,IAAI;EAC3B,KAAK;EACL,SAAS,EAAE,KAAK;EACjB,CAAC;;AAGJ,SAAgB,iBAAiB,MAAc,KAAkC;AAC/E,QAAO,IAAI,oBAAoB,0BAA0B,WAAW,QAAQ;EAC1E,KAAK,aAAa,KAAK,QAAQ,IAAI;EACnC,KAAK;EACL,SAAS;GAAE;GAAM;GAAK;EACvB,CAAC;;AAGJ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AU,QAAQ;IAAU,GAAG,EAAE;GAC5F;EACF,CAAC;;AAGJ,SAAgB,wBAAwB,OAA+C;AACrF,QAAO,IAAI,oBAAoB,kCAAkC,8BAA8B;EAC7F,KAAK,oEAAoE,MAAM,KAAK,KAAK,CAAC;EAC1F,KAAK;EACL,SAAS,EAAE,OAAO;EACnB,CAAC;;AAGJ,SAAgB,iBAAiB,UAAkB,QAAqC;AACtF,QAAO,IAAI,oBAAoB,0BAA0B,qBAAqB;EAC5E,KAAK,iBAAiB,SAAS,gBAAgB;EAC/C,KAAK;EACL,SAAS;GAAE,MAAM;GAAU;GAAQ;EACpC,CAAC;;AAWJ,SAAgB,oBAAoB,SAAsC;AACxE,QAAO,IAAI,oBAAoB,8BAA8B,oBAAoB;EAC/E,KAAK,aAAa,QAAQ;EAC1B,KAAK;EACL,SAAS,EAAE,SAAS;EACrB,CAAC;;AAGJ,SAAgB,cAAc,iBAAyD;AACrF,QAAO,IAAI,oBAAoB,uBAAuB,yCAAyC;EAC7F,KAAK,wGAAwG,gBAAgB,KAAK,KAAK,CAAC;EACxI,KAAK;EACL,SAAS,EAAE,iBAAiB;EAC7B,CAAC;;AAGJ,SAAgB,qBAAqB,OAAoC;AACvE,QAAO,IAAI,oBAAoB,+BAA+B,qBAAqB;EACjF,KAAK,cAAc,MAAM;EACzB,KAAK;EACL,SAAS,EAAE,OAAO;EACnB,CAAC;;AAGJ,SAAgB,0BAA0B,aAA0C;AAClF,QAAO,IAAI,oBACT,oCACA,4CACA;EACE,KAAK,0CAA0C,YAAY;EAC3D,KAAK;EACL,SAAS,EAAE,aAAa;EACzB,CACF"}
1
+ {"version":3,"file":"errors-BmiSgz1j.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Structured error for migration tooling operations.\n *\n * Follows the NAMESPACE.SUBCODE convention from ADR 027. All codes live under\n * the MIGRATION namespace. These are tooling-time errors (file I/O, attestation,\n * migration history reconstruction), distinct from the runtime MIGRATION.* codes for apply-time\n * failures (PRECHECK_FAILED, POSTCHECK_FAILED, etc.).\n *\n * Fields:\n * - code: Stable machine-readable code (MIGRATION.SUBCODE)\n * - category: Always 'MIGRATION'\n * - why: Explains the cause in plain language\n * - fix: Actionable remediation step\n * - details: Machine-readable structured data for agents\n */\nexport class MigrationToolsError extends Error {\n readonly code: string;\n readonly category = 'MIGRATION' as const;\n readonly why: string;\n readonly fix: string;\n readonly details: Record<string, unknown> | undefined;\n\n constructor(\n code: string,\n summary: string,\n options: {\n readonly why: string;\n readonly fix: string;\n readonly details?: Record<string, unknown>;\n },\n ) {\n super(summary);\n this.name = 'MigrationToolsError';\n this.code = code;\n this.why = options.why;\n this.fix = options.fix;\n this.details = options.details;\n }\n\n static is(error: unknown): error is MigrationToolsError {\n if (!(error instanceof Error)) return false;\n const candidate = error as MigrationToolsError;\n return candidate.name === 'MigrationToolsError' && typeof candidate.code === 'string';\n }\n}\n\nexport function errorDirectoryExists(dir: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.DIR_EXISTS', 'Migration directory already exists', {\n why: `The directory \"${dir}\" already exists. Each migration must have a unique directory.`,\n fix: 'Use --name to pick a different name, or delete the existing directory and re-run.',\n details: { dir },\n });\n}\n\nexport function errorMissingFile(file: string, dir: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.FILE_MISSING', `Missing ${file}`, {\n why: `Expected \"${file}\" in \"${dir}\" but the file does not exist.`,\n fix: 'Ensure the migration directory contains both migration.json and ops.json. If the directory is corrupt, delete it and re-run migration plan.',\n details: { file, dir },\n });\n}\n\nexport function errorInvalidJson(filePath: string, parseError: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_JSON', 'Invalid JSON in migration file', {\n why: `Failed to parse \"${filePath}\": ${parseError}`,\n fix: 'Fix the JSON syntax error, or delete the migration directory and re-run migration plan.',\n details: { filePath, parseError },\n });\n}\n\nexport function errorInvalidManifest(filePath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_MANIFEST', 'Invalid migration manifest', {\n why: `Manifest at \"${filePath}\" is invalid: ${reason}`,\n fix: 'Ensure the manifest has all required fields (from, to, kind, toContract). If corrupt, delete and re-plan.',\n details: { filePath, reason },\n });\n}\n\nexport function errorInvalidSlug(slug: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_NAME', 'Invalid migration name', {\n why: `The slug \"${slug}\" contains no valid characters after sanitization (only a-z, 0-9 are kept).`,\n fix: 'Provide a name with at least one alphanumeric character, e.g. --name add_users.',\n details: { slug },\n });\n}\n\nexport function errorInvalidDestName(destName: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_DEST_NAME', 'Invalid copy destination name', {\n why: `The destination name \"${destName}\" must be a single path segment (no \"..\" or directory separators).`,\n fix: 'Use a simple file name such as \"contract.json\" for each destination in the copy list.',\n details: { destName },\n });\n}\n\nexport function errorSameSourceAndTarget(dirName: string, hash: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.SAME_SOURCE_AND_TARGET',\n 'Migration has same source and target',\n {\n why: `Migration \"${dirName}\" has from === to === \"${hash}\". A migration must transition between two different contract states.`,\n fix: 'Delete the invalid migration directory and re-run migration plan.',\n details: { dirName, hash },\n },\n );\n}\n\nexport function errorAmbiguousTarget(\n branchTips: readonly string[],\n context?: {\n divergencePoint: string;\n branches: readonly {\n tip: string;\n edges: readonly { dirName: string; from: string; to: string }[];\n }[];\n },\n): MigrationToolsError {\n const divergenceInfo = context\n ? `\\nDivergence point: ${context.divergencePoint}\\nBranches:\\n${context.branches.map((b) => ` → ${b.tip} (${b.edges.length} edge(s): ${b.edges.map((e) => e.dirName).join(' → ') || 'direct'})`).join('\\n')}`\n : '';\n return new MigrationToolsError('MIGRATION.AMBIGUOUS_TARGET', 'Ambiguous migration target', {\n why: `The migration history has diverged into multiple branches: ${branchTips.join(', ')}. This typically happens when two developers plan migrations from the same starting point.${divergenceInfo}`,\n fix: 'Use `migration ref set <name> <hash>` to target a specific branch, delete one of the conflicting migration directories and re-run `migration plan`, or use --from <hash> to explicitly select a starting point.',\n details: {\n branchTips,\n ...(context ? { divergencePoint: context.divergencePoint, branches: context.branches } : {}),\n },\n });\n}\n\nexport function errorNoInitialMigration(nodes: readonly string[]): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.NO_INITIAL_MIGRATION', 'No initial migration found', {\n why: `No migration starts from the empty contract state (known hashes: ${nodes.join(', ')}). At least one migration must originate from the empty state.`,\n fix: 'Inspect the migrations directory for corrupted migration.json files. At least one migration must start from the empty contract hash.',\n details: { nodes },\n });\n}\n\nexport function errorInvalidRefs(refsPath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REFS', 'Invalid refs.json', {\n why: `refs.json at \"${refsPath}\" is invalid: ${reason}`,\n fix: 'Ensure refs.json is a flat object mapping valid ref names to contract hash strings.',\n details: { path: refsPath, reason },\n });\n}\n\nexport function errorInvalidRefFile(filePath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_FILE', 'Invalid ref file', {\n why: `Ref file at \"${filePath}\" is invalid: ${reason}`,\n fix: 'Ensure the ref file contains valid JSON with { \"hash\": \"sha256:<64 hex chars>\", \"invariants\": [\"...\"] }.',\n details: { path: filePath, reason },\n });\n}\n\nexport function errorInvalidRefName(refName: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_NAME', 'Invalid ref name', {\n why: `Ref name \"${refName}\" is invalid. Names must be lowercase alphanumeric with hyphens or forward slashes (no \".\" or \"..\" segments).`,\n fix: `Use a valid ref name (e.g., \"staging\", \"envs/production\").`,\n details: { refName },\n });\n}\n\nexport function errorNoTarget(reachableHashes: readonly string[]): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.NO_TARGET', 'No migration target could be resolved', {\n why: `The migration history contains cycles and no target can be resolved automatically (reachable hashes: ${reachableHashes.join(', ')}). This typically happens after rollback migrations (e.g., C1→C2→C1).`,\n fix: 'Use --from <hash> to specify the planning origin explicitly.',\n details: { reachableHashes },\n });\n}\n\nexport function errorInvalidRefValue(value: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_VALUE', 'Invalid ref value', {\n why: `Ref value \"${value}\" is not a valid contract hash. Values must be in the format \"sha256:<64 hex chars>\" or \"sha256:empty\".`,\n fix: 'Use a valid storage hash from `prisma-next contract emit` output or an existing migration.',\n details: { value },\n });\n}\n\nexport function errorDuplicateMigrationId(migrationId: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.DUPLICATE_MIGRATION_ID',\n 'Duplicate migrationId in migration graph',\n {\n why: `Multiple migrations share migrationId \"${migrationId}\". Each migration must have a unique content-addressed identity.`,\n fix: 'Regenerate one of the conflicting migrations so each migrationId is unique, then re-run migration commands.',\n details: { migrationId },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,AAAS;CACT,AAAS,WAAW;CACpB,AAAS;CACT,AAAS;CACT,AAAS;CAET,YACE,MACA,SACA,SAKA;AACA,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,OAAO;AACZ,OAAK,MAAM,QAAQ;AACnB,OAAK,MAAM,QAAQ;AACnB,OAAK,UAAU,QAAQ;;CAGzB,OAAO,GAAG,OAA8C;AACtD,MAAI,EAAE,iBAAiB,OAAQ,QAAO;EACtC,MAAM,YAAY;AAClB,SAAO,UAAU,SAAS,yBAAyB,OAAO,UAAU,SAAS;;;AAIjF,SAAgB,qBAAqB,KAAkC;AACrE,QAAO,IAAI,oBAAoB,wBAAwB,sCAAsC;EAC3F,KAAK,kBAAkB,IAAI;EAC3B,KAAK;EACL,SAAS,EAAE,KAAK;EACjB,CAAC;;AAGJ,SAAgB,iBAAiB,MAAc,KAAkC;AAC/E,QAAO,IAAI,oBAAoB,0BAA0B,WAAW,QAAQ;EAC1E,KAAK,aAAa,KAAK,QAAQ,IAAI;EACnC,KAAK;EACL,SAAS;GAAE;GAAM;GAAK;EACvB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AQ;IAAiB,UAAU,QAAQ;IAAU,GAAG,EAAE;GAC5F;EACF,CAAC;;AAGJ,SAAgB,wBAAwB,OAA+C;AACrF,QAAO,IAAI,oBAAoB,kCAAkC,8BAA8B;EAC7F,KAAK,oEAAoE,MAAM,KAAK,KAAK,CAAC;EAC1F,KAAK;EACL,SAAS,EAAE,OAAO;EACnB,CAAC;;AAWJ,SAAgB,oBAAoB,UAAkB,QAAqC;AACzF,QAAO,IAAI,oBAAoB,8BAA8B,oBAAoB;EAC/E,KAAK,gBAAgB,SAAS,gBAAgB;EAC9C,KAAK;EACL,SAAS;GAAE,MAAM;GAAU;GAAQ;EACpC,CAAC;;AAGJ,SAAgB,oBAAoB,SAAsC;AACxE,QAAO,IAAI,oBAAoB,8BAA8B,oBAAoB;EAC/E,KAAK,aAAa,QAAQ;EAC1B,KAAK;EACL,SAAS,EAAE,SAAS;EACrB,CAAC;;AAGJ,SAAgB,cAAc,iBAAyD;AACrF,QAAO,IAAI,oBAAoB,uBAAuB,yCAAyC;EAC7F,KAAK,wGAAwG,gBAAgB,KAAK,KAAK,CAAC;EACxI,KAAK;EACL,SAAS,EAAE,iBAAiB;EAC7B,CAAC;;AAGJ,SAAgB,qBAAqB,OAAoC;AACvE,QAAO,IAAI,oBAAoB,+BAA+B,qBAAqB;EACjF,KAAK,cAAc,MAAM;EACzB,KAAK;EACL,SAAS,EAAE,OAAO;EACnB,CAAC;;AAGJ,SAAgB,0BAA0B,aAA0C;AAClF,QAAO,IAAI,oBACT,oCACA,4CACA;EACE,KAAK,0CAA0C,YAAY;EAC3D,KAAK;EACL,SAAS,EAAE,aAAa;EACzB,CACF"}
@@ -1,4 +1,4 @@
1
- import "../io-CCnYsUHU.mjs";
2
- import { n as verifyMigration, r as verifyMigrationBundle, t as computeMigrationId } from "../attestation-DtF8tEOM.mjs";
1
+ import "../io-Cd6GLyjK.mjs";
2
+ import { n as verifyMigration, r as verifyMigrationBundle, t as computeMigrationId } from "../attestation-BnzTb0Qp.mjs";
3
3
 
4
4
  export { computeMigrationId, verifyMigration, verifyMigrationBundle };
@@ -1,4 +1,4 @@
1
- import { h as errorSameSourceAndTarget, i as errorDuplicateMigrationId, m as errorNoTarget, n as errorAmbiguousTarget, p as errorNoInitialMigration } from "../errors-BKbRGCJM.mjs";
1
+ import { h as errorSameSourceAndTarget, i as errorDuplicateMigrationId, m as errorNoTarget, n as errorAmbiguousTarget, p as errorNoInitialMigration } from "../errors-BmiSgz1j.mjs";
2
2
  import { t as EMPTY_CONTRACT_HASH } from "../constants-BRi0X7B_.mjs";
3
3
  import { ifDefined } from "@prisma-next/utils/defined";
4
4
 
@@ -1,3 +1,3 @@
1
- import { a as writeMigrationManifest, i as readMigrationsDir, n as formatMigrationDirName, o as writeMigrationOps, r as readMigrationPackage, s as writeMigrationPackage, t as copyFilesWithRename } from "../io-CCnYsUHU.mjs";
1
+ import { a as writeMigrationManifest, i as readMigrationsDir, n as formatMigrationDirName, o as writeMigrationOps, r as readMigrationPackage, s as writeMigrationPackage, t as copyFilesWithRename } from "../io-Cd6GLyjK.mjs";
2
2
 
3
3
  export { copyFilesWithRename, formatMigrationDirName, readMigrationPackage, readMigrationsDir, writeMigrationManifest, writeMigrationOps, writeMigrationPackage };
@@ -1,5 +1,5 @@
1
- import "../io-CCnYsUHU.mjs";
2
- import { t as computeMigrationId } from "../attestation-DtF8tEOM.mjs";
1
+ import "../io-Cd6GLyjK.mjs";
2
+ import { t as computeMigrationId } from "../attestation-BnzTb0Qp.mjs";
3
3
  import { type } from "arktype";
4
4
  import { ifDefined } from "@prisma-next/utils/defined";
5
5
  import { realpathSync } from "node:fs";
@@ -1,10 +1,16 @@
1
1
  //#region src/refs.d.ts
2
- type Refs = Readonly<Record<string, string>>;
2
+ interface RefEntry {
3
+ readonly hash: string;
4
+ readonly invariants: readonly string[];
5
+ }
6
+ type Refs = Readonly<Record<string, RefEntry>>;
3
7
  declare function validateRefName(name: string): boolean;
4
8
  declare function validateRefValue(value: string): boolean;
5
- declare function readRefs(refsPath: string): Promise<Refs>;
6
- declare function writeRefs(refsPath: string, refs: Refs): Promise<void>;
7
- declare function resolveRef(refs: Refs, name: string): string;
9
+ declare function readRef(refsDir: string, name: string): Promise<RefEntry>;
10
+ declare function readRefs(refsDir: string): Promise<Refs>;
11
+ declare function writeRef(refsDir: string, name: string, entry: RefEntry): Promise<void>;
12
+ declare function deleteRef(refsDir: string, name: string): Promise<void>;
13
+ declare function resolveRef(refs: Refs, name: string): RefEntry;
8
14
  //#endregion
9
- export { type Refs, readRefs, resolveRef, validateRefName, validateRefValue, writeRefs };
15
+ export { type RefEntry, type Refs, deleteRef, readRef, readRefs, resolveRef, validateRefName, validateRefValue, writeRef };
10
16
  //# sourceMappingURL=refs.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"refs.d.mts","names":[],"sources":["../../src/refs.ts"],"sourcesContent":[],"mappings":";KAUY,IAAA,GAAO,SAAS;AAAhB,iBAKI,eAAA,CALW,IAAA,EAAA,MAAA,CAAA,EAAA,OAAA;AAKX,iBAQA,gBAAA,CARe,KAAA,EAAA,MAAA,CAAA,EAAA,OAAA;AAQf,iBAaM,QAAA,CAbU,QAAA,EAAA,MAAA,CAAA,EAakB,OAblB,CAa0B,IAb1B,CAAA;AAaV,iBA0BA,SAAA,CA1B4B,QAAO,EAAA,MAAA,EAAA,IAAA,EA0BD,IA1BC,CAAA,EA0BM,OA1BN,CAAA,IAAA,CAAA;AA0BnC,iBAoBN,UAAA,CApB+C,IAAA,EAoB9B,IApBqC,EAAA,IAAA,EAAA,MAAA,CAAA,EAAA,MAAA"}
1
+ {"version":3,"file":"refs.d.mts","names":[],"sources":["../../src/refs.ts"],"sourcesContent":[],"mappings":";UAUiB,QAAA;EAAA,SAAA,IAAQ,EAAA,MAAA;EAKb,SAAI,UAAA,EAAA,SAAA,MAAA,EAAA;;AAAY,KAAhB,IAAA,GAAO,QAAS,CAAA,MAAA,CAAA,MAAA,EAAe,QAAf,CAAA,CAAA;AAAT,iBAKH,eAAA,CALG,IAAA,EAAA,MAAA,CAAA,EAAA,OAAA;AAAQ,iBAaX,gBAAA,CAbW,KAAA,EAAA,MAAA,CAAA,EAAA,OAAA;AAKX,iBA8BM,OAAA,CA9BS,OAAA,EAAA,MAAA,EAAA,IAAA,EAAA,MAAA,CAAA,EA8B+B,OA9B/B,CA8BuC,QA9BvC,CAAA;AAQf,iBAyDM,QAAA,CAzDU,OAAA,EAAA,MAAA,CAAA,EAyDiB,OAzDjB,CAyDyB,IAzDzB,CAAA;AAsBV,iBAsFA,QAAA,CAtFgD,OAAR,EAAA,MAAO,EAAA,IAAA,EAAA,MAAA,EAAA,KAAA,EAsFA,QAtFA,CAAA,EAsFW,OAtFX,CAAA,IAAA,CAAA;AAmC/C,iBAuEA,SAAA,CAvE2B,OAAO,EAAA,MAAA,EAAA,IAAA,EAAA,MAAA,CAAA,EAuEQ,OAvER,CAAA,IAAA,CAAA;AAmDlC,iBA0DN,UAAA,CA1DqD,IAAW,EA0D/C,IA1DsD,EAAA,IAAA,EAAA,MAAA,CAAA,EA0DjC,QA1DiC"}
@@ -1,7 +1,7 @@
1
- import { c as errorInvalidRefName, l as errorInvalidRefValue, t as MigrationToolsError, u as errorInvalidRefs } from "../errors-BKbRGCJM.mjs";
2
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
1
+ import { c as errorInvalidRefFile, l as errorInvalidRefName, t as MigrationToolsError, u as errorInvalidRefValue } from "../errors-BmiSgz1j.mjs";
2
+ import { mkdir, readFile, readdir, rename, rmdir, unlink, writeFile } from "node:fs/promises";
3
3
  import { type } from "arktype";
4
- import { dirname, join } from "pathe";
4
+ import { dirname, join, relative } from "pathe";
5
5
 
6
6
  //#region src/refs.ts
7
7
  const REF_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\/[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
@@ -16,58 +16,134 @@ function validateRefName(name) {
16
16
  function validateRefValue(value) {
17
17
  return REF_VALUE_PATTERN.test(value);
18
18
  }
19
- const RefsSchema = type("Record<string, string>").narrow((refs, ctx) => {
20
- for (const [key, value] of Object.entries(refs)) {
21
- if (!validateRefName(key)) return ctx.mustBe(`valid ref names (invalid: "${key}")`);
22
- if (!validateRefValue(value)) return ctx.mustBe(`valid contract hashes (invalid value for "${key}": "${value}")`);
23
- }
19
+ const RefEntrySchema = type({
20
+ hash: "string",
21
+ invariants: "string[]"
22
+ }).narrow((entry, ctx) => {
23
+ if (!validateRefValue(entry.hash)) return ctx.mustBe(`a valid contract hash (got "${entry.hash}")`);
24
24
  return true;
25
25
  });
26
- async function readRefs(refsPath) {
26
+ function refFilePath(refsDir, name) {
27
+ return join(refsDir, `${name}.json`);
28
+ }
29
+ function refNameFromPath(refsDir, filePath) {
30
+ return relative(refsDir, filePath).replace(/\.json$/, "");
31
+ }
32
+ async function readRef(refsDir, name) {
33
+ if (!validateRefName(name)) throw errorInvalidRefName(name);
34
+ const filePath = refFilePath(refsDir, name);
27
35
  let raw;
28
36
  try {
29
- raw = await readFile(refsPath, "utf-8");
37
+ raw = await readFile(filePath, "utf-8");
30
38
  } catch (error) {
31
- if (error instanceof Error && error.code === "ENOENT") return {};
39
+ if (error instanceof Error && error.code === "ENOENT") throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
40
+ why: `No ref file found at "${filePath}".`,
41
+ fix: `Create the ref with: prisma-next migration ref set ${name} <hash>`,
42
+ details: {
43
+ refName: name,
44
+ filePath
45
+ }
46
+ });
32
47
  throw error;
33
48
  }
34
49
  let parsed;
35
50
  try {
36
51
  parsed = JSON.parse(raw);
37
52
  } catch {
38
- throw errorInvalidRefs(refsPath, "Failed to parse as JSON");
53
+ throw errorInvalidRefFile(filePath, "Failed to parse as JSON");
39
54
  }
40
- const result = RefsSchema(parsed);
41
- if (result instanceof type.errors) throw errorInvalidRefs(refsPath, result.summary);
55
+ const result = RefEntrySchema(parsed);
56
+ if (result instanceof type.errors) throw errorInvalidRefFile(filePath, result.summary);
42
57
  return result;
43
58
  }
44
- async function writeRefs(refsPath, refs) {
45
- for (const [key, value] of Object.entries(refs)) {
46
- if (!validateRefName(key)) throw errorInvalidRefName(key);
47
- if (!validateRefValue(value)) throw errorInvalidRefValue(value);
59
+ async function readRefs(refsDir) {
60
+ let entries;
61
+ try {
62
+ entries = await readdir(refsDir, {
63
+ recursive: true,
64
+ encoding: "utf-8"
65
+ });
66
+ } catch (error) {
67
+ if (error instanceof Error && error.code === "ENOENT") return {};
68
+ throw error;
69
+ }
70
+ const jsonFiles = entries.filter((entry) => entry.endsWith(".json"));
71
+ const refs = {};
72
+ for (const jsonFile of jsonFiles) {
73
+ const filePath = join(refsDir, jsonFile);
74
+ const name = refNameFromPath(refsDir, filePath);
75
+ let raw;
76
+ try {
77
+ raw = await readFile(filePath, "utf-8");
78
+ } catch (error) {
79
+ const code = error instanceof Error ? error.code : void 0;
80
+ if (code === "ENOENT" || code === "EISDIR") continue;
81
+ throw error;
82
+ }
83
+ let parsed;
84
+ try {
85
+ parsed = JSON.parse(raw);
86
+ } catch {
87
+ throw errorInvalidRefFile(filePath, "Failed to parse as JSON");
88
+ }
89
+ const result = RefEntrySchema(parsed);
90
+ if (result instanceof type.errors) throw errorInvalidRefFile(filePath, result.summary);
91
+ refs[name] = result;
48
92
  }
49
- const sorted = Object.fromEntries(Object.entries(refs).sort(([a], [b]) => a.localeCompare(b)));
50
- const dir = dirname(refsPath);
93
+ return refs;
94
+ }
95
+ async function writeRef(refsDir, name, entry) {
96
+ if (!validateRefName(name)) throw errorInvalidRefName(name);
97
+ if (!validateRefValue(entry.hash)) throw errorInvalidRefValue(entry.hash);
98
+ const filePath = refFilePath(refsDir, name);
99
+ const dir = dirname(filePath);
51
100
  await mkdir(dir, { recursive: true });
52
- const tmpPath = join(dir, `.refs.json.${Date.now()}.tmp`);
53
- await writeFile(tmpPath, `${JSON.stringify(sorted, null, 2)}\n`);
54
- await rename(tmpPath, refsPath);
101
+ const tmpPath = join(dir, `.${name.split("/").pop()}.json.${Date.now()}.tmp`);
102
+ await writeFile(tmpPath, `${JSON.stringify({
103
+ hash: entry.hash,
104
+ invariants: [...entry.invariants]
105
+ }, null, 2)}\n`);
106
+ await rename(tmpPath, filePath);
107
+ }
108
+ async function deleteRef(refsDir, name) {
109
+ if (!validateRefName(name)) throw errorInvalidRefName(name);
110
+ const filePath = refFilePath(refsDir, name);
111
+ try {
112
+ await unlink(filePath);
113
+ } catch (error) {
114
+ if (error instanceof Error && error.code === "ENOENT") throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
115
+ why: `No ref file found at "${filePath}".`,
116
+ fix: "Run `prisma-next migration ref list` to see available refs.",
117
+ details: {
118
+ refName: name,
119
+ filePath
120
+ }
121
+ });
122
+ throw error;
123
+ }
124
+ let dir = dirname(filePath);
125
+ while (dir !== refsDir && dir.startsWith(refsDir)) try {
126
+ await rmdir(dir);
127
+ dir = dirname(dir);
128
+ } catch (error) {
129
+ const code = error instanceof Error ? error.code : void 0;
130
+ if (code === "ENOTEMPTY" || code === "EEXIST" || code === "ENOENT") break;
131
+ throw error;
132
+ }
55
133
  }
56
134
  function resolveRef(refs, name) {
57
135
  if (!validateRefName(name)) throw errorInvalidRefName(name);
58
- const hash = refs[name];
59
- if (hash === void 0) throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
60
- why: `No ref named "${name}" exists in refs.json.`,
61
- fix: `Available refs: ${Object.keys(refs).join(", ") || "(none)"}. Create a ref with: set the "${name}" key in migrations/refs.json.`,
136
+ if (!Object.hasOwn(refs, name)) throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
137
+ why: `No ref named "${name}" exists.`,
138
+ fix: `Available refs: ${Object.keys(refs).join(", ") || "(none)"}. Create a ref with: prisma-next migration ref set ${name} <hash>`,
62
139
  details: {
63
140
  refName: name,
64
141
  availableRefs: Object.keys(refs)
65
142
  }
66
143
  });
67
- if (!validateRefValue(hash)) throw errorInvalidRefValue(hash);
68
- return hash;
144
+ return refs[name];
69
145
  }
70
146
 
71
147
  //#endregion
72
- export { readRefs, resolveRef, validateRefName, validateRefValue, writeRefs };
148
+ export { deleteRef, readRef, readRefs, resolveRef, validateRefName, validateRefValue, writeRef };
73
149
  //# sourceMappingURL=refs.mjs.map
@@ -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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AGjC,SAAgB,WAAW,MAAY,MAAsB;AAC3D,KAAI,CAAC,gBAAgB,KAAK,CACxB,OAAM,oBAAoB,KAAK;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;AA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,IAAI,WAAW,QAAQ,CAC/C,KAAI;AACF,QAAM,MAAM,IAAI;AAChB,QAAM,QAAQ,IAAI;UACX,OAAO;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"}
@@ -1,3 +1,3 @@
1
- import { t as MigrationToolsError } from "../errors-BKbRGCJM.mjs";
1
+ import { t as MigrationToolsError } from "../errors-BmiSgz1j.mjs";
2
2
 
3
3
  export { MigrationToolsError };
@@ -1,4 +1,4 @@
1
- import { a as errorInvalidDestName, d as errorInvalidSlug, f as errorMissingFile, o as errorInvalidJson, r as errorDirectoryExists, s as errorInvalidManifest } from "./errors-BKbRGCJM.mjs";
1
+ import { a as errorInvalidDestName, d as errorInvalidSlug, f as errorMissingFile, o as errorInvalidJson, r as errorDirectoryExists, s as errorInvalidManifest } from "./errors-BmiSgz1j.mjs";
2
2
  import { copyFile, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
3
3
  import { type } from "arktype";
4
4
  import { basename, dirname, join } from "pathe";
@@ -150,4 +150,4 @@ function formatMigrationDirName(timestamp, slug) {
150
150
 
151
151
  //#endregion
152
152
  export { writeMigrationManifest as a, readMigrationsDir as i, formatMigrationDirName as n, writeMigrationOps as o, readMigrationPackage as r, writeMigrationPackage as s, copyFilesWithRename as t };
153
- //# sourceMappingURL=io-CCnYsUHU.mjs.map
153
+ //# sourceMappingURL=io-Cd6GLyjK.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"io-CCnYsUHU.mjs","names":["manifestRaw: string","opsRaw: string","manifest: MigrationManifest","ops: MigrationOps","entries: string[]","packages: MigrationBundle[]"],"sources":["../src/io.ts"],"sourcesContent":["import { copyFile, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { type } from 'arktype';\nimport { basename, dirname, join } from 'pathe';\nimport {\n errorDirectoryExists,\n errorInvalidDestName,\n errorInvalidJson,\n errorInvalidManifest,\n errorInvalidSlug,\n errorMissingFile,\n} from './errors';\nimport type { MigrationBundle, MigrationManifest, MigrationOps } from './types';\n\nconst MANIFEST_FILE = 'migration.json';\nconst OPS_FILE = 'ops.json';\nconst MAX_SLUG_LENGTH = 64;\n\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n return error instanceof Error && (error as { code?: string }).code === code;\n}\n\nconst MigrationHintsSchema = type({\n used: 'string[]',\n applied: 'string[]',\n plannerVersion: 'string',\n});\n\nconst MigrationManifestSchema = type({\n from: 'string',\n to: 'string',\n migrationId: 'string',\n kind: \"'regular' | 'baseline'\",\n fromContract: 'object | null',\n toContract: 'object',\n hints: MigrationHintsSchema,\n labels: 'string[]',\n 'authorship?': type({\n 'author?': 'string',\n 'email?': 'string',\n }),\n 'signature?': type({\n keyId: 'string',\n value: 'string',\n }).or('null'),\n createdAt: 'string',\n});\n\nconst MigrationOpSchema = type({\n id: 'string',\n label: 'string',\n operationClass: \"'additive' | 'widening' | 'destructive' | 'data'\",\n});\n\n// Intentionally shallow: operation-specific payload validation is owned by planner/runner layers.\nconst MigrationOpsSchema = MigrationOpSchema.array();\n\nexport async function writeMigrationPackage(\n dir: string,\n manifest: MigrationManifest,\n ops: MigrationOps,\n): Promise<void> {\n await mkdir(dirname(dir), { recursive: true });\n\n try {\n await mkdir(dir);\n } catch (error) {\n if (hasErrnoCode(error, 'EEXIST')) {\n throw errorDirectoryExists(dir);\n }\n throw error;\n }\n\n await writeFile(join(dir, MANIFEST_FILE), JSON.stringify(manifest, null, 2), { flag: 'wx' });\n await writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2), { flag: 'wx' });\n}\n\n/**\n * Copy a list of files into `destDir`, optionally renaming each one.\n *\n * The destination directory is created (with `recursive: true`) if it\n * does not already exist. Each source path is copied byte-for-byte into\n * `destDir/<destName>`; missing sources throw `ENOENT`. The helper is\n * intentionally generic: callers own the list of files (e.g. a contract\n * emitter's emitted output) and the naming convention (e.g. renaming\n * the destination contract to `end-contract.*` and the source contract\n * to `start-contract.*`).\n */\nexport async function copyFilesWithRename(\n destDir: string,\n files: readonly { readonly sourcePath: string; readonly destName: string }[],\n): Promise<void> {\n await mkdir(destDir, { recursive: true });\n for (const file of files) {\n if (basename(file.destName) !== file.destName) {\n throw errorInvalidDestName(file.destName);\n }\n await copyFile(file.sourcePath, join(destDir, file.destName));\n }\n}\n\nexport async function writeMigrationManifest(\n dir: string,\n manifest: MigrationManifest,\n): Promise<void> {\n await writeFile(join(dir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`);\n}\n\nexport async function writeMigrationOps(dir: string, ops: MigrationOps): Promise<void> {\n await writeFile(join(dir, OPS_FILE), `${JSON.stringify(ops, null, 2)}\\n`);\n}\n\nexport async function readMigrationPackage(dir: string): Promise<MigrationBundle> {\n const manifestPath = join(dir, MANIFEST_FILE);\n const opsPath = join(dir, OPS_FILE);\n\n let manifestRaw: string;\n try {\n manifestRaw = await readFile(manifestPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorMissingFile(MANIFEST_FILE, dir);\n }\n throw error;\n }\n\n let opsRaw: string;\n try {\n opsRaw = await readFile(opsPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorMissingFile(OPS_FILE, dir);\n }\n throw error;\n }\n\n let manifest: MigrationManifest;\n try {\n manifest = JSON.parse(manifestRaw);\n } catch (e) {\n throw errorInvalidJson(manifestPath, e instanceof Error ? e.message : String(e));\n }\n\n let ops: MigrationOps;\n try {\n ops = JSON.parse(opsRaw);\n } catch (e) {\n throw errorInvalidJson(opsPath, e instanceof Error ? e.message : String(e));\n }\n\n validateManifest(manifest, manifestPath);\n validateOps(ops, opsPath);\n\n return {\n dirName: basename(dir),\n dirPath: dir,\n manifest,\n ops,\n };\n}\n\nfunction validateManifest(\n manifest: unknown,\n filePath: string,\n): asserts manifest is MigrationManifest {\n const result = MigrationManifestSchema(manifest);\n if (result instanceof type.errors) {\n throw errorInvalidManifest(filePath, result.summary);\n }\n}\n\nfunction validateOps(ops: unknown, filePath: string): asserts ops is MigrationOps {\n const result = MigrationOpsSchema(ops);\n if (result instanceof type.errors) {\n throw errorInvalidManifest(filePath, result.summary);\n }\n}\n\nexport async function readMigrationsDir(\n migrationsRoot: string,\n): Promise<readonly MigrationBundle[]> {\n let entries: string[];\n try {\n entries = await readdir(migrationsRoot);\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return [];\n }\n throw error;\n }\n\n const packages: MigrationBundle[] = [];\n\n for (const entry of entries.sort()) {\n const entryPath = join(migrationsRoot, entry);\n const entryStat = await stat(entryPath);\n if (!entryStat.isDirectory()) continue;\n\n const manifestPath = join(entryPath, MANIFEST_FILE);\n try {\n await stat(manifestPath);\n } catch {\n continue; // skip non-migration directories\n }\n\n packages.push(await readMigrationPackage(entryPath));\n }\n\n return packages;\n}\n\nexport function formatMigrationDirName(timestamp: Date, slug: string): string {\n const sanitized = slug\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '');\n\n if (sanitized.length === 0) {\n throw errorInvalidSlug(slug);\n }\n\n const truncated = sanitized.slice(0, MAX_SLUG_LENGTH);\n\n const y = timestamp.getUTCFullYear();\n const mo = String(timestamp.getUTCMonth() + 1).padStart(2, '0');\n const d = String(timestamp.getUTCDate()).padStart(2, '0');\n const h = String(timestamp.getUTCHours()).padStart(2, '0');\n const mi = String(timestamp.getUTCMinutes()).padStart(2, '0');\n\n return `${y}${mo}${d}T${h}${mi}_${truncated}`;\n}\n"],"mappings":";;;;;;AAaA,MAAM,gBAAgB;AACtB,MAAM,WAAW;AACjB,MAAM,kBAAkB;AAExB,SAAS,aAAa,OAAgB,MAAuB;AAC3D,QAAO,iBAAiB,SAAU,MAA4B,SAAS;;AASzE,MAAM,0BAA0B,KAAK;CACnC,MAAM;CACN,IAAI;CACJ,aAAa;CACb,MAAM;CACN,cAAc;CACd,YAAY;CACZ,OAb2B,KAAK;EAChC,MAAM;EACN,SAAS;EACT,gBAAgB;EACjB,CAAC;CAUA,QAAQ;CACR,eAAe,KAAK;EAClB,WAAW;EACX,UAAU;EACX,CAAC;CACF,cAAc,KAAK;EACjB,OAAO;EACP,OAAO;EACR,CAAC,CAAC,GAAG,OAAO;CACb,WAAW;CACZ,CAAC;AASF,MAAM,qBAPoB,KAAK;CAC7B,IAAI;CACJ,OAAO;CACP,gBAAgB;CACjB,CAAC,CAG2C,OAAO;AAEpD,eAAsB,sBACpB,KACA,UACA,KACe;AACf,OAAM,MAAM,QAAQ,IAAI,EAAE,EAAE,WAAW,MAAM,CAAC;AAE9C,KAAI;AACF,QAAM,MAAM,IAAI;UACT,OAAO;AACd,MAAI,aAAa,OAAO,SAAS,CAC/B,OAAM,qBAAqB,IAAI;AAEjC,QAAM;;AAGR,OAAM,UAAU,KAAK,KAAK,cAAc,EAAE,KAAK,UAAU,UAAU,MAAM,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAC5F,OAAM,UAAU,KAAK,KAAK,SAAS,EAAE,KAAK,UAAU,KAAK,MAAM,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;;;;;;;;;;;;;AAcpF,eAAsB,oBACpB,SACA,OACe;AACf,OAAM,MAAM,SAAS,EAAE,WAAW,MAAM,CAAC;AACz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"version":3,"file":"io-Cd6GLyjK.mjs","names":["manifestRaw: string","opsRaw: string","manifest: MigrationManifest","ops: MigrationOps","entries: string[]","packages: MigrationBundle[]"],"sources":["../src/io.ts"],"sourcesContent":["import { copyFile, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { type } from 'arktype';\nimport { basename, dirname, join } from 'pathe';\nimport {\n errorDirectoryExists,\n errorInvalidDestName,\n errorInvalidJson,\n errorInvalidManifest,\n errorInvalidSlug,\n errorMissingFile,\n} from './errors';\nimport type { MigrationBundle, MigrationManifest, MigrationOps } from './types';\n\nconst MANIFEST_FILE = 'migration.json';\nconst OPS_FILE = 'ops.json';\nconst MAX_SLUG_LENGTH = 64;\n\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n return error instanceof Error && (error as { code?: string }).code === code;\n}\n\nconst MigrationHintsSchema = type({\n used: 'string[]',\n applied: 'string[]',\n plannerVersion: 'string',\n});\n\nconst MigrationManifestSchema = type({\n from: 'string',\n to: 'string',\n migrationId: 'string',\n kind: \"'regular' | 'baseline'\",\n fromContract: 'object | null',\n toContract: 'object',\n hints: MigrationHintsSchema,\n labels: 'string[]',\n 'authorship?': type({\n 'author?': 'string',\n 'email?': 'string',\n }),\n 'signature?': type({\n keyId: 'string',\n value: 'string',\n }).or('null'),\n createdAt: 'string',\n});\n\nconst MigrationOpSchema = type({\n id: 'string',\n label: 'string',\n operationClass: \"'additive' | 'widening' | 'destructive' | 'data'\",\n});\n\n// Intentionally shallow: operation-specific payload validation is owned by planner/runner layers.\nconst MigrationOpsSchema = MigrationOpSchema.array();\n\nexport async function writeMigrationPackage(\n dir: string,\n manifest: MigrationManifest,\n ops: MigrationOps,\n): Promise<void> {\n await mkdir(dirname(dir), { recursive: true });\n\n try {\n await mkdir(dir);\n } catch (error) {\n if (hasErrnoCode(error, 'EEXIST')) {\n throw errorDirectoryExists(dir);\n }\n throw error;\n }\n\n await writeFile(join(dir, MANIFEST_FILE), JSON.stringify(manifest, null, 2), { flag: 'wx' });\n await writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2), { flag: 'wx' });\n}\n\n/**\n * Copy a list of files into `destDir`, optionally renaming each one.\n *\n * The destination directory is created (with `recursive: true`) if it\n * does not already exist. Each source path is copied byte-for-byte into\n * `destDir/<destName>`; missing sources throw `ENOENT`. The helper is\n * intentionally generic: callers own the list of files (e.g. a contract\n * emitter's emitted output) and the naming convention (e.g. renaming\n * the destination contract to `end-contract.*` and the source contract\n * to `start-contract.*`).\n */\nexport async function copyFilesWithRename(\n destDir: string,\n files: readonly { readonly sourcePath: string; readonly destName: string }[],\n): Promise<void> {\n await mkdir(destDir, { recursive: true });\n for (const file of files) {\n if (basename(file.destName) !== file.destName) {\n throw errorInvalidDestName(file.destName);\n }\n await copyFile(file.sourcePath, join(destDir, file.destName));\n }\n}\n\nexport async function writeMigrationManifest(\n dir: string,\n manifest: MigrationManifest,\n): Promise<void> {\n await writeFile(join(dir, MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`);\n}\n\nexport async function writeMigrationOps(dir: string, ops: MigrationOps): Promise<void> {\n await writeFile(join(dir, OPS_FILE), `${JSON.stringify(ops, null, 2)}\\n`);\n}\n\nexport async function readMigrationPackage(dir: string): Promise<MigrationBundle> {\n const manifestPath = join(dir, MANIFEST_FILE);\n const opsPath = join(dir, OPS_FILE);\n\n let manifestRaw: string;\n try {\n manifestRaw = await readFile(manifestPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorMissingFile(MANIFEST_FILE, dir);\n }\n throw error;\n }\n\n let opsRaw: string;\n try {\n opsRaw = await readFile(opsPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorMissingFile(OPS_FILE, dir);\n }\n throw error;\n }\n\n let manifest: MigrationManifest;\n try {\n manifest = JSON.parse(manifestRaw);\n } catch (e) {\n throw errorInvalidJson(manifestPath, e instanceof Error ? e.message : String(e));\n }\n\n let ops: MigrationOps;\n try {\n ops = JSON.parse(opsRaw);\n } catch (e) {\n throw errorInvalidJson(opsPath, e instanceof Error ? e.message : String(e));\n }\n\n validateManifest(manifest, manifestPath);\n validateOps(ops, opsPath);\n\n return {\n dirName: basename(dir),\n dirPath: dir,\n manifest,\n ops,\n };\n}\n\nfunction validateManifest(\n manifest: unknown,\n filePath: string,\n): asserts manifest is MigrationManifest {\n const result = MigrationManifestSchema(manifest);\n if (result instanceof type.errors) {\n throw errorInvalidManifest(filePath, result.summary);\n }\n}\n\nfunction validateOps(ops: unknown, filePath: string): asserts ops is MigrationOps {\n const result = MigrationOpsSchema(ops);\n if (result instanceof type.errors) {\n throw errorInvalidManifest(filePath, result.summary);\n }\n}\n\nexport async function readMigrationsDir(\n migrationsRoot: string,\n): Promise<readonly MigrationBundle[]> {\n let entries: string[];\n try {\n entries = await readdir(migrationsRoot);\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return [];\n }\n throw error;\n }\n\n const packages: MigrationBundle[] = [];\n\n for (const entry of entries.sort()) {\n const entryPath = join(migrationsRoot, entry);\n const entryStat = await stat(entryPath);\n if (!entryStat.isDirectory()) continue;\n\n const manifestPath = join(entryPath, MANIFEST_FILE);\n try {\n await stat(manifestPath);\n } catch {\n continue; // skip non-migration directories\n }\n\n packages.push(await readMigrationPackage(entryPath));\n }\n\n return packages;\n}\n\nexport function formatMigrationDirName(timestamp: Date, slug: string): string {\n const sanitized = slug\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '');\n\n if (sanitized.length === 0) {\n throw errorInvalidSlug(slug);\n }\n\n const truncated = sanitized.slice(0, MAX_SLUG_LENGTH);\n\n const y = timestamp.getUTCFullYear();\n const mo = String(timestamp.getUTCMonth() + 1).padStart(2, '0');\n const d = String(timestamp.getUTCDate()).padStart(2, '0');\n const h = String(timestamp.getUTCHours()).padStart(2, '0');\n const mi = String(timestamp.getUTCMinutes()).padStart(2, '0');\n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"module",
5
5
  "sideEffects": false,
6
6
  "description": "On-disk migration persistence, attestation, and chain reconstruction for Prisma Next",
@@ -8,9 +8,9 @@
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.3",
12
- "@prisma-next/framework-components": "0.5.0-dev.3",
13
- "@prisma-next/utils": "0.5.0-dev.3"
11
+ "@prisma-next/contract": "0.5.0-dev.4",
12
+ "@prisma-next/framework-components": "0.5.0-dev.4",
13
+ "@prisma-next/utils": "0.5.0-dev.4"
14
14
  },
15
15
  "devDependencies": {
16
16
  "tsdown": "0.18.4",
@@ -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/refs.ts CHANGED
@@ -1,14 +1,19 @@
1
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
1
+ import { mkdir, readdir, readFile, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
2
2
  import { type } from 'arktype';
3
- import { dirname, join } from 'pathe';
3
+ import { dirname, join, relative } from 'pathe';
4
4
  import {
5
+ errorInvalidRefFile,
5
6
  errorInvalidRefName,
6
- errorInvalidRefs,
7
7
  errorInvalidRefValue,
8
8
  MigrationToolsError,
9
9
  } from './errors';
10
10
 
11
- export type Refs = Readonly<Record<string, string>>;
11
+ export interface RefEntry {
12
+ readonly hash: string;
13
+ readonly invariants: readonly string[];
14
+ }
15
+
16
+ export type Refs = Readonly<Record<string, RefEntry>>;
12
17
 
13
18
  const REF_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\/[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
14
19
  const REF_VALUE_PATTERN = /^sha256:(empty|[0-9a-f]{64})$/;
@@ -25,22 +30,40 @@ export function validateRefValue(value: string): boolean {
25
30
  return REF_VALUE_PATTERN.test(value);
26
31
  }
27
32
 
28
- const RefsSchema = type('Record<string, string>').narrow((refs, ctx) => {
29
- for (const [key, value] of Object.entries(refs)) {
30
- if (!validateRefName(key)) return ctx.mustBe(`valid ref names (invalid: "${key}")`);
31
- if (!validateRefValue(value))
32
- return ctx.mustBe(`valid contract hashes (invalid value for "${key}": "${value}")`);
33
- }
33
+ const RefEntrySchema = type({
34
+ hash: 'string',
35
+ invariants: 'string[]',
36
+ }).narrow((entry, ctx) => {
37
+ if (!validateRefValue(entry.hash))
38
+ return ctx.mustBe(`a valid contract hash (got "${entry.hash}")`);
34
39
  return true;
35
40
  });
36
41
 
37
- export async function readRefs(refsPath: string): Promise<Refs> {
42
+ function refFilePath(refsDir: string, name: string): string {
43
+ return join(refsDir, `${name}.json`);
44
+ }
45
+
46
+ function refNameFromPath(refsDir: string, filePath: string): string {
47
+ const rel = relative(refsDir, filePath);
48
+ return rel.replace(/\.json$/, '');
49
+ }
50
+
51
+ export async function readRef(refsDir: string, name: string): Promise<RefEntry> {
52
+ if (!validateRefName(name)) {
53
+ throw errorInvalidRefName(name);
54
+ }
55
+
56
+ const filePath = refFilePath(refsDir, name);
38
57
  let raw: string;
39
58
  try {
40
- raw = await readFile(refsPath, 'utf-8');
59
+ raw = await readFile(filePath, 'utf-8');
41
60
  } catch (error) {
42
61
  if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
43
- return {};
62
+ throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref "${name}"`, {
63
+ why: `No ref file found at "${filePath}".`,
64
+ fix: `Create the ref with: prisma-next migration ref set ${name} <hash>`,
65
+ details: { refName: name, filePath },
66
+ });
44
67
  }
45
68
  throw error;
46
69
  }
@@ -49,54 +72,142 @@ export async function readRefs(refsPath: string): Promise<Refs> {
49
72
  try {
50
73
  parsed = JSON.parse(raw);
51
74
  } catch {
52
- throw errorInvalidRefs(refsPath, 'Failed to parse as JSON');
75
+ throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');
53
76
  }
54
77
 
55
- const result = RefsSchema(parsed);
78
+ const result = RefEntrySchema(parsed);
56
79
  if (result instanceof type.errors) {
57
- throw errorInvalidRefs(refsPath, result.summary);
80
+ throw errorInvalidRefFile(filePath, result.summary);
58
81
  }
59
82
 
60
83
  return result;
61
84
  }
62
85
 
63
- export async function writeRefs(refsPath: string, refs: Refs): Promise<void> {
64
- for (const [key, value] of Object.entries(refs)) {
65
- if (!validateRefName(key)) {
66
- throw errorInvalidRefName(key);
86
+ export async function readRefs(refsDir: string): Promise<Refs> {
87
+ let entries: string[];
88
+ try {
89
+ entries = await readdir(refsDir, { recursive: true, encoding: 'utf-8' });
90
+ } catch (error) {
91
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
92
+ return {};
93
+ }
94
+ throw error;
95
+ }
96
+
97
+ const jsonFiles = entries.filter((entry) => entry.endsWith('.json'));
98
+ const refs: Record<string, RefEntry> = {};
99
+
100
+ for (const jsonFile of jsonFiles) {
101
+ const filePath = join(refsDir, jsonFile);
102
+ const name = refNameFromPath(refsDir, filePath);
103
+
104
+ let raw: string;
105
+ try {
106
+ raw = await readFile(filePath, 'utf-8');
107
+ } catch (error) {
108
+ // Tolerate the TOCTOU race between `readdir` and `readFile` (ENOENT) and
109
+ // benign EISDIR if a directory happens to end in `.json`. Anything else
110
+ // (EACCES, EIO, EMFILE, …) is a real failure and propagates so the CLI
111
+ // surfaces it rather than silently dropping the ref.
112
+ const code = error instanceof Error ? (error as { code?: string }).code : undefined;
113
+ if (code === 'ENOENT' || code === 'EISDIR') {
114
+ continue;
115
+ }
116
+ throw error;
117
+ }
118
+
119
+ let parsed: unknown;
120
+ try {
121
+ parsed = JSON.parse(raw);
122
+ } catch {
123
+ throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');
67
124
  }
68
- if (!validateRefValue(value)) {
69
- throw errorInvalidRefValue(value);
125
+
126
+ const result = RefEntrySchema(parsed);
127
+ if (result instanceof type.errors) {
128
+ throw errorInvalidRefFile(filePath, result.summary);
70
129
  }
130
+
131
+ refs[name] = result;
71
132
  }
72
133
 
73
- const sorted = Object.fromEntries(Object.entries(refs).sort(([a], [b]) => a.localeCompare(b)));
134
+ return refs;
135
+ }
136
+
137
+ export async function writeRef(refsDir: string, name: string, entry: RefEntry): Promise<void> {
138
+ if (!validateRefName(name)) {
139
+ throw errorInvalidRefName(name);
140
+ }
141
+ if (!validateRefValue(entry.hash)) {
142
+ throw errorInvalidRefValue(entry.hash);
143
+ }
74
144
 
75
- const dir = dirname(refsPath);
145
+ const filePath = refFilePath(refsDir, name);
146
+ const dir = dirname(filePath);
76
147
  await mkdir(dir, { recursive: true });
77
148
 
78
- const tmpPath = join(dir, `.refs.json.${Date.now()}.tmp`);
79
- await writeFile(tmpPath, `${JSON.stringify(sorted, null, 2)}\n`);
80
- await rename(tmpPath, refsPath);
149
+ const tmpPath = join(dir, `.${name.split('/').pop()}.json.${Date.now()}.tmp`);
150
+ await writeFile(
151
+ tmpPath,
152
+ `${JSON.stringify({ hash: entry.hash, invariants: [...entry.invariants] }, null, 2)}\n`,
153
+ );
154
+ await rename(tmpPath, filePath);
81
155
  }
82
156
 
83
- export function resolveRef(refs: Refs, name: string): string {
157
+ export async function deleteRef(refsDir: string, name: string): Promise<void> {
84
158
  if (!validateRefName(name)) {
85
159
  throw errorInvalidRefName(name);
86
160
  }
87
161
 
88
- const hash = refs[name];
89
- if (hash === undefined) {
162
+ const filePath = refFilePath(refsDir, name);
163
+ try {
164
+ await unlink(filePath);
165
+ } catch (error) {
166
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
167
+ throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref "${name}"`, {
168
+ why: `No ref file found at "${filePath}".`,
169
+ fix: 'Run `prisma-next migration ref list` to see available refs.',
170
+ details: { refName: name, filePath },
171
+ });
172
+ }
173
+ throw error;
174
+ }
175
+
176
+ // Clean empty parent directories up to refsDir. Stop walking on the expected
177
+ // "directory has siblings" signal (ENOTEMPTY on Linux, EEXIST on some BSDs)
178
+ // and on ENOENT (concurrent removal). Anything else (EACCES, EIO, …) is a
179
+ // real failure and propagates.
180
+ let dir = dirname(filePath);
181
+ while (dir !== refsDir && dir.startsWith(refsDir)) {
182
+ try {
183
+ await rmdir(dir);
184
+ dir = dirname(dir);
185
+ } catch (error) {
186
+ const code = error instanceof Error ? (error as { code?: string }).code : undefined;
187
+ if (code === 'ENOTEMPTY' || code === 'EEXIST' || code === 'ENOENT') {
188
+ break;
189
+ }
190
+ throw error;
191
+ }
192
+ }
193
+ }
194
+
195
+ export function resolveRef(refs: Refs, name: string): RefEntry {
196
+ if (!validateRefName(name)) {
197
+ throw errorInvalidRefName(name);
198
+ }
199
+
200
+ // Object.hasOwn gate: plain-object `refs` would otherwise let
201
+ // `refs['constructor']` return Object.prototype.constructor and bypass the
202
+ // UNKNOWN_REF throw. validateRefName accepts `"constructor"` as a name shape.
203
+ if (!Object.hasOwn(refs, name)) {
90
204
  throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref "${name}"`, {
91
- why: `No ref named "${name}" exists in refs.json.`,
92
- fix: `Available refs: ${Object.keys(refs).join(', ') || '(none)'}. Create a ref with: set the "${name}" key in migrations/refs.json.`,
205
+ why: `No ref named "${name}" exists.`,
206
+ fix: `Available refs: ${Object.keys(refs).join(', ') || '(none)'}. Create a ref with: prisma-next migration ref set ${name} <hash>`,
93
207
  details: { refName: name, availableRefs: Object.keys(refs) },
94
208
  });
95
209
  }
96
210
 
97
- if (!validateRefValue(hash)) {
98
- throw errorInvalidRefValue(hash);
99
- }
100
-
101
- return hash;
211
+ // biome-ignore lint/style/noNonNullAssertion: Object.hasOwn gate above guarantees this is defined
212
+ return refs[name]!;
102
213
  }