prisma-next 0.5.0-dev.73 → 0.5.0-dev.75

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 (92) hide show
  1. package/dist/cli.mjs +8 -8
  2. package/dist/{client-0ZX24FXF.mjs → client-qVH-rEgd.mjs} +433 -236
  3. package/dist/client-qVH-rEgd.mjs.map +1 -0
  4. package/dist/{result-handler-DWb1rFS-.mjs → command-helpers-BeZHkxV8.mjs} +22 -24
  5. package/dist/command-helpers-BeZHkxV8.mjs.map +1 -0
  6. package/dist/commands/contract-emit.mjs +1 -1
  7. package/dist/commands/contract-infer.mjs +1 -1
  8. package/dist/commands/db-init.d.mts.map +1 -1
  9. package/dist/commands/db-init.mjs +7 -5
  10. package/dist/commands/db-init.mjs.map +1 -1
  11. package/dist/commands/db-schema.mjs +5 -4
  12. package/dist/commands/db-schema.mjs.map +1 -1
  13. package/dist/commands/db-sign.mjs +6 -5
  14. package/dist/commands/db-sign.mjs.map +1 -1
  15. package/dist/commands/db-update.d.mts.map +1 -1
  16. package/dist/commands/db-update.mjs +7 -5
  17. package/dist/commands/db-update.mjs.map +1 -1
  18. package/dist/commands/db-verify.mjs +1 -1
  19. package/dist/commands/migration-apply.d.mts +29 -17
  20. package/dist/commands/migration-apply.d.mts.map +1 -1
  21. package/dist/commands/migration-apply.mjs +35 -129
  22. package/dist/commands/migration-apply.mjs.map +1 -1
  23. package/dist/commands/migration-new.mjs +4 -3
  24. package/dist/commands/migration-new.mjs.map +1 -1
  25. package/dist/commands/migration-plan.d.mts +19 -1
  26. package/dist/commands/migration-plan.d.mts.map +1 -1
  27. package/dist/commands/migration-plan.mjs +2 -2
  28. package/dist/commands/migration-ref.d.mts +1 -1
  29. package/dist/commands/migration-ref.mjs +3 -2
  30. package/dist/commands/migration-ref.mjs.map +1 -1
  31. package/dist/commands/migration-show.d.mts +1 -1
  32. package/dist/commands/migration-show.mjs +5 -4
  33. package/dist/commands/migration-show.mjs.map +1 -1
  34. package/dist/commands/migration-status.d.mts +104 -1
  35. package/dist/commands/migration-status.d.mts.map +1 -1
  36. package/dist/commands/migration-status.mjs +2 -2
  37. package/dist/{contract-emit-DkMqO7f2.mjs → contract-emit-9DBda5Ou.mjs} +7 -5
  38. package/dist/{contract-emit-DkMqO7f2.mjs.map → contract-emit-9DBda5Ou.mjs.map} +1 -1
  39. package/dist/{contract-emit-B3ChISB_.mjs → contract-emit-B77TsJqf.mjs} +4 -15
  40. package/dist/{contract-emit-B3ChISB_.mjs.map → contract-emit-B77TsJqf.mjs.map} +1 -1
  41. package/dist/{contract-enrichment-CF6ogEJ_.mjs → contract-enrichment-Dani0mMW.mjs} +1 -1
  42. package/dist/{contract-enrichment-CF6ogEJ_.mjs.map → contract-enrichment-Dani0mMW.mjs.map} +1 -1
  43. package/dist/{contract-infer-BDKAE0B0.mjs → contract-infer-BK9YFGEG.mjs} +5 -4
  44. package/dist/{contract-infer-BDKAE0B0.mjs.map → contract-infer-BK9YFGEG.mjs.map} +1 -1
  45. package/dist/{db-verify-B4TdDKOI.mjs → db-verify-C0y1PCO2.mjs} +7 -6
  46. package/dist/{db-verify-B4TdDKOI.mjs.map → db-verify-C0y1PCO2.mjs.map} +1 -1
  47. package/dist/exports/control-api.d.mts +3 -746
  48. package/dist/exports/control-api.d.mts.map +1 -1
  49. package/dist/exports/control-api.mjs +3 -3
  50. package/dist/exports/index.mjs +1 -1
  51. package/dist/exports/init-output.mjs +1 -1
  52. package/dist/extension-pack-inputs-C7xgE-vv.mjs +74 -0
  53. package/dist/extension-pack-inputs-C7xgE-vv.mjs.map +1 -0
  54. package/dist/{framework-components-gwAHl7ml.mjs → framework-components-ChqVUxR-.mjs} +1 -1
  55. package/dist/{framework-components-gwAHl7ml.mjs.map → framework-components-ChqVUxR-.mjs.map} +1 -1
  56. package/dist/global-flags-Icqpxk23.d.mts +12 -0
  57. package/dist/global-flags-Icqpxk23.d.mts.map +1 -0
  58. package/dist/helpers-eqdN8tH6.mjs +25 -0
  59. package/dist/helpers-eqdN8tH6.mjs.map +1 -0
  60. package/dist/{init-Deo7U8_U.mjs → init-CoDVPvQ4.mjs} +4 -4
  61. package/dist/{init-Deo7U8_U.mjs.map → init-CoDVPvQ4.mjs.map} +1 -1
  62. package/dist/{inspect-live-schema-BAgQMYpD.mjs → inspect-live-schema-CWYxGKlb.mjs} +4 -4
  63. package/dist/{inspect-live-schema-BAgQMYpD.mjs.map → inspect-live-schema-CWYxGKlb.mjs.map} +1 -1
  64. package/dist/{migration-command-scaffold-B8J702Uh.mjs → migration-command-scaffold-B5dORFEv.mjs} +4 -4
  65. package/dist/{migration-command-scaffold-B8J702Uh.mjs.map → migration-command-scaffold-B5dORFEv.mjs.map} +1 -1
  66. package/dist/{migration-plan-BcKNnTM7.mjs → migration-plan-C6lVaHsO.mjs} +47 -23
  67. package/dist/migration-plan-C6lVaHsO.mjs.map +1 -0
  68. package/dist/{migration-status-CjwB2of-.mjs → migration-status-CZ-D5k7k.mjs} +161 -7
  69. package/dist/migration-status-CZ-D5k7k.mjs.map +1 -0
  70. package/dist/{migrations-CIK94AJf.mjs → migrations-D_UJnpuW.mjs} +67 -24
  71. package/dist/migrations-D_UJnpuW.mjs.map +1 -0
  72. package/dist/{output-DnjfCC_u.mjs → output-B16Kefzx.mjs} +1 -1
  73. package/dist/{output-DnjfCC_u.mjs.map → output-B16Kefzx.mjs.map} +1 -1
  74. package/dist/{progress-adapter-xASh41wr.mjs → progress-adapter-DFfvZcYL.mjs} +1 -1
  75. package/dist/{progress-adapter-xASh41wr.mjs.map → progress-adapter-DFfvZcYL.mjs.map} +1 -1
  76. package/dist/result-handler-rmPVKIP2.mjs +25 -0
  77. package/dist/result-handler-rmPVKIP2.mjs.map +1 -0
  78. package/dist/rolldown-runtime-twds-ZHy.mjs +14 -0
  79. package/dist/{terminal-ui-zaRDhJnP.mjs → terminal-ui-C_hFNbAn.mjs} +3 -23
  80. package/dist/terminal-ui-C_hFNbAn.mjs.map +1 -0
  81. package/dist/types-D7x-IFLO.d.mts +858 -0
  82. package/dist/types-D7x-IFLO.d.mts.map +1 -0
  83. package/dist/{verify-BEIa9638.mjs → verify-CiwNWM9N.mjs} +2 -2
  84. package/dist/{verify-BEIa9638.mjs.map → verify-CiwNWM9N.mjs.map} +1 -1
  85. package/package.json +10 -10
  86. package/dist/client-0ZX24FXF.mjs.map +0 -1
  87. package/dist/migration-plan-BcKNnTM7.mjs.map +0 -1
  88. package/dist/migration-status-CjwB2of-.mjs.map +0 -1
  89. package/dist/migrations-CIK94AJf.mjs.map +0 -1
  90. package/dist/result-handler-DWb1rFS-.mjs.map +0 -1
  91. package/dist/terminal-ui-zaRDhJnP.mjs.map +0 -1
  92. /package/dist/{cli-errors-QH8kf-C2.d.mts → cli-errors-B9OBbled.d.mts} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-D7x-IFLO.d.mts","names":[],"sources":["../src/control-api/operations/db-verify.ts","../src/control-api/types.ts"],"mappings":";;;;;;;;;;;;;;AAwCA;;;;;UAAiB,sBAAA;EAAA,SACN,MAAA,EAAQ,qBAAA,CAAsB,SAAA,EAAW,SAAA;EAAA,SACzC,cAAA,EAAgB,qBAAA,CAAsB,SAAA;EAAA,SACtC,QAAA,EAAU,QAAA;EAAA,SACV,aAAA;EAAA,SACA,QAAA,EAAU,SAAA;EAAA,SACV,cAAA,EAAgB,aAAA,CAAc,0BAAA,CAA2B,SAAA,EAAW,SAAA;EAAA,SACpE,mBAAA,EAAqB,aAAA,CAAc,8BAAA,CAA+B,SAAA,EAAW,SAAA;EAAA,SAC7E,IAAA;EAAA,SACA,UAAA;EAAA,SACA,UAAA;EAAA,SACA,UAAA,GAAa,iBAAA;AAAA;;;;;;;;;;;;;UAeP,sBAAA;EAAA,SACN,aAAA,EAAe,WAAA,SAAoB,0BAAA;EAAA,SACnC,WAAA;EAAA,SACA,UAAA;AAAA;AAAA,KAGC,qBAAA,GAAwB,MAAA,CAAO,sBAAA,EAAwB,kBAAA;;;;;;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AA,CAAS,OAAA,EAAS,eAAA,GAAkB,OAAA,CAAQ,cAAA;;;;;;;;;;;;;;EAe5C,QAAA,CAAS,OAAA,EAAS,eAAA,GAAkB,OAAA,CAAQ,qBAAA;;;;;;;EAQ5C,UAAA,IAAc,OAAA,CAAQ,oBAAA;;;;;;EAOtB,cAAA,IAAkB,OAAA,CAAQ,WAAA,SAAoB,oBAAA;;;;;;;;;;;;EAa9C,cAAA,CAAe,OAAA,EAAS,qBAAA,GAAwB,OAAA,CAAQ,oBAAA;;;;;;;EAQxD,UAAA,CAAW,OAAA,GAAU,iBAAA,GAAoB,OAAA;;;;;;;;EASzC,YAAA,CAAa,QAAA,YAAoB,cAAA;;;;;;;;EASjC,gBAAA,CAAiB,QAAA,YAAoB,cAAA;;;;;;;;;EAUrC,kBAAA,CAAmB,UAAA,WAAqB,sBAAA,KAA2B,gBAAA;;;;;;;;EASnE,IAAA,CAAK,OAAA,EAAS,WAAA,GAAc,OAAA,CAAQ,UAAA;AAAA"}
@@ -1,4 +1,4 @@
1
- import { a as createColorFormatter, o as formatDim, s as isVerbose } from "./terminal-ui-zaRDhJnP.mjs";
1
+ import { n as formatDim, r as isVerbose, t as createColorFormatter } from "./helpers-eqdN8tH6.mjs";
2
2
  import { ifDefined } from "@prisma-next/utils/defined";
3
3
  import { bold, cyan, dim, green, magenta, red, yellow } from "colorette";
4
4
  //#region src/utils/formatters/verify.ts
@@ -381,4 +381,4 @@ function formatSignJson(result) {
381
381
  //#endregion
382
382
  export { formatSignJson as a, formatVerifyOutput as c, formatSchemaVerifyOutput as i, formatIntrospectOutput as n, formatSignOutput as o, formatSchemaVerifyJson as r, formatVerifyJson as s, formatIntrospectJson as t };
383
383
 
384
- //# sourceMappingURL=verify-BEIa9638.mjs.map
384
+ //# sourceMappingURL=verify-CiwNWM9N.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"verify-BEIa9638.mjs","names":[],"sources":["../src/utils/formatters/verify.ts"],"sourcesContent":["import type {\n CoreSchemaView,\n IntrospectSchemaResult,\n SchemaTreeNode,\n SchemaVerificationNode,\n SignDatabaseResult,\n VerifyDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { bold, cyan, dim, green, magenta, red, yellow } from 'colorette';\nimport type { GlobalFlags } from '../global-flags';\nimport { createColorFormatter, formatDim, isVerbose } from './helpers';\n\n// ============================================================================\n// Verify Output Formatters\n// ============================================================================\n\nexport interface DbVerifyCommandSuccessResult {\n readonly ok: true;\n readonly mode: 'full' | 'marker-only';\n readonly summary: string;\n readonly contract: VerifyDatabaseResult['contract'];\n readonly marker?: VerifyDatabaseResult['marker'];\n readonly target: VerifyDatabaseResult['target'];\n readonly missingCodecs?: VerifyDatabaseResult['missingCodecs'];\n readonly codecCoverageSkipped?: VerifyDatabaseResult['codecCoverageSkipped'];\n readonly schema?: {\n readonly summary: string;\n readonly counts: VerifyDatabaseSchemaResult['schema']['counts'];\n readonly strict: boolean;\n };\n readonly warning?: string;\n readonly meta?:\n | (NonNullable<VerifyDatabaseResult['meta']> & {\n readonly schemaVerification: 'performed' | 'skipped';\n })\n | {\n readonly schemaVerification: 'performed' | 'skipped';\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\n/**\n * Formats human-readable output for database verify.\n */\nexport function formatVerifyOutput(\n result: DbVerifyCommandSuccessResult,\n flags: GlobalFlags,\n): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n const useColor = flags.color !== false;\n const formatGreen = createColorFormatter(useColor, green);\n const formatYellow = createColorFormatter(useColor, yellow);\n const formatDimText = (text: string) => formatDim(useColor, text);\n const verificationMode =\n result.mode === 'full'\n ? `marker + schema${result.schema?.strict ? ' (strict)' : ' (tolerant)'}`\n : 'marker only (--marker-only)';\n\n lines.push(`${formatGreen('✔')} ${result.summary}`);\n lines.push(`${formatDimText(` verification: ${verificationMode}`)}`);\n lines.push(`${formatDimText(` storageHash: ${result.contract.storageHash}`)}`);\n if (result.contract.profileHash) {\n lines.push(`${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);\n }\n if (result.mode === 'full' && result.schema && isVerbose(flags, 1)) {\n lines.push(\n `${formatDimText(` schema: pass=${result.schema.counts.pass} warn=${result.schema.counts.warn} fail=${result.schema.counts.fail}`)}`,\n );\n }\n if (result.warning) {\n lines.push('');\n lines.push(`${formatYellow('⚠')} ${result.warning}`);\n }\n\n if (isVerbose(flags, 1)) {\n if (result.codecCoverageSkipped) {\n lines.push(\n `${formatDimText(' Codec coverage check skipped (helper returned no supported types)')}`,\n );\n }\n lines.push(`${formatDimText(` Total time: ${result.timings.total}ms`)}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for database verify.\n */\nexport function formatVerifyJson(result: DbVerifyCommandSuccessResult): string {\n const output = {\n ok: result.ok,\n summary: result.summary,\n mode: result.mode,\n contract: result.contract,\n ...ifDefined('marker', result.marker),\n target: result.target,\n ...ifDefined('missingCodecs', result.missingCodecs),\n ...ifDefined('codecCoverageSkipped', result.codecCoverageSkipped),\n ...ifDefined('schema', result.schema),\n ...ifDefined('warning', result.warning),\n ...ifDefined('meta', result.meta),\n timings: result.timings,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Formats JSON output for database introspection.\n */\nexport function formatIntrospectJson(result: IntrospectSchemaResult<unknown>): string {\n return JSON.stringify(result, null, 2);\n}\n\n/**\n * Renders a schema tree structure from CoreSchemaView.\n * Matches the style of renderSchemaVerificationTree for consistency.\n */\nfunction renderSchemaTree(\n node: SchemaTreeNode,\n flags: GlobalFlags,\n options: {\n readonly isLast: boolean;\n readonly prefix: string;\n readonly useColor: boolean;\n readonly formatDimText: (text: string) => string;\n readonly isRoot?: boolean;\n },\n): string[] {\n const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;\n const lines: string[] = [];\n\n // Format node label with color based on kind (matching schema-verify style)\n let formattedLabel: string = node.label;\n\n if (useColor) {\n switch (node.kind) {\n case 'root':\n formattedLabel = bold(node.label);\n break;\n case 'entity': {\n // Parse \"table tableName\" format - color \"table\" dim, tableName cyan\n const tableMatch = node.label.match(/^table\\s+(.+)$/);\n if (tableMatch?.[1]) {\n const tableName = tableMatch[1];\n formattedLabel = `${dim('table')} ${cyan(tableName)}`;\n } else {\n // Fallback: color entire label with cyan\n formattedLabel = cyan(node.label);\n }\n break;\n }\n case 'collection': {\n // \"columns\" grouping node - dim the label\n formattedLabel = dim(node.label);\n break;\n }\n case 'field': {\n // Parse column name format: \"columnName: typeDisplay (nullability)\"\n // Color code: column name (cyan), type (default), nullability (dim)\n const columnMatch = node.label.match(/^([^:]+):\\s*(.+)$/);\n if (columnMatch?.[1] && columnMatch[2]) {\n const columnName = columnMatch[1];\n const rest = columnMatch[2];\n // Parse rest: \"typeDisplay (nullability)\"\n const typeMatch = rest.match(/^([^\\s(]+)\\s*(\\([^)]+\\))$/);\n if (typeMatch?.[1] && typeMatch[2]) {\n const typeDisplay = typeMatch[1];\n const nullability = typeMatch[2];\n formattedLabel = `${cyan(columnName)}: ${typeDisplay} ${dim(nullability)}`;\n } else {\n // Fallback if format doesn't match\n formattedLabel = `${cyan(columnName)}: ${rest}`;\n }\n } else {\n formattedLabel = node.label;\n }\n break;\n }\n case 'index': {\n // Parse index/unique constraint/primary key formats\n // \"primary key: columnName\" -> dim \"primary key\", cyan columnName\n const pkMatch = node.label.match(/^primary key:\\s*(.+)$/);\n if (pkMatch?.[1]) {\n const columnNames = pkMatch[1];\n formattedLabel = `${dim('primary key')}: ${cyan(columnNames)}`;\n } else {\n // \"unique name\" -> dim \"unique\", cyan \"name\"\n const uniqueMatch = node.label.match(/^unique\\s+(.+)$/);\n if (uniqueMatch?.[1]) {\n const name = uniqueMatch[1];\n formattedLabel = `${dim('unique')} ${cyan(name)}`;\n } else {\n // \"index name\" or \"unique index name\" -> dim label prefix, cyan name\n const indexMatch = node.label.match(/^(unique\\s+)?index\\s+(.+)$/);\n if (indexMatch?.[2]) {\n const indexPrefix = indexMatch[1] ? `${dim('unique')} ` : '';\n const name = indexMatch[2];\n formattedLabel = `${indexPrefix}${dim('index')} ${cyan(name)}`;\n } else {\n formattedLabel = dim(node.label);\n }\n }\n }\n break;\n }\n case 'dependency': {\n // Parse extension message formats similar to schema-verify\n // \"extensionName extension is enabled\" -> cyan extensionName, dim rest\n const extMatch = node.label.match(/^([^\\s]+)\\s+(extension is enabled)$/);\n if (extMatch?.[1] && extMatch[2]) {\n const extName = extMatch[1];\n const rest = extMatch[2];\n formattedLabel = `${cyan(extName)} ${dim(rest)}`;\n } else {\n // Fallback: color entire label with magenta\n formattedLabel = magenta(node.label);\n }\n break;\n }\n default:\n formattedLabel = node.label;\n break;\n }\n }\n\n // Root node renders without tree characters or prefix\n if (isRoot) {\n lines.push(formattedLabel);\n } else {\n const treeChar = isLast ? '└' : '├';\n const treePrefix = `${formatDimText(treeChar)}─ `;\n lines.push(`${prefix}${treePrefix}${formattedLabel}`);\n }\n\n // Render children if present\n if (node.children && node.children.length > 0) {\n const childPrefix = isRoot ? '' : `${prefix}${isLast ? ' ' : `${formatDimText('│')} `}`;\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n if (!child) continue;\n const isLastChild = i === node.children.length - 1;\n const childLines = renderSchemaTree(child, flags, {\n isLast: isLastChild,\n prefix: childPrefix,\n useColor,\n formatDimText,\n isRoot: false,\n });\n lines.push(...childLines);\n }\n }\n\n return lines;\n}\n\n/**\n * Formats human-readable output for database introspection.\n */\nexport function formatIntrospectOutput(\n result: IntrospectSchemaResult<unknown>,\n schemaView: CoreSchemaView | undefined,\n flags: GlobalFlags,\n): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n const useColor = flags.color !== false;\n const formatDimText = (text: string) => formatDim(useColor, text);\n\n if (schemaView) {\n // Render tree structure - root node is special (no tree characters)\n const treeLines = renderSchemaTree(schemaView.root, flags, {\n isLast: true,\n prefix: '',\n useColor,\n formatDimText,\n isRoot: true,\n });\n lines.push(...treeLines);\n } else {\n // Fallback: print summary when toSchemaView is not available\n lines.push(`✔ ${result.summary}`);\n if (isVerbose(flags, 1)) {\n lines.push(` Target: ${result.target.familyId}/${result.target.id}`);\n if (result.meta?.dbUrl) {\n lines.push(` Database: ${result.meta.dbUrl}`);\n }\n }\n }\n\n // Add timings in verbose mode\n if (isVerbose(flags, 1)) {\n lines.push(`${formatDimText(` Total time: ${result.timings.total}ms`)}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Renders a schema verification tree structure from SchemaVerificationNode.\n * Similar to renderSchemaTree but for verification nodes with status-based colors and glyphs.\n */\nfunction renderSchemaVerificationTree(\n node: SchemaVerificationNode,\n flags: GlobalFlags,\n options: {\n readonly isLast: boolean;\n readonly prefix: string;\n readonly useColor: boolean;\n readonly formatDimText: (text: string) => string;\n readonly isRoot?: boolean;\n },\n): string[] {\n const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;\n const lines: string[] = [];\n\n // Format status glyph and color based on status\n let statusGlyph = '';\n let statusColor: (text: string) => string = (text) => text;\n if (useColor) {\n switch (node.status) {\n case 'pass':\n statusGlyph = '✔';\n statusColor = green;\n break;\n case 'warn':\n statusGlyph = '⚠';\n statusColor = (text) => (useColor ? yellow(text) : text);\n break;\n case 'fail':\n statusGlyph = '✖';\n statusColor = red;\n break;\n }\n } else {\n switch (node.status) {\n case 'pass':\n statusGlyph = '✔';\n break;\n case 'warn':\n statusGlyph = '⚠';\n break;\n case 'fail':\n statusGlyph = '✖';\n break;\n }\n }\n\n // Format node label with color based on kind\n // For column nodes, we need to parse the name to color code different parts\n let labelColor: (text: string) => string = (text) => text;\n let formattedLabel: string = node.name;\n\n if (useColor) {\n switch (node.kind) {\n case 'contract':\n case 'schema':\n labelColor = bold;\n formattedLabel = labelColor(node.name);\n break;\n case 'table': {\n // Parse \"table tableName\" format - color \"table\" dim, tableName cyan\n const tableMatch = node.name.match(/^table\\s+(.+)$/);\n if (tableMatch?.[1]) {\n const tableName = tableMatch[1];\n formattedLabel = `${dim('table')} ${cyan(tableName)}`;\n } else {\n formattedLabel = dim(node.name);\n }\n break;\n }\n case 'columns':\n labelColor = dim;\n formattedLabel = labelColor(node.name);\n break;\n case 'column': {\n // Parse column name format: \"columnName: contractType -> nativeType (nullability)\"\n // Color code: column name (cyan), contract type (default), native type (dim), nullability (dim)\n const columnMatch = node.name.match(/^([^:]+):\\s*(.+)$/);\n if (columnMatch?.[1] && columnMatch[2]) {\n const columnName = columnMatch[1];\n const rest = columnMatch[2];\n // Parse rest: \"contractType -> nativeType (nullability)\"\n // Match contract type (can contain /, @, etc.), arrow, native type, then nullability in parentheses\n const typeMatch = rest.match(/^([^\\s→]+)\\s*→\\s*([^\\s(]+)\\s*(\\([^)]+\\))$/);\n if (typeMatch?.[1] && typeMatch[2] && typeMatch[3]) {\n const contractType = typeMatch[1];\n const nativeType = typeMatch[2];\n const nullability = typeMatch[3];\n formattedLabel = `${cyan(columnName)}: ${contractType} → ${dim(nativeType)} ${dim(nullability)}`;\n } else {\n // Fallback if format doesn't match (e.g., no native type or no nullability)\n formattedLabel = `${cyan(columnName)}: ${rest}`;\n }\n } else {\n formattedLabel = node.name;\n }\n break;\n }\n case 'type':\n case 'nullability':\n labelColor = (text) => text; // Default color\n formattedLabel = labelColor(node.name);\n break;\n case 'primaryKey': {\n // Parse \"primary key: columnName\" format - color \"primary key\" dim, columnName cyan\n const pkMatch = node.name.match(/^primary key:\\s*(.+)$/);\n if (pkMatch?.[1]) {\n const columnNames = pkMatch[1];\n formattedLabel = `${dim('primary key')}: ${cyan(columnNames)}`;\n } else {\n formattedLabel = dim(node.name);\n }\n break;\n }\n case 'foreignKey':\n case 'unique':\n case 'index':\n labelColor = dim;\n formattedLabel = labelColor(node.name);\n break;\n case 'dependency': {\n // Parse specific extension message formats\n // \"database is postgres\" -> dim \"database is\", cyan \"postgres\"\n const dbMatch = node.name.match(/^database is\\s+(.+)$/);\n if (dbMatch?.[1]) {\n const dbName = dbMatch[1];\n formattedLabel = `${dim('database is')} ${cyan(dbName)}`;\n } else {\n // \"vector extension is enabled\" -> dim everything except extension name\n // Match pattern: \"extensionName extension is enabled\"\n const extMatch = node.name.match(/^([^\\s]+)\\s+(extension is enabled)$/);\n if (extMatch?.[1] && extMatch[2]) {\n const extName = extMatch[1];\n const rest = extMatch[2];\n formattedLabel = `${cyan(extName)} ${dim(rest)}`;\n } else {\n // Fallback: color entire name with magenta\n labelColor = magenta;\n formattedLabel = labelColor(node.name);\n }\n }\n break;\n }\n default:\n formattedLabel = node.name;\n break;\n }\n } else {\n formattedLabel = node.name;\n }\n\n const statusGlyphColored = statusColor(statusGlyph);\n\n // Build the label with optional message for failure/warn nodes\n let nodeLabel = formattedLabel;\n if (\n (node.status === 'fail' || node.status === 'warn') &&\n node.message &&\n node.message.length > 0\n ) {\n // Always show message for failure/warn nodes - it provides crucial context\n // For parent nodes, the message summarizes child failures\n // For leaf nodes, the message explains the specific issue\n const messageText = formatDimText(`(${node.message})`);\n nodeLabel = `${formattedLabel} ${messageText}`;\n }\n\n // Root node renders without tree characters or | prefix\n // Root node renders without tree characters or prefix\n if (isRoot) {\n lines.push(`${statusGlyphColored} ${nodeLabel}`);\n } else {\n const treeChar = isLast ? '└' : '├';\n const treePrefix = `${formatDimText(treeChar)}─ `;\n lines.push(`${prefix}${treePrefix}${statusGlyphColored} ${nodeLabel}`);\n }\n\n // Render children if present\n if (node.children && node.children.length > 0) {\n const childPrefix = isRoot ? '' : `${prefix}${isLast ? ' ' : `${formatDimText('│')} `}`;\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n if (!child) continue;\n const isLastChild = i === node.children.length - 1;\n const childLines = renderSchemaVerificationTree(child, flags, {\n isLast: isLastChild,\n prefix: childPrefix,\n useColor,\n formatDimText,\n isRoot: false,\n });\n lines.push(...childLines);\n }\n }\n\n return lines;\n}\n\n/**\n * Formats human-readable output for database schema verification.\n */\nexport function formatSchemaVerifyOutput(\n result: VerifyDatabaseSchemaResult,\n flags: GlobalFlags,\n): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n const useColor = flags.color !== false;\n const formatGreen = createColorFormatter(useColor, green);\n const formatRed = createColorFormatter(useColor, red);\n const formatDimText = (text: string) => formatDim(useColor, text);\n\n // Render verification tree first\n const treeLines = renderSchemaVerificationTree(result.schema.root, flags, {\n isLast: true,\n prefix: '',\n useColor,\n formatDimText,\n isRoot: true,\n });\n lines.push(...treeLines);\n\n // Add counts and timings in verbose mode\n if (isVerbose(flags, 1)) {\n lines.push(`${formatDimText(` Total time: ${result.timings.total}ms`)}`);\n lines.push(\n `${formatDimText(` pass=${result.schema.counts.pass} warn=${result.schema.counts.warn} fail=${result.schema.counts.fail}`)}`,\n );\n }\n\n // Blank line before summary\n lines.push('');\n\n // Summary line at the end: summary with status glyph\n if (result.ok) {\n lines.push(`${formatGreen('✔')} ${result.summary}`);\n } else {\n const codeText = result.code ? ` (${result.code})` : '';\n lines.push(`${formatRed('✖')} ${result.summary}${codeText}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for database schema verification.\n */\nexport function formatSchemaVerifyJson(result: VerifyDatabaseSchemaResult): string {\n return JSON.stringify(result, null, 2);\n}\n\n// ============================================================================\n// Sign Output Formatters\n// ============================================================================\n\n/**\n * Formats human-readable output for database sign.\n */\nexport function formatSignOutput(result: SignDatabaseResult, flags: GlobalFlags): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n const useColor = flags.color !== false;\n const formatGreen = createColorFormatter(useColor, green);\n const formatDimText = (text: string) => formatDim(useColor, text);\n\n if (result.ok) {\n // Main success message in white (not dimmed)\n lines.push(`${formatGreen('✔')} Database signed`);\n\n // Show from -> to hashes with clear labels\n const previousHash = result.marker.previous?.storageHash ?? 'none';\n const currentHash = result.contract.storageHash;\n\n lines.push(`${formatDimText(` from: ${previousHash}`)}`);\n lines.push(`${formatDimText(` to: ${currentHash}`)}`);\n\n if (isVerbose(flags, 1)) {\n if (result.contract.profileHash) {\n lines.push(`${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);\n }\n if (result.marker.previous?.profileHash) {\n lines.push(\n `${formatDimText(` previous profileHash: ${result.marker.previous.profileHash}`)}`,\n );\n }\n lines.push(`${formatDimText(` Total time: ${result.timings.total}ms`)}`);\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for database sign.\n */\nexport function formatSignJson(result: SignDatabaseResult): string {\n return JSON.stringify(result, null, 2);\n}\n"],"mappings":";;;;;;;AAgDA,SAAgB,mBACd,QACA,OACQ;CACR,IAAI,MAAM,OACR,OAAO;CAGT,MAAM,QAAkB,EAAE;CAE1B,MAAM,WAAW,MAAM,UAAU;CACjC,MAAM,cAAc,qBAAqB,UAAU,MAAM;CACzD,MAAM,eAAe,qBAAqB,UAAU,OAAO;CAC3D,MAAM,iBAAiB,SAAiB,UAAU,UAAU,KAAK;CACjE,MAAM,mBACJ,OAAO,SAAS,SACZ,kBAAkB,OAAO,QAAQ,SAAS,cAAc,kBACxD;CAEN,MAAM,KAAK,GAAG,YAAY,IAAI,CAAC,GAAG,OAAO,UAAU;CACnD,MAAM,KAAK,GAAG,cAAc,mBAAmB,mBAAmB,GAAG;CACrE,MAAM,KAAK,GAAG,cAAc,kBAAkB,OAAO,SAAS,cAAc,GAAG;CAC/E,IAAI,OAAO,SAAS,aAClB,MAAM,KAAK,GAAG,cAAc,kBAAkB,OAAO,SAAS,cAAc,GAAG;CAEjF,IAAI,OAAO,SAAS,UAAU,OAAO,UAAU,UAAU,OAAO,EAAE,EAChE,MAAM,KACJ,GAAG,cAAc,kBAAkB,OAAO,OAAO,OAAO,KAAK,QAAQ,OAAO,OAAO,OAAO,KAAK,QAAQ,OAAO,OAAO,OAAO,OAAO,GACpI;CAEH,IAAI,OAAO,SAAS;EAClB,MAAM,KAAK,GAAG;EACd,MAAM,KAAK,GAAG,aAAa,IAAI,CAAC,GAAG,OAAO,UAAU;;CAGtD,IAAI,UAAU,OAAO,EAAE,EA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View,\n IntrospectSchemaResult,\n SchemaTreeNode,\n SchemaVerificationNode,\n SignDatabaseResult,\n VerifyDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { bold, cyan, dim, green, magenta, red, yellow } from 'colorette';\nimport type { GlobalFlags } from '../global-flags';\nimport { createColorFormatter, formatDim, isVerbose } from './helpers';\n\n// ============================================================================\n// Verify Output Formatters\n// ============================================================================\n\nexport interface DbVerifyCommandSuccessResult {\n readonly ok: true;\n readonly mode: 'full' | 'marker-only';\n readonly summary: string;\n readonly contract: VerifyDatabaseResult['contract'];\n readonly marker?: VerifyDatabaseResult['marker'];\n readonly target: VerifyDatabaseResult['target'];\n readonly missingCodecs?: VerifyDatabaseResult['missingCodecs'];\n readonly codecCoverageSkipped?: VerifyDatabaseResult['codecCoverageSkipped'];\n readonly schema?: {\n readonly summary: string;\n readonly counts: VerifyDatabaseSchemaResult['schema']['counts'];\n readonly strict: boolean;\n };\n readonly warning?: string;\n readonly meta?:\n | (NonNullable<VerifyDatabaseResult['meta']> & {\n readonly schemaVerification: 'performed' | 'skipped';\n })\n | {\n readonly schemaVerification: 'performed' | 'skipped';\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\n/**\n * Formats human-readable output for database verify.\n */\nexport function formatVerifyOutput(\n result: DbVerifyCommandSuccessResult,\n flags: GlobalFlags,\n): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n const useColor = flags.color !== false;\n const formatGreen = createColorFormatter(useColor, green);\n const formatYellow = createColorFormatter(useColor, yellow);\n const formatDimText = (text: string) => formatDim(useColor, text);\n const verificationMode =\n result.mode === 'full'\n ? `marker + schema${result.schema?.strict ? ' (strict)' : ' (tolerant)'}`\n : 'marker only (--marker-only)';\n\n lines.push(`${formatGreen('✔')} ${result.summary}`);\n lines.push(`${formatDimText(` verification: ${verificationMode}`)}`);\n lines.push(`${formatDimText(` storageHash: ${result.contract.storageHash}`)}`);\n if (result.contract.profileHash) {\n lines.push(`${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);\n }\n if (result.mode === 'full' && result.schema && isVerbose(flags, 1)) {\n lines.push(\n `${formatDimText(` schema: pass=${result.schema.counts.pass} warn=${result.schema.counts.warn} fail=${result.schema.counts.fail}`)}`,\n );\n }\n if (result.warning) {\n lines.push('');\n lines.push(`${formatYellow('⚠')} ${result.warning}`);\n }\n\n if (isVerbose(flags, 1)) {\n if (result.codecCoverageSkipped) {\n lines.push(\n `${formatDimText(' Codec coverage check skipped (helper returned no supported types)')}`,\n );\n }\n lines.push(`${formatDimText(` Total time: ${result.timings.total}ms`)}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for database verify.\n */\nexport function formatVerifyJson(result: DbVerifyCommandSuccessResult): string {\n const output = {\n ok: result.ok,\n summary: result.summary,\n mode: result.mode,\n contract: result.contract,\n ...ifDefined('marker', result.marker),\n target: result.target,\n ...ifDefined('missingCodecs', result.missingCodecs),\n ...ifDefined('codecCoverageSkipped', result.codecCoverageSkipped),\n ...ifDefined('schema', result.schema),\n ...ifDefined('warning', result.warning),\n ...ifDefined('meta', result.meta),\n timings: result.timings,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Formats JSON output for database introspection.\n */\nexport function formatIntrospectJson(result: IntrospectSchemaResult<unknown>): string {\n return JSON.stringify(result, null, 2);\n}\n\n/**\n * Renders a schema tree structure from CoreSchemaView.\n * Matches the style of renderSchemaVerificationTree for consistency.\n */\nfunction renderSchemaTree(\n node: SchemaTreeNode,\n flags: GlobalFlags,\n options: {\n readonly isLast: boolean;\n readonly prefix: string;\n readonly useColor: boolean;\n readonly formatDimText: (text: string) => string;\n readonly isRoot?: boolean;\n },\n): string[] {\n const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;\n const lines: string[] = [];\n\n // Format node label with color based on kind (matching schema-verify style)\n let formattedLabel: string = node.label;\n\n if (useColor) {\n switch (node.kind) {\n case 'root':\n formattedLabel = bold(node.label);\n break;\n case 'entity': {\n // Parse \"table tableName\" format - color \"table\" dim, tableName cyan\n const tableMatch = node.label.match(/^table\\s+(.+)$/);\n if (tableMatch?.[1]) {\n const tableName = tableMatch[1];\n formattedLabel = `${dim('table')} ${cyan(tableName)}`;\n } else {\n // Fallback: color entire label with cyan\n formattedLabel = cyan(node.label);\n }\n break;\n }\n case 'collection': {\n // \"columns\" grouping node - dim the label\n formattedLabel = dim(node.label);\n break;\n }\n case 'field': {\n // Parse column name format: \"columnName: typeDisplay (nullability)\"\n // Color code: column name (cyan), type (default), nullability (dim)\n const columnMatch = node.label.match(/^([^:]+):\\s*(.+)$/);\n if (columnMatch?.[1] && columnMatch[2]) {\n const columnName = columnMatch[1];\n const rest = columnMatch[2];\n // Parse rest: \"typeDisplay (nullability)\"\n const typeMatch = rest.match(/^([^\\s(]+)\\s*(\\([^)]+\\))$/);\n if (typeMatch?.[1] && typeMatch[2]) {\n const typeDisplay = typeMatch[1];\n const nullability = typeMatch[2];\n formattedLabel = `${cyan(columnName)}: ${typeDisplay} ${dim(nullability)}`;\n } else {\n // Fallback if format doesn't match\n formattedLabel = `${cyan(columnName)}: ${rest}`;\n }\n } else {\n formattedLabel = node.label;\n }\n break;\n }\n case 'index': {\n // Parse index/unique constraint/primary key formats\n // \"primary key: columnName\" -> dim \"primary key\", cyan columnName\n const pkMatch = node.label.match(/^primary key:\\s*(.+)$/);\n if (pkMatch?.[1]) {\n const columnNames = pkMatch[1];\n formattedLabel = `${dim('primary key')}: ${cyan(columnNames)}`;\n } else {\n // \"unique name\" -> dim \"unique\", cyan \"name\"\n const uniqueMatch = node.label.match(/^unique\\s+(.+)$/);\n if (uniqueMatch?.[1]) {\n const name = uniqueMatch[1];\n formattedLabel = `${dim('unique')} ${cyan(name)}`;\n } else {\n // \"index name\" or \"unique index name\" -> dim label prefix, cyan name\n const indexMatch = node.label.match(/^(unique\\s+)?index\\s+(.+)$/);\n if (indexMatch?.[2]) {\n const indexPrefix = indexMatch[1] ? `${dim('unique')} ` : '';\n const name = indexMatch[2];\n formattedLabel = `${indexPrefix}${dim('index')} ${cyan(name)}`;\n } else {\n formattedLabel = dim(node.label);\n }\n }\n }\n break;\n }\n case 'dependency': {\n // Parse extension message formats similar to schema-verify\n // \"extensionName extension is enabled\" -> cyan extensionName, dim rest\n const extMatch = node.label.match(/^([^\\s]+)\\s+(extension is enabled)$/);\n if (extMatch?.[1] && extMatch[2]) {\n const extName = extMatch[1];\n const rest = extMatch[2];\n formattedLabel = `${cyan(extName)} ${dim(rest)}`;\n } else {\n // Fallback: color entire label with magenta\n formattedLabel = magenta(node.label);\n }\n break;\n }\n default:\n formattedLabel = node.label;\n break;\n }\n }\n\n // Root node renders without tree characters or prefix\n if (isRoot) {\n lines.push(formattedLabel);\n } else {\n const treeChar = isLast ? '└' : '├';\n const treePrefix = `${formatDimText(treeChar)}─ `;\n lines.push(`${prefix}${treePrefix}${formattedLabel}`);\n }\n\n // Render children if present\n if (node.children && node.children.length > 0) {\n const childPrefix = isRoot ? '' : `${prefix}${isLast ? ' ' : `${formatDimText('│')} `}`;\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n if (!child) continue;\n const isLastChild = i === node.children.length - 1;\n const childLines = renderSchemaTree(child, flags, {\n isLast: isLastChild,\n prefix: childPrefix,\n useColor,\n formatDimText,\n isRoot: false,\n });\n lines.push(...childLines);\n }\n }\n\n return lines;\n}\n\n/**\n * Formats human-readable output for database introspection.\n */\nexport function formatIntrospectOutput(\n result: IntrospectSchemaResult<unknown>,\n schemaView: CoreSchemaView | undefined,\n flags: GlobalFlags,\n): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n const useColor = flags.color !== false;\n const formatDimText = (text: string) => formatDim(useColor, text);\n\n if (schemaView) {\n // Render tree structure - root node is special (no tree characters)\n const treeLines = renderSchemaTree(schemaView.root, flags, {\n isLast: true,\n prefix: '',\n useColor,\n formatDimText,\n isRoot: true,\n });\n lines.push(...treeLines);\n } else {\n // Fallback: print summary when toSchemaView is not available\n lines.push(`✔ ${result.summary}`);\n if (isVerbose(flags, 1)) {\n lines.push(` Target: ${result.target.familyId}/${result.target.id}`);\n if (result.meta?.dbUrl) {\n lines.push(` Database: ${result.meta.dbUrl}`);\n }\n }\n }\n\n // Add timings in verbose mode\n if (isVerbose(flags, 1)) {\n lines.push(`${formatDimText(` Total time: ${result.timings.total}ms`)}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Renders a schema verification tree structure from SchemaVerificationNode.\n * Similar to renderSchemaTree but for verification nodes with status-based colors and glyphs.\n */\nfunction renderSchemaVerificationTree(\n node: SchemaVerificationNode,\n flags: GlobalFlags,\n options: {\n readonly isLast: boolean;\n readonly prefix: string;\n readonly useColor: boolean;\n readonly formatDimText: (text: string) => string;\n readonly isRoot?: boolean;\n },\n): string[] {\n const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;\n const lines: string[] = [];\n\n // Format status glyph and color based on status\n let statusGlyph = '';\n let statusColor: (text: string) => string = (text) => text;\n if (useColor) {\n switch (node.status) {\n case 'pass':\n statusGlyph = '✔';\n statusColor = green;\n break;\n case 'warn':\n statusGlyph = '⚠';\n statusColor = (text) => (useColor ? yellow(text) : text);\n break;\n case 'fail':\n statusGlyph = '✖';\n statusColor = red;\n break;\n }\n } else {\n switch (node.status) {\n case 'pass':\n statusGlyph = '✔';\n break;\n case 'warn':\n statusGlyph = '⚠';\n break;\n case 'fail':\n statusGlyph = '✖';\n break;\n }\n }\n\n // Format node label with color based on kind\n // For column nodes, we need to parse the name to color code different parts\n let labelColor: (text: string) => string = (text) => text;\n let formattedLabel: string = node.name;\n\n if (useColor) {\n switch (node.kind) {\n case 'contract':\n case 'schema':\n labelColor = bold;\n formattedLabel = labelColor(node.name);\n break;\n case 'table': {\n // Parse \"table tableName\" format - color \"table\" dim, tableName cyan\n const tableMatch = node.name.match(/^table\\s+(.+)$/);\n if (tableMatch?.[1]) {\n const tableName = tableMatch[1];\n formattedLabel = `${dim('table')} ${cyan(tableName)}`;\n } else {\n formattedLabel = dim(node.name);\n }\n break;\n }\n case 'columns':\n labelColor = dim;\n formattedLabel = labelColor(node.name);\n break;\n case 'column': {\n // Parse column name format: \"columnName: contractType -> nativeType (nullability)\"\n // Color code: column name (cyan), contract type (default), native type (dim), nullability (dim)\n const columnMatch = node.name.match(/^([^:]+):\\s*(.+)$/);\n if (columnMatch?.[1] && columnMatch[2]) {\n const columnName = columnMatch[1];\n const rest = columnMatch[2];\n // Parse rest: \"contractType -> nativeType (nullability)\"\n // Match contract type (can contain /, @, etc.), arrow, native type, then nullability in parentheses\n const typeMatch = rest.match(/^([^\\s→]+)\\s*→\\s*([^\\s(]+)\\s*(\\([^)]+\\))$/);\n if (typeMatch?.[1] && typeMatch[2] && typeMatch[3]) {\n const contractType = typeMatch[1];\n const nativeType = typeMatch[2];\n const nullability = typeMatch[3];\n formattedLabel = `${cyan(columnName)}: ${contractType} → ${dim(nativeType)} ${dim(nullability)}`;\n } else {\n // Fallback if format doesn't match (e.g., no native type or no nullability)\n formattedLabel = `${cyan(columnName)}: ${rest}`;\n }\n } else {\n formattedLabel = node.name;\n }\n break;\n }\n case 'type':\n case 'nullability':\n labelColor = (text) => text; // Default color\n formattedLabel = labelColor(node.name);\n break;\n case 'primaryKey': {\n // Parse \"primary key: columnName\" format - color \"primary key\" dim, columnName cyan\n const pkMatch = node.name.match(/^primary key:\\s*(.+)$/);\n if (pkMatch?.[1]) {\n const columnNames = pkMatch[1];\n formattedLabel = `${dim('primary key')}: ${cyan(columnNames)}`;\n } else {\n formattedLabel = dim(node.name);\n }\n break;\n }\n case 'foreignKey':\n case 'unique':\n case 'index':\n labelColor = dim;\n formattedLabel = labelColor(node.name);\n break;\n case 'dependency': {\n // Parse specific extension message formats\n // \"database is postgres\" -> dim \"database is\", cyan \"postgres\"\n const dbMatch = node.name.match(/^database is\\s+(.+)$/);\n if (dbMatch?.[1]) {\n const dbName = dbMatch[1];\n formattedLabel = `${dim('database is')} ${cyan(dbName)}`;\n } else {\n // \"vector extension is enabled\" -> dim everything except extension name\n // Match pattern: \"extensionName extension is enabled\"\n const extMatch = node.name.match(/^([^\\s]+)\\s+(extension is enabled)$/);\n if (extMatch?.[1] && extMatch[2]) {\n const extName = extMatch[1];\n const rest = extMatch[2];\n formattedLabel = `${cyan(extName)} ${dim(rest)}`;\n } else {\n // Fallback: color entire name with magenta\n labelColor = magenta;\n formattedLabel = labelColor(node.name);\n }\n }\n break;\n }\n default:\n formattedLabel = node.name;\n break;\n }\n } else {\n formattedLabel = node.name;\n }\n\n const statusGlyphColored = statusColor(statusGlyph);\n\n // Build the label with optional message for failure/warn nodes\n let nodeLabel = formattedLabel;\n if (\n (node.status === 'fail' || node.status === 'warn') &&\n node.message &&\n node.message.length > 0\n ) {\n // Always show message for failure/warn nodes - it provides crucial context\n // For parent nodes, the message summarizes child failures\n // For leaf nodes, the message explains the specific issue\n const messageText = formatDimText(`(${node.message})`);\n nodeLabel = `${formattedLabel} ${messageText}`;\n }\n\n // Root node renders without tree characters or | prefix\n // Root node renders without tree characters or prefix\n if (isRoot) {\n lines.push(`${statusGlyphColored} ${nodeLabel}`);\n } else {\n const treeChar = isLast ? '└' : '├';\n const treePrefix = `${formatDimText(treeChar)}─ `;\n lines.push(`${prefix}${treePrefix}${statusGlyphColored} ${nodeLabel}`);\n }\n\n // Render children if present\n if (node.children && node.children.length > 0) {\n const childPrefix = isRoot ? '' : `${prefix}${isLast ? ' ' : `${formatDimText('│')} `}`;\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n if (!child) continue;\n const isLastChild = i === node.children.length - 1;\n const childLines = renderSchemaVerificationTree(child, flags, {\n isLast: isLastChild,\n prefix: childPrefix,\n useColor,\n formatDimText,\n isRoot: false,\n });\n lines.push(...childLines);\n }\n }\n\n return lines;\n}\n\n/**\n * Formats human-readable output for database schema verification.\n */\nexport function formatSchemaVerifyOutput(\n result: VerifyDatabaseSchemaResult,\n flags: GlobalFlags,\n): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n const useColor = flags.color !== false;\n const formatGreen = createColorFormatter(useColor, green);\n const formatRed = createColorFormatter(useColor, red);\n const formatDimText = (text: string) => formatDim(useColor, text);\n\n // Render verification tree first\n const treeLines = renderSchemaVerificationTree(result.schema.root, flags, {\n isLast: true,\n prefix: '',\n useColor,\n formatDimText,\n isRoot: true,\n });\n lines.push(...treeLines);\n\n // Add counts and timings in verbose mode\n if (isVerbose(flags, 1)) {\n lines.push(`${formatDimText(` Total time: ${result.timings.total}ms`)}`);\n lines.push(\n `${formatDimText(` pass=${result.schema.counts.pass} warn=${result.schema.counts.warn} fail=${result.schema.counts.fail}`)}`,\n );\n }\n\n // Blank line before summary\n lines.push('');\n\n // Summary line at the end: summary with status glyph\n if (result.ok) {\n lines.push(`${formatGreen('✔')} ${result.summary}`);\n } else {\n const codeText = result.code ? ` (${result.code})` : '';\n lines.push(`${formatRed('✖')} ${result.summary}${codeText}`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for database schema verification.\n */\nexport function formatSchemaVerifyJson(result: VerifyDatabaseSchemaResult): string {\n return JSON.stringify(result, null, 2);\n}\n\n// ============================================================================\n// Sign Output Formatters\n// ============================================================================\n\n/**\n * Formats human-readable output for database sign.\n */\nexport function formatSignOutput(result: SignDatabaseResult, flags: GlobalFlags): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n const useColor = flags.color !== false;\n const formatGreen = createColorFormatter(useColor, green);\n const formatDimText = (text: string) => formatDim(useColor, text);\n\n if (result.ok) {\n // Main success message in white (not dimmed)\n lines.push(`${formatGreen('✔')} Database signed`);\n\n // Show from -> to hashes with clear labels\n const previousHash = result.marker.previous?.storageHash ?? 'none';\n const currentHash = result.contract.storageHash;\n\n lines.push(`${formatDimText(` from: ${previousHash}`)}`);\n lines.push(`${formatDimText(` to: ${currentHash}`)}`);\n\n if (isVerbose(flags, 1)) {\n if (result.contract.profileHash) {\n lines.push(`${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);\n }\n if (result.marker.previous?.profileHash) {\n lines.push(\n `${formatDimText(` previous profileHash: ${result.marker.previous.profileHash}`)}`,\n );\n }\n lines.push(`${formatDimText(` Total time: ${result.timings.total}ms`)}`);\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for database sign.\n */\nexport function formatSignJson(result: SignDatabaseResult): string {\n return JSON.stringify(result, null, 2);\n}\n"],"mappings":";;;;;;;AAgDA,SAAgB,mBACd,QACA,OACQ;CACR,IAAI,MAAM,OACR,OAAO;CAGT,MAAM,QAAkB,EAAE;CAE1B,MAAM,WAAW,MAAM,UAAU;CACjC,MAAM,cAAc,qBAAqB,UAAU,MAAM;CACzD,MAAM,eAAe,qBAAqB,UAAU,OAAO;CAC3D,MAAM,iBAAiB,SAAiB,UAAU,UAAU,KAAK;CACjE,MAAM,mBACJ,OAAO,SAAS,SACZ,kBAAkB,OAAO,QAAQ,SAAS,cAAc,kBACxD;CAEN,MAAM,KAAK,GAAG,YAAY,IAAI,CAAC,GAAG,OAAO,UAAU;CACnD,MAAM,KAAK,GAAG,cAAc,mBAAmB,mBAAmB,GAAG;CACrE,MAAM,KAAK,GAAG,cAAc,kBAAkB,OAAO,SAAS,cAAc,GAAG;CAC/E,IAAI,OAAO,SAAS,aAClB,MAAM,KAAK,GAAG,cAAc,kBAAkB,OAAO,SAAS,cAAc,GAAG;CAEjF,IAAI,OAAO,SAAS,UAAU,OAAO,UAAU,UAAU,OAAO,EAAE,EAChE,MAAM,KACJ,GAAG,cAAc,kBAAkB,OAAO,OAAO,OAAO,KAAK,QAAQ,OAAO,OAAO,OAAO,KAAK,QAAQ,OAAO,OAAO,OAAO,OAAO,GACpI;CAEH,IAAI,OAAO,SAAS;EAClB,MAAM,KAAK,GAAG;EACd,MAAM,KAAK,GAAG,aAAa,IAAI,CAAC,GAAG,OAAO,UAAU;;CAGtD,IAAI,UAAU,OAAO,EAAE,EAA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.5.0-dev.75",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -27,17 +27,17 @@
27
27
  "string-width": "^8.2.1",
28
28
  "strip-ansi": "^7.2.0",
29
29
  "wrap-ansi": "^10.0.0",
30
- "@prisma-next/config": "0.5.0-dev.73",
31
- "@prisma-next/emitter": "0.5.0-dev.73",
32
- "@prisma-next/errors": "0.5.0-dev.73",
33
- "@prisma-next/framework-components": "0.5.0-dev.73",
34
- "@prisma-next/migration-tools": "0.5.0-dev.73",
35
- "@prisma-next/utils": "0.5.0-dev.73",
36
- "@prisma-next/psl-printer": "0.5.0-dev.73",
37
- "@prisma-next/contract": "0.5.0-dev.73"
30
+ "@prisma-next/config": "0.5.0-dev.75",
31
+ "@prisma-next/contract": "0.5.0-dev.75",
32
+ "@prisma-next/emitter": "0.5.0-dev.75",
33
+ "@prisma-next/errors": "0.5.0-dev.75",
34
+ "@prisma-next/migration-tools": "0.5.0-dev.75",
35
+ "@prisma-next/framework-components": "0.5.0-dev.75",
36
+ "@prisma-next/psl-printer": "0.5.0-dev.75",
37
+ "@prisma-next/utils": "0.5.0-dev.75"
38
38
  },
39
39
  "devDependencies": {
40
- "@prisma-next/cli": "0.5.0-dev.73"
40
+ "@prisma-next/cli": "0.5.0-dev.75"
41
41
  },
42
42
  "publishConfig": {
43
43
  "access": "public"
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-0ZX24FXF.mjs","names":["SPAN_IDS","emitContractArtifacts"],"sources":["../src/control-api/errors.ts","../src/utils/contract-space-aggregate-loader.ts","../src/control-api/operations/migration-helpers.ts","../src/control-api/operations/db-apply-aggregate.ts","../src/control-api/operations/db-init.ts","../src/control-api/operations/db-update.ts","../src/control-api/operations/db-verify.ts","../src/control-api/operations/migration-apply.ts","../src/control-api/client.ts"],"sourcesContent":["export class ContractValidationError extends Error {\n override readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'ContractValidationError';\n this.cause = cause;\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { ControlExtensionDescriptor } from '@prisma-next/framework-components/control';\nimport type {\n ContractSpaceAggregate,\n DeclaredExtensionEntry,\n LoadAggregateError,\n LoadAggregateInput,\n LoadAggregateOutput,\n} from '@prisma-next/migration-tools/aggregate';\nimport { loadContractSpaceAggregate } from '@prisma-next/migration-tools/aggregate';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { CliStructuredError } from './cli-errors';\n\n/**\n * Structural shape the aggregate loader needs from each declared\n * `Config.extensionPacks` entry. Mirrors the SQL family's\n * `SqlControlExtensionDescriptor.contractSpace` shape but kept\n * structural so the loader doesn't depend on the SQL family.\n */\ntype ExtensionPackForAggregate = {\n readonly id: string;\n readonly targetId: string;\n readonly contractSpace?: {\n readonly contractJson: unknown;\n readonly headRef: { readonly hash: string; readonly invariants: readonly string[] };\n };\n};\n\n/**\n * Convert the CLI's `Config.extensionPacks` array into the loader's\n * `DeclaredExtensionEntry[]` shape.\n *\n * The loader hashes `contractSpace.contractJson` to compare against the\n * on-disk `refs/head.json.hash` (drift detection). Rather than re-running\n * the canonical-JSON + SHA-256 pipeline at the CLI surface, we look up\n * the descriptor's pre-computed `headRef.hash` via reference identity\n * on the contract JSON value — the loader passes the same\n * `entry.contractSpace.contractJson` reference through to the hasher,\n * so identity-keyed lookup is safe.\n */\nfunction toDeclaredExtensions(extensionPacks: ReadonlyArray<ExtensionPackForAggregate>): {\n readonly entries: ReadonlyArray<DeclaredExtensionEntry>;\n readonly hashByContractJson: Map<unknown, string>;\n} {\n const entries: DeclaredExtensionEntry[] = [];\n const hashByContractJson = new Map<unknown, string>();\n for (const pack of extensionPacks) {\n const entry: DeclaredExtensionEntry = pack.contractSpace\n ? {\n id: pack.id,\n targetId: pack.targetId,\n contractSpace: { contractJson: pack.contractSpace.contractJson },\n }\n : { id: pack.id, targetId: pack.targetId };\n entries.push(entry);\n if (pack.contractSpace) {\n hashByContractJson.set(pack.contractSpace.contractJson, pack.contractSpace.headRef.hash);\n }\n }\n return { entries, hashByContractJson };\n}\n\n/**\n * Render a {@link LoadAggregateError} into a CLI structured-error\n * envelope. Preserves error codes `5001` (layout) and `5002` (marker /\n * drift / disjointness / etc.) so existing integration tests and\n * downstream tooling continue to assert on the same `meta.violations[]`\n * shape they did under the old precheck/marker-check helpers.\n */\nexport function mapLoadAggregateError(error: LoadAggregateError): CliStructuredError {\n if (error.kind === 'layoutViolation') {\n const lines = error.violations.map((v) => `- [${v.kind}] ${v.spaceId}`);\n const summary =\n error.violations.length === 1\n ? 'Contract-space layout violation detected'\n : `Contract-space layout violations detected (${error.violations.length})`;\n return new CliStructuredError('5001', summary, {\n domain: 'MIG',\n why: `The on-disk \\`migrations/\\` directory and your \\`extensionPacks\\` declaration are not in agreement.\\n${lines.join('\\n')}`,\n fix: 'Run `prisma-next migrate` to materialise on-disk artefacts for declared extensions, or remove the orphan directory.',\n docsUrl: 'https://pris.ly/contract-spaces',\n meta: {\n violations: error.violations.map((v) => ({\n kind: v.kind,\n spaceId: v.spaceId,\n })),\n },\n });\n }\n if (error.kind === 'driftViolation') {\n return new CliStructuredError('5002', `Contract-space drift detected for \"${error.spaceId}\"`, {\n domain: 'MIG',\n why: `The on-disk contract for space \"${error.spaceId}\" (hash ${error.priorHeadHash}) does not match the live extension descriptor (hash ${error.liveHash}).`,\n fix: 'Run `prisma-next migrate` to refresh the on-disk artefacts to match the live descriptor.',\n docsUrl: 'https://pris.ly/contract-spaces',\n meta: {\n violations: [\n {\n kind: 'drift',\n spaceId: error.spaceId,\n priorHeadHash: error.priorHeadHash,\n liveHash: error.liveHash,\n },\n ],\n },\n });\n }\n if (error.kind === 'disjointnessViolation') {\n return new CliStructuredError(\n '5002',\n `Contract-space disjointness violation: storage element \"${error.element}\" claimed by multiple spaces`,\n {\n domain: 'MIG',\n why: `Spaces ${error.claimedBy.map((s) => `\"${s}\"`).join(', ')} all claim the storage element \"${error.element}\". Each storage element must be owned by exactly one contract space.`,\n fix: 'Update the conflicting contracts so each storage element is claimed by exactly one space.',\n docsUrl: 'https://pris.ly/contract-spaces',\n meta: {\n violations: [\n {\n kind: 'disjointness',\n spaceId: error.claimedBy.join(','),\n element: error.element,\n claimedBy: error.claimedBy,\n },\n ],\n },\n },\n );\n }\n if (error.kind === 'integrityFailure') {\n return new CliStructuredError(\n '5002',\n `Contract-space integrity failure for \"${error.spaceId}\"`,\n {\n domain: 'MIG',\n why: error.detail,\n fix: 'Run `prisma-next migrate` to refresh on-disk artefacts, or restore the on-disk `migrations/` directory from version control.',\n docsUrl: 'https://pris.ly/contract-spaces',\n meta: {\n violations: [{ kind: 'integrity', spaceId: error.spaceId, detail: error.detail }],\n },\n },\n );\n }\n if (error.kind === 'validationFailure') {\n return new CliStructuredError(\n '5002',\n `Contract-space contract validation failed for \"${error.spaceId}\"`,\n {\n domain: 'MIG',\n why: error.detail,\n fix: 'Run `prisma-next migrate` to refresh on-disk artefacts, or fix the extension descriptor producing the invalid contract.',\n meta: {\n violations: [{ kind: 'validation', spaceId: error.spaceId, detail: error.detail }],\n },\n },\n );\n }\n // targetMismatch\n return new CliStructuredError('5002', `Contract-space target mismatch for \"${error.spaceId}\"`, {\n domain: 'MIG',\n why: `Space \"${error.spaceId}\" targets \"${error.actual}\" but the project's adapter targets \"${error.expected}\".`,\n fix: 'Update the extension descriptor to target the configured database, or change the project adapter.',\n meta: {\n violations: [\n {\n kind: 'targetMismatch',\n spaceId: error.spaceId,\n expected: error.expected,\n actual: error.actual,\n },\n ],\n },\n });\n}\n\n/**\n * Inputs needed to compose the aggregate loader at the CLI surface.\n *\n * Keeps the loader framework-neutral (no `Config` import) by accepting\n * already-resolved structural inputs: validated app contract, target\n * id, migrations root directory, and the set of extension descriptors.\n */\nexport interface BuildAggregateInputs<TFamilyId extends string, TTargetId extends string> {\n readonly targetId: TTargetId;\n readonly migrationsDir: string;\n readonly appContract: Contract;\n readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly validateContract: (contractJson: unknown) => Contract;\n}\n\n/**\n * Run the aggregate loader at the CLI surface, mapping any\n * {@link LoadAggregateError} into a {@link CliStructuredError} envelope.\n *\n * App-side migration packages are intentionally not threaded through:\n * `db init` / `db update` go through the planner's `synth` strategy for\n * the app member (driven by `callerPolicy.ignoreGraphFor`), so the\n * app's authored `migrations/` graph is not walked.\n *\n * @see specs/contract-space-aggregate-spec.md § Loader.\n */\nexport async function buildContractSpaceAggregate<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n inputs: BuildAggregateInputs<TFamilyId, TTargetId>,\n): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {\n const { entries, hashByContractJson } = toDeclaredExtensions(\n inputs.extensionPacks as ReadonlyArray<ExtensionPackForAggregate>,\n );\n\n const loadInput: LoadAggregateInput = {\n targetId: inputs.targetId,\n migrationsDir: inputs.migrationsDir,\n appContract: inputs.appContract,\n declaredExtensions: entries,\n validateContract: inputs.validateContract,\n hashContract: (contractJson: unknown) => {\n const precomputed = hashByContractJson.get(contractJson);\n if (precomputed === undefined) {\n throw new Error(\n 'CLI aggregate loader: encountered an extension contract without a pre-computed descriptor hash. This is a wiring bug.',\n );\n }\n return precomputed;\n },\n appMigrationPackages: [],\n };\n\n const result: LoadAggregateOutput = await loadContractSpaceAggregate(loadInput);\n if (!result.ok) {\n return notOk(mapLoadAggregateError(result.failure));\n }\n return ok(result.value.aggregate);\n}\n","import type { MigrationPlanOperation } from '@prisma-next/framework-components/control';\nimport type { ControlActionName, OnControlProgress } from '../types';\n\n/**\n * Strips operation objects to their public shape (id, label, operationClass).\n * Used at the API boundary to avoid leaking internal fields (precheck, execute, postcheck, etc.).\n */\nexport function stripOperations(\n operations: readonly MigrationPlanOperation[],\n): ReadonlyArray<{ readonly id: string; readonly label: string; readonly operationClass: string }> {\n return operations.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n }));\n}\n\n/**\n * Creates per-operation progress callbacks for the runner.\n * Returns undefined when no onProgress callback is provided.\n */\nexport function createOperationCallbacks(\n onProgress: OnControlProgress | undefined,\n action: ControlActionName,\n parentSpanId: string,\n) {\n if (!onProgress) {\n return undefined;\n }\n return {\n onOperationStart: (op: MigrationPlanOperation) => {\n onProgress({\n action,\n kind: 'spanStart',\n spanId: `operation:${op.id}`,\n parentSpanId,\n label: op.label,\n });\n },\n onOperationComplete: (op: MigrationPlanOperation) => {\n onProgress({\n action,\n kind: 'spanEnd',\n spanId: `operation:${op.id}`,\n outcome: 'ok',\n });\n },\n };\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n MigrationOperationPolicy,\n MigrationPlanOperation,\n MultiSpaceCapableRunner,\n MultiSpaceRunnerPerSpaceOptions,\n OperationPreview,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport {\n hasMultiSpaceRunner,\n hasOperationPreview,\n} from '@prisma-next/framework-components/control';\nimport {\n type AggregatePerSpacePlan,\n type AggregatePlannerError,\n type ContractSpaceAggregate,\n planAggregate,\n} from '@prisma-next/migration-tools/aggregate';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { CliStructuredError, errorRunnerFailed } from '../../utils/cli-errors';\nimport {\n type BuildAggregateInputs,\n buildContractSpaceAggregate,\n} from '../../utils/contract-space-aggregate-loader';\nimport type {\n DbInitFailure,\n DbInitResult,\n DbInitSuccess,\n DbUpdateFailure,\n DbUpdateResult,\n DbUpdateSuccess,\n OnControlProgress,\n} from '../types';\nimport { stripOperations } from './migration-helpers';\n\n/**\n * Span IDs emitted via `onProgress` during the aggregate apply flow.\n * Stable identifiers consumed by the structured-output renderer and by\n * tests asserting on span ids.\n */\nconst SPAN_IDS = {\n introspect: 'introspect',\n plan: 'plan',\n apply: 'apply',\n} as const;\n\n/**\n * Inputs shared by `db init` and `db update` aggregate apply flows.\n *\n * Accepts the already-validated app contract + descriptor list — the\n * loader gathers the rest from disk + descriptors. The CLI is the\n * descriptor-import boundary; everything downstream is descriptor-free.\n */\nexport interface ExecuteAggregateApplyOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly contract: Contract;\n readonly mode: 'plan' | 'apply';\n readonly migrations: TargetMigrationsCapability<\n TFamilyId,\n TTargetId,\n ControlFamilyInstance<TFamilyId, unknown>\n >;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n readonly migrationsDir: string;\n readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly targetId: TTargetId;\n readonly policy: MigrationOperationPolicy;\n readonly action: 'dbInit' | 'dbUpdate';\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Loader → planner → runner pipeline shared by `db init` and `db update`.\n *\n * The pipeline:\n *\n * 1. **Load**: build a {@link ContractSpaceAggregate} from the descriptor\n * set + on-disk on-disk artefacts. Any layout / drift / disjointness /\n * integrity violation short-circuits with a structured error.\n * 2. **Read DB state**: marker rows (`familyInstance.readAllMarkers`)\n * + introspected schema (`familyInstance.introspect`).\n * 3. **Plan**: {@link planAggregate} chooses graph-walk vs synth per\n * member according to `callerPolicy.ignoreGraphFor`. The app member\n * is forced through synth (today's daily-driver behaviour); every\n * extension member walks its on-disk graph.\n * 4. **Apply** (when `mode === 'apply'`): every per-space `MigrationPlan`\n * feeds into the runner's `executeAcrossSpaces` — one outer\n * transaction across every space; failure on any space rolls back\n * every space's writes.\n */\nexport async function executeAggregateApply<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteAggregateApplyOptions<TFamilyId, TTargetId>,\n): Promise<DbInitResult | DbUpdateResult> {\n const {\n driver,\n familyInstance,\n contract,\n mode,\n migrations,\n frameworkComponents,\n migrationsDir,\n extensionPacks,\n targetId,\n policy,\n action,\n onProgress,\n } = options;\n\n // 1. Load aggregate from descriptors + on-disk state.\n const loadInputs: BuildAggregateInputs<TFamilyId, TTargetId> = {\n targetId,\n migrationsDir,\n appContract: contract,\n extensionPacks,\n validateContract: (json) => familyInstance.validateContract(json),\n };\n const loaded = await buildContractSpaceAggregate(loadInputs);\n if (!loaded.ok) {\n throw loaded.failure;\n }\n const aggregate = loaded.value;\n\n // 2. Read live DB state (markers + schema).\n const markerRows = await familyInstance.readAllMarkers({ driver });\n\n // 2a. Orphan-marker pre-flight: refuse to apply when a marker row\n // exists for a space that is not declared in the aggregate.\n // Mirrors the M2 marker-check that `db init` / `db update` ran via\n // `runContractSpaceVerifierMarkerCheck`. Runs before planning so a\n // user with an orphaned marker (e.g. a retired extension whose\n // migrations directory has been removed) is told to clean it up\n // rather than silently advancing the app's marker.\n const orphanMarkerError = detectOrphanMarkers(aggregate, markerRows);\n if (orphanMarkerError !== null) {\n throw orphanMarkerError;\n }\n\n onProgress?.({\n action,\n kind: 'spanStart',\n spanId: SPAN_IDS.introspect,\n label: 'Introspecting database schema',\n });\n const schemaIR = await familyInstance.introspect({ driver });\n onProgress?.({ action, kind: 'spanEnd', spanId: SPAN_IDS.introspect, outcome: 'ok' });\n\n // 3. Plan via aggregate planner. App is forced through synth (today's\n // `db init` / `db update` daily-driver behaviour); extensions walk\n // their on-disk migration graphs.\n onProgress?.({\n action,\n kind: 'spanStart',\n spanId: SPAN_IDS.plan,\n label: 'Planning migration',\n });\n const planResult = await planAggregate<TFamilyId, TTargetId>({\n aggregate,\n currentDBState: { markersBySpaceId: markerRows, schemaIntrospection: schemaIR },\n familyInstance,\n migrations,\n frameworkComponents,\n callerPolicy: { ignoreGraphFor: new Set([aggregate.app.spaceId]) },\n operationPolicy: policy,\n });\n if (!planResult.ok) {\n onProgress?.({ action, kind: 'spanEnd', spanId: SPAN_IDS.plan, outcome: 'error' });\n return mapPlannerError(planResult.failure);\n }\n onProgress?.({ action, kind: 'spanEnd', spanId: SPAN_IDS.plan, outcome: 'ok' });\n\n const orderedResolutions = collectOrdered(planResult.value.applyOrder, planResult.value.perSpace);\n\n // The destination's structural shape comes from the app's plan — its\n // `destination` is the storage hash users see in CLI output.\n const appResolution = orderedResolutions.find((r) => r.spaceId === aggregate.app.spaceId);\n if (!appResolution) {\n throw new Error(\n 'Aggregate planner returned no plan for the app member — the planner is supposed to always emit one.',\n );\n }\n const appPlan = appResolution.entry.plan;\n\n // 4. Plan-mode: surface aggregate operations without applying.\n if (mode === 'plan') {\n const aggregateOps = orderedResolutions.flatMap((r) => r.entry.displayOps);\n const preview = hasOperationPreview(familyInstance)\n ? familyInstance.toOperationPreview(aggregateOps)\n : undefined;\n const summary = `Planned ${aggregateOps.length} operation(s) across ${orderedResolutions.length} space(s)`;\n return wrapPlanResult({\n operations: aggregateOps,\n destination: appPlan.destination,\n preview,\n summary,\n });\n }\n\n // 5. Apply mode: dispatch into the multi-space runner.\n const runner = migrations.createRunner(familyInstance);\n if (!hasMultiSpaceRunner(runner)) {\n throw errorRunnerFailed(\n `Runner for target \"${aggregate.targetId}\" does not implement \\`executeAcrossSpaces\\``,\n {\n why: `${action === 'dbInit' ? 'db init' : 'db update'} requires multi-space-capable runners (today: every SQL family runner).`,\n },\n );\n }\n\n onProgress?.({\n action,\n kind: 'spanStart',\n spanId: SPAN_IDS.apply,\n label: 'Applying migration plan across spaces',\n });\n\n const perSpaceOptions: MultiSpaceRunnerPerSpaceOptions<TFamilyId, TTargetId>[] =\n orderedResolutions.map((r) => ({\n space: r.spaceId,\n plan: r.entry.plan,\n driver,\n destinationContract: r.entry.destinationContract,\n policy,\n executionChecks: { prechecks: false, postchecks: false, idempotencyChecks: false },\n frameworkComponents,\n // Per-space post-apply schema verification is non-strict: each\n // space's `destinationContract` describes only its own slice; a\n // strict verifier would treat every other space's tables as\n // `extras`. Tolerant mode still catches missing tables / columns.\n // SQL family runners read `strictVerification` via structural\n // typing.\n strictVerification: false,\n })) as MultiSpaceRunnerPerSpaceOptions<TFamilyId, TTargetId>[];\n\n const runnerResult = await (\n runner as MultiSpaceCapableRunner<TFamilyId, TTargetId>\n ).executeAcrossSpaces({ driver, perSpaceOptions });\n\n if (!runnerResult.ok) {\n onProgress?.({ action, kind: 'spanEnd', spanId: SPAN_IDS.apply, outcome: 'error' });\n return buildRunnerFailure({\n summary: runnerResult.failure.summary,\n ...ifDefined('why', runnerResult.failure.why),\n meta: {\n ...(runnerResult.failure.meta ?? {}),\n failingSpace: runnerResult.failure.failingSpace,\n },\n });\n }\n onProgress?.({ action, kind: 'spanEnd', spanId: SPAN_IDS.apply, outcome: 'ok' });\n\n const totalOpsPlanned = runnerResult.value.perSpaceResults.reduce(\n (sum, r) => sum + r.value.operationsPlanned,\n 0,\n );\n const totalOpsExecuted = runnerResult.value.perSpaceResults.reduce(\n (sum, r) => sum + r.value.operationsExecuted,\n 0,\n );\n\n const aggregateOps = orderedResolutions.flatMap((r) => r.entry.displayOps);\n const summary =\n action === 'dbInit'\n ? `Applied ${totalOpsExecuted} operation(s) across ${orderedResolutions.length} space(s), database signed`\n : totalOpsExecuted === 0\n ? `Database already matches contract across ${orderedResolutions.length} space(s), signature updated`\n : `Applied ${totalOpsExecuted} operation(s) across ${orderedResolutions.length} space(s), signature updated`;\n\n return wrapApplyResult({\n operations: aggregateOps,\n destination: appPlan.destination,\n operationsPlanned: totalOpsPlanned,\n operationsExecuted: totalOpsExecuted,\n summary,\n });\n}\n\n/**\n * Compare the live `_prisma_marker` rows against the aggregate's\n * declared members. Any marker row whose `space` is not a member of\n * the aggregate is an \"orphan\" — typically a marker left behind by\n * an extension that was removed from `extensionPacks` without first\n * cleaning up its on-disk migrations / database tables.\n *\n * Returns a {@link CliStructuredError} envelope (code `5002`,\n * `kind: 'orphanMarker'`) for the first orphan it finds, or `null`\n * when every marker row maps to a declared member. Mirrors the M2\n * `runContractSpaceVerifierMarkerCheck` envelope so downstream\n * tooling (integration tests, JSON consumers) keeps asserting on the\n * same shape.\n */\nfunction detectOrphanMarkers(\n aggregate: ContractSpaceAggregate,\n markerRows: ReadonlyMap<string, unknown>,\n): CliStructuredError | null {\n const memberSpaceIds = new Set<string>([\n aggregate.app.spaceId,\n ...aggregate.extensions.map((m) => m.spaceId),\n ]);\n const orphans: string[] = [];\n for (const [spaceId, row] of markerRows) {\n if (row !== null && row !== undefined && !memberSpaceIds.has(spaceId)) {\n orphans.push(spaceId);\n }\n }\n if (orphans.length === 0) return null;\n orphans.sort((a, b) => a.localeCompare(b));\n const summary =\n orphans.length === 1\n ? `Orphan contract-space marker detected for \"${orphans[0]}\"`\n : `Orphan contract-space markers detected for ${orphans.length} spaces`;\n return new CliStructuredError('5002', summary, {\n domain: 'MIG',\n why: `The database has \\`_prisma_marker\\` rows for spaces (${orphans\n .map((s) => `\"${s}\"`)\n .join(\n ', ',\n )}) that are not declared in the project's \\`extensionPacks\\`. The aggregate pipeline refuses to advance markers it cannot account for.`,\n fix: 'Either re-declare the missing extension(s) in `extensionPacks` (so the aggregate owns them again), or remove the orphan marker row(s) from `_prisma_marker` once you have confirmed the corresponding tables can be safely retired.',\n docsUrl: 'https://pris.ly/contract-spaces',\n meta: {\n violations: orphans.map((spaceId) => ({ kind: 'orphanMarker', spaceId })),\n },\n });\n}\n\ninterface OrderedResolution {\n readonly spaceId: string;\n readonly entry: AggregatePerSpacePlan;\n}\n\nfunction collectOrdered(\n applyOrder: readonly string[],\n perSpace: ReadonlyMap<string, AggregatePerSpacePlan>,\n): readonly OrderedResolution[] {\n return applyOrder.map((spaceId) => {\n const entry = perSpace.get(spaceId);\n if (!entry) {\n throw new Error(`Aggregate planner output missing per-space plan for \"${spaceId}\"`);\n }\n return { spaceId, entry };\n });\n}\n\nfunction mapPlannerError(error: AggregatePlannerError): DbInitResult | DbUpdateResult {\n if (error.kind === 'appSynthFailure') {\n const failure: DbInitFailure | DbUpdateFailure = {\n code: 'PLANNING_FAILED',\n summary: 'Migration planning failed due to conflicts',\n conflicts: error.conflicts,\n why: undefined,\n meta: undefined,\n };\n return notOk(failure) as DbInitResult | DbUpdateResult;\n }\n if (error.kind === 'extensionPathUnreachable') {\n return buildRunnerFailure({\n summary: `Cannot resolve apply path for extension space \"${error.spaceId}\"`,\n why: `No path in the on-disk migration graph for extension space \"${error.spaceId}\" reaches the on-disk head ref hash \"${error.target}\".`,\n meta: { spaceId: error.spaceId, target: error.target },\n });\n }\n if (error.kind === 'extensionPathUnsatisfiable') {\n return buildRunnerFailure({\n summary: `Cannot resolve apply path for extension space \"${error.spaceId}\"`,\n why: `On-disk migration graph for extension space \"${error.spaceId}\" reaches the on-disk head ref but does not cover required invariants: ${error.missingInvariants.join(', ')}.`,\n meta: { spaceId: error.spaceId, missingInvariants: error.missingInvariants },\n });\n }\n // policyConflict — surfaces as a runner-style failure naming the\n // space; conceptually a configuration bug, but mapping it onto the\n // existing failure surface keeps callers untouched.\n return buildRunnerFailure({\n summary: `Aggregate planner policy conflict for space \"${error.spaceId}\"`,\n why: error.detail,\n meta: { spaceId: error.spaceId },\n });\n}\n\nfunction wrapPlanResult(args: {\n readonly operations: readonly MigrationPlanOperation[];\n readonly destination: { readonly storageHash: string; readonly profileHash?: string };\n readonly preview: OperationPreview | undefined;\n readonly summary: string;\n}): DbInitResult | DbUpdateResult {\n const success: DbInitSuccess | DbUpdateSuccess = {\n mode: 'plan',\n plan: {\n operations: stripOperations(args.operations),\n ...ifDefined('preview', args.preview),\n },\n destination: {\n storageHash: args.destination.storageHash,\n ...ifDefined('profileHash', args.destination.profileHash),\n },\n summary: args.summary,\n };\n return ok(success);\n}\n\nfunction wrapApplyResult(args: {\n readonly operations: readonly MigrationPlanOperation[];\n readonly destination: { readonly storageHash: string; readonly profileHash?: string };\n readonly operationsPlanned: number;\n readonly operationsExecuted: number;\n readonly summary: string;\n}): DbInitResult | DbUpdateResult {\n const success: DbInitSuccess | DbUpdateSuccess = {\n mode: 'apply',\n plan: { operations: stripOperations(args.operations) },\n destination: {\n storageHash: args.destination.storageHash,\n ...ifDefined('profileHash', args.destination.profileHash),\n },\n execution: {\n operationsPlanned: args.operationsPlanned,\n operationsExecuted: args.operationsExecuted,\n },\n marker: args.destination.profileHash\n ? { storageHash: args.destination.storageHash, profileHash: args.destination.profileHash }\n : { storageHash: args.destination.storageHash },\n summary: args.summary,\n };\n return ok(success);\n}\n\nfunction buildRunnerFailure(args: {\n readonly summary: string;\n readonly why?: string;\n readonly meta: Record<string, unknown>;\n}): DbInitResult | DbUpdateResult {\n const failure: DbInitFailure | DbUpdateFailure = {\n code: 'RUNNER_FAILED',\n summary: args.summary,\n why: args.why,\n meta: args.meta,\n conflicts: undefined,\n };\n return notOk(failure) as DbInitResult | DbUpdateResult;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { DbInitResult, OnControlProgress } from '../types';\nimport { executeAggregateApply } from './db-apply-aggregate';\n\n/**\n * Options for executing the `db init` operation.\n *\n * `db init` runs the loader → planner → runner pipeline:\n *\n * 1. {@link executeAggregateApply} loads a `ContractSpaceAggregate` via\n * {@link import('@prisma-next/migration-tools/aggregate').loadContractSpaceAggregate}\n * from the supplied descriptor set + on-disk on-disk artefacts.\n * 2. The aggregate planner runs with `callerPolicy.ignoreGraphFor`\n * locked to the app member — synth strategy for the app, graph-walk\n * for every extension.\n * 3. The runner's `executeAcrossSpaces` applies the per-space plans\n * inside one outer transaction.\n *\n * `extensionPacks` mirrors `Config.extensionPacks` (descriptor list).\n * The loader (sub-spec § Loader) is the sole descriptor-import boundary.\n */\nexport interface ExecuteDbInitOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly contract: Contract;\n readonly mode: 'plan' | 'apply';\n readonly migrations: TargetMigrationsCapability<\n TFamilyId,\n TTargetId,\n ControlFamilyInstance<TFamilyId, unknown>\n >;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n /**\n * On-disk migrations directory the aggregate loader reads on-disk\n * artefacts from. Required.\n */\n readonly migrationsDir: string;\n /**\n * Resolved adapter target id. Threaded through to the loader for\n * target-consistency checks across descriptors and the app contract.\n */\n readonly targetId: TTargetId;\n /**\n * Declared extension descriptors. Defaults to an empty list, which\n * routes through the same loader → planner → runner pipeline with no\n * extension members in the aggregate.\n */\n readonly extensionPacks?: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n /** Optional progress callback for observing operation progress */\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Execute `db init` against the configured contract.\n *\n * Routes through the loader → planner → runner pipeline (sub-spec\n * \"Commit-by-commit § Commit 4\"). Always additive-only; destructive\n * changes belong to `db update`.\n */\nexport async function executeDbInit<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbInitOptions<TFamilyId, TTargetId>,\n): Promise<DbInitResult> {\n const result = await executeAggregateApply<TFamilyId, TTargetId>({\n driver: options.driver,\n familyInstance: options.familyInstance,\n contract: options.contract,\n mode: options.mode,\n migrations: options.migrations,\n frameworkComponents: options.frameworkComponents,\n migrationsDir: options.migrationsDir,\n targetId: options.targetId,\n extensionPacks: options.extensionPacks ?? [],\n policy: { allowedOperationClasses: ['additive'] },\n action: 'dbInit',\n ...ifDefined('onProgress', options.onProgress),\n });\n return result as DbInitResult;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk } from '@prisma-next/utils/result';\nimport type { DbUpdateResult, OnControlProgress } from '../types';\nimport { executeAggregateApply } from './db-apply-aggregate';\n\nconst DB_UPDATE_POLICY = {\n allowedOperationClasses: ['additive', 'widening', 'destructive'] as const,\n} as const;\n\n/**\n * Options for the `db update` operation.\n *\n * Same loader → planner → runner pipeline as `db init`, but with the\n * widened operation policy (additive + widening + destructive). The\n * destructive-change confirmation gate runs at this layer: when\n * `mode === 'apply'` and `acceptDataLoss` is `false`, the operation\n * pre-plans, surfaces destructive ops to the caller, and aborts.\n */\nexport interface ExecuteDbUpdateOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly contract: Contract;\n readonly mode: 'plan' | 'apply';\n readonly migrations: TargetMigrationsCapability<\n TFamilyId,\n TTargetId,\n ControlFamilyInstance<TFamilyId, unknown>\n >;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n readonly acceptDataLoss?: boolean;\n readonly migrationsDir: string;\n readonly targetId: TTargetId;\n readonly extensionPacks?: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Execute `db update` against the configured contract.\n *\n * Routes through the loader → planner → runner pipeline. Destructive\n * operations require either `acceptDataLoss: true` or a prior\n * `mode: 'plan'` invocation that surfaces the destructive ops; the\n * confirmation gate is implemented here so the lower-level applier\n * remains policy-agnostic.\n */\nexport async function executeDbUpdate<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbUpdateOptions<TFamilyId, TTargetId>,\n): Promise<DbUpdateResult> {\n const sharedInputs = {\n driver: options.driver,\n familyInstance: options.familyInstance,\n contract: options.contract,\n migrations: options.migrations,\n frameworkComponents: options.frameworkComponents,\n migrationsDir: options.migrationsDir,\n targetId: options.targetId,\n extensionPacks: options.extensionPacks ?? [],\n policy: DB_UPDATE_POLICY,\n action: 'dbUpdate' as const,\n ...ifDefined('onProgress', options.onProgress),\n };\n if (options.mode === 'apply' && !options.acceptDataLoss) {\n const gate = await guardDestructiveChanges<TFamilyId, TTargetId>(sharedInputs);\n if (gate !== null) return gate;\n }\n return (await executeAggregateApply<TFamilyId, TTargetId>({\n ...sharedInputs,\n mode: options.mode,\n })) as DbUpdateResult;\n}\n\n/**\n * Pre-plan once when running `db update apply` without `acceptDataLoss`.\n * Surfaces destructive operations across every space; if any are\n * planned, returns a `DESTRUCTIVE_CHANGES` failure that the CLI shows\n * as a confirmation prompt. Returns `null` when the apply is safe to\n * run.\n */\nasync function guardDestructiveChanges<TFamilyId extends string, TTargetId extends string>(\n sharedInputs: Omit<Parameters<typeof executeAggregateApply<TFamilyId, TTargetId>>[0], 'mode'>,\n): Promise<DbUpdateResult | null> {\n const planResult = (await executeAggregateApply<TFamilyId, TTargetId>({\n ...sharedInputs,\n mode: 'plan',\n })) as DbUpdateResult;\n if (!planResult.ok) return planResult;\n const destructiveOps = planResult.value.plan.operations\n .filter((op) => op.operationClass === 'destructive')\n .map((op) => ({ id: op.id, label: op.label }));\n if (destructiveOps.length === 0) return null;\n return notOk({\n code: 'DESTRUCTIVE_CHANGES',\n summary: `Planned ${destructiveOps.length} destructive operation(s) that require confirmation`,\n why: 'Destructive operations require confirmation — re-run with -y to accept',\n conflicts: undefined,\n meta: { destructiveOperations: destructiveOps },\n });\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyInstance,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport {\n type AggregateVerifierOutput,\n type ContractSpaceMember,\n verifyAggregate,\n} from '@prisma-next/migration-tools/aggregate';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { CliStructuredError } from '../../utils/cli-errors';\nimport {\n type BuildAggregateInputs,\n buildContractSpaceAggregate,\n} from '../../utils/contract-space-aggregate-loader';\nimport type { OnControlProgress } from '../types';\n\n/**\n * Span IDs emitted via `onProgress` during the aggregate verify flow.\n * Mirrors the span identifiers used by the legacy precheck / marker-check\n * helpers so structured-output renderers and progress tests keep working.\n */\nconst SPAN_IDS = {\n introspect: 'introspect',\n verify: 'verify',\n} as const;\n\n/**\n * Inputs for the aggregate `db verify` operation.\n *\n * Loader → verifier pipeline. The loader (sole descriptor-import\n * boundary) builds a {@link import('@prisma-next/migration-tools/aggregate').ContractSpaceAggregate};\n * the aggregate verifier bundles `markerCheck` + per-space pre-projected\n * `schemaCheck`. `mode: 'strict' | 'lenient'` maps directly to the user\n * facing `--strict` flag.\n */\nexport interface ExecuteDbVerifyOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly contract: Contract;\n readonly migrationsDir: string;\n readonly targetId: TTargetId;\n readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n readonly mode: 'strict' | 'lenient';\n readonly skipSchema: boolean;\n readonly skipMarker: boolean;\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Result of the aggregate verify operation.\n *\n * Marker-check failures are surfaced as a {@link CliStructuredError}\n * (same envelope code `5002` the legacy `runContractSpaceVerifierMarkerCheck`\n * emitted, so downstream tooling and integration tests assert on the\n * same shape).\n *\n * On success, the per-space schema results are returned for the CLI to\n * render. When `skipSchema` is true (`--marker-only`), the schema map\n * is empty.\n */\nexport interface ExecuteDbVerifySuccess {\n readonly schemaResults: ReadonlyMap<string, VerifyDatabaseSchemaResult>;\n readonly memberOrder: readonly string[];\n readonly appSpaceId: string;\n}\n\nexport type ExecuteDbVerifyResult = Result<ExecuteDbVerifySuccess, CliStructuredError>;\n\n/**\n * Loader → verifier pipeline shared by `db verify` modes (`full`,\n * `marker-only`, `schema-only`).\n *\n * 1. **Load**: build a {@link import('@prisma-next/migration-tools/aggregate').ContractSpaceAggregate}\n * from descriptors + on-disk on-disk artefacts. Layout / drift /\n * integrity / disjointness violations short-circuit with a\n * structured CLI error.\n * 2. **Read DB state**: marker rows + (when `skipSchema` is `false`)\n * schema introspection.\n * 3. **Verify**: {@link verifyAggregate} returns per-space\n * `markerCheck` + per-space pre-projected `schemaCheck` (closes F23).\n * Marker mismatches map to `CliStructuredError` (code `5002`) so\n * callers (CLI command) can render and exit. Schema results are\n * returned to the caller verbatim.\n */\nexport async function executeDbVerify<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbVerifyOptions<TFamilyId, TTargetId>,\n): Promise<ExecuteDbVerifyResult> {\n const { driver, familyInstance, onProgress, skipSchema, skipMarker } = options;\n const loaded = await buildContractSpaceAggregate(buildLoadInputs(options));\n if (!loaded.ok) return notOk(loaded.failure);\n const aggregate = loaded.value;\n\n const markersBySpaceId = await familyInstance.readAllMarkers({ driver });\n const schemaIntrospection = skipSchema\n ? null\n : await runIntrospection({ driver, familyInstance, onProgress });\n\n emitVerifySpan(onProgress, 'spanStart');\n const verifyResult = verifyAggregate({\n aggregate,\n markersBySpaceId,\n schemaIntrospection,\n mode: options.mode,\n verifySchemaForMember: createPerMemberVerifier(options),\n });\n return finaliseVerifyResult({ verifyResult, aggregate, skipMarker, onProgress });\n}\n\nfunction buildLoadInputs<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbVerifyOptions<TFamilyId, TTargetId>,\n): BuildAggregateInputs<TFamilyId, TTargetId> {\n return {\n targetId: options.targetId,\n migrationsDir: options.migrationsDir,\n appContract: options.contract,\n extensionPacks: options.extensionPacks,\n validateContract: (json) => options.familyInstance.validateContract(json),\n };\n}\n\nasync function runIntrospection<TFamilyId extends string, TTargetId extends string>(args: {\n driver: ControlDriverInstance<TFamilyId, TTargetId>;\n familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n onProgress: OnControlProgress | undefined;\n}): Promise<unknown> {\n const { driver, familyInstance, onProgress } = args;\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanStart',\n spanId: SPAN_IDS.introspect,\n label: 'Introspecting database schema',\n });\n try {\n const result = await familyInstance.introspect({ driver });\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanEnd',\n spanId: SPAN_IDS.introspect,\n outcome: 'ok',\n });\n return result;\n } catch (error) {\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanEnd',\n spanId: SPAN_IDS.introspect,\n outcome: 'error',\n });\n throw error;\n }\n}\n\n/**\n * Build the per-member schema callback handed to the aggregate verifier.\n * When `skipSchema` is true the callback short-circuits with a synthetic\n * `ok` result so the verifier still runs the (cheap) schemaCheck loop\n * without invoking the family's verification path.\n */\nfunction createPerMemberVerifier<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteDbVerifyOptions<TFamilyId, TTargetId>,\n): (\n projectedSchema: unknown,\n member: ContractSpaceMember,\n verifyMode: 'strict' | 'lenient',\n) => VerifyDatabaseSchemaResult {\n const { skipSchema, familyInstance, frameworkComponents } = options;\n return (projectedSchema, member, verifyMode) => {\n if (skipSchema) return buildSkippedSchemaResult(member);\n return familyInstance.schemaVerifyAgainstSchema({\n contract: member.contract,\n // The family's `TSchemaIR` is opaque to migration-tools; the\n // aggregate verifier passes through whatever we hand it. The\n // family expects its own IR shape on the way back.\n schema: projectedSchema as never,\n strict: verifyMode === 'strict',\n frameworkComponents,\n });\n };\n}\n\nfunction emitVerifySpan(\n onProgress: OnControlProgress | undefined,\n kind: 'spanStart' | 'spanEndOk' | 'spanEndError',\n): void {\n if (kind === 'spanStart') {\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanStart',\n spanId: SPAN_IDS.verify,\n label: 'Verifying contract spaces',\n });\n return;\n }\n onProgress?.({\n action: 'dbVerify',\n kind: 'spanEnd',\n spanId: SPAN_IDS.verify,\n outcome: kind === 'spanEndOk' ? 'ok' : 'error',\n });\n}\n\n/**\n * Map an {@link AggregateVerifierOutput} to the operation's\n * {@link ExecuteDbVerifyResult}, applying the `skipMarker` policy used\n * by the CLI's `--schema-only` mode.\n */\nfunction finaliseVerifyResult(args: {\n verifyResult: AggregateVerifierOutput<VerifyDatabaseSchemaResult>;\n aggregate: {\n readonly app: { readonly spaceId: string };\n readonly extensions: ReadonlyArray<{ readonly spaceId: string }>;\n };\n skipMarker: boolean;\n onProgress: OnControlProgress | undefined;\n}): ExecuteDbVerifyResult {\n const { verifyResult, aggregate, skipMarker, onProgress } = args;\n if (!verifyResult.ok) {\n emitVerifySpan(onProgress, 'spanEndError');\n return notOk(\n new CliStructuredError('5002', 'Aggregate verifier introspection failed', {\n domain: 'MIG',\n why: verifyResult.failure.detail,\n fix: 'Check database connectivity and the introspection tooling.',\n docsUrl: 'https://pris.ly/contract-spaces',\n }),\n );\n }\n const markerError = skipMarker\n ? null\n : mapMarkerCheckFailures(aggregate.app.spaceId, verifyResult.value.markerCheck);\n if (markerError !== null) {\n emitVerifySpan(onProgress, 'spanEndError');\n return notOk(markerError);\n }\n emitVerifySpan(onProgress, 'spanEndOk');\n return ok({\n schemaResults: verifyResult.value.schemaCheck.perSpace,\n memberOrder: [aggregate.app.spaceId, ...aggregate.extensions.map((e) => e.spaceId)],\n appSpaceId: aggregate.app.spaceId,\n });\n}\n\nfunction buildSkippedSchemaResult(member: ContractSpaceMember): VerifyDatabaseSchemaResult {\n const profileHash = (member.contract as { profileHash?: string }).profileHash;\n return {\n ok: true,\n summary: 'Schema verification skipped',\n contract: {\n storageHash: member.headRef.hash,\n ...(profileHash ? { profileHash } : {}),\n },\n target: { expected: member.contract.target },\n schema: {\n issues: [],\n root: {\n status: 'pass',\n kind: 'skipped',\n name: member.spaceId,\n contractPath: '',\n code: 'SKIPPED',\n message: 'Schema verification skipped',\n expected: undefined,\n actual: undefined,\n children: [],\n },\n counts: { pass: 0, warn: 0, fail: 0, totalNodes: 0 },\n },\n timings: { total: 0 },\n };\n}\n\n/**\n * Translate per-space marker check failures and orphan markers into a\n * single CLI structured error envelope. Preserves the legacy code\n * `5002` (was emitted by `runContractSpaceVerifierMarkerCheck`).\n */\nfunction mapMarkerCheckFailures(\n appSpaceId: string,\n section: {\n readonly perSpace: ReadonlyMap<\n string,\n | { readonly kind: 'ok' }\n | { readonly kind: 'absent' }\n | { readonly kind: 'hashMismatch'; readonly markerHash: string; readonly expected: string }\n | { readonly kind: 'missingInvariants'; readonly missing: readonly string[] }\n >;\n readonly orphanMarkers: readonly { readonly spaceId: string; readonly row: unknown }[];\n },\n): CliStructuredError | null {\n const violations: Array<{\n kind: string;\n spaceId: string;\n remediation: string;\n }> = [];\n for (const [spaceId, result] of section.perSpace) {\n if (result.kind === 'ok' || result.kind === 'absent') continue;\n if (result.kind === 'hashMismatch') {\n violations.push({\n kind: 'hashMismatch',\n spaceId,\n remediation:\n spaceId === appSpaceId\n ? 'Run `prisma-next db update` to advance the marker, or roll the database back to the recorded hash.'\n : `Apply on-disk migrations under \\`migrations/${spaceId}/\\` to advance the marker, or remove the conflicting marker row.`,\n });\n continue;\n }\n if (result.kind === 'missingInvariants') {\n violations.push({\n kind: 'invariantsMismatch',\n spaceId,\n remediation: `Re-apply the migrations under \\`migrations/${spaceId}/\\` so the marker carries invariants: ${result.missing.join(', ')}.`,\n });\n }\n }\n for (const orphan of section.orphanMarkers) {\n violations.push({\n kind: 'orphanMarker',\n spaceId: orphan.spaceId,\n remediation: `Add the corresponding extension to \\`extensionPacks\\` in \\`prisma-next.config.ts\\`, or delete the orphan marker row for \"${orphan.spaceId}\".`,\n });\n }\n if (violations.length === 0) return null;\n const lines = violations.map((v) => `- [${v.kind}] ${v.spaceId}: ${v.remediation}`);\n const summary =\n violations.length === 1\n ? 'Contract-space verifier found a violation'\n : `Contract-space verifier found violations (${violations.length})`;\n return new CliStructuredError('5002', summary, {\n domain: 'MIG',\n why: `The on-disk \\`migrations/\\` directory, the \\`extensionPacks\\` declaration, and the live database marker rows are not in agreement.\\n${lines.join('\\n')}`,\n fix: violations[0]?.remediation ?? 'Review and reconcile the violations listed above.',\n docsUrl: 'https://pris.ly/contract-spaces',\n meta: { violations },\n });\n}\n","import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlFamilyInstance,\n MigrationRunnerResult,\n TargetMigrationsCapability,\n} from '@prisma-next/framework-components/control';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport type {\n MigrationApplyAppliedEntry,\n MigrationApplyResult,\n MigrationApplyStep,\n OnControlProgress,\n} from '../types';\n\nexport interface ExecuteMigrationApplyOptions<TFamilyId extends string, TTargetId extends string> {\n readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;\n readonly familyInstance: ControlFamilyInstance<TFamilyId, unknown>;\n readonly originHash: string;\n readonly destinationHash: string;\n readonly pendingMigrations: readonly MigrationApplyStep[];\n readonly migrations: TargetMigrationsCapability<\n TFamilyId,\n TTargetId,\n ControlFamilyInstance<TFamilyId, unknown>\n >;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n readonly targetId: string;\n readonly onProgress?: OnControlProgress;\n}\n\n/**\n * Apply a sequence of migration packages against the configured driver.\n *\n * Validates the path's continuity (origin → ... → destination, no gaps),\n * then drives the family/target's migration runner over each package's\n * operations in order, surfacing per-migration progress through `onProgress`.\n *\n * The `pendingMigrations` parameter is trusted input. Callers are responsible\n * for upstream verification of the originating migration packages — typically\n * by loading them via `readMigrationPackage` from\n * `@prisma-next/migration-tools/io`, which performs hash-integrity checks at\n * the load boundary. This operation does not re-verify the packages and\n * assumes the `(metadata, ops)` pairs on disk have not been tampered with\n * since emit.\n */\nexport async function executeMigrationApply<TFamilyId extends string, TTargetId extends string>(\n options: ExecuteMigrationApplyOptions<TFamilyId, TTargetId>,\n): Promise<MigrationApplyResult> {\n const {\n driver,\n familyInstance,\n originHash,\n destinationHash,\n pendingMigrations,\n migrations,\n frameworkComponents,\n targetId,\n onProgress,\n } = options;\n\n if (pendingMigrations.length === 0) {\n if (originHash !== destinationHash) {\n return notOk({\n code: 'MIGRATION_PATH_NOT_FOUND' as const,\n summary: 'No migrations provided for requested origin and destination',\n why: `Requested ${originHash} -> ${destinationHash} but pendingMigrations is empty`,\n meta: { originHash, destinationHash },\n });\n }\n return ok({\n migrationsApplied: 0,\n markerHash: originHash,\n applied: [],\n summary: 'Already up to date',\n });\n }\n\n const firstMigration = pendingMigrations[0]!;\n const lastMigration = pendingMigrations[pendingMigrations.length - 1]!;\n // Manifest `from` is `string | null` (null = baseline). The live-marker\n // layer encodes \"no prior state\" as EMPTY_CONTRACT_HASH; bridge here so the\n // string comparisons below work uniformly.\n const firstFromMarker = firstMigration.from ?? EMPTY_CONTRACT_HASH;\n if (firstFromMarker !== originHash || lastMigration.to !== destinationHash) {\n return notOk({\n code: 'MIGRATION_PATH_NOT_FOUND' as const,\n summary: 'Migration apply path does not match requested origin and destination',\n why: `Path resolved as ${firstFromMarker} -> ${lastMigration.to}, but requested ${originHash} -> ${destinationHash}`,\n meta: {\n originHash,\n destinationHash,\n pathOrigin: firstFromMarker,\n pathDestination: lastMigration.to,\n },\n });\n }\n\n for (let i = 1; i < pendingMigrations.length; i++) {\n const previous = pendingMigrations[i - 1]!;\n const current = pendingMigrations[i]!;\n const currentFromMarker = current.from ?? EMPTY_CONTRACT_HASH;\n if (previous.to !== currentFromMarker) {\n return notOk({\n code: 'MIGRATION_PATH_NOT_FOUND' as const,\n summary: 'Migration apply path contains a discontinuity between adjacent migrations',\n why: `Migration \"${previous.dirName}\" ends at ${previous.to}, but next migration \"${current.dirName}\" starts at ${currentFromMarker}`,\n meta: {\n originHash,\n destinationHash,\n previousDirName: previous.dirName,\n previousTo: previous.to,\n currentDirName: current.dirName,\n currentFrom: currentFromMarker,\n discontinuityIndex: i,\n },\n });\n }\n }\n\n const runner = migrations.createRunner(familyInstance);\n const applied: MigrationApplyAppliedEntry[] = [];\n\n for (const migration of pendingMigrations) {\n const migrationSpanId = `migration:${migration.dirName}`;\n onProgress?.({\n action: 'migrationApply',\n kind: 'spanStart',\n spanId: migrationSpanId,\n label: `Applying ${migration.dirName}`,\n });\n\n const { operations } = migration;\n\n // Allow all operation classes. The policy gate belongs at plan time, not\n // apply time — the planner already decided what to emit. Restricting here\n // would be a tautology (the allowed set would just mirror what's in ops).\n const policy = {\n allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'] as const,\n };\n\n // Manifest `from === null` means \"no prior state\" — the runner expects\n // `origin: null` for a fresh database (no marker present).\n //\n // M3 will thread the package's owning space id through `MigrationApplyStep`\n // and use it here. Until then, all on-disk migration packages live under\n // the app's `migrations/` directory, so this path is exclusively app-scope\n // and we pass `APP_SPACE_ID` explicitly.\n const plan = {\n targetId,\n spaceId: APP_SPACE_ID,\n origin: migration.from === null ? null : { storageHash: migration.from },\n destination: { storageHash: migration.to },\n operations,\n providedInvariants: migration.providedInvariants,\n };\n\n const destinationContract = familyInstance.validateContract(migration.toContract);\n\n const runnerResult: MigrationRunnerResult = await runner.execute({\n plan,\n driver,\n destinationContract,\n policy,\n executionChecks: {\n prechecks: true,\n postchecks: true,\n idempotencyChecks: true,\n },\n frameworkComponents,\n });\n\n if (!runnerResult.ok) {\n onProgress?.({\n action: 'migrationApply',\n kind: 'spanEnd',\n spanId: migrationSpanId,\n outcome: 'error',\n });\n return notOk({\n code: 'RUNNER_FAILED' as const,\n summary: runnerResult.failure.summary,\n why: runnerResult.failure.why,\n meta: {\n migration: migration.dirName,\n from: migration.from,\n to: migration.to,\n ...(runnerResult.failure.meta ?? {}),\n },\n });\n }\n\n onProgress?.({\n action: 'migrationApply',\n kind: 'spanEnd',\n spanId: migrationSpanId,\n outcome: 'ok',\n });\n\n applied.push({\n dirName: migration.dirName,\n from: migration.from,\n to: migration.to,\n operationsExecuted: runnerResult.value.operationsExecuted,\n });\n }\n\n const finalHash = pendingMigrations[pendingMigrations.length - 1]!.to;\n const totalOps = applied.reduce((sum, a) => sum + a.operationsExecuted, 0);\n\n return ok({\n migrationsApplied: applied.length,\n markerHash: finalHash,\n applied,\n summary: `Applied ${applied.length} migration(s) (${totalOps} operation(s)), marker at ${finalHash}`,\n });\n}\n","import type { Contract, ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { emit as emitContractArtifacts } from '@prisma-next/emitter';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlDriverInstance,\n ControlFamilyInstance,\n ControlStack,\n CoreSchemaView,\n MigrationPlanOperation,\n OperationPreview,\n SignDatabaseResult,\n VerifyDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport {\n APP_SPACE_ID,\n createControlStack,\n hasMigrations,\n hasOperationPreview,\n hasPslContractInfer,\n hasSchemaView,\n} from '@prisma-next/framework-components/control';\nimport type { PslDocumentAst } from '@prisma-next/framework-components/psl-ast';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport { assertFrameworkComponentsCompatible } from '../utils/framework-components';\nimport { enrichContract } from './contract-enrichment';\nimport { ContractValidationError } from './errors';\nimport { executeDbInit } from './operations/db-init';\nimport { executeDbUpdate } from './operations/db-update';\nimport { type ExecuteDbVerifyResult, executeDbVerify } from './operations/db-verify';\nimport { executeMigrationApply } from './operations/migration-apply';\n\nimport type {\n ControlActionName,\n ControlClient,\n ControlClientOptions,\n DbInitOptions,\n DbInitResult,\n DbUpdateOptions,\n DbUpdateResult,\n DbVerifyOptions,\n EmitOptions,\n EmitResult,\n IntrospectOptions,\n MigrationApplyOptions,\n MigrationApplyResult,\n OnControlProgress,\n SchemaVerifyOptions,\n SignOptions,\n VerifyOptions,\n} from './types';\n\n/**\n * Creates a programmatic control client for Prisma Next operations.\n *\n * The client accepts framework component descriptors at creation time,\n * manages driver lifecycle via connect()/close(), and exposes domain\n * operations that delegate to the existing family instance methods.\n *\n * @see {@link ControlClient} for the client interface\n * @see README.md \"Programmatic Control API\" section for usage examples\n */\nexport function createControlClient(options: ControlClientOptions): ControlClient {\n return new ControlClientImpl(options);\n}\n\n/**\n * Implementation of ControlClient.\n * Manages initialization and connection state, delegates operations to family instance.\n */\nclass ControlClientImpl implements ControlClient {\n private readonly options: ControlClientOptions;\n private stack: ControlStack | null = null;\n private driver: ControlDriverInstance<string, string> | null = null;\n private familyInstance: ControlFamilyInstance<string, unknown> | null = null;\n private frameworkComponents: ReadonlyArray<\n TargetBoundComponentDescriptor<string, string>\n > | null = null;\n private initialized = false;\n private readonly defaultConnection: unknown;\n\n constructor(options: ControlClientOptions) {\n this.options = options;\n this.defaultConnection = options.connection;\n }\n\n init(): void {\n if (this.initialized) {\n return; // Idempotent\n }\n\n this.stack = createControlStack({\n family: this.options.family,\n target: this.options.target,\n adapter: this.options.adapter,\n driver: this.options.driver,\n extensionPacks: this.options.extensionPacks,\n });\n\n this.familyInstance = this.options.family.create(this.stack);\n\n // Validate and type-narrow framework components\n const rawComponents = [\n this.options.target,\n this.options.adapter,\n ...(this.options.extensionPacks ?? []),\n ];\n this.frameworkComponents = assertFrameworkComponentsCompatible(\n this.options.family.familyId,\n this.options.target.targetId,\n rawComponents,\n );\n\n this.initialized = true;\n }\n\n async connect(connection?: unknown): Promise<void> {\n // Auto-init if needed\n this.init();\n\n if (this.driver) {\n throw new Error('Already connected. Call close() before reconnecting.');\n }\n\n // Resolve connection: argument > default from options\n const resolvedConnection = connection ?? this.defaultConnection;\n if (resolvedConnection === undefined) {\n throw new Error(\n 'No connection provided. Pass a connection to connect() or provide a default connection when creating the client.',\n );\n }\n\n // Check for driver descriptor\n if (!this.stack?.driver) {\n throw new Error(\n 'Driver is not configured. Pass a driver descriptor when creating the control client to enable database operations.',\n );\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: required for runtime connection type flexibility\n this.driver = await this.stack.driver.create(resolvedConnection as any);\n }\n\n async close(): Promise<void> {\n if (this.driver) {\n await this.driver.close();\n this.driver = null;\n }\n }\n\n private async ensureConnected(): Promise<{\n driver: ControlDriverInstance<string, string>;\n familyInstance: ControlFamilyInstance<string, unknown>;\n frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<string, string>>;\n }> {\n // Auto-init if needed\n this.init();\n\n // Auto-connect if not connected and default connection is available\n if (!this.driver && this.defaultConnection !== undefined) {\n await this.connect(this.defaultConnection);\n }\n\n if (!this.driver || !this.familyInstance || !this.frameworkComponents) {\n throw new Error('Not connected. Call connect(connection) first.');\n }\n return {\n driver: this.driver,\n familyInstance: this.familyInstance,\n frameworkComponents: this.frameworkComponents,\n };\n }\n\n private async connectWithProgress(\n connection: unknown | undefined,\n action: ControlActionName,\n onProgress?: OnControlProgress,\n ): Promise<void> {\n if (connection === undefined) return;\n onProgress?.({\n action,\n kind: 'spanStart',\n spanId: 'connect',\n label: 'Connecting to database...',\n });\n try {\n await this.connect(connection);\n onProgress?.({ action, kind: 'spanEnd', spanId: 'connect', outcome: 'ok' });\n } catch (error) {\n onProgress?.({ action, kind: 'spanEnd', spanId: 'connect', outcome: 'error' });\n throw error;\n }\n }\n\n async verify(options: VerifyOptions): Promise<VerifyDatabaseResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'verify', onProgress);\n const { driver, familyInstance } = await this.ensureConnected();\n\n // Validate contract using family instance\n let contract: Contract;\n try {\n contract = familyInstance.validateContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n // Emit verify span\n onProgress?.({\n action: 'verify',\n kind: 'spanStart',\n spanId: 'verify',\n label: 'Verifying database marker...',\n });\n\n try {\n // Delegate to family instance verify method\n // Note: We pass empty strings for contractPath/configPath since the programmatic\n // API doesn't deal with file paths. The family instance accepts these as optional\n // metadata for error reporting.\n const result = await familyInstance.verify({\n driver,\n contract,\n expectedTargetId: this.options.target.targetId,\n contractPath: '',\n });\n\n onProgress?.({\n action: 'verify',\n kind: 'spanEnd',\n spanId: 'verify',\n outcome: result.ok ? 'ok' : 'error',\n });\n\n return result;\n } catch (error) {\n onProgress?.({\n action: 'verify',\n kind: 'spanEnd',\n spanId: 'verify',\n outcome: 'error',\n });\n throw error;\n }\n }\n\n async schemaVerify(options: SchemaVerifyOptions): Promise<VerifyDatabaseSchemaResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'schemaVerify', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n // Validate contract using family instance\n let contract: Contract;\n try {\n contract = familyInstance.validateContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n // Emit schemaVerify span\n onProgress?.({\n action: 'schemaVerify',\n kind: 'spanStart',\n spanId: 'schemaVerify',\n label: 'Verifying database schema...',\n });\n\n try {\n // Delegate to family instance schemaVerify method\n const result = await familyInstance.schemaVerify({\n driver,\n contract,\n strict: options.strict ?? false,\n contractPath: '',\n frameworkComponents,\n });\n\n onProgress?.({\n action: 'schemaVerify',\n kind: 'spanEnd',\n spanId: 'schemaVerify',\n outcome: result.ok ? 'ok' : 'error',\n });\n\n return result;\n } catch (error) {\n onProgress?.({\n action: 'schemaVerify',\n kind: 'spanEnd',\n spanId: 'schemaVerify',\n outcome: 'error',\n });\n throw error;\n }\n }\n\n async sign(options: SignOptions): Promise<SignDatabaseResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'sign', onProgress);\n const { driver, familyInstance } = await this.ensureConnected();\n\n // Validate contract using family instance\n let contract: Contract;\n try {\n contract = familyInstance.validateContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n // Emit sign span\n onProgress?.({\n action: 'sign',\n kind: 'spanStart',\n spanId: 'sign',\n label: 'Signing database...',\n });\n\n try {\n // Delegate to family instance sign method\n const result = await familyInstance.sign({\n driver,\n contract,\n contractPath: options.contractPath ?? '',\n ...ifDefined('configPath', options.configPath),\n });\n\n onProgress?.({\n action: 'sign',\n kind: 'spanEnd',\n spanId: 'sign',\n outcome: 'ok',\n });\n\n return result;\n } catch (error) {\n onProgress?.({\n action: 'sign',\n kind: 'spanEnd',\n spanId: 'sign',\n outcome: 'error',\n });\n throw error;\n }\n }\n\n async dbInit(options: DbInitOptions): Promise<DbInitResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'dbInit', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n if (!hasMigrations(this.options.target)) {\n throw new Error(`Target \"${this.options.target.targetId}\" does not support migrations`);\n }\n\n let contract: Contract;\n try {\n contract = familyInstance.validateContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n return executeDbInit({\n driver,\n familyInstance,\n contract,\n mode: options.mode,\n migrations: this.options.target.migrations,\n frameworkComponents,\n migrationsDir: options.migrationsDir,\n targetId: this.options.target.targetId,\n extensionPacks: this.options.extensionPacks ?? [],\n ...ifDefined('onProgress', onProgress),\n });\n }\n\n async dbUpdate(options: DbUpdateOptions): Promise<DbUpdateResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'dbUpdate', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n if (!hasMigrations(this.options.target)) {\n throw new Error(`Target \"${this.options.target.targetId}\" does not support migrations`);\n }\n\n let contract: Contract;\n try {\n contract = familyInstance.validateContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n return executeDbUpdate({\n driver,\n familyInstance,\n contract,\n mode: options.mode,\n migrations: this.options.target.migrations,\n frameworkComponents,\n migrationsDir: options.migrationsDir,\n targetId: this.options.target.targetId,\n extensionPacks: this.options.extensionPacks ?? [],\n ...ifDefined('acceptDataLoss', options.acceptDataLoss),\n ...ifDefined('onProgress', onProgress),\n });\n }\n\n async dbVerify(options: DbVerifyOptions): Promise<ExecuteDbVerifyResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'dbVerify', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n let contract: Contract;\n try {\n contract = familyInstance.validateContract(options.contract);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ContractValidationError(message, error);\n }\n\n return executeDbVerify({\n driver,\n familyInstance,\n contract,\n migrationsDir: options.migrationsDir,\n targetId: this.options.target.targetId,\n extensionPacks: this.options.extensionPacks ?? [],\n frameworkComponents,\n mode: options.strict ? 'strict' : 'lenient',\n skipSchema: options.skipSchema,\n skipMarker: options.skipMarker,\n ...ifDefined('onProgress', onProgress),\n });\n }\n\n async readMarker(): Promise<ContractMarkerRecord | null> {\n const { driver, familyInstance } = await this.ensureConnected();\n // The CLI client's readMarker reads the app's marker. Per-extension\n // readers go through the orchestrator's per-space planner / runner\n // boundary, which threads the extension's space id through the\n // family interface explicitly.\n return familyInstance.readMarker({ driver, space: APP_SPACE_ID });\n }\n\n async readAllMarkers(): Promise<ReadonlyMap<string, ContractMarkerRecord>> {\n const { driver, familyInstance } = await this.ensureConnected();\n return familyInstance.readAllMarkers({ driver });\n }\n\n async migrationApply(options: MigrationApplyOptions): Promise<MigrationApplyResult> {\n const { onProgress } = options;\n await this.connectWithProgress(options.connection, 'migrationApply', onProgress);\n const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();\n\n if (!hasMigrations(this.options.target)) {\n throw new Error(`Target \"${this.options.target.targetId}\" does not support migrations`);\n }\n\n return executeMigrationApply({\n driver,\n familyInstance,\n originHash: options.originHash,\n destinationHash: options.destinationHash,\n pendingMigrations: options.pendingMigrations,\n migrations: this.options.target.migrations,\n frameworkComponents,\n targetId: this.options.target.targetId,\n ...(onProgress ? { onProgress } : {}),\n });\n }\n\n async introspect(options?: IntrospectOptions): Promise<unknown> {\n const onProgress = options?.onProgress;\n await this.connectWithProgress(options?.connection, 'introspect', onProgress);\n const { driver, familyInstance } = await this.ensureConnected();\n\n // TODO: Pass schema option to familyInstance.introspect when schema filtering is implemented\n const _schema = options?.schema;\n void _schema;\n\n // Emit introspect span\n onProgress?.({\n action: 'introspect',\n kind: 'spanStart',\n spanId: 'introspect',\n label: 'Introspecting database schema...',\n });\n\n try {\n const result = await familyInstance.introspect({ driver });\n\n onProgress?.({\n action: 'introspect',\n kind: 'spanEnd',\n spanId: 'introspect',\n outcome: 'ok',\n });\n\n return result;\n } catch (error) {\n onProgress?.({\n action: 'introspect',\n kind: 'spanEnd',\n spanId: 'introspect',\n outcome: 'error',\n });\n throw error;\n }\n }\n\n toSchemaView(schemaIR: unknown): CoreSchemaView | undefined {\n this.init();\n if (this.familyInstance && hasSchemaView(this.familyInstance)) {\n return this.familyInstance.toSchemaView(schemaIR);\n }\n return undefined;\n }\n\n inferPslContract(schemaIR: unknown): PslDocumentAst | undefined {\n this.init();\n if (this.familyInstance && hasPslContractInfer(this.familyInstance)) {\n return this.familyInstance.inferPslContract(schemaIR);\n }\n return undefined;\n }\n\n toOperationPreview(operations: readonly MigrationPlanOperation[]): OperationPreview | undefined {\n this.init();\n if (this.familyInstance && hasOperationPreview(this.familyInstance)) {\n return this.familyInstance.toOperationPreview(operations);\n }\n return undefined;\n }\n\n async emit(options: EmitOptions): Promise<EmitResult> {\n const { onProgress, contractConfig } = options;\n\n // Ensure initialized (creates stack and family instance)\n // emit() does NOT require a database connection\n this.init();\n\n if (!this.familyInstance) {\n throw new Error('Family instance was not initialized. This is a bug.');\n }\n\n let contractRaw: unknown;\n onProgress?.({\n action: 'emit',\n kind: 'spanStart',\n spanId: 'resolveSource',\n label: 'Resolving contract source...',\n });\n\n try {\n const stack = this.stack!;\n const sourceContext = {\n composedExtensionPacks: stack.extensionPacks.map((p) => p.id),\n scalarTypeDescriptors: stack.scalarTypeDescriptors,\n authoringContributions: stack.authoringContributions,\n codecLookup: stack.codecLookup,\n controlMutationDefaults: stack.controlMutationDefaults,\n resolvedInputs: contractConfig.source.inputs ?? [],\n };\n const providerResult = await contractConfig.source.load(sourceContext);\n if (!providerResult.ok) {\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'resolveSource',\n outcome: 'error',\n });\n\n return notOk({\n code: 'CONTRACT_SOURCE_INVALID',\n summary: providerResult.failure.summary,\n why: providerResult.failure.summary,\n meta: providerResult.failure.meta,\n diagnostics: providerResult.failure,\n });\n }\n contractRaw = providerResult.value;\n\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'resolveSource',\n outcome: 'ok',\n });\n } catch (error) {\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'resolveSource',\n outcome: 'error',\n });\n\n const message = error instanceof Error ? error.message : String(error);\n return notOk({\n code: 'CONTRACT_SOURCE_INVALID',\n summary: 'Failed to resolve contract source',\n why: message,\n diagnostics: {\n summary: 'Contract source provider threw an exception',\n diagnostics: [\n {\n code: 'PROVIDER_THROW',\n message,\n },\n ],\n },\n meta: undefined,\n });\n }\n\n // Emit contract\n onProgress?.({\n action: 'emit',\n kind: 'spanStart',\n spanId: 'emit',\n label: 'Emitting contract...',\n });\n\n try {\n const enrichedIR = enrichContract(contractRaw as Contract, this.frameworkComponents ?? []);\n\n try {\n this.familyInstance.validateContract(enrichedIR);\n } catch (error) {\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'emit',\n outcome: 'error',\n });\n const message = error instanceof Error ? error.message : String(error);\n return notOk({\n code: 'CONTRACT_VALIDATION_FAILED',\n summary: 'Contract validation failed',\n why: message,\n meta: undefined,\n });\n }\n\n const result = await emitContractArtifacts(\n enrichedIR,\n this.stack!,\n this.options.family.emission,\n );\n\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'emit',\n outcome: 'ok',\n });\n\n return ok({\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n profileHash: result.profileHash,\n contractJson: result.contractJson,\n contractDts: result.contractDts,\n });\n } catch (error) {\n onProgress?.({\n action: 'emit',\n kind: 'spanEnd',\n spanId: 'emit',\n outcome: 'error',\n });\n\n return notOk({\n code: 'EMIT_FAILED',\n summary: 'Failed to emit contract',\n why: error instanceof Error ? error.message : String(error),\n meta: undefined,\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAa,0BAAb,cAA6C,MAAM;CACjD;CAEA,YAAY,SAAiB,OAAiB;EAC5C,MAAM,QAAQ;EACd,KAAK,OAAO;EACZ,KAAK,QAAQ;;;;;;;;;;;;;;;;;ACkCjB,SAAS,qBAAqB,gBAG5B;CACA,MAAM,UAAoC,EAAE;CAC5C,MAAM,qCAAqB,IAAI,KAAsB;CACrD,KAAK,MAAM,QAAQ,gBAAgB;EACjC,MAAM,QAAgC,KAAK,gBACvC;GACE,IAAI,KAAK;GACT,UAAU,KAAK;GACf,eAAe,EAAE,cAAc,KAAK,cAAc,cAAc;GACjE,GACD;GAAE,IAAI,KAAK;GAAI,UAAU,KAAK;GAAU;EAC5C,QAAQ,KAAK,MAAM;EACnB,IAAI,KAAK,eACP,mBAAmB,IAAI,KAAK,cAAc,cAAc,KAAK,cAAc,QAAQ,KAAK;;CAG5F,OAAO;EAAE;EAAS;EAAoB;;;;;;;;;AAUxC,SAAgB,sBAAsB,OAA+C;CACnF,IAAI,MAAM,SAAS,mBAAmB;EACpC,MAAM,QAAQ,MAAM,WAAW,KAAK,MAAM,MAAM,EAAE,KAAK,IAAI,EAAE,UAAU;EAKvE,OAAO,IAAI,mBAAmB,QAH5B,MAAM,WAAW,WAAW,IACxB,6CACA,8CAA8C,MAAM,WAAW,OAAO,IAC7B;GAC7C,QAAQ;GACR,KAAK,wGAAwG,MAAM,KAAK,KAAK;GAC7H,KAAK;GACL,SAAS;GACT,MAAM,EACJ,YAAY,MAAM,WAAW,KAAK,OAAO;IACvC,MAAM,EAAE;IACR,SAAS,EAAE;IACZ,EAAE,EACJ;GACF,CAAC;;CAEJ,IAAI,MAAM,SAAS,kBACj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N,SAAS;IACT,KAAK;IACL,aAAa;KACX,SAAS;KACT,aAAa,CACX;MACE,MAAM;MACN;MACD,CACF;KACF;IACD,MAAM,KAAA;IACP,CAAC;;EAIJ,aAAa;GACX,QAAQ;GACR,MAAM;GACN,QAAQ;GACR,OAAO;GACR,CAAC;EAEF,IAAI;GACF,MAAM,aAAa,eAAe,aAAyB,KAAK,uBAAuB,EAAE,CAAC;GAE1F,IAAI;IACF,KAAK,eAAe,iBAAiB,WAAW;YACzC,OAAO;IACd,aAAa;KACX,QAAQ;KACR,MAAM;KACN,QAAQ;KACR,SAAS;KACV,CAAC;IAEF,OAAO,MAAM;KACX,MAAM;KACN,SAAS;KACT,KAJc,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;KAKpE,MAAM,KAAA;KACP,CAAC;;GAGJ,MAAM,SAAS,MAAMC,KACnB,YACA,KAAK,OACL,KAAK,QAAQ,OAAO,SACrB;GAED,aAAa;IACX,QAAQ;IACR,MAAM;IACN,QAAQ;IACR,SAAS;IACV,CAAC;GAEF,OAAO,GAAG;IACR,aAAa,OAAO;IACpB,GAAG,UAAU,iBAAiB,OAAO,cAAc;IACnD,aAAa,OAAO;IACpB,cAAc,OAAO;IACrB,aAAa,OAAO;IACrB,CAAC;WACK,OAAO;GACd,aAAa;IACX,QAAQ;IACR,MAAM;IACN,QAAQ;IACR,SAAS;IACV,CAAC;GAEF,OAAO,MAAM;IACX,MAAM;IACN,SAAS;IACT,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;IAC3D,MAAM,KAAA;IACP,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"migration-plan-BcKNnTM7.mjs","names":[],"sources":["../src/utils/contract-space-extension-migrations-pass.ts","../src/utils/contract-space-migrate-pass.ts","../src/commands/migration-plan.ts"],"sourcesContent":["import { materialiseExtensionMigrationPackageIfMissing } from '@prisma-next/migration-tools/io';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport type { MigrationOps } from '@prisma-next/migration-tools/package';\nimport {\n planAllSpaces,\n type SpacePlanOutput,\n spaceMigrationDirectory,\n} from '@prisma-next/migration-tools/spaces';\n\n/**\n * In-memory authored migration package shipped by an extension descriptor.\n * Mirrors `MigrationPackage` from `@prisma-next/migration-tools/io`\n * (the on-disk shape minus `dirPath`); redeclared structurally here so\n * the CLI helper does not couple to the SQL family's `ExtensionMigrationPackage`\n * type — any family that ships pre-built migration packages can pass them\n * through unchanged.\n */\nexport interface DescriptorMigrationPackage {\n readonly dirName: string;\n readonly metadata: MigrationMetadata;\n readonly ops: MigrationOps;\n}\n\n/**\n * Minimal descriptor view consumed by the migration-materialisation pass.\n * Mirrors {@link import('./contract-space-migrate-pass').MigrateExtensionInput}\n * but adds the `migrations` field — the canonical set of pre-built\n * migration packages the extension ships.\n */\nexport interface ExtensionMigrationsExtensionInput {\n readonly id: string;\n readonly contractSpace?: {\n readonly contractJson: unknown;\n readonly migrations: readonly DescriptorMigrationPackage[];\n readonly headRef: { readonly hash: string; readonly invariants: readonly string[] };\n };\n}\n\nexport interface ContractSpaceExtensionMigrationsPassInputs {\n readonly migrationsDir: string;\n readonly extensionPacks: ReadonlyArray<ExtensionMigrationsExtensionInput>;\n}\n\nexport interface ContractSpaceExtensionMigrationsPassResult {\n readonly emitted: readonly { readonly spaceId: string; readonly dirName: string }[];\n readonly skipped: readonly { readonly spaceId: string; readonly dirName: string }[];\n}\n\n/**\n * Materialise an extension's pre-built migration packages onto disk\n * under `migrations/<spaceId>/<dirName>/` for every package that does\n * not yet exist there.\n *\n * Helper-location pattern — the per-space \"planner\" for extension\n * spaces is a no-op that just returns the descriptor's `migrations`\n * verbatim; the value `planAllSpaces` brings to this consumer site is\n * **deterministic ordering** (alphabetical by spaceId) and\n * **duplicate-spaceId detection**. The actual write is performed via\n * `materialiseMigrationPackage` per package.\n *\n * Idempotent: an existing `migrations/<spaceId>/<dirName>/` is left\n * untouched and reported in `result.skipped` — the helper never\n * overwrites authored migration content, ensuring re-running\n * `migrate` does not corrupt or churn extension migration packages.\n *\n * Per-space artefacts (`contract.json`, `contract.d.ts`,\n * `refs/head.json`) are emitted by\n * {@link import('./contract-space-migrate-pass').runContractSpaceMigratePass}\n * separately — they cover the head-pointer side of the ledger. This\n * helper covers the migration-graph side.\n */\nexport async function runContractSpaceExtensionMigrationsPass(\n inputs: ContractSpaceExtensionMigrationsPassInputs,\n): Promise<ContractSpaceExtensionMigrationsPassResult> {\n const planInputs = inputs.extensionPacks\n .filter(\n (\n pack,\n ): pack is ExtensionMigrationsExtensionInput & {\n contractSpace: NonNullable<ExtensionMigrationsExtensionInput['contractSpace']>;\n } => pack.contractSpace !== undefined,\n )\n .map((pack) => ({\n spaceId: pack.id,\n priorContract: null,\n newContract: pack.contractSpace.contractJson,\n __migrations: pack.contractSpace.migrations,\n }));\n\n // Threading the descriptor's pre-built migrations into the\n // `planAllSpaces` callback by piggybacking on the input shape.\n // The framework helper is generic over the per-space planner output;\n // here the \"planner\" is a no-op that returns the descriptor's\n // `migrations` array. The benefit of routing through `planAllSpaces`\n // is duplicate-spaceId detection + alphabetical ordering — failures\n // there throw `MIGRATION.DUPLICATE_SPACE_ID` before any write.\n const planned: readonly SpacePlanOutput<DescriptorMigrationPackage>[] = planAllSpaces(\n planInputs,\n (input) =>\n (input as typeof input & { readonly __migrations: readonly DescriptorMigrationPackage[] })\n .__migrations,\n );\n\n const emitted: { spaceId: string; dirName: string }[] = [];\n const skipped: { spaceId: string; dirName: string }[] = [];\n\n for (const space of planned) {\n const spaceDir = spaceMigrationDirectory(inputs.migrationsDir, space.spaceId);\n for (const pkg of space.migrationPackages) {\n const { written } = await materialiseExtensionMigrationPackageIfMissing(spaceDir, pkg);\n if (written) {\n emitted.push({ spaceId: space.spaceId, dirName: pkg.dirName });\n } else {\n skipped.push({ spaceId: space.spaceId, dirName: pkg.dirName });\n }\n }\n }\n\n return { emitted, skipped };\n}\n","import {\n detectSpaceContractDrift,\n emitContractSpaceArtefacts,\n readContractSpaceHeadRef,\n type SpaceContractDriftResult,\n} from '@prisma-next/migration-tools/spaces';\n\n/**\n * Minimal descriptor view consumed by the migrate-time per-space pass.\n *\n * The CLI receives descriptors typed against the SQL family (or any other\n * family in the future); this helper only needs the structural shape of\n * `contractSpace`, so it accepts an `unknown`-typed `contractJson` and\n * a structurally-typed `headRef`. SQL-family callers pass the same\n * `Contract<SqlStorage>` value through unchanged — `emitContractSpaceArtefacts`\n * already serialises through `canonicalizeJson` and is framework-neutral.\n *\n * @see specs/framework-mechanism.spec.md § 3 — Per-space helper location.\n */\nexport interface MigrateExtensionInput {\n readonly id: string;\n readonly contractSpace?: {\n readonly contractJson: unknown;\n readonly headRef: { readonly hash: string; readonly invariants: readonly string[] };\n };\n}\n\n/**\n * Inputs needed to compose the migrate-time per-space pass at the CLI\n * surface — typically called once after the app-space migration package\n * has been written, regardless of whether the app-space had structural\n * changes (an extension bump alone should still re-pin its artefacts).\n */\nexport interface ContractSpaceMigratePassInputs {\n readonly migrationsDir: string;\n readonly extensionPacks: ReadonlyArray<MigrateExtensionInput>;\n}\n\nexport interface ContractSpaceMigratePassResult {\n readonly drifts: readonly SpaceContractDriftResult[];\n readonly emittedSpaceIds: readonly string[];\n}\n\n/**\n * Run drift detection + on-disk artefact emission for every loaded\n * extension space at `migrate` time.\n *\n * Per sub-spec § 3:\n *\n * - For each declared extension that exposes a `contractSpace`:\n * - Read the on-disk head hash from `migrations/<spaceId>/refs/head.json`\n * (returns `null` on first emit).\n * - Compare against the descriptor's `headRef.hash` via\n * `detectSpaceContractDrift`. The `kind` discriminant decides whether\n * the user sees a warning (`drift`), a no-op silent emit (`firstEmit`,\n * `noDrift`), or nothing at all.\n * - Always re-emit the on-disk artefacts (`contract.json`, `contract.d.ts`,\n * `refs/head.json`). The framework owns these files and the helper is\n * idempotent.\n *\n * Drift warnings are returned to the caller for formatting (TerminalUI,\n * structured-output envelope, etc.) — the helper does not print directly,\n * keeping it framework-neutral and unit-testable.\n *\n * Extension migration packages (the descriptor's pre-canned `migrations`\n * array → `migrations/<spaceId>/<dirName>/`) are intentionally not\n * materialised here — that interaction will be wired in a follow-on round\n * once the runner-side single-tx slice (sub-spec § 6) is in place.\n * On-disk artefacts are sufficient to lock the drift-warning behaviour\n * and the always-on re-emit AC for R2.\n *\n * @see specs/framework-mechanism.spec.md § 3 — Drift detection (T1.9).\n */\nexport async function runContractSpaceMigratePass(\n inputs: ContractSpaceMigratePassInputs,\n): Promise<ContractSpaceMigratePassResult> {\n const drifts: SpaceContractDriftResult[] = [];\n const emittedSpaceIds: string[] = [];\n\n for (const pack of inputs.extensionPacks) {\n if (pack.contractSpace === undefined) continue;\n const { contractJson, headRef } = pack.contractSpace;\n\n const onDiskHeadRef = await readContractSpaceHeadRef(inputs.migrationsDir, pack.id);\n const drift = detectSpaceContractDrift(pack.id, {\n descriptorHash: headRef.hash,\n priorHeadHash: onDiskHeadRef?.hash ?? null,\n });\n drifts.push(drift);\n\n await emitContractSpaceArtefacts(inputs.migrationsDir, pack.id, {\n contract: contractJson,\n contractDts: buildPlaceholderContractDts(pack.id),\n headRef: { hash: headRef.hash, invariants: headRef.invariants },\n });\n emittedSpaceIds.push(pack.id);\n }\n\n return { drifts, emittedSpaceIds };\n}\n\n/**\n * Format the user-facing drift warning for a single space. Callers\n * funnel this through their preferred output channel (TerminalUI line,\n * structured-output envelope `warnings[]`, etc.).\n *\n * Locks AM7 — drift warning surfaces the extension name and the diff\n * direction (descriptor → on-disk head).\n */\nexport function formatContractSpaceDriftWarning(drift: SpaceContractDriftResult): string {\n if (drift.kind !== 'drift') {\n throw new Error(`formatContractSpaceDriftWarning called with non-drift result: ${drift.kind}`);\n }\n return (\n `Contract-space drift detected for \"${drift.spaceId}\": descriptor hash ` +\n `${drift.descriptorHash} differs from on-disk head hash ${drift.priorHeadHash ?? '<none>'}. ` +\n `The on-disk artefacts under migrations/${drift.spaceId}/ will be refreshed to match the descriptor.`\n );\n}\n\n/**\n * Placeholder `.d.ts` content for an extension space's on-disk mirror.\n *\n * Rendering a fully-typed `.d.ts` for an extension contract requires the\n * SQL-family renderer with the codec / typemap registry threaded\n * through; that integration is tracked under sub-spec Open Question 3\n * (see `projects/extension-contract-spaces/specs/framework-mechanism.spec.md`).\n *\n * Until that ships, the on-disk `.d.ts` is a `@ts-nocheck` stub. The\n * spec gap closing alongside the typed renderer is **AC2 / AC14**\n * (byte-equivalence of per-space artefacts under `migrate`):\n * a placeholder cannot be byte-equal to a fully-rendered `.d.ts` from\n * the same descriptor, so AC2 / AC14 are PARTIAL today and become\n * fully-PASS once OQ3 closes.\n *\n * Scheduled to close in **M3** (cipherstash editor tooling) — that's\n * the milestone where the typed renderer gets its first real\n * extension-space consumer and the byte-equivalence guarantee is\n * practically required.\n */\nfunction buildPlaceholderContractDts(spaceId: string): string {\n return [\n '// @ts-nocheck',\n '/**',\n ` * Placeholder \\`.d.ts\\` for extension space \"${spaceId}\".`,\n ' *',\n ' * The framework re-emits this file on every `migrate` run alongside',\n ' * `contract.json` and `refs/head.json`. A typed `.d.ts` rendering',\n \" * pass for extension contracts is tracked under the project's open\",\n ' * questions; until that ships, consumers should import',\n ' * `contract.json` directly with `validateContract<…>(…)`.',\n ' */',\n 'export {};',\n '',\n ].join('\\n');\n}\n","import { readFile } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport {\n APP_SPACE_ID,\n createControlStack,\n hasOperationPreview,\n type MigrationPlanOperation,\n type OperationPreview,\n} from '@prisma-next/framework-components/control';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { computeMigrationHash } from '@prisma-next/migration-tools/hash';\nimport { deriveProvidedInvariants } from '@prisma-next/migration-tools/invariants';\nimport {\n copyFilesWithRename,\n formatMigrationDirName,\n writeMigrationPackage,\n} from '@prisma-next/migration-tools/io';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport { findLatestMigration } from '@prisma-next/migration-tools/migration-graph';\nimport { writeMigrationTs } from '@prisma-next/migration-tools/migration-ts';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { join, relative } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport {\n type CliErrorConflict,\n CliStructuredError,\n errorContractValidationFailed,\n errorFileNotFound,\n errorMigrationPlanningFailed,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n mapMigrationToolsError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n getTargetMigrations,\n loadMigrationPackages,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport {\n type ExtensionMigrationsExtensionInput,\n runContractSpaceExtensionMigrationsPass,\n} from '../utils/contract-space-extension-migrations-pass';\nimport {\n formatContractSpaceDriftWarning,\n type MigrateExtensionInput,\n runContractSpaceMigratePass,\n} from '../utils/contract-space-migrate-pass';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport { assertFrameworkComponentsCompatible } from '../utils/framework-components';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationPlanOptions extends CommonCommandOptions {\n readonly config?: string;\n readonly name?: string;\n readonly from?: string;\n}\n\nexport interface MigrationPlanResult {\n readonly ok: boolean;\n readonly noOp: boolean;\n readonly from: string | null;\n readonly to: string;\n readonly dir?: string;\n readonly operations: readonly {\n readonly id: string;\n readonly label: string;\n readonly operationClass: string;\n }[];\n /**\n * Family-agnostic textual preview of the migration plan operations.\n * Replaces the previous `sql?: readonly string[]` field; consumers should\n * read `result.preview?.statements`.\n */\n readonly preview?: OperationPreview;\n readonly summary: string;\n /**\n * When true, `migration.ts` was written but contains unfilled\n * `placeholder(...)` calls. The user must edit the file and then run\n * `node migration.ts` to self-emit `ops.json` / `migration.json`.\n */\n readonly pendingPlaceholders?: boolean;\n readonly timings: {\n readonly total: number;\n };\n}\n\nasync function executeMigrationPlanCommand(\n options: MigrationPlanOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<MigrationPlanResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, appMigrationsDir, appMigrationsRelative } =\n resolveMigrationPaths(options.config, config);\n\n const contractPathAbsolute = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n { label: 'migrations', value: appMigrationsRelative },\n ];\n if (options.from) {\n details.push({ label: 'from', value: options.from });\n }\n if (options.name) {\n details.push({ label: 'name', value: options.name });\n }\n const header = formatStyledHeader({\n command: 'migration plan',\n description: 'Plan a migration from contract changes',\n url: 'https://pris.ly/migration-plan',\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // Load contract file (the \"to\" contract)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n let toContractJson: Contract;\n try {\n toContractJson = JSON.parse(contractJsonContent) as Contract;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n const rawStorageHash = toContractJson.storage?.storageHash;\n if (typeof rawStorageHash !== 'string') {\n return notOk(\n errorContractValidationFailed('Contract is missing storageHash', {\n where: { path: contractPathAbsolute },\n }),\n );\n }\n const toStorageHash = rawStorageHash;\n\n // Read existing migrations and determine \"from\" contract\n let fromContract: Contract | null = null;\n let fromHash: string | null = null;\n let fromContractSourceDir: string | null = null;\n\n try {\n const { bundles, graph } = await loadMigrationPackages(appMigrationsDir);\n\n if (options.from) {\n const resolved = resolveBundleByPrefix(bundles, options.from);\n if (!resolved.ok) {\n const f = resolved.failure;\n return notOk(\n f.reason === 'ambiguous'\n ? errorRuntime('Multiple matching migrations found', {\n why: `Prefix \"${options.from}\" matches ${f.count} migrations in ${appMigrationsRelative}`,\n fix: 'Provide a longer prefix to disambiguate, or omit --from to use the latest migration target.',\n })\n : errorRuntime('Starting contract not found', {\n why: `No migration with to hash matching \"${options.from}\" exists in ${appMigrationsRelative}`,\n fix: 'Check that the --from hash matches a known migration target hash, or omit --from to use the latest migration target.',\n }),\n );\n }\n fromHash = resolved.value.metadata.to;\n fromContract = resolved.value.metadata.toContract;\n fromContractSourceDir = resolved.value.dirPath;\n } else {\n const latestMigration = findLatestMigration(graph);\n if (latestMigration) {\n fromHash = latestMigration.to;\n const leafPkg = bundles.find(\n (p) => p.metadata.migrationHash === latestMigration.migrationHash,\n );\n if (leafPkg) {\n fromContract = leafPkg.metadata.toContract;\n fromContractSourceDir = leafPkg.dirPath;\n }\n }\n }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n // Wrap unexpected (non-MigrationToolsError) failures from the migration\n // load phase in a structured CLI envelope. Letting them throw would\n // bypass `handleResult()` and crash the command — see CLI structured-\n // errors guideline (CliStructuredError + Result pattern).\n const message = error instanceof Error ? error.message : String(error);\n return notOk(\n errorUnexpected(message, {\n why: `Unexpected error while loading migrations: ${message}`,\n }),\n );\n }\n\n // Per-space migrate pass: drift detection + on-disk artefact emission for\n // every loaded extension that exposes a `contractSpace`. Runs *before*\n // the app-space no-op check so that an extension bump alone (with no\n // structural app-space change) still re-pins extension artefacts on\n // disk. Drift warnings are non-fatal — the on-disk artefacts are refreshed\n // and the user is notified that the bump is being captured.\n const extensionInputs: readonly MigrateExtensionInput[] = (config.extensionPacks ?? []).map(\n (pack) => {\n const cs = (pack as { readonly contractSpace?: MigrateExtensionInput['contractSpace'] })\n .contractSpace;\n return cs !== undefined ? { id: pack.id, contractSpace: cs } : { id: pack.id };\n },\n );\n const migratePass = await runContractSpaceMigratePass({\n migrationsDir,\n extensionPacks: extensionInputs,\n });\n if (!flags.json && !flags.quiet) {\n for (const drift of migratePass.drifts) {\n if (drift.kind === 'drift') {\n ui.stderr(formatContractSpaceDriftWarning(drift));\n }\n }\n }\n\n // Materialise descriptor-shipped migration packages onto disk under\n // `migrations/<spaceId>/<dirName>/` for any package not yet present.\n // Idempotent (existing dirs are left untouched).\n // Uses `planAllSpaces` for deterministic ordering + duplicate-spaceId\n // detection.\n const extensionMigrationsInputs: readonly ExtensionMigrationsExtensionInput[] = (\n config.extensionPacks ?? []\n ).map((pack) => {\n const cs = (\n pack as {\n readonly contractSpace?: ExtensionMigrationsExtensionInput['contractSpace'];\n }\n ).contractSpace;\n return cs !== undefined ? { id: pack.id, contractSpace: cs } : { id: pack.id };\n });\n const extensionMigrationsResult = await runContractSpaceExtensionMigrationsPass({\n migrationsDir,\n extensionPacks: extensionMigrationsInputs,\n });\n if (!flags.json && !flags.quiet) {\n for (const entry of extensionMigrationsResult.emitted) {\n ui.step(`Emitted ${entry.spaceId}/${entry.dirName}`);\n }\n }\n\n // Check for no-op (same hash means no changes)\n if (fromHash === toStorageHash) {\n const result: MigrationPlanResult = {\n ok: true,\n noOp: true,\n from: fromHash,\n to: toStorageHash,\n operations: [],\n summary: 'No changes detected between contracts',\n timings: { total: Date.now() - startTime },\n };\n return ok(result);\n }\n\n // Check target supports migrations\n const migrations = getTargetMigrations(config.target);\n if (!migrations) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n [config.target, config.adapter, ...(config.extensionPacks ?? [])],\n );\n\n // Build manifest and write migration package\n const timestamp = new Date();\n const slug = options.name ?? 'migration';\n const dirName = formatMigrationDirName(timestamp, slug);\n const packageDir = join(appMigrationsDir, dirName);\n\n const baseMetadata: Omit<MigrationMetadata, 'migrationHash' | 'providedInvariants'> = {\n from: fromHash,\n to: toStorageHash,\n fromContract,\n toContract: toContractJson,\n hints: {\n used: [],\n applied: [],\n plannerVersion: '2.0.0',\n },\n labels: [],\n createdAt: timestamp.toISOString(),\n };\n\n try {\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n const planner = migrations.createPlanner(familyInstance);\n const fromSchema = migrations.contractToSchema(fromContract, frameworkComponents);\n const plannerResult = planner.plan({\n contract: toContractJson,\n schema: fromSchema,\n policy: { allowedOperationClasses: ['additive', 'widening', 'destructive', 'data'] },\n fromContract,\n frameworkComponents,\n spaceId: APP_SPACE_ID,\n });\n if (plannerResult.kind === 'failure') {\n return notOk(\n errorMigrationPlanningFailed({\n conflicts: plannerResult.conflicts as readonly CliErrorConflict[],\n }),\n );\n }\n\n // Accessing .operations triggers toOp() on each call. If any call\n // is a DataTransformCall with an unfilled placeholder stub, toOp()\n // throws PN-MIG-2001. We catch that here so the migration can still\n // be scaffolded with `ops: []`; the user fills the placeholder, then\n // re-runs `node migration.ts` to attest with the real ops.\n let plannedOps: readonly MigrationPlanOperation[] = [];\n let hasPlaceholders = false;\n try {\n plannedOps = plannerResult.plan.operations;\n if (plannedOps.length === 0) {\n return notOk(\n errorMigrationPlanningFailed({\n conflicts: [\n {\n kind: 'unsupportedChange',\n summary:\n 'Contract changed but planner produced no operations. ' +\n 'This indicates unsupported or ignored changes.',\n },\n ],\n }),\n );\n }\n } catch (e) {\n if (CliStructuredError.is(e) && e.domain === 'MIG' && e.code === '2001') {\n hasPlaceholders = true;\n } else {\n throw e;\n }\n }\n\n const migrationTsContent = plannerResult.plan.renderTypeScript();\n\n // Always-attest: compute migrationHash over (metadata, ops). When\n // placeholders blocked lowering, ops is `[]` and the hash is computed\n // over the empty list — re-emitting after the user fills the placeholder\n // produces a different hash (over the real ops). This is intentional;\n // there is no on-disk \"draft\" state.\n const opsForWrite = hasPlaceholders ? [] : plannedOps;\n const metadataWithInvariants: Omit<MigrationMetadata, 'migrationHash'> = {\n ...baseMetadata,\n providedInvariants: deriveProvidedInvariants(opsForWrite),\n };\n const metadata: MigrationMetadata = {\n ...metadataWithInvariants,\n migrationHash: computeMigrationHash(metadataWithInvariants, opsForWrite),\n };\n\n await writeMigrationPackage(packageDir, metadata, opsForWrite);\n const destinationArtifacts = getEmittedArtifactPaths(contractPathAbsolute);\n await copyFilesWithRename(packageDir, [\n { sourcePath: destinationArtifacts.jsonPath, destName: 'end-contract.json' },\n { sourcePath: destinationArtifacts.dtsPath, destName: 'end-contract.d.ts' },\n ]);\n if (fromContractSourceDir !== null) {\n const sourceArtifacts = getEmittedArtifactPaths(\n join(fromContractSourceDir, 'end-contract.json'),\n );\n await copyFilesWithRename(packageDir, [\n { sourcePath: sourceArtifacts.jsonPath, destName: 'start-contract.json' },\n { sourcePath: sourceArtifacts.dtsPath, destName: 'start-contract.d.ts' },\n ]);\n }\n await writeMigrationTs(packageDir, migrationTsContent);\n\n if (hasPlaceholders) {\n const result: MigrationPlanResult = {\n ok: true,\n noOp: false,\n from: fromHash,\n to: toStorageHash,\n dir: relative(process.cwd(), packageDir),\n operations: [],\n pendingPlaceholders: true,\n summary:\n 'Planned migration with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit',\n timings: { total: Date.now() - startTime },\n };\n return ok(result);\n }\n\n const preview = hasOperationPreview(familyInstance)\n ? familyInstance.toOperationPreview(plannedOps)\n : undefined;\n const result: MigrationPlanResult = {\n ok: true,\n noOp: false,\n from: fromHash,\n to: toStorageHash,\n dir: relative(process.cwd(), packageDir),\n operations: plannedOps.map((op) => ({\n id: op.id,\n label: op.label,\n operationClass: op.operationClass,\n })),\n ...(preview !== undefined ? { preview } : {}),\n summary: `Planned ${plannedOps.length} operation(s)`,\n timings: { total: Date.now() - startTime },\n };\n return ok(result);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n const message = error instanceof Error ? error.message : String(error);\n return notOk(\n errorUnexpected(message, {\n why: `Unexpected error during migration plan: ${message}`,\n }),\n );\n }\n}\n\nexport function createMigrationPlanCommand(): Command {\n const command = new Command('plan');\n setCommandDescriptions(\n command,\n 'Plan a migration from contract changes',\n 'Compares the emitted contract against the latest on-disk migration state and\\n' +\n 'produces a new migration package with the required operations. No database\\n' +\n 'connection is needed — this is a fully offline operation.',\n );\n setCommandExamples(command, [\n 'prisma-next migration plan',\n 'prisma-next migration plan --name add-users-table',\n ]);\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--name <slug>', 'Name slug for the migration directory', 'migration')\n .option('--from <hash>', 'Explicit starting contract hash (overrides latest migration target)')\n .action(async (options: MigrationPlanOptions) => {\n const flags = parseGlobalFlags(options);\n const startTime = Date.now();\n\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeMigrationPlanCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (planResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(planResult, null, 2));\n } else if (!flags.quiet) {\n ui.log(formatMigrationPlanOutput(planResult, flags));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n\nfunction formatMigrationPlanOutput(result: MigrationPlanResult, flags: GlobalFlags): string {\n const lines: string[] = [];\n const useColor = flags.color !== false;\n\n const green_ = useColor ? (s: string) => `\\x1b[32m${s}\\x1b[0m` : (s: string) => s;\n const yellow_ = useColor ? (s: string) => `\\x1b[33m${s}\\x1b[0m` : (s: string) => s;\n const dim_ = useColor ? (s: string) => `\\x1b[2m${s}\\x1b[0m` : (s: string) => s;\n\n if (result.noOp) {\n lines.push(`${green_('✔')} No changes detected`);\n lines.push(dim_(` from: ${result.from}`));\n lines.push(dim_(` to: ${result.to}`));\n return lines.join('\\n');\n }\n\n if (result.pendingPlaceholders) {\n lines.push(`${yellow_('⚠')} ${result.summary}`);\n lines.push('');\n lines.push(dim_(`from: ${result.from}`));\n lines.push(dim_(`to: ${result.to}`));\n if (result.dir) {\n lines.push(dim_(`dir: ${result.dir}`));\n }\n lines.push('');\n lines.push(\n 'Open migration.ts and replace each `placeholder(...)` call with your actual query.',\n );\n lines.push(`Then run: ${green_(`node ${result.dir ?? '<dir>'}/migration.ts`)}`);\n return lines.join('\\n');\n }\n\n lines.push(`${green_('✔')} ${result.summary}`);\n lines.push('');\n\n if (result.operations.length > 0) {\n lines.push(dim_('│'));\n for (let i = 0; i < result.operations.length; i++) {\n const op = result.operations[i]!;\n const isLast = i === result.operations.length - 1;\n const treeChar = isLast ? '└' : '├';\n const opClassLabel =\n op.operationClass === 'destructive'\n ? yellow_(`[${op.operationClass}]`)\n : dim_(`[${op.operationClass}]`);\n lines.push(`${dim_(treeChar)}─ ${op.label} ${opClassLabel}`);\n }\n\n const hasDestructive = result.operations.some((op) => op.operationClass === 'destructive');\n if (hasDestructive) {\n lines.push('');\n lines.push(\n `${yellow_('⚠')} This migration contains destructive operations that may cause data loss.`,\n );\n }\n lines.push('');\n }\n\n lines.push(dim_(`from: ${result.from}`));\n lines.push(dim_(`to: ${result.to}`));\n if (result.dir) {\n lines.push(dim_(`dir: ${result.dir}`));\n }\n\n lines.push('');\n lines.push(\n `Next: review ${green_(result.dir ?? '<dir>')} if needed, then run ${green_('prisma-next migration apply')}.`,\n );\n\n if (result.preview && result.preview.statements.length > 0) {\n // The non-empty length is already guaranteed by the surrounding check, so\n // a plain `every` here is equivalent to the helper in formatters/migrations.ts.\n const allSql = result.preview.statements.every((s) => s.language === 'sql');\n lines.push('');\n lines.push(dim_(allSql ? 'DDL preview' : 'Operation preview'));\n lines.push('');\n for (const statement of result.preview.statements) {\n const trimmed = statement.text.trim();\n if (!trimmed) continue;\n const line = statement.language === 'sql' && !trimmed.endsWith(';') ? `${trimmed};` : trimmed;\n lines.push(line);\n }\n }\n\n if (flags.verbose && result.timings) {\n lines.push('');\n lines.push(dim_(`Total time: ${result.timings.total}ms`));\n }\n\n return lines.join('\\n');\n}\n\nexport type PrefixResolutionFailure =\n | { reason: 'ambiguous'; count: number }\n | { reason: 'not-found' };\n\n/**\n * Resolve a migration package by **target contract hash** (`metadata.to`)\n * using exact match or prefix match.\n *\n * Note: matches `metadata.to` (the contract hash this migration produces),\n * not `metadata.migrationHash` (the package's content-addressed identity).\n * Tries exact match first, then prefix match (auto-prepending `sha256:` when\n * the needle omits the scheme). Returns the matched package on success, or a\n * discriminated failure indicating whether the prefix was ambiguous or simply\n * not found.\n *\n * @internal Exported for testing only.\n */\nexport function resolveBundleByPrefix<T extends { metadata: { to: string } }>(\n bundles: readonly T[],\n needle: string,\n): Result<T, PrefixResolutionFailure> {\n const exact = bundles.find((p) => p.metadata.to === needle);\n if (exact) return ok(exact);\n\n const prefixWithScheme = needle.startsWith('sha256:') ? needle : `sha256:${needle}`;\n const candidates = bundles.filter((p) => p.metadata.to.startsWith(prefixWithScheme));\n\n if (candidates.length === 1) return ok(candidates[0]!);\n if (candidates.length > 1) return notOk({ reason: 'ambiguous', count: candidates.length });\n return notOk({ reason: 'not-found' });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,eAAsB,wCACpB,QACqD;CAuBrD,MAAM,UAAkE,cAtBrD,OAAO,eACvB,QAEG,SAGG,KAAK,kBAAkB,KAAA,EAC7B,CACA,KAAK,UAAU;EACd,SAAS,KAAK;EACd,eAAe;EACf,aAAa,KAAK,cAAc;EAChC,cAAc,KAAK,cAAc;EAClC,EAUS,GACT,UACE,MACE,aACN;CAED,MAAM,UAAkD,EAAE;CAC1D,MAAM,UAAkD,EAAE;CAE1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