prisma-next 0.5.0-dev.66 → 0.5.0-dev.68

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 (115) hide show
  1. package/dist/{cli-errors-By1iVE3z.mjs → cli-errors-D3_sMh2K.mjs} +2 -3
  2. package/dist/{cli-errors-By1iVE3z.mjs.map → cli-errors-D3_sMh2K.mjs.map} +1 -1
  3. package/dist/{cli-errors-DDeVsP2Y.d.mts → cli-errors-QH8kf-C2.d.mts} +0 -2
  4. package/dist/cli.mjs +12 -76
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/client-0ZX24FXF.mjs +1398 -0
  7. package/dist/client-0ZX24FXF.mjs.map +1 -0
  8. package/dist/commands/contract-emit.d.mts.map +1 -1
  9. package/dist/commands/contract-emit.mjs +2 -4
  10. package/dist/commands/contract-infer.d.mts.map +1 -1
  11. package/dist/commands/contract-infer.mjs +2 -4
  12. package/dist/commands/db-init.d.mts.map +1 -1
  13. package/dist/commands/db-init.mjs +11 -11
  14. package/dist/commands/db-init.mjs.map +1 -1
  15. package/dist/commands/db-schema.d.mts.map +1 -1
  16. package/dist/commands/db-schema.mjs +5 -7
  17. package/dist/commands/db-schema.mjs.map +1 -1
  18. package/dist/commands/db-sign.d.mts.map +1 -1
  19. package/dist/commands/db-sign.mjs +8 -9
  20. package/dist/commands/db-sign.mjs.map +1 -1
  21. package/dist/commands/db-update.d.mts.map +1 -1
  22. package/dist/commands/db-update.mjs +11 -11
  23. package/dist/commands/db-update.mjs.map +1 -1
  24. package/dist/commands/db-verify.d.mts.map +1 -1
  25. package/dist/commands/db-verify.mjs +1 -321
  26. package/dist/commands/migration-apply.d.mts.map +1 -1
  27. package/dist/commands/migration-apply.mjs +16 -17
  28. package/dist/commands/migration-apply.mjs.map +1 -1
  29. package/dist/commands/migration-new.d.mts +0 -1
  30. package/dist/commands/migration-new.d.mts.map +1 -1
  31. package/dist/commands/migration-new.mjs +10 -11
  32. package/dist/commands/migration-new.mjs.map +1 -1
  33. package/dist/commands/migration-plan.d.mts.map +1 -1
  34. package/dist/commands/migration-plan.mjs +1 -345
  35. package/dist/commands/migration-ref.d.mts +1 -1
  36. package/dist/commands/migration-ref.d.mts.map +1 -1
  37. package/dist/commands/migration-ref.mjs +5 -6
  38. package/dist/commands/migration-ref.mjs.map +1 -1
  39. package/dist/commands/migration-show.d.mts +1 -1
  40. package/dist/commands/migration-show.d.mts.map +1 -1
  41. package/dist/commands/migration-show.mjs +13 -13
  42. package/dist/commands/migration-show.mjs.map +1 -1
  43. package/dist/commands/migration-status.d.mts.map +1 -1
  44. package/dist/commands/migration-status.mjs +2 -4
  45. package/dist/{config-loader-ih8ViDb_.mjs → config-loader-B6sJjXTv.mjs} +2 -4
  46. package/dist/config-loader-B6sJjXTv.mjs.map +1 -0
  47. package/dist/config-loader.d.mts +0 -1
  48. package/dist/config-loader.d.mts.map +1 -1
  49. package/dist/config-loader.mjs +2 -3
  50. package/dist/{contract-emit-CnTXVVbF.mjs → contract-emit-B3ChISB_.mjs} +22 -13
  51. package/dist/contract-emit-B3ChISB_.mjs.map +1 -0
  52. package/dist/{contract-emit-CcZr3HS9.mjs → contract-emit-DkMqO7f2.mjs} +8 -10
  53. package/dist/contract-emit-DkMqO7f2.mjs.map +1 -0
  54. package/dist/{contract-enrichment-xDeJBC-o.mjs → contract-enrichment-CF6ogEJ_.mjs} +2 -2
  55. package/dist/contract-enrichment-CF6ogEJ_.mjs.map +1 -0
  56. package/dist/{contract-infer-sER84Le-.mjs → contract-infer-BDKAE0B0.mjs} +5 -7
  57. package/dist/{contract-infer-sER84Le-.mjs.map → contract-infer-BDKAE0B0.mjs.map} +1 -1
  58. package/dist/db-verify-B4TdDKOI.mjs +403 -0
  59. package/dist/db-verify-B4TdDKOI.mjs.map +1 -0
  60. package/dist/exports/config-types.mjs +1 -2
  61. package/dist/exports/control-api.d.mts +202 -7
  62. package/dist/exports/control-api.d.mts.map +1 -1
  63. package/dist/exports/control-api.mjs +4 -6
  64. package/dist/exports/index.d.mts.map +1 -1
  65. package/dist/exports/index.mjs +28 -30
  66. package/dist/exports/index.mjs.map +1 -1
  67. package/dist/exports/init-output.d.mts +2 -4
  68. package/dist/exports/init-output.d.mts.map +1 -1
  69. package/dist/exports/init-output.mjs +2 -3
  70. package/dist/{framework-components-Bgcre3Z6.mjs → framework-components-gwAHl7ml.mjs} +3 -4
  71. package/dist/{framework-components-Bgcre3Z6.mjs.map → framework-components-gwAHl7ml.mjs.map} +1 -1
  72. package/dist/{init-DC4sL4Rp.mjs → init-Deo7U8_U.mjs} +13 -30
  73. package/dist/init-Deo7U8_U.mjs.map +1 -0
  74. package/dist/{inspect-live-schema-BQN21nNO.mjs → inspect-live-schema-BAgQMYpD.mjs} +7 -8
  75. package/dist/inspect-live-schema-BAgQMYpD.mjs.map +1 -0
  76. package/dist/migration-cli.d.mts +0 -1
  77. package/dist/migration-cli.d.mts.map +1 -1
  78. package/dist/migration-cli.mjs +2 -3
  79. package/dist/migration-cli.mjs.map +1 -1
  80. package/dist/{migration-command-scaffold-DLmYGRug.mjs → migration-command-scaffold-B8J702Uh.mjs} +7 -8
  81. package/dist/migration-command-scaffold-B8J702Uh.mjs.map +1 -0
  82. package/dist/migration-plan-BcKNnTM7.mjs +530 -0
  83. package/dist/migration-plan-BcKNnTM7.mjs.map +1 -0
  84. package/dist/{migration-status-CDW4RDsO.mjs → migration-status-CjwB2of-.mjs} +10 -14
  85. package/dist/migration-status-CjwB2of-.mjs.map +1 -0
  86. package/dist/{migrations-MEoKMiV5.mjs → migrations-CIK94AJf.mjs} +3 -4
  87. package/dist/migrations-CIK94AJf.mjs.map +1 -0
  88. package/dist/{output-BpcQrnnq.mjs → output-DnjfCC_u.mjs} +9 -3
  89. package/dist/output-DnjfCC_u.mjs.map +1 -0
  90. package/dist/{progress-adapter-DgRGldpT.mjs → progress-adapter-xASh41wr.mjs} +2 -2
  91. package/dist/{progress-adapter-DgRGldpT.mjs.map → progress-adapter-xASh41wr.mjs.map} +1 -1
  92. package/dist/{result-handler-Ch6hVnOo.mjs → result-handler-DWb1rFS-.mjs} +20 -10
  93. package/dist/result-handler-DWb1rFS-.mjs.map +1 -0
  94. package/dist/{terminal-ui-u2YgKghu.mjs → terminal-ui-zaRDhJnP.mjs} +2 -6
  95. package/dist/{terminal-ui-u2YgKghu.mjs.map → terminal-ui-zaRDhJnP.mjs.map} +1 -1
  96. package/dist/{verify-BT9tgCOH.mjs → verify-BEIa9638.mjs} +3 -4
  97. package/dist/verify-BEIa9638.mjs.map +1 -0
  98. package/package.json +17 -17
  99. package/dist/client-hUCMXFE_.mjs +0 -1031
  100. package/dist/client-hUCMXFE_.mjs.map +0 -1
  101. package/dist/commands/db-verify.mjs.map +0 -1
  102. package/dist/commands/migration-plan.mjs.map +0 -1
  103. package/dist/config-loader-ih8ViDb_.mjs.map +0 -1
  104. package/dist/contract-emit-BkRH9lGt.mjs +0 -4
  105. package/dist/contract-emit-CcZr3HS9.mjs.map +0 -1
  106. package/dist/contract-emit-CnTXVVbF.mjs.map +0 -1
  107. package/dist/contract-enrichment-xDeJBC-o.mjs.map +0 -1
  108. package/dist/init-DC4sL4Rp.mjs.map +0 -1
  109. package/dist/inspect-live-schema-BQN21nNO.mjs.map +0 -1
  110. package/dist/migration-command-scaffold-DLmYGRug.mjs.map +0 -1
  111. package/dist/migration-status-CDW4RDsO.mjs.map +0 -1
  112. package/dist/migrations-MEoKMiV5.mjs.map +0 -1
  113. package/dist/output-BpcQrnnq.mjs.map +0 -1
  114. package/dist/result-handler-Ch6hVnOo.mjs.map +0 -1
  115. package/dist/verify-BT9tgCOH.mjs.map +0 -1
@@ -1,8 +1,8 @@
1
- import { t as loadConfig } from "../config-loader-ih8ViDb_.mjs";
2
- import { _ as errorUnexpected, h as errorTargetMigrationNotSupported, m as errorRuntime, t as CliStructuredError, v as mapMigrationToolsError } from "../cli-errors-By1iVE3z.mjs";
3
- import { t as assertFrameworkComponentsCompatible } from "../framework-components-Bgcre3Z6.mjs";
4
- import { t as TerminalUI } from "../terminal-ui-u2YgKghu.mjs";
5
- import { c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, g as parseGlobalFlags, i as getTargetMigrations, l as resolveMigrationPaths, n as addGlobalOptions, t as handleResult, y as formatStyledHeader } from "../result-handler-Ch6hVnOo.mjs";
1
+ import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
2
+ import { _ as errorUnexpected, h as errorTargetMigrationNotSupported, m as errorRuntime, t as CliStructuredError, v as mapMigrationToolsError } from "../cli-errors-D3_sMh2K.mjs";
3
+ import { t as assertFrameworkComponentsCompatible } from "../framework-components-gwAHl7ml.mjs";
4
+ import { t as TerminalUI } from "../terminal-ui-zaRDhJnP.mjs";
5
+ import { c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, g as parseGlobalFlags, i as getTargetMigrations, l as resolveMigrationPaths, n as addGlobalOptions, t as handleResult, y as formatStyledHeader } from "../result-handler-DWb1rFS-.mjs";
6
6
  import { Command } from "commander";
7
7
  import { getEmittedArtifactPaths } from "@prisma-next/emitter";
8
8
  import { notOk, ok } from "@prisma-next/utils/result";
@@ -14,7 +14,6 @@ import { readFileSync } from "node:fs";
14
14
  import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
15
15
  import { computeMigrationHash } from "@prisma-next/migration-tools/hash";
16
16
  import { writeMigrationTs } from "@prisma-next/migration-tools/migration-ts";
17
-
18
17
  //#region src/commands/migration-new.ts
19
18
  /**
20
19
  * `migration new` — scaffolds a migration package with a `migration.ts` file
@@ -27,7 +26,7 @@ import { writeMigrationTs } from "@prisma-next/migration-tools/migration-ts";
27
26
  */
28
27
  async function executeMigrationNewCommand(options) {
29
28
  const config = await loadConfig(options.config);
30
- const { migrationsDir, migrationsRelative } = resolveMigrationPaths(options.config, config);
29
+ const { appMigrationsDir, appMigrationsRelative } = resolveMigrationPaths(options.config, config);
31
30
  const contractPathAbsolute = resolveContractPath(config);
32
31
  let contractJsonContent;
33
32
  try {
@@ -57,13 +56,13 @@ async function executeMigrationNewCommand(options) {
57
56
  let fromHash = null;
58
57
  let fromContractSourceDir = null;
59
58
  try {
60
- const packages = await readMigrationsDir(migrationsDir);
59
+ const packages = await readMigrationsDir(appMigrationsDir);
61
60
  if (packages.length > 0) {
62
61
  const graph = reconstructGraph(packages);
63
62
  if (options.from) {
64
63
  const match = packages.find((p) => p.metadata.to.startsWith(options.from));
65
64
  if (!match) return notOk(errorRuntime("Starting contract not found", {
66
- why: `No migration with to hash matching "${options.from}" exists in ${migrationsRelative}`,
65
+ why: `No migration with to hash matching "${options.from}" exists in ${appMigrationsRelative}`,
67
66
  fix: "Check that the --from hash matches a known migration target hash."
68
67
  }));
69
68
  fromHash = match.metadata.to;
@@ -90,7 +89,7 @@ async function executeMigrationNewCommand(options) {
90
89
  fix: "Change the contract and run `prisma-next contract emit` before creating a new migration. To author a data-only migration on the current contract hash, pass `--from <hash>` explicitly."
91
90
  }));
92
91
  const timestamp = /* @__PURE__ */ new Date();
93
- const packageDir = join(migrationsDir, formatMigrationDirName(timestamp, options.name ?? "migration"));
92
+ const packageDir = join(appMigrationsDir, formatMigrationDirName(timestamp, options.name ?? "migration"));
94
93
  const baseMetadata = {
95
94
  from: fromHash,
96
95
  to: toStorageHash,
@@ -188,7 +187,7 @@ function createMigrationNewCommand() {
188
187
  });
189
188
  return command;
190
189
  }
191
-
192
190
  //#endregion
193
191
  export { createMigrationNewCommand };
192
+
194
193
  //# sourceMappingURL=migration-new.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"migration-new.mjs","names":["contractJsonContent: string","toContractJson: Contract","fromContract: Contract | null","fromHash: string | null","fromContractSourceDir: string | null","baseMetadata: Omit<MigrationMetadata, 'migrationHash'>","metadata: MigrationMetadata"],"sources":["../../src/commands/migration-new.ts"],"sourcesContent":["/**\n * `migration new` — scaffolds a migration package with a `migration.ts` file\n * for manual authoring.\n *\n * The planner's `emptyMigration(context)` returns a\n * `MigrationPlanWithAuthoringSurface`, whose `renderTypeScript()` produces\n * the target-appropriate empty stub. The CLI writes the returned source\n * verbatim.\n */\n\nimport { readFileSync } from 'node:fs';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { APP_SPACE_ID, createControlStack } from '@prisma-next/framework-components/control';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { computeMigrationHash } from '@prisma-next/migration-tools/hash';\nimport {\n copyFilesWithRename,\n formatMigrationDirName,\n readMigrationsDir,\n writeMigrationPackage,\n} from '@prisma-next/migration-tools/io';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport {\n findLatestMigration,\n reconstructGraph,\n} 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 CliStructuredError,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n mapMigrationToolsError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n getTargetMigrations,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport { assertFrameworkComponentsCompatible } from '../utils/framework-components';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationNewOptions extends CommonCommandOptions {\n readonly name?: string;\n readonly from?: string;\n readonly config?: string;\n}\n\ninterface MigrationNewResult {\n readonly ok: true;\n readonly dir: string;\n readonly from: string | null;\n readonly to: string;\n readonly summary: string;\n}\n\nasync function executeMigrationNewCommand(\n options: MigrationNewOptions,\n): Promise<Result<MigrationNewResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { migrationsDir, migrationsRelative } = resolveMigrationPaths(options.config, config);\n\n const contractPathAbsolute = resolveContractPath(config);\n\n let contractJsonContent: string;\n try {\n contractJsonContent = readFileSync(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorRuntime(`Contract file not found at ${contractPathAbsolute}`, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: 'Run `prisma-next contract emit` first to generate the contract',\n }),\n );\n }\n throw error;\n }\n\n let toContractJson: Contract;\n try {\n toContractJson = JSON.parse(contractJsonContent) as Contract;\n } catch (error) {\n return notOk(\n errorRuntime('Contract JSON is invalid', {\n why: `Failed to parse ${contractPathAbsolute}: ${error instanceof Error ? error.message : String(error)}`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n const toStorageHash = (\n (toContractJson as unknown as Record<string, unknown>)['storage'] as\n | Record<string, unknown>\n | undefined\n )?.['storageHash'] as string | undefined;\n if (!toStorageHash) {\n return notOk(\n errorRuntime('Contract is missing storageHash', {\n why: `Contract at ${contractPathAbsolute} has no storageHash`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n let fromContract: Contract | null = null;\n let fromHash: string | null = null;\n let fromContractSourceDir: string | null = null;\n\n try {\n const packages = await readMigrationsDir(migrationsDir);\n\n if (packages.length > 0) {\n const graph = reconstructGraph(packages);\n\n if (options.from) {\n const match = packages.find((p) => p.metadata.to.startsWith(options.from!));\n if (!match) {\n return notOk(\n errorRuntime('Starting contract not found', {\n why: `No migration with to hash matching \"${options.from}\" exists in ${migrationsRelative}`,\n fix: 'Check that the --from hash matches a known migration target hash.',\n }),\n );\n }\n fromHash = match.metadata.to;\n fromContract = match.metadata.toContract;\n fromContractSourceDir = match.dirPath;\n } else {\n const latestMigration = findLatestMigration(graph);\n if (latestMigration) {\n fromHash = latestMigration.to;\n const leafPkg = packages.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 }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n\n if (fromHash === toStorageHash && !options.from) {\n return notOk(\n errorRuntime('No changes detected', {\n why: 'The from and to contract hashes are identical — there is nothing to migrate.',\n fix: 'Change the contract and run `prisma-next contract emit` before creating a new migration. To author a data-only migration on the current contract hash, pass `--from <hash>` explicitly.',\n }),\n );\n }\n\n const timestamp = new Date();\n const slug = options.name ?? 'migration';\n const dirName = formatMigrationDirName(timestamp, slug);\n const packageDir = join(migrationsDir, dirName);\n\n // `migration new` scaffolds an empty `migration.ts` for the user to\n // fill, so we attest over `ops: []`. Re-running self-emit after the\n // user adds operations will produce a different `migrationHash` (over\n // the real ops). This is intentional — there is no on-disk draft.\n const baseMetadata: Omit<MigrationMetadata, 'migrationHash'> = {\n from: fromHash,\n to: toStorageHash,\n fromContract,\n toContract: toContractJson,\n hints: {\n used: [],\n applied: [],\n plannerVersion: '1.0.0',\n },\n labels: [],\n providedInvariants: [],\n createdAt: timestamp.toISOString(),\n };\n const metadata: MigrationMetadata = {\n ...baseMetadata,\n migrationHash: computeMigrationHash(baseMetadata, []),\n };\n\n const migrations = getTargetMigrations(config.target);\n if (!migrations) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.targetId}\" does not support migrations`,\n }),\n );\n }\n\n try {\n assertFrameworkComponentsCompatible(config.family.familyId, config.target.targetId, [\n config.target,\n config.adapter,\n ...(config.extensionPacks ?? []),\n ]);\n\n await writeMigrationPackage(packageDir, metadata, []);\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\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n const planner = migrations.createPlanner(familyInstance);\n const emptyPlan = planner.emptyMigration(\n {\n packageDir,\n contractJsonPath: join(packageDir, 'end-contract.json'),\n fromHash,\n toHash: toStorageHash,\n },\n APP_SPACE_ID,\n );\n await writeMigrationTs(packageDir, emptyPlan.renderTypeScript());\n\n return ok({\n ok: true as const,\n dir: relative(process.cwd(), packageDir),\n from: fromHash,\n to: toStorageHash,\n summary: `Scaffolded migration at ${relative(process.cwd(), packageDir)}`,\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to scaffold migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n\nexport function createMigrationNewCommand(): Command {\n const command = new Command('new');\n setCommandDescriptions(\n command,\n 'Scaffold a new migration for manual authoring',\n 'Creates a migration package with a migration.ts file for manual authoring.\\n' +\n 'Write the migration body in migration.ts, then run the file with Node\\n' +\n '(`node migration.ts`) to self-emit ops.json and attest the package.',\n );\n setCommandExamples(command, [\n 'prisma-next migration new --name split-name',\n 'prisma-next migration new --name custom-fk --from sha256:abc...',\n ]);\n addGlobalOptions(command)\n .option('--name <slug>', 'Migration name (used in directory name)')\n .option('--from <hash>', 'Starting contract hash (default: latest migration target)')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: MigrationNewOptions) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n if (!flags.json && !flags.quiet) {\n const header = formatStyledHeader({\n command: 'migration new',\n description: 'Scaffold a new migration',\n details: [],\n flags,\n });\n ui.stderr(header);\n }\n\n const result = await executeMigrationNewCommand(options);\n\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value, null, 2));\n } else if (!flags.quiet) {\n ui.output(`\\nScaffolded migration at ${value.dir}`);\n ui.output(` from: ${value.from}`);\n ui.output(` to: ${value.to}`);\n ui.output(\n `\\nEdit migration.ts, then run it directly (\\`node \"${value.dir}/migration.ts\"\\`) to self-emit and attest.`,\n );\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,eAAe,2BACb,SACyD;CACzD,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,EAAE,eAAe,uBAAuB,sBAAsB,QAAQ,QAAQ,OAAO;CAE3F,MAAM,uBAAuB,oBAAoB,OAAO;CAExD,IAAIA;AACJ,KAAI;AACF,wBAAsB,aAAa,sBAAsB,QAAQ;UAC1D,OAAO;AACd,MAAI,iBAAiB,SAAU,MAA4B,SAAS,SAClE,QAAO,MACL,aAAa,8BAA8B,wBAAwB;GACjE,KAAK,8BAA8B;GACnC,KAAK;GACN,CAAC,CACH;AAEH,QAAM;;CAGR,IAAIC;AACJ,KAAI;AACF,mBAAiB,KAAK,MAAM,oBAAoB;UACzC,OAAO;AACd,SAAO,MACL,aAAa,4BAA4B;GACvC,KAAK,mBAAmB,qBAAqB,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GACvG,KAAK;GACN,CAAC,CACH;;CAGH,MAAM,gBACH,eAAsD,aAGrD;AACJ,KAAI,CAAC,cACH,QAAO,MACL,aAAa,mCAAmC;EAC9C,KAAK,eAAe,qBAAqB;EACzC,KAAK;EACN,CAAC,CACH;CAGH,IAAIC,eAAgC;CACpC,IAAIC,WAA0B;CAC9B,IAAIC,wBAAuC;AAE3C,KAAI;EACF,MAAM,WAAW,MAAM,kBAAkB,cAAc;AAEvD,MAAI,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4BAAqC;CACnD,MAAM,UAAU,IAAI,QAAQ,MAAM;AAClC,wBACE,SACA,iDACA,yNAGD;AACD,oBAAmB,SAAS,CAC1B,+CACA,kEACD,CAAC;AACF,kBAAiB,QAAQ,CACtB,OAAO,iBAAiB,0CAA0C,CAClE,OAAO,iBAAiB,4DAA4D,CACpF,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,OAAO,YAAiC;EAC9C,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,MAAM,KAAK,IAAI,WAAW;GAAE,OAAO,MAAM;GAAO,aAAa,MAAM;GAAa,CAAC;AAEjF,MAAI,CAAC,MAAM,QAAQ,CAAC,MAAM,OAAO;GAC/B,MAAM,SAAS,mBAAmB;IAChC,SAAS;IACT,aAAa;IACb,SAAS,EAAE;IACX;IACD,CAAC;AACF,MAAG,OAAO,OAAO;;EAKnB,MAAM,WAAW,aAFF,MAAM,2BAA2B,QAAQ,EAElB,OAAO,KAAK,UAAU;AAC1D,OAAI,MAAM,KACR,IAAG,OAAO,KAAK,UAAU,OAAO,MAAM,EAAE,CAAC;YAChC,CAAC,MAAM,OAAO;AACvB,OAAG,OAAO,6BAA6B,MAAM,MAAM;AACnD,OAAG,OAAO,WAAW,MAAM,OAAO;AAClC,OAAG,OAAO,WAAW,MAAM,KAAK;AAChC,OAAG,OACD,sDAAsD,MAAM,IAAI,4CACjE;;IAEH;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
1
+ {"version":3,"file":"migration-new.mjs","names":[],"sources":["../../src/commands/migration-new.ts"],"sourcesContent":["/**\n * `migration new` — scaffolds a migration package with a `migration.ts` file\n * for manual authoring.\n *\n * The planner's `emptyMigration(context)` returns a\n * `MigrationPlanWithAuthoringSurface`, whose `renderTypeScript()` produces\n * the target-appropriate empty stub. The CLI writes the returned source\n * verbatim.\n */\n\nimport { readFileSync } from 'node:fs';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { APP_SPACE_ID, createControlStack } from '@prisma-next/framework-components/control';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport { computeMigrationHash } from '@prisma-next/migration-tools/hash';\nimport {\n copyFilesWithRename,\n formatMigrationDirName,\n readMigrationsDir,\n writeMigrationPackage,\n} from '@prisma-next/migration-tools/io';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport {\n findLatestMigration,\n reconstructGraph,\n} 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 CliStructuredError,\n errorRuntime,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n mapMigrationToolsError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n getTargetMigrations,\n resolveContractPath,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport { assertFrameworkComponentsCompatible } from '../utils/framework-components';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationNewOptions extends CommonCommandOptions {\n readonly name?: string;\n readonly from?: string;\n readonly config?: string;\n}\n\ninterface MigrationNewResult {\n readonly ok: true;\n readonly dir: string;\n readonly from: string | null;\n readonly to: string;\n readonly summary: string;\n}\n\nasync function executeMigrationNewCommand(\n options: MigrationNewOptions,\n): Promise<Result<MigrationNewResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { appMigrationsDir, appMigrationsRelative } = resolveMigrationPaths(options.config, config);\n\n const contractPathAbsolute = resolveContractPath(config);\n\n let contractJsonContent: string;\n try {\n contractJsonContent = readFileSync(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorRuntime(`Contract file not found at ${contractPathAbsolute}`, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: 'Run `prisma-next contract emit` first to generate the contract',\n }),\n );\n }\n throw error;\n }\n\n let toContractJson: Contract;\n try {\n toContractJson = JSON.parse(contractJsonContent) as Contract;\n } catch (error) {\n return notOk(\n errorRuntime('Contract JSON is invalid', {\n why: `Failed to parse ${contractPathAbsolute}: ${error instanceof Error ? error.message : String(error)}`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n const toStorageHash = (\n (toContractJson as unknown as Record<string, unknown>)['storage'] as\n | Record<string, unknown>\n | undefined\n )?.['storageHash'] as string | undefined;\n if (!toStorageHash) {\n return notOk(\n errorRuntime('Contract is missing storageHash', {\n why: `Contract at ${contractPathAbsolute} has no storageHash`,\n fix: 'Run `prisma-next contract emit` to regenerate the contract',\n }),\n );\n }\n\n let fromContract: Contract | null = null;\n let fromHash: string | null = null;\n let fromContractSourceDir: string | null = null;\n\n try {\n const packages = await readMigrationsDir(appMigrationsDir);\n\n if (packages.length > 0) {\n const graph = reconstructGraph(packages);\n\n if (options.from) {\n const match = packages.find((p) => p.metadata.to.startsWith(options.from!));\n if (!match) {\n return notOk(\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.',\n }),\n );\n }\n fromHash = match.metadata.to;\n fromContract = match.metadata.toContract;\n fromContractSourceDir = match.dirPath;\n } else {\n const latestMigration = findLatestMigration(graph);\n if (latestMigration) {\n fromHash = latestMigration.to;\n const leafPkg = packages.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 }\n } catch (error) {\n if (MigrationToolsError.is(error)) {\n return notOk(mapMigrationToolsError(error));\n }\n throw error;\n }\n\n if (fromHash === toStorageHash && !options.from) {\n return notOk(\n errorRuntime('No changes detected', {\n why: 'The from and to contract hashes are identical — there is nothing to migrate.',\n fix: 'Change the contract and run `prisma-next contract emit` before creating a new migration. To author a data-only migration on the current contract hash, pass `--from <hash>` explicitly.',\n }),\n );\n }\n\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 // `migration new` scaffolds an empty `migration.ts` for the user to\n // fill, so we attest over `ops: []`. Re-running self-emit after the\n // user adds operations will produce a different `migrationHash` (over\n // the real ops). This is intentional — there is no on-disk draft.\n const baseMetadata: Omit<MigrationMetadata, 'migrationHash'> = {\n from: fromHash,\n to: toStorageHash,\n fromContract,\n toContract: toContractJson,\n hints: {\n used: [],\n applied: [],\n plannerVersion: '1.0.0',\n },\n labels: [],\n providedInvariants: [],\n createdAt: timestamp.toISOString(),\n };\n const metadata: MigrationMetadata = {\n ...baseMetadata,\n migrationHash: computeMigrationHash(baseMetadata, []),\n };\n\n const migrations = getTargetMigrations(config.target);\n if (!migrations) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.targetId}\" does not support migrations`,\n }),\n );\n }\n\n try {\n assertFrameworkComponentsCompatible(config.family.familyId, config.target.targetId, [\n config.target,\n config.adapter,\n ...(config.extensionPacks ?? []),\n ]);\n\n await writeMigrationPackage(packageDir, metadata, []);\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\n const stack = createControlStack(config);\n const familyInstance = config.family.create(stack);\n const planner = migrations.createPlanner(familyInstance);\n const emptyPlan = planner.emptyMigration(\n {\n packageDir,\n contractJsonPath: join(packageDir, 'end-contract.json'),\n fromHash,\n toHash: toStorageHash,\n },\n APP_SPACE_ID,\n );\n await writeMigrationTs(packageDir, emptyPlan.renderTypeScript());\n\n return ok({\n ok: true as const,\n dir: relative(process.cwd(), packageDir),\n from: fromHash,\n to: toStorageHash,\n summary: `Scaffolded migration at ${relative(process.cwd(), packageDir)}`,\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to scaffold migration: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n\nexport function createMigrationNewCommand(): Command {\n const command = new Command('new');\n setCommandDescriptions(\n command,\n 'Scaffold a new migration for manual authoring',\n 'Creates a migration package with a migration.ts file for manual authoring.\\n' +\n 'Write the migration body in migration.ts, then run the file with Node\\n' +\n '(`node migration.ts`) to self-emit ops.json and attest the package.',\n );\n setCommandExamples(command, [\n 'prisma-next migration new --name split-name',\n 'prisma-next migration new --name custom-fk --from sha256:abc...',\n ]);\n addGlobalOptions(command)\n .option('--name <slug>', 'Migration name (used in directory name)')\n .option('--from <hash>', 'Starting contract hash (default: latest migration target)')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: MigrationNewOptions) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n\n if (!flags.json && !flags.quiet) {\n const header = formatStyledHeader({\n command: 'migration new',\n description: 'Scaffold a new migration',\n details: [],\n flags,\n });\n ui.stderr(header);\n }\n\n const result = await executeMigrationNewCommand(options);\n\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value, null, 2));\n } else if (!flags.quiet) {\n ui.output(`\\nScaffolded migration at ${value.dir}`);\n ui.output(` from: ${value.from}`);\n ui.output(` to: ${value.to}`);\n ui.output(\n `\\nEdit migration.ts, then run it directly (\\`node \"${value.dir}/migration.ts\"\\`) to self-emit and attest.`,\n );\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,eAAe,2BACb,SACyD;CACzD,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,EAAE,kBAAkB,0BAA0B,sBAAsB,QAAQ,QAAQ,OAAO;CAEjG,MAAM,uBAAuB,oBAAoB,OAAO;CAExD,IAAI;CACJ,IAAI;EACF,sBAAsB,aAAa,sBAAsB,QAAQ;UAC1D,OAAO;EACd,IAAI,iBAAiB,SAAU,MAA4B,SAAS,UAClE,OAAO,MACL,aAAa,8BAA8B,wBAAwB;GACjE,KAAK,8BAA8B;GACnC,KAAK;GACN,CAAC,CACH;EAEH,MAAM;;CAGR,IAAI;CACJ,IAAI;EACF,iBAAiB,KAAK,MAAM,oBAAoB;UACzC,OAAO;EACd,OAAO,MACL,aAAa,4BAA4B;GACvC,KAAK,mBAAmB,qBAAqB,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GACvG,KAAK;GACN,CAAC,CACH;;CAGH,MAAM,gBACH,eAAsD,aAGrD;CACJ,IAAI,CAAC,eACH,OAAO,MACL,aAAa,mCAAmC;EAC9C,KAAK,eAAe,qBAAqB;EACzC,KAAK;EACN,CAAC,CACH;CAGH,IAAI,eAAgC;CACpC,IAAI,WAA0B;CAC9B,IAAI,wBAAuC;CAE3C,IAAI;EACF,MAAM,WAAW,MAAM,kBAAkB,iBAAiB;EAE1D,IAAI,SAAS,SAAS,GAAG;GACvB,MAAM,QAAQ,iBAAiB,SAAS;GAExC,IAAI,QAAQ,MAAM;IAChB,MAAM,QAAQ,SAAS,MAAM,MAAM,EAAE,SAAS,GAAG,WAAW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AAA;;;;;;;;;;;;;;;;;;;iBAiBI;;;;qBACI,sBAEjB,OAAO,GAAG"}
1
+ {"version":3,"file":"migration-plan.d.mts","names":[],"sources":["../../src/commands/migration-plan.ts"],"mappings":";;;;;UAmEiB,mBAAA;EAAA,SACN,EAAA;EAAA,SACA,IAAA;EAAA,SACA,IAAA;EAAA,SACA,EAAA;EAAA,SACA,GAAA;EAAA,SACA,UAAA;IAAA,SACE,EAAA;IAAA,SACA,KAAA;IAAA,SACA,cAAA;EAAA;EAHF;;;;;EAAA,SAUA,OAAA,GAAU,gBAAA;EAAA,SACV,OAAA;EAMA;;;;;EAAA,SAAA,mBAAA;EAAA,SACA,OAAA;IAAA,SACE,KAAA;EAAA;AAAA;AAAA,iBAqXG,0BAAA,CAAA,GAA8B,OAAA;AAAA,KAiIlC,uBAAA;EACN,MAAA;EAAqB,KAAA;AAAA;EACrB,MAAA;AAAA;;;AAeN;;;;;;;;;;;iBAAgB,qBAAA;EAAkC,QAAA;IAAY,EAAA;EAAA;AAAA,EAAA,CAC5D,OAAA,WAAkB,CAAA,IAClB,MAAA,WACC,MAAA,CAAO,CAAA,EAAG,uBAAA"}
@@ -1,346 +1,2 @@
1
- import { t as loadConfig } from "../config-loader-ih8ViDb_.mjs";
2
- import { _ as errorUnexpected, a as errorContractValidationFailed, f as errorMigrationPlanningFailed, h as errorTargetMigrationNotSupported, l as errorFileNotFound, m as errorRuntime, t as CliStructuredError, v as mapMigrationToolsError } from "../cli-errors-By1iVE3z.mjs";
3
- import { t as assertFrameworkComponentsCompatible } from "../framework-components-Bgcre3Z6.mjs";
4
- import { t as TerminalUI } from "../terminal-ui-u2YgKghu.mjs";
5
- import { a as loadMigrationPackages, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, g as parseGlobalFlags, i as getTargetMigrations, l as resolveMigrationPaths, n as addGlobalOptions, t as handleResult, y as formatStyledHeader } from "../result-handler-Ch6hVnOo.mjs";
6
- import { Command } from "commander";
7
- import { getEmittedArtifactPaths } from "@prisma-next/emitter";
8
- import { notOk, ok } from "@prisma-next/utils/result";
9
- import { join, relative } from "pathe";
10
- import { readFile } from "node:fs/promises";
11
- import { APP_SPACE_ID, createControlStack, hasOperationPreview } from "@prisma-next/framework-components/control";
12
- import { copyFilesWithRename, formatMigrationDirName, writeMigrationPackage } from "@prisma-next/migration-tools/io";
13
- import { findLatestMigration } from "@prisma-next/migration-tools/migration-graph";
14
- import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
15
- import { computeMigrationHash } from "@prisma-next/migration-tools/hash";
16
- import { writeMigrationTs } from "@prisma-next/migration-tools/migration-ts";
17
- import { deriveProvidedInvariants } from "@prisma-next/migration-tools/invariants";
18
-
19
- //#region src/commands/migration-plan.ts
20
- async function executeMigrationPlanCommand(options, flags, ui, startTime) {
21
- const config = await loadConfig(options.config);
22
- const { configPath, migrationsDir, migrationsRelative } = resolveMigrationPaths(options.config, config);
23
- const contractPathAbsolute = resolveContractPath(config);
24
- const contractPath = relative(process.cwd(), contractPathAbsolute);
25
- if (!flags.json && !flags.quiet) {
26
- const details = [
27
- {
28
- label: "config",
29
- value: configPath
30
- },
31
- {
32
- label: "contract",
33
- value: contractPath
34
- },
35
- {
36
- label: "migrations",
37
- value: migrationsRelative
38
- }
39
- ];
40
- if (options.from) details.push({
41
- label: "from",
42
- value: options.from
43
- });
44
- if (options.name) details.push({
45
- label: "name",
46
- value: options.name
47
- });
48
- const header = formatStyledHeader({
49
- command: "migration plan",
50
- description: "Plan a migration from contract changes",
51
- url: "https://pris.ly/migration-plan",
52
- details,
53
- flags
54
- });
55
- ui.stderr(header);
56
- }
57
- let contractJsonContent;
58
- try {
59
- contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
60
- } catch (error) {
61
- if (error instanceof Error && error.code === "ENOENT") return notOk(errorFileNotFound(contractPathAbsolute, {
62
- why: `Contract file not found at ${contractPathAbsolute}`,
63
- fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
64
- }));
65
- return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}` }));
66
- }
67
- let toContractJson;
68
- try {
69
- toContractJson = JSON.parse(contractJsonContent);
70
- } catch (error) {
71
- return notOk(errorContractValidationFailed(`Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`, { where: { path: contractPathAbsolute } }));
72
- }
73
- const rawStorageHash = toContractJson.storage?.storageHash;
74
- if (typeof rawStorageHash !== "string") return notOk(errorContractValidationFailed("Contract is missing storageHash", { where: { path: contractPathAbsolute } }));
75
- const toStorageHash = rawStorageHash;
76
- let fromContract = null;
77
- let fromHash = null;
78
- let fromContractSourceDir = null;
79
- try {
80
- const { bundles, graph } = await loadMigrationPackages(migrationsDir);
81
- if (options.from) {
82
- const resolved = resolveBundleByPrefix(bundles, options.from);
83
- if (!resolved.ok) {
84
- const f = resolved.failure;
85
- return notOk(f.reason === "ambiguous" ? errorRuntime("Multiple matching migrations found", {
86
- why: `Prefix "${options.from}" matches ${f.count} migrations in ${migrationsRelative}`,
87
- fix: "Provide a longer prefix to disambiguate, or omit --from to use the latest migration target."
88
- }) : errorRuntime("Starting contract not found", {
89
- why: `No migration with to hash matching "${options.from}" exists in ${migrationsRelative}`,
90
- fix: "Check that the --from hash matches a known migration target hash, or omit --from to use the latest migration target."
91
- }));
92
- }
93
- fromHash = resolved.value.metadata.to;
94
- fromContract = resolved.value.metadata.toContract;
95
- fromContractSourceDir = resolved.value.dirPath;
96
- } else {
97
- const latestMigration = findLatestMigration(graph);
98
- if (latestMigration) {
99
- fromHash = latestMigration.to;
100
- const leafPkg = bundles.find((p) => p.metadata.migrationHash === latestMigration.migrationHash);
101
- if (leafPkg) {
102
- fromContract = leafPkg.metadata.toContract;
103
- fromContractSourceDir = leafPkg.dirPath;
104
- }
105
- }
106
- }
107
- } catch (error) {
108
- if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));
109
- const message = error instanceof Error ? error.message : String(error);
110
- return notOk(errorUnexpected(message, { why: `Unexpected error while loading migrations: ${message}` }));
111
- }
112
- if (fromHash === toStorageHash) return ok({
113
- ok: true,
114
- noOp: true,
115
- from: fromHash,
116
- to: toStorageHash,
117
- operations: [],
118
- summary: "No changes detected between contracts",
119
- timings: { total: Date.now() - startTime }
120
- });
121
- const migrations = getTargetMigrations(config.target);
122
- if (!migrations) return notOk(errorTargetMigrationNotSupported({ why: `Target "${config.target.id}" does not support migrations` }));
123
- const frameworkComponents = assertFrameworkComponentsCompatible(config.family.familyId, config.target.targetId, [
124
- config.target,
125
- config.adapter,
126
- ...config.extensionPacks ?? []
127
- ]);
128
- const timestamp = /* @__PURE__ */ new Date();
129
- const packageDir = join(migrationsDir, formatMigrationDirName(timestamp, options.name ?? "migration"));
130
- const baseMetadata = {
131
- from: fromHash,
132
- to: toStorageHash,
133
- fromContract,
134
- toContract: toContractJson,
135
- hints: {
136
- used: [],
137
- applied: [],
138
- plannerVersion: "2.0.0"
139
- },
140
- labels: [],
141
- createdAt: timestamp.toISOString()
142
- };
143
- try {
144
- const stack = createControlStack(config);
145
- const familyInstance = config.family.create(stack);
146
- const planner = migrations.createPlanner(familyInstance);
147
- const fromSchema = migrations.contractToSchema(fromContract, frameworkComponents);
148
- const plannerResult = planner.plan({
149
- contract: toContractJson,
150
- schema: fromSchema,
151
- policy: { allowedOperationClasses: [
152
- "additive",
153
- "widening",
154
- "destructive",
155
- "data"
156
- ] },
157
- fromContract,
158
- frameworkComponents,
159
- spaceId: APP_SPACE_ID
160
- });
161
- if (plannerResult.kind === "failure") return notOk(errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts }));
162
- let plannedOps = [];
163
- let hasPlaceholders = false;
164
- try {
165
- plannedOps = plannerResult.plan.operations;
166
- if (plannedOps.length === 0) return notOk(errorMigrationPlanningFailed({ conflicts: [{
167
- kind: "unsupportedChange",
168
- summary: "Contract changed but planner produced no operations. This indicates unsupported or ignored changes."
169
- }] }));
170
- } catch (e) {
171
- if (CliStructuredError.is(e) && e.domain === "MIG" && e.code === "2001") hasPlaceholders = true;
172
- else throw e;
173
- }
174
- const migrationTsContent = plannerResult.plan.renderTypeScript();
175
- const opsForWrite = hasPlaceholders ? [] : plannedOps;
176
- const metadataWithInvariants = {
177
- ...baseMetadata,
178
- providedInvariants: deriveProvidedInvariants(opsForWrite)
179
- };
180
- await writeMigrationPackage(packageDir, {
181
- ...metadataWithInvariants,
182
- migrationHash: computeMigrationHash(metadataWithInvariants, opsForWrite)
183
- }, opsForWrite);
184
- const destinationArtifacts = getEmittedArtifactPaths(contractPathAbsolute);
185
- await copyFilesWithRename(packageDir, [{
186
- sourcePath: destinationArtifacts.jsonPath,
187
- destName: "end-contract.json"
188
- }, {
189
- sourcePath: destinationArtifacts.dtsPath,
190
- destName: "end-contract.d.ts"
191
- }]);
192
- if (fromContractSourceDir !== null) {
193
- const sourceArtifacts = getEmittedArtifactPaths(join(fromContractSourceDir, "end-contract.json"));
194
- await copyFilesWithRename(packageDir, [{
195
- sourcePath: sourceArtifacts.jsonPath,
196
- destName: "start-contract.json"
197
- }, {
198
- sourcePath: sourceArtifacts.dtsPath,
199
- destName: "start-contract.d.ts"
200
- }]);
201
- }
202
- await writeMigrationTs(packageDir, migrationTsContent);
203
- if (hasPlaceholders) return ok({
204
- ok: true,
205
- noOp: false,
206
- from: fromHash,
207
- to: toStorageHash,
208
- dir: relative(process.cwd(), packageDir),
209
- operations: [],
210
- pendingPlaceholders: true,
211
- summary: "Planned migration with placeholder(s) — edit migration.ts then run `node migration.ts` to self-emit",
212
- timings: { total: Date.now() - startTime }
213
- });
214
- const preview = hasOperationPreview(familyInstance) ? familyInstance.toOperationPreview(plannedOps) : void 0;
215
- return ok({
216
- ok: true,
217
- noOp: false,
218
- from: fromHash,
219
- to: toStorageHash,
220
- dir: relative(process.cwd(), packageDir),
221
- operations: plannedOps.map((op) => ({
222
- id: op.id,
223
- label: op.label,
224
- operationClass: op.operationClass
225
- })),
226
- ...preview !== void 0 ? { preview } : {},
227
- summary: `Planned ${plannedOps.length} operation(s)`,
228
- timings: { total: Date.now() - startTime }
229
- });
230
- } catch (error) {
231
- if (CliStructuredError.is(error)) return notOk(error);
232
- if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));
233
- const message = error instanceof Error ? error.message : String(error);
234
- return notOk(errorUnexpected(message, { why: `Unexpected error during migration plan: ${message}` }));
235
- }
236
- }
237
- function createMigrationPlanCommand() {
238
- const command = new Command("plan");
239
- setCommandDescriptions(command, "Plan a migration from contract changes", "Compares the emitted contract against the latest on-disk migration state and\nproduces a new migration package with the required operations. No database\nconnection is needed — this is a fully offline operation.");
240
- setCommandExamples(command, ["prisma-next migration plan", "prisma-next migration plan --name add-users-table"]);
241
- addGlobalOptions(command).option("--config <path>", "Path to prisma-next.config.ts").option("--name <slug>", "Name slug for the migration directory", "migration").option("--from <hash>", "Explicit starting contract hash (overrides latest migration target)").action(async (options) => {
242
- const flags = parseGlobalFlags(options);
243
- const startTime = Date.now();
244
- const ui = new TerminalUI({
245
- color: flags.color,
246
- interactive: flags.interactive
247
- });
248
- const exitCode = handleResult(await executeMigrationPlanCommand(options, flags, ui, startTime), flags, ui, (planResult) => {
249
- if (flags.json) ui.output(JSON.stringify(planResult, null, 2));
250
- else if (!flags.quiet) ui.log(formatMigrationPlanOutput(planResult, flags));
251
- });
252
- process.exit(exitCode);
253
- });
254
- return command;
255
- }
256
- function formatMigrationPlanOutput(result, flags) {
257
- const lines = [];
258
- const useColor = flags.color !== false;
259
- const green_ = useColor ? (s) => `\x1b[32m${s}\x1b[0m` : (s) => s;
260
- const yellow_ = useColor ? (s) => `\x1b[33m${s}\x1b[0m` : (s) => s;
261
- const dim_ = useColor ? (s) => `\x1b[2m${s}\x1b[0m` : (s) => s;
262
- if (result.noOp) {
263
- lines.push(`${green_("✔")} No changes detected`);
264
- lines.push(dim_(` from: ${result.from}`));
265
- lines.push(dim_(` to: ${result.to}`));
266
- return lines.join("\n");
267
- }
268
- if (result.pendingPlaceholders) {
269
- lines.push(`${yellow_("⚠")} ${result.summary}`);
270
- lines.push("");
271
- lines.push(dim_(`from: ${result.from}`));
272
- lines.push(dim_(`to: ${result.to}`));
273
- if (result.dir) lines.push(dim_(`dir: ${result.dir}`));
274
- lines.push("");
275
- lines.push("Open migration.ts and replace each `placeholder(...)` call with your actual query.");
276
- lines.push(`Then run: ${green_(`node ${result.dir ?? "<dir>"}/migration.ts`)}`);
277
- return lines.join("\n");
278
- }
279
- lines.push(`${green_("✔")} ${result.summary}`);
280
- lines.push("");
281
- if (result.operations.length > 0) {
282
- lines.push(dim_("│"));
283
- for (let i = 0; i < result.operations.length; i++) {
284
- const op = result.operations[i];
285
- const treeChar = i === result.operations.length - 1 ? "└" : "├";
286
- const opClassLabel = op.operationClass === "destructive" ? yellow_(`[${op.operationClass}]`) : dim_(`[${op.operationClass}]`);
287
- lines.push(`${dim_(treeChar)}─ ${op.label} ${opClassLabel}`);
288
- }
289
- if (result.operations.some((op) => op.operationClass === "destructive")) {
290
- lines.push("");
291
- lines.push(`${yellow_("⚠")} This migration contains destructive operations that may cause data loss.`);
292
- }
293
- lines.push("");
294
- }
295
- lines.push(dim_(`from: ${result.from}`));
296
- lines.push(dim_(`to: ${result.to}`));
297
- if (result.dir) lines.push(dim_(`dir: ${result.dir}`));
298
- lines.push("");
299
- lines.push(`Next: review ${green_(result.dir ?? "<dir>")} if needed, then run ${green_("prisma-next migration apply")}.`);
300
- if (result.preview && result.preview.statements.length > 0) {
301
- const allSql = result.preview.statements.every((s) => s.language === "sql");
302
- lines.push("");
303
- lines.push(dim_(allSql ? "DDL preview" : "Operation preview"));
304
- lines.push("");
305
- for (const statement of result.preview.statements) {
306
- const trimmed = statement.text.trim();
307
- if (!trimmed) continue;
308
- const line = statement.language === "sql" && !trimmed.endsWith(";") ? `${trimmed};` : trimmed;
309
- lines.push(line);
310
- }
311
- }
312
- if (flags.verbose && result.timings) {
313
- lines.push("");
314
- lines.push(dim_(`Total time: ${result.timings.total}ms`));
315
- }
316
- return lines.join("\n");
317
- }
318
- /**
319
- * Resolve a migration package by **target contract hash** (`metadata.to`)
320
- * using exact match or prefix match.
321
- *
322
- * Note: matches `metadata.to` (the contract hash this migration produces),
323
- * not `metadata.migrationHash` (the package's content-addressed identity).
324
- * Tries exact match first, then prefix match (auto-prepending `sha256:` when
325
- * the needle omits the scheme). Returns the matched package on success, or a
326
- * discriminated failure indicating whether the prefix was ambiguous or simply
327
- * not found.
328
- *
329
- * @internal Exported for testing only.
330
- */
331
- function resolveBundleByPrefix(bundles, needle) {
332
- const exact = bundles.find((p) => p.metadata.to === needle);
333
- if (exact) return ok(exact);
334
- const prefixWithScheme = needle.startsWith("sha256:") ? needle : `sha256:${needle}`;
335
- const candidates = bundles.filter((p) => p.metadata.to.startsWith(prefixWithScheme));
336
- if (candidates.length === 1) return ok(candidates[0]);
337
- if (candidates.length > 1) return notOk({
338
- reason: "ambiguous",
339
- count: candidates.length
340
- });
341
- return notOk({ reason: "not-found" });
342
- }
343
-
344
- //#endregion
1
+ import { n as resolveBundleByPrefix, t as createMigrationPlanCommand } from "../migration-plan-BcKNnTM7.mjs";
345
2
  export { createMigrationPlanCommand, resolveBundleByPrefix };
346
- //# sourceMappingURL=migration-plan.mjs.map
@@ -1,4 +1,4 @@
1
- import { t as CliStructuredError } from "../cli-errors-DDeVsP2Y.mjs";
1
+ import { t as CliStructuredError } from "../cli-errors-QH8kf-C2.mjs";
2
2
  import { Command } from "commander";
3
3
  import { Result } from "@prisma-next/utils/result";
4
4
  import { RefEntry } from "@prisma-next/migration-tools/refs";
@@ -1 +1 @@
1
- {"version":3,"file":"migration-ref.d.mts","names":[],"sources":["../../src/commands/migration-ref.ts"],"sourcesContent":[],"mappings":";;;;;;UA6BU,YAAA;;EAAA,SAAA,GAAA,EAAA,MAAY;EAOZ,SAAA,IAAA,EAAY,MAAA;EAOZ,SAAA,UAAe,EAAA,SAAA,MAAA,EAAA;AAAA;AAQF,UAfb,YAAA,CAyBD;EAO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UA6BU,YAAA;EAAA,SACC,EAAA;EAAA,SACA,GAAA;EAAA,SACA,IAAA;EAAA,SACA,UAAA;AAAA;AAAA,UAGD,YAAA;EAAA,SACC,EAAA;EAAA,SACA,GAAA;EAAA,SACA,IAAA;EAAA,SACA,UAAA;AAAA;AAAA,UAGD,eAAA;EAAA,SACC,EAAA;EAAA,SACA,GAAA;EAAA,SACA,OAAA;AAAA;AAAA,UAGD,aAAA;EAAA,SACC,EAAA;EAAA,SACA,IAAA,EAAM,MAAA,SAAe,QAAA;AAAA;AAAA,iBAUvB,sBAAA,CAAuB,IAAA,WAAe,kBAAA;AAAA,iBAOtC,uBAAA,CAAwB,IAAA,WAAe,kBAAA;AAAA,iBAOjC,oBAAA,CACb,IAAA,UACA,IAAA,UACA,OAAA;EAAW,MAAA;AAAA,IACV,OAAA,CAAQ,MAAA,CAAO,YAAA,EAAc,kBAAA;AAAA,iBAoBjB,oBAAA,CACb,IAAA,UACA,OAAA;EAAW,MAAA;AAAA,IACV,OAAA,CAAQ,MAAA,CAAO,YAAA,EAAc,kBAAA;AAAA,iBAYjB,uBAAA,CACb,IAAA,UACA,OAAA;EAAW,MAAA;AAAA,IACV,OAAA,CAAQ,MAAA,CAAO,eAAA,EAAiB,kBAAA;AAAA,iBAYpB,qBAAA,CAAsB,OAAA;EACnC,MAAA;AAAA,IACE,OAAA,CAAQ,MAAA,CAAO,aAAA,EAAe,kBAAA;AAAA,iBA8IlB,yBAAA,CAAA,GAA6B,OAAA"}
@@ -1,12 +1,11 @@
1
- import { t as loadConfig } from "../config-loader-ih8ViDb_.mjs";
2
- import { _ as errorUnexpected, m as errorRuntime, t as CliStructuredError, v as mapMigrationToolsError } from "../cli-errors-By1iVE3z.mjs";
3
- import { t as TerminalUI } from "../terminal-ui-u2YgKghu.mjs";
4
- import { _ as formatCommandHelp, d as setCommandDescriptions, g as parseGlobalFlags, l as resolveMigrationPaths, n as addGlobalOptions, t as handleResult } from "../result-handler-Ch6hVnOo.mjs";
1
+ import { t as loadConfig } from "../config-loader-B6sJjXTv.mjs";
2
+ import { _ as errorUnexpected, m as errorRuntime, t as CliStructuredError, v as mapMigrationToolsError } from "../cli-errors-D3_sMh2K.mjs";
3
+ import { t as TerminalUI } from "../terminal-ui-zaRDhJnP.mjs";
4
+ import { _ as formatCommandHelp, d as setCommandDescriptions, g as parseGlobalFlags, l as resolveMigrationPaths, n as addGlobalOptions, t as handleResult } from "../result-handler-DWb1rFS-.mjs";
5
5
  import { Command } from "commander";
6
6
  import { notOk, ok } from "@prisma-next/utils/result";
7
7
  import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
8
8
  import { deleteRef, readRef, readRefs, validateRefName, validateRefValue, writeRef } from "@prisma-next/migration-tools/refs";
9
-
10
9
  //#region src/commands/migration-ref.ts
11
10
  function mapError(error) {
12
11
  if (MigrationToolsError.is(error)) return mapMigrationToolsError(error);
@@ -180,7 +179,7 @@ function createMigrationRefCommand() {
180
179
  command.addCommand(createRefListCommand());
181
180
  return command;
182
181
  }
183
-
184
182
  //#endregion
185
183
  export { cliErrorInvalidRefName, cliErrorInvalidRefValue, createMigrationRefCommand, executeRefDeleteCommand, executeRefGetCommand, executeRefListCommand, executeRefSetCommand };
184
+
186
185
  //# sourceMappingURL=migration-ref.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"migration-ref.mjs","names":[],"sources":["../../src/commands/migration-ref.ts"],"sourcesContent":["import { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport type { RefEntry } from '@prisma-next/migration-tools/refs';\nimport {\n deleteRef,\n readRef,\n readRefs,\n validateRefName,\n validateRefValue,\n writeRef,\n} from '@prisma-next/migration-tools/refs';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport {\n CliStructuredError,\n errorRuntime,\n errorUnexpected,\n mapMigrationToolsError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveMigrationPaths,\n setCommandDescriptions,\n} from '../utils/command-helpers';\nimport { formatCommandHelp } from '../utils/formatters/help';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface RefSetResult {\n readonly ok: true;\n readonly ref: string;\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\ninterface RefGetResult {\n readonly ok: true;\n readonly ref: string;\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\ninterface RefDeleteResult {\n readonly ok: true;\n readonly ref: string;\n readonly deleted: true;\n}\n\ninterface RefListResult {\n readonly ok: true;\n readonly refs: Record<string, RefEntry>;\n}\n\nfunction mapError(error: unknown): CliStructuredError {\n if (MigrationToolsError.is(error)) {\n return mapMigrationToolsError(error);\n }\n return errorUnexpected(error instanceof Error ? error.message : String(error));\n}\n\nfunction cliErrorInvalidRefName(name: string): CliStructuredError {\n return errorRuntime(`Invalid ref name \"${name}\"`, {\n why: `Ref name \"${name}\" does not match the required format`,\n fix: 'Ref names must be lowercase alphanumeric with hyphens or forward slashes, no `.` or `..` segments',\n });\n}\n\nfunction cliErrorInvalidRefValue(hash: string): CliStructuredError {\n return errorRuntime(`Invalid contract hash \"${hash}\"`, {\n why: `\"${hash}\" is not a valid contract hash`,\n fix: 'Contract hashes must match the format \"sha256:<64 hex chars>\". Copy the hash from `prisma-next contract emit` or `migration status --json`.',\n });\n}\n\nasync function executeRefSetCommand(\n name: string,\n hash: string,\n options: { config?: string },\n): Promise<Result<RefSetResult, CliStructuredError>> {\n if (!validateRefName(name)) {\n return notOk(cliErrorInvalidRefName(name));\n }\n if (!validateRefValue(hash)) {\n return notOk(cliErrorInvalidRefValue(hash));\n }\n\n try {\n const config = await loadConfig(options.config);\n const { refsDir } = resolveMigrationPaths(options.config, config);\n const entry: RefEntry = { hash, invariants: [] };\n await writeRef(refsDir, name, entry);\n return ok({ ok: true as const, ref: name, hash, invariants: [] });\n } catch (error) {\n if (error instanceof CliStructuredError) return notOk(error);\n return notOk(mapError(error));\n }\n}\n\nasync function executeRefGetCommand(\n name: string,\n options: { config?: string },\n): Promise<Result<RefGetResult, CliStructuredError>> {\n try {\n const config = await loadConfig(options.config);\n const { refsDir } = resolveMigrationPaths(options.config, config);\n const entry = await readRef(refsDir, name);\n return ok({ ok: true as const, ref: name, hash: entry.hash, invariants: entry.invariants });\n } catch (error) {\n if (error instanceof CliStructuredError) return notOk(error);\n return notOk(mapError(error));\n }\n}\n\nasync function executeRefDeleteCommand(\n name: string,\n options: { config?: string },\n): Promise<Result<RefDeleteResult, CliStructuredError>> {\n try {\n const config = await loadConfig(options.config);\n const { refsDir } = resolveMigrationPaths(options.config, config);\n await deleteRef(refsDir, name);\n return ok({ ok: true as const, ref: name, deleted: true as const });\n } catch (error) {\n if (error instanceof CliStructuredError) return notOk(error);\n return notOk(mapError(error));\n }\n}\n\nasync function executeRefListCommand(options: {\n config?: string;\n}): Promise<Result<RefListResult, CliStructuredError>> {\n try {\n const config = await loadConfig(options.config);\n const { refsDir } = resolveMigrationPaths(options.config, config);\n const refs = await readRefs(refsDir);\n return ok({ ok: true as const, refs });\n } catch (error) {\n if (error instanceof CliStructuredError) return notOk(error);\n return notOk(mapError(error));\n }\n}\n\nfunction createRefSetCommand(): Command {\n const command = new Command('set');\n setCommandDescriptions(\n command,\n 'Set a ref to a contract hash',\n 'Sets a named ref to point to a contract hash in migrations/refs/.',\n );\n addGlobalOptions(command)\n .argument('<name>', 'Ref name (e.g., staging, production)')\n .argument('<hash>', 'Contract hash to point to')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(\n async (\n name: string,\n hash: string,\n options: { config?: string; json?: string | boolean; quiet?: boolean },\n ) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeRefSetCommand(name, hash, options);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value));\n } else if (!flags.quiet) {\n ui.output(`Set ref \"${value.ref}\" → ${value.hash}`);\n }\n });\n process.exit(exitCode);\n },\n );\n return command;\n}\n\nfunction createRefGetCommand(): Command {\n const command = new Command('get');\n setCommandDescriptions(\n command,\n 'Get the hash for a ref',\n 'Reads a named ref from migrations/refs/ and prints its contract hash.',\n );\n addGlobalOptions(command)\n .argument('<name>', 'Ref name to look up')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(\n async (\n name: string,\n options: { config?: string; json?: string | boolean; quiet?: boolean },\n ) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeRefGetCommand(name, options);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value));\n } else {\n ui.output(value.hash);\n }\n });\n process.exit(exitCode);\n },\n );\n return command;\n}\n\nfunction createRefDeleteCommand(): Command {\n const command = new Command('delete');\n setCommandDescriptions(command, 'Delete a ref', 'Removes a named ref from migrations/refs/.');\n addGlobalOptions(command)\n .argument('<name>', 'Ref name to delete')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(\n async (\n name: string,\n options: { config?: string; json?: string | boolean; quiet?: boolean },\n ) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeRefDeleteCommand(name, options);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value));\n } else if (!flags.quiet) {\n ui.output(`Deleted ref \"${value.ref}\"`);\n }\n });\n process.exit(exitCode);\n },\n );\n return command;\n}\n\nfunction createRefListCommand(): Command {\n const command = new Command('list');\n setCommandDescriptions(command, 'List all refs', 'Lists all named refs from migrations/refs/.');\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: { config?: string; json?: string | boolean; quiet?: boolean }) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeRefListCommand(options);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value));\n } else if (!flags.quiet) {\n const entries = Object.entries(value.refs);\n if (entries.length === 0) {\n ui.output('No refs defined');\n } else {\n for (const [refName, entry] of entries) {\n const invariantsSuffix =\n entry.invariants.length > 0 ? ` [invariants: ${entry.invariants.join(', ')}]` : '';\n ui.output(`${refName} → ${entry.hash}${invariantsSuffix}`);\n }\n }\n }\n });\n process.exit(exitCode);\n });\n return command;\n}\n\nexport {\n executeRefSetCommand,\n executeRefGetCommand,\n executeRefDeleteCommand,\n executeRefListCommand,\n cliErrorInvalidRefName,\n cliErrorInvalidRefValue,\n};\n\nexport function createMigrationRefCommand(): Command {\n const command = new Command('ref');\n setCommandDescriptions(\n command,\n 'Manage migration refs',\n 'Manage named refs in migrations/refs/. Refs map logical environment\\n' +\n 'names (e.g., staging, production) to contract hashes.',\n );\n addGlobalOptions(command).configureHelp({\n formatHelp: (cmd) => formatCommandHelp({ command: cmd, flags: parseGlobalFlags({}) }),\n subcommandDescription: () => '',\n });\n command.addCommand(createRefSetCommand());\n command.addCommand(createRefGetCommand());\n command.addCommand(createRefDeleteCommand());\n command.addCommand(createRefListCommand());\n return command;\n}\n"],"mappings":";;;;;;;;;;AAsDA,SAAS,SAAS,OAAoC;AACpD,KAAI,oBAAoB,GAAG,MAAM,CAC/B,QAAO,uBAAuB,MAAM;AAEtC,QAAO,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,CAAC;;AAGhF,SAAS,uBAAuB,MAAkC;AAChE,QAAO,aAAa,qBAAqB,KAAK,IAAI;EAChD,KAAK,aAAa,KAAK;EACvB,KAAK;EACN,CAAC;;AAGJ,SAAS,wBAAwB,MAAkC;AACjE,QAAO,aAAa,0BAA0B,KAAK,IAAI;EACrD,KAAK,IAAI,KAAK;EACd,KAAK;EACN,CAAC;;AAGJ,eAAe,qBACb,MACA,MACA,SACmD;AACnD,KAAI,CAAC,gBAAgB,KAAK,CACxB,QA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,MAAM,CAAC,SAAS,UAAU,SAAS;KACtC,MAAM,mBACJ,MAAM,WAAW,SAAS,IAAI,iBAAiB,MAAM,WAAW,KAAK,KAAK,CAAC,KAAK;AAClF,QAAG,OAAO,GAAG,QAAQ,KAAK,MAAM,OAAO,mBAAmB;;;IAIhE;AACF,UAAQ,KAAK,SAAS;GACtB;AACJ,QAAO;;AAYT,SAAgB,4BAAqC;CACnD,MAAM,UAAU,IAAI,QAAQ,MAAM;AAClC,wBACE,SACA,yBACA,6HAED;AACD,kBAAiB,QAAQ,CAAC,cAAc;EACtC,aAAa,QAAQ,kBAAkB;GAAE,SAAS;GAAK,OAAO,iBAAiB,EAAE,CAAC;GAAE,CAAC;EACrF,6BAA6B;EAC9B,CAAC;AACF,SAAQ,WAAW,qBAAqB,CAAC;AACzC,SAAQ,WAAW,qBAAqB,CAAC;AACzC,SAAQ,WAAW,wBAAwB,CAAC;AAC5C,SAAQ,WAAW,sBAAsB,CAAC;AAC1C,QAAO"}
1
+ {"version":3,"file":"migration-ref.mjs","names":[],"sources":["../../src/commands/migration-ref.ts"],"sourcesContent":["import { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport type { RefEntry } from '@prisma-next/migration-tools/refs';\nimport {\n deleteRef,\n readRef,\n readRefs,\n validateRefName,\n validateRefValue,\n writeRef,\n} from '@prisma-next/migration-tools/refs';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport {\n CliStructuredError,\n errorRuntime,\n errorUnexpected,\n mapMigrationToolsError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveMigrationPaths,\n setCommandDescriptions,\n} from '../utils/command-helpers';\nimport { formatCommandHelp } from '../utils/formatters/help';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface RefSetResult {\n readonly ok: true;\n readonly ref: string;\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\ninterface RefGetResult {\n readonly ok: true;\n readonly ref: string;\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\ninterface RefDeleteResult {\n readonly ok: true;\n readonly ref: string;\n readonly deleted: true;\n}\n\ninterface RefListResult {\n readonly ok: true;\n readonly refs: Record<string, RefEntry>;\n}\n\nfunction mapError(error: unknown): CliStructuredError {\n if (MigrationToolsError.is(error)) {\n return mapMigrationToolsError(error);\n }\n return errorUnexpected(error instanceof Error ? error.message : String(error));\n}\n\nfunction cliErrorInvalidRefName(name: string): CliStructuredError {\n return errorRuntime(`Invalid ref name \"${name}\"`, {\n why: `Ref name \"${name}\" does not match the required format`,\n fix: 'Ref names must be lowercase alphanumeric with hyphens or forward slashes, no `.` or `..` segments',\n });\n}\n\nfunction cliErrorInvalidRefValue(hash: string): CliStructuredError {\n return errorRuntime(`Invalid contract hash \"${hash}\"`, {\n why: `\"${hash}\" is not a valid contract hash`,\n fix: 'Contract hashes must match the format \"sha256:<64 hex chars>\". Copy the hash from `prisma-next contract emit` or `migration status --json`.',\n });\n}\n\nasync function executeRefSetCommand(\n name: string,\n hash: string,\n options: { config?: string },\n): Promise<Result<RefSetResult, CliStructuredError>> {\n if (!validateRefName(name)) {\n return notOk(cliErrorInvalidRefName(name));\n }\n if (!validateRefValue(hash)) {\n return notOk(cliErrorInvalidRefValue(hash));\n }\n\n try {\n const config = await loadConfig(options.config);\n const { refsDir } = resolveMigrationPaths(options.config, config);\n const entry: RefEntry = { hash, invariants: [] };\n await writeRef(refsDir, name, entry);\n return ok({ ok: true as const, ref: name, hash, invariants: [] });\n } catch (error) {\n if (error instanceof CliStructuredError) return notOk(error);\n return notOk(mapError(error));\n }\n}\n\nasync function executeRefGetCommand(\n name: string,\n options: { config?: string },\n): Promise<Result<RefGetResult, CliStructuredError>> {\n try {\n const config = await loadConfig(options.config);\n const { refsDir } = resolveMigrationPaths(options.config, config);\n const entry = await readRef(refsDir, name);\n return ok({ ok: true as const, ref: name, hash: entry.hash, invariants: entry.invariants });\n } catch (error) {\n if (error instanceof CliStructuredError) return notOk(error);\n return notOk(mapError(error));\n }\n}\n\nasync function executeRefDeleteCommand(\n name: string,\n options: { config?: string },\n): Promise<Result<RefDeleteResult, CliStructuredError>> {\n try {\n const config = await loadConfig(options.config);\n const { refsDir } = resolveMigrationPaths(options.config, config);\n await deleteRef(refsDir, name);\n return ok({ ok: true as const, ref: name, deleted: true as const });\n } catch (error) {\n if (error instanceof CliStructuredError) return notOk(error);\n return notOk(mapError(error));\n }\n}\n\nasync function executeRefListCommand(options: {\n config?: string;\n}): Promise<Result<RefListResult, CliStructuredError>> {\n try {\n const config = await loadConfig(options.config);\n const { refsDir } = resolveMigrationPaths(options.config, config);\n const refs = await readRefs(refsDir);\n return ok({ ok: true as const, refs });\n } catch (error) {\n if (error instanceof CliStructuredError) return notOk(error);\n return notOk(mapError(error));\n }\n}\n\nfunction createRefSetCommand(): Command {\n const command = new Command('set');\n setCommandDescriptions(\n command,\n 'Set a ref to a contract hash',\n 'Sets a named ref to point to a contract hash in migrations/refs/.',\n );\n addGlobalOptions(command)\n .argument('<name>', 'Ref name (e.g., staging, production)')\n .argument('<hash>', 'Contract hash to point to')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(\n async (\n name: string,\n hash: string,\n options: { config?: string; json?: string | boolean; quiet?: boolean },\n ) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeRefSetCommand(name, hash, options);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value));\n } else if (!flags.quiet) {\n ui.output(`Set ref \"${value.ref}\" → ${value.hash}`);\n }\n });\n process.exit(exitCode);\n },\n );\n return command;\n}\n\nfunction createRefGetCommand(): Command {\n const command = new Command('get');\n setCommandDescriptions(\n command,\n 'Get the hash for a ref',\n 'Reads a named ref from migrations/refs/ and prints its contract hash.',\n );\n addGlobalOptions(command)\n .argument('<name>', 'Ref name to look up')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(\n async (\n name: string,\n options: { config?: string; json?: string | boolean; quiet?: boolean },\n ) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeRefGetCommand(name, options);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value));\n } else {\n ui.output(value.hash);\n }\n });\n process.exit(exitCode);\n },\n );\n return command;\n}\n\nfunction createRefDeleteCommand(): Command {\n const command = new Command('delete');\n setCommandDescriptions(command, 'Delete a ref', 'Removes a named ref from migrations/refs/.');\n addGlobalOptions(command)\n .argument('<name>', 'Ref name to delete')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(\n async (\n name: string,\n options: { config?: string; json?: string | boolean; quiet?: boolean },\n ) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeRefDeleteCommand(name, options);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value));\n } else if (!flags.quiet) {\n ui.output(`Deleted ref \"${value.ref}\"`);\n }\n });\n process.exit(exitCode);\n },\n );\n return command;\n}\n\nfunction createRefListCommand(): Command {\n const command = new Command('list');\n setCommandDescriptions(command, 'List all refs', 'Lists all named refs from migrations/refs/.');\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: { config?: string; json?: string | boolean; quiet?: boolean }) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const result = await executeRefListCommand(options);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value));\n } else if (!flags.quiet) {\n const entries = Object.entries(value.refs);\n if (entries.length === 0) {\n ui.output('No refs defined');\n } else {\n for (const [refName, entry] of entries) {\n const invariantsSuffix =\n entry.invariants.length > 0 ? ` [invariants: ${entry.invariants.join(', ')}]` : '';\n ui.output(`${refName} → ${entry.hash}${invariantsSuffix}`);\n }\n }\n }\n });\n process.exit(exitCode);\n });\n return command;\n}\n\nexport {\n executeRefSetCommand,\n executeRefGetCommand,\n executeRefDeleteCommand,\n executeRefListCommand,\n cliErrorInvalidRefName,\n cliErrorInvalidRefValue,\n};\n\nexport function createMigrationRefCommand(): Command {\n const command = new Command('ref');\n setCommandDescriptions(\n command,\n 'Manage migration refs',\n 'Manage named refs in migrations/refs/. Refs map logical environment\\n' +\n 'names (e.g., staging, production) to contract hashes.',\n );\n addGlobalOptions(command).configureHelp({\n formatHelp: (cmd) => formatCommandHelp({ command: cmd, flags: parseGlobalFlags({}) }),\n subcommandDescription: () => '',\n });\n command.addCommand(createRefSetCommand());\n command.addCommand(createRefGetCommand());\n command.addCommand(createRefDeleteCommand());\n command.addCommand(createRefListCommand());\n return command;\n}\n"],"mappings":";;;;;;;;;AAsDA,SAAS,SAAS,OAAoC;CACpD,IAAI,oBAAoB,GAAG,MAAM,EAC/B,OAAO,uBAAuB,MAAM;CAEtC,OAAO,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,CAAC;;AAGhF,SAAS,uBAAuB,MAAkC;CAChE,OAAO,aAAa,qBAAqB,KAAK,IAAI;EAChD,KAAK,aAAa,KAAK;EACvB,KAAK;EACN,CAAC;;AAGJ,SAAS,wBAAwB,MAAkC;CACjE,OAAO,aAAa,0BAA0B,KAAK,IAAI;EACrD,KAAK,IAAI,KAAK;EACd,KAAK;EACN,CAAC;;AAGJ,eAAe,qBACb,MACA,MACA,SACmD;CACnD,IAAI,CAAC,gBAAgB,KAAK,EACxB,OAAO,MAAM,uBAAuB,KAAK,CAAC;CAE5C,IAAI,CAAC,iBAAiB,KAAK,EACzB,OAAO,MAAM,wBAAwB,KAAK,CAAC;CAG7C,IAAI;EACF,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;EAC/C,MAAM,EAAE,YAAY,sBAAs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,mBAAmB;;;IAIhE;EACF,QAAQ,KAAK,SAAS;GACtB;CACJ,OAAO;;AAYT,SAAgB,4BAAqC;CACnD,MAAM,UAAU,IAAI,QAAQ,MAAM;CAClC,uBACE,SACA,yBACA,6HAED;CACD,iBAAiB,QAAQ,CAAC,cAAc;EACtC,aAAa,QAAQ,kBAAkB;GAAE,SAAS;GAAK,OAAO,iBAAiB,EAAE,CAAC;GAAE,CAAC;EACrF,6BAA6B;EAC9B,CAAC;CACF,QAAQ,WAAW,qBAAqB,CAAC;CACzC,QAAQ,WAAW,qBAAqB,CAAC;CACzC,QAAQ,WAAW,wBAAwB,CAAC;CAC5C,QAAQ,WAAW,sBAAsB,CAAC;CAC1C,OAAO"}
@@ -1,4 +1,4 @@
1
- import { t as CliStructuredError } from "../cli-errors-DDeVsP2Y.mjs";
1
+ import { t as CliStructuredError } from "../cli-errors-QH8kf-C2.mjs";
2
2
  import { Command } from "commander";
3
3
  import { Result } from "@prisma-next/utils/result";
4
4
  import { OperationPreview } from "@prisma-next/framework-components/control";
@@ -1 +1 @@
1
- {"version":3,"file":"migration-show.d.mts","names":[],"sources":["../../src/commands/migration-show.ts"],"sourcesContent":[],"mappings":";;;;;;;UAsCiB,mBAAA;;EAAA,SAAA,OAAA,EAAA,MAAmB;EA2BpB,SAAA,OAAA,EAAA,MAAmB;EACd,SAAA,IAAA,EAAA,MAAA,GAAA,IAAA;EAEX,SAAA,EAAA,EAAA,MAAA;EAAwB,SAAA,aAAA,EAAA,MAAA;EAA/B,SAAA,SAAA,EAAA,MAAA;EAAM,SAAA,UAAA,EAAA,SAAA;IAqJO,SAAA,EAAA,EAAA,MAAA;;;;;;;;;;oBAhKI;;;iBAQJ,mBAAA,oBACK,2CAElB,OAAO,wBAAwB;iBAqJlB,0BAAA,CAAA,GAA8B"}
1
+ {"version":3,"file":"migration-show.d.mts","names":[],"sources":["../../src/commands/migration-show.ts"],"mappings":";;;;;;;UAuCiB,mBAAA;EAAA,SACN,EAAA;EAAA,SACA,OAAA;EAAA,SACA,OAAA;EAAA,SACA,IAAA;EAAA,SACA,EAAA;EAAA,SACA,aAAA;EAAA,SACA,SAAA;EAAA,SACA,UAAA;IAAA,SACE,EAAA;IAAA,SACA,KAAA;IAAA,SACA,cAAA;EAAA;EAHF;;;;;;EAAA,SAWA,OAAA,EAAS,gBAAA;EAAA,SACT,OAAA;AAAA;AAAA,iBAOK,mBAAA,CACd,QAAA,WAAmB,sBAAA,IACnB,MAAA,WACC,MAAA,CAAO,sBAAA,EAAwB,kBAAA;AAAA,iBAsJlB,0BAAA,CAAA,GAA8B,OAAA"}