@prisma-next/cli 0.11.0-dev.6 → 0.11.0-dev.60

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 (180) hide show
  1. package/README.md +13 -9
  2. package/dist/cli.mjs +9 -10
  3. package/dist/cli.mjs.map +1 -1
  4. package/dist/{client-oXO2WCPD.mjs → client-CD3om3R0.mjs} +44 -24
  5. package/dist/client-CD3om3R0.mjs.map +1 -0
  6. package/dist/{command-helpers-DtavI0wJ.mjs → command-helpers-CoceqqMl.mjs} +642 -45
  7. package/dist/command-helpers-CoceqqMl.mjs.map +1 -0
  8. package/dist/commands/contract-emit.d.mts.map +1 -1
  9. package/dist/commands/contract-emit.mjs +1 -1
  10. package/dist/commands/contract-infer.d.mts.map +1 -1
  11. package/dist/commands/contract-infer.mjs +1 -1
  12. package/dist/commands/db-init.d.mts.map +1 -1
  13. package/dist/commands/db-init.mjs +32 -7
  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 +3 -4
  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 +12 -10
  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 +41 -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 -1
  26. package/dist/commands/migrate.d.mts +5 -1
  27. package/dist/commands/migrate.d.mts.map +1 -1
  28. package/dist/commands/migrate.mjs +75 -40
  29. package/dist/commands/migrate.mjs.map +1 -1
  30. package/dist/commands/migration-check.d.mts +4 -3
  31. package/dist/commands/migration-check.d.mts.map +1 -1
  32. package/dist/commands/migration-check.mjs +1 -280
  33. package/dist/commands/migration-graph.d.mts +11 -2
  34. package/dist/commands/migration-graph.d.mts.map +1 -1
  35. package/dist/commands/migration-graph.mjs +15 -30
  36. package/dist/commands/migration-graph.mjs.map +1 -1
  37. package/dist/commands/migration-list.d.mts +66 -4
  38. package/dist/commands/migration-list.d.mts.map +1 -1
  39. package/dist/commands/migration-list.mjs +2 -103
  40. package/dist/commands/migration-log.d.mts +10 -1
  41. package/dist/commands/migration-log.d.mts.map +1 -1
  42. package/dist/commands/migration-log.mjs +10 -15
  43. package/dist/commands/migration-log.mjs.map +1 -1
  44. package/dist/commands/migration-new.d.mts.map +1 -1
  45. package/dist/commands/migration-new.mjs +32 -38
  46. package/dist/commands/migration-new.mjs.map +1 -1
  47. package/dist/commands/migration-plan.d.mts +2 -1
  48. package/dist/commands/migration-plan.d.mts.map +1 -1
  49. package/dist/commands/migration-plan.mjs +1 -1
  50. package/dist/commands/migration-show.d.mts +4 -55
  51. package/dist/commands/migration-show.d.mts.map +1 -1
  52. package/dist/commands/migration-show.mjs +61 -153
  53. package/dist/commands/migration-show.mjs.map +1 -1
  54. package/dist/commands/migration-status.d.mts +5 -40
  55. package/dist/commands/migration-status.d.mts.map +1 -1
  56. package/dist/commands/migration-status.mjs +81 -76
  57. package/dist/commands/migration-status.mjs.map +1 -1
  58. package/dist/commands/ref.d.mts +1 -1
  59. package/dist/commands/ref.d.mts.map +1 -1
  60. package/dist/commands/ref.mjs +38 -10
  61. package/dist/commands/ref.mjs.map +1 -1
  62. package/dist/config-loader-B6sJjXTv.mjs.map +1 -1
  63. package/dist/config-loader.d.mts.map +1 -1
  64. package/dist/contract-at-errors-Bhf2jnkp.mjs +42 -0
  65. package/dist/contract-at-errors-Bhf2jnkp.mjs.map +1 -0
  66. package/dist/{contract-emit-CmsklifJ.mjs → contract-emit-C47r1loe.mjs} +4 -6
  67. package/dist/{contract-emit-CmsklifJ.mjs.map → contract-emit-C47r1loe.mjs.map} +1 -1
  68. package/dist/{contract-emit-o-8VmdQX.mjs → contract-emit-DxEfEc-M.mjs} +21 -7
  69. package/dist/{contract-emit-o-8VmdQX.mjs.map → contract-emit-DxEfEc-M.mjs.map} +1 -1
  70. package/dist/{contract-enrichment-Dani0mMW.mjs → contract-enrichment-a0V5Y_mL.mjs} +4 -25
  71. package/dist/contract-enrichment-a0V5Y_mL.mjs.map +1 -0
  72. package/dist/{contract-infer-pKkiCt7C.mjs → contract-infer-B5EhTqdR.mjs} +3 -4
  73. package/dist/{contract-infer-pKkiCt7C.mjs.map → contract-infer-B5EhTqdR.mjs.map} +1 -1
  74. package/dist/contract-space-aggregate-loader-lafgkTwG.mjs +247 -0
  75. package/dist/contract-space-aggregate-loader-lafgkTwG.mjs.map +1 -0
  76. package/dist/{db-verify-AoIUriL4.mjs → db-verify-B7fbkGnp.mjs} +5 -7
  77. package/dist/{db-verify-AoIUriL4.mjs.map → db-verify-B7fbkGnp.mjs.map} +1 -1
  78. package/dist/exports/control-api.d.mts +1 -1
  79. package/dist/exports/control-api.d.mts.map +1 -1
  80. package/dist/exports/control-api.mjs +3 -3
  81. package/dist/exports/index.d.mts.map +1 -1
  82. package/dist/exports/index.mjs +1 -1
  83. package/dist/exports/index.mjs.map +1 -1
  84. package/dist/exports/init-output.d.mts.map +1 -1
  85. package/dist/exports/init-output.mjs +1 -1
  86. package/dist/extension-pack-inputs-IDvjRCi3.mjs +62 -0
  87. package/dist/extension-pack-inputs-IDvjRCi3.mjs.map +1 -0
  88. package/dist/{framework-components-65gOHkHB.mjs → framework-components-R_O3y5IW.mjs} +2 -2
  89. package/dist/{framework-components-65gOHkHB.mjs.map → framework-components-R_O3y5IW.mjs.map} +1 -1
  90. package/dist/global-flags-2SPgqWma.d.mts +34 -0
  91. package/dist/global-flags-2SPgqWma.d.mts.map +1 -0
  92. package/dist/{graph-render-DJVv0_uf.mjs → graph-render-rFAqZujX.mjs} +2 -2
  93. package/dist/{graph-render-DJVv0_uf.mjs.map → graph-render-rFAqZujX.mjs.map} +1 -1
  94. package/dist/{init-Db5Itt5r.mjs → init-BQNpPozW.mjs} +4 -5
  95. package/dist/{init-Db5Itt5r.mjs.map → init-BQNpPozW.mjs.map} +1 -1
  96. package/dist/{inspect-live-schema-LeWvkZVz.mjs → inspect-live-schema-CQJnuPgD.mjs} +4 -5
  97. package/dist/{inspect-live-schema-LeWvkZVz.mjs.map → inspect-live-schema-CQJnuPgD.mjs.map} +1 -1
  98. package/dist/migration-check-CKfQlAWR.mjs +341 -0
  99. package/dist/migration-check-CKfQlAWR.mjs.map +1 -0
  100. package/dist/migration-cli.d.mts.map +1 -1
  101. package/dist/migration-cli.mjs +4 -4
  102. package/dist/migration-cli.mjs.map +1 -1
  103. package/dist/{migration-command-scaffold-BtkunvFQ.mjs → migration-command-scaffold-CE931d1-.mjs} +4 -5
  104. package/dist/{migration-command-scaffold-BtkunvFQ.mjs.map → migration-command-scaffold-CE931d1-.mjs.map} +1 -1
  105. package/dist/migration-list-A3bJ4j5e.mjs +780 -0
  106. package/dist/migration-list-A3bJ4j5e.mjs.map +1 -0
  107. package/dist/{migration-plan-C2jeH1J5.mjs → migration-plan-ZZm8C0s-.mjs} +372 -133
  108. package/dist/migration-plan-ZZm8C0s-.mjs.map +1 -0
  109. package/dist/{migration-types-BXWvz12q.d.mts → migration-types-q64xAI_J.d.mts} +1 -1
  110. package/dist/{migration-types-BXWvz12q.d.mts.map → migration-types-q64xAI_J.d.mts.map} +1 -1
  111. package/dist/{migrations-CwZMa1Ck.mjs → migrations-CjO1DsYe.mjs} +12 -13
  112. package/dist/migrations-CjO1DsYe.mjs.map +1 -0
  113. package/dist/{output-BlsrGMEF.mjs → output-DEg3SSnJ.mjs} +1 -1
  114. package/dist/{output-BlsrGMEF.mjs.map → output-DEg3SSnJ.mjs.map} +1 -1
  115. package/dist/{progress-adapter-DFfvZcYL.mjs → progress-adapter-C644QK8l.mjs} +1 -1
  116. package/dist/{progress-adapter-DFfvZcYL.mjs.map → progress-adapter-C644QK8l.mjs.map} +1 -1
  117. package/dist/ref-advancement-DUZqsue6.mjs +50 -0
  118. package/dist/ref-advancement-DUZqsue6.mjs.map +1 -0
  119. package/dist/terminal-ui-sLZt2cxc.d.mts +133 -0
  120. package/dist/terminal-ui-sLZt2cxc.d.mts.map +1 -0
  121. package/dist/{types-C9FfXb1l.d.mts → types-DK-ge7eR.d.mts} +5 -11
  122. package/dist/types-DK-ge7eR.d.mts.map +1 -0
  123. package/dist/{verify-Bom75OYI.mjs → verify-vl983Ed-.mjs} +2 -2
  124. package/dist/{verify-Bom75OYI.mjs.map → verify-vl983Ed-.mjs.map} +1 -1
  125. package/package.json +19 -19
  126. package/src/commands/db-init.ts +48 -2
  127. package/src/commands/db-sign.ts +9 -5
  128. package/src/commands/db-update.ts +54 -8
  129. package/src/commands/migrate.ts +123 -42
  130. package/src/commands/migration-check.ts +43 -83
  131. package/src/commands/migration-graph.ts +15 -41
  132. package/src/commands/migration-list.ts +231 -74
  133. package/src/commands/migration-log.ts +8 -14
  134. package/src/commands/migration-new.ts +44 -48
  135. package/src/commands/migration-plan.ts +411 -196
  136. package/src/commands/migration-show.ts +65 -284
  137. package/src/commands/migration-status.ts +116 -110
  138. package/src/commands/ref.ts +53 -8
  139. package/src/control-api/client.ts +0 -1
  140. package/src/control-api/contract-enrichment.ts +6 -42
  141. package/src/control-api/operations/contract-emit.ts +7 -2
  142. package/src/control-api/operations/db-verify.ts +9 -5
  143. package/src/control-api/operations/migration-apply.ts +36 -23
  144. package/src/control-api/types.ts +3 -10
  145. package/src/migration-cli.ts +4 -4
  146. package/src/utils/cli-errors.ts +234 -0
  147. package/src/utils/command-helpers.ts +1 -20
  148. package/src/utils/contract-at-errors.ts +96 -0
  149. package/src/utils/contract-space-aggregate-loader.ts +336 -117
  150. package/src/utils/formatters/migration-list-data-column.ts +115 -0
  151. package/src/utils/formatters/migration-list-graph-layout.ts +268 -0
  152. package/src/utils/formatters/migration-list-graph-render.ts +311 -0
  153. package/src/utils/formatters/migration-list-graph-topology.ts +158 -0
  154. package/src/utils/formatters/migration-list-render.ts +191 -0
  155. package/src/utils/formatters/migration-list-styler.ts +61 -0
  156. package/src/utils/formatters/migration-list-types.ts +21 -0
  157. package/src/utils/formatters/migrations.ts +29 -38
  158. package/src/utils/glyph-mode.ts +22 -0
  159. package/src/utils/integrity-violation-to-check-failure.ts +130 -0
  160. package/src/utils/plan-resolution.ts +258 -0
  161. package/src/utils/ref-advancement.ts +68 -0
  162. package/src/utils/terminal-ui.ts +42 -1
  163. package/dist/cli-errors-Czmx92Zy.d.mts +0 -3
  164. package/dist/cli-errors-Djtz98Vm.mjs +0 -71
  165. package/dist/cli-errors-Djtz98Vm.mjs.map +0 -1
  166. package/dist/client-oXO2WCPD.mjs.map +0 -1
  167. package/dist/command-helpers-DtavI0wJ.mjs.map +0 -1
  168. package/dist/commands/migration-check.mjs.map +0 -1
  169. package/dist/commands/migration-list.mjs.map +0 -1
  170. package/dist/contract-enrichment-Dani0mMW.mjs.map +0 -1
  171. package/dist/contract-space-aggregate-loader-BmNQwlws.mjs +0 -160
  172. package/dist/contract-space-aggregate-loader-BmNQwlws.mjs.map +0 -1
  173. package/dist/global-flags-CdE7M0d9.d.mts +0 -15
  174. package/dist/global-flags-CdE7M0d9.d.mts.map +0 -1
  175. package/dist/migration-plan-C2jeH1J5.mjs.map +0 -1
  176. package/dist/migrations-CwZMa1Ck.mjs.map +0 -1
  177. package/dist/rolldown-runtime-twds-ZHy.mjs +0 -14
  178. package/dist/terminal-ui-BiB_8KNo.mjs +0 -379
  179. package/dist/terminal-ui-BiB_8KNo.mjs.map +0 -1
  180. package/dist/types-C9FfXb1l.d.mts.map +0 -1
@@ -12,11 +12,11 @@ import {
12
12
  type ContractSpaceAggregate,
13
13
  type ContractSpaceMember,
14
14
  graphWalkStrategy,
15
+ requireHeadRef,
15
16
  } from '@prisma-next/migration-tools/aggregate';
16
17
  import { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';
17
18
  import { errorNoInvariantPath } from '@prisma-next/migration-tools/errors';
18
19
  import { findPathWithDecision } from '@prisma-next/migration-tools/migration-graph';
19
- import type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';
20
20
  import { ifDefined } from '@prisma-next/utils/defined';
21
21
  import { notOk, ok } from '@prisma-next/utils/result';
22
22
  import {
@@ -56,15 +56,6 @@ export interface ExecuteMigrationApplyOptions<TFamilyId extends string, TTargetI
56
56
  readonly migrationsDir: string;
57
57
  readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;
58
58
  readonly targetId: TTargetId;
59
- /**
60
- * Already-loaded app-space migration packages. The CLI command
61
- * loads these via `loadMigrationPackages(appMigrationsDir)`; the
62
- * operation hydrates the app member's graph with them. Required
63
- * because the framework-neutral aggregate loader doesn't know how
64
- * to read the user's `migrations/` directory layout (it's family-
65
- * aware: ops.json shape, manifest keys, etc.).
66
- */
67
- readonly appMigrationPackages: ReadonlyArray<OnDiskMigrationPackage>;
68
59
  /**
69
60
  * Optional app-space ref override. When provided, the app member's
70
61
  * graph-walk targets this hash instead of `member.headRef.hash`.
@@ -125,7 +116,6 @@ export async function executeMigrationApply<TFamilyId extends string, TTargetId
125
116
  migrationsDir,
126
117
  extensionPacks,
127
118
  targetId,
128
- appMigrationPackages,
129
119
  refHash,
130
120
  refInvariants,
131
121
  refName,
@@ -138,7 +128,6 @@ export async function executeMigrationApply<TFamilyId extends string, TTargetId
138
128
  appContract: contract,
139
129
  extensionPacks,
140
130
  deserializeContract: (json) => familyInstance.deserializeContract(json),
141
- appMigrationPackages,
142
131
  };
143
132
  const loaded = await buildContractSpaceAggregate(loadInputs);
144
133
  if (!loaded.ok) {
@@ -161,12 +150,15 @@ export async function executeMigrationApply<TFamilyId extends string, TTargetId
161
150
  const atHeadResolutions = new Map<string, AggregatePerSpacePlan>();
162
151
  for (const member of allMembers) {
163
152
  const isAppMember = member.spaceId === aggregate.app.spaceId;
164
- const targetHash = isAppMember && refHash !== undefined ? refHash : member.headRef.hash;
153
+ // The aggregate passed the integrity gate, so every member's head ref
154
+ // is resolved (the app's is synthesised from the live contract).
155
+ const headRef = requireHeadRef(member);
156
+ const targetHash = isAppMember && refHash !== undefined ? refHash : headRef.hash;
165
157
  const liveMarker = markerRows.get(member.spaceId) ?? null;
166
158
 
167
159
  // Empty-graph members fail loudly: replay needs an on-disk path
168
160
  // and an empty graph means the user has never planned this space.
169
- if (member.migrations.graph.nodes.size === 0) {
161
+ if (member.graph().nodes.size === 0) {
170
162
  // Edge case: target == EMPTY (greenfield, nothing to do) or
171
163
  // the live marker already matches the target. Loader integrity
172
164
  // allows this for extensions whose head ref is the empty
@@ -197,9 +189,9 @@ export async function executeMigrationApply<TFamilyId extends string, TTargetId
197
189
  const targetInvariants =
198
190
  isAppMember && refHash !== undefined && refInvariants !== undefined
199
191
  ? refInvariants
200
- : member.headRef.invariants;
192
+ : headRef.invariants;
201
193
  const targetMember: ContractSpaceMember =
202
- targetHash === member.headRef.hash && targetInvariants === member.headRef.invariants
194
+ targetHash === headRef.hash && targetInvariants === headRef.invariants
203
195
  ? member
204
196
  : { ...member, headRef: { hash: targetHash, invariants: targetInvariants } };
205
197
 
@@ -224,7 +216,7 @@ export async function executeMigrationApply<TFamilyId extends string, TTargetId
224
216
  // is never a graph node, producing an empty `structuralPath` and
225
217
  // a less actionable diagnostic.
226
218
  const fromHash = liveMarker?.storageHash ?? EMPTY_CONTRACT_HASH;
227
- const structural = findPathWithDecision(targetMember.migrations.graph, fromHash, targetHash, {
219
+ const structural = findPathWithDecision(targetMember.graph(), fromHash, targetHash, {
228
220
  required: new Set<string>(),
229
221
  });
230
222
  const structuralPath =
@@ -369,7 +361,7 @@ function buildAtHeadResolution(args: {
369
361
  providedInvariants: [],
370
362
  },
371
363
  displayOps: [],
372
- destinationContract: member.contract,
364
+ destinationContract: member.contract(),
373
365
  strategy: 'graph-walk',
374
366
  migrationEdges: [],
375
367
  };
@@ -407,7 +399,7 @@ function buildSuccess(args: BuildSuccessArgs): MigrationApplySuccess {
407
399
  (r) => r.spaceId === args.aggregate.app.spaceId,
408
400
  );
409
401
  const appMarkerHash =
410
- appResolution?.entry.plan.destination.storageHash ?? args.aggregate.app.headRef.hash;
402
+ appResolution?.entry.plan.destination.storageHash ?? requireHeadRef(args.aggregate.app).hash;
411
403
 
412
404
  // Per-migration entries (one per authored edge) preserve the
413
405
  // single-space `migrationsApplied` count semantics for back-compat
@@ -458,16 +450,37 @@ function buildSuccess(args: BuildSuccessArgs): MigrationApplySuccess {
458
450
  };
459
451
  }
460
452
 
461
- function buildNeverPlannedFailure(spaceId: string, targetHash: string): MigrationApplyFailure {
453
+ /**
454
+ * Build the `neverPlanned` failure raised when a contract space has no on-disk
455
+ * migration graph but migrate was asked to reach a target hash. The `why`
456
+ * states only the condition; the recovery sequence is composed by
457
+ * `errorPathUnreachable`'s `fix`.
458
+ *
459
+ * @internal Exported for testing only.
460
+ */
461
+ export function buildNeverPlannedFailure(
462
+ spaceId: string,
463
+ targetHash: string,
464
+ ): MigrationApplyFailure {
462
465
  return {
463
466
  code: 'MIGRATION_PATH_NOT_FOUND',
464
467
  summary: `No on-disk migrations for contract space "${spaceId}"`,
465
- why: `migrate is replay-only: every contract space must have an authored migration graph on disk. Space "${spaceId}" has no migrations under \`migrations/${spaceId}/\` but its head ref targets "${targetHash}". Run \`prisma-next migration plan\` first to materialise the path.`,
468
+ why: `migrate is replay-only: every contract space must have an authored migration graph on disk. Space "${spaceId}" has no migrations under \`migrations/${spaceId}/\` but its head ref targets "${targetHash}".`,
466
469
  meta: { spaceId, target: targetHash, kind: 'neverPlanned' },
467
470
  };
468
471
  }
469
472
 
470
- function buildPathNotFoundFailure(
473
+ /**
474
+ * Build the `pathUnreachable` failure raised when an emitted contract has no
475
+ * on-disk migration edge from the current marker to the target. The `why`
476
+ * states only the condition (no edge between the two named states, and migrate
477
+ * replays edges rather than inventing them); the recovery sequence — plan the
478
+ * edge, then re-apply — is composed by `errorPathUnreachable`'s `fix`, so the
479
+ * two read as one non-redundant plan-then-apply story.
480
+ *
481
+ * @internal Exported for testing only.
482
+ */
483
+ export function buildPathNotFoundFailure(
471
484
  spaceId: string,
472
485
  marker: ContractMarkerRecordLike | null,
473
486
  targetHash: string,
@@ -485,7 +498,7 @@ function buildPathNotFoundFailure(
485
498
  return {
486
499
  code: 'MIGRATION_PATH_NOT_FOUND',
487
500
  summary,
488
- why: `Cannot reach target "${targetHash}" from current marker "${fromHash}" in space "${spaceId}". The on-disk migration graph for this space does not connect the two states. Run \`prisma-next migration plan\` to materialise the path.`,
501
+ why: `No migration edge connects the current state "${fromHash}" to the target "${targetHash}" in contract space "${spaceId}". The on-disk migration graph does not join the two, and migrate replays existing edges it never invents one.`,
489
502
  meta: { spaceId, fromHash, targetHash, kind: 'pathUnreachable' },
490
503
  };
491
504
  }
@@ -18,7 +18,6 @@ import type {
18
18
  VerifyDatabaseSchemaResult,
19
19
  } from '@prisma-next/framework-components/control';
20
20
  import type { PslDocumentAst } from '@prisma-next/framework-components/psl-ast';
21
- import type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';
22
21
  import type { Result } from '@prisma-next/utils/result';
23
22
  import type { ExecuteDbVerifyResult } from './operations/db-verify';
24
23
 
@@ -548,12 +547,6 @@ export interface MigrationApplyOptions {
548
547
  readonly contract: unknown;
549
548
  /** Migrations root directory (`migrations/` under the project). */
550
549
  readonly migrationsDir: string;
551
- /**
552
- * Already-loaded app-space migration packages. The CLI loads these
553
- * via `loadMigrationPackages(appMigrationsDir)` before invoking
554
- * `migrationApply`.
555
- */
556
- readonly appMigrationPackages: ReadonlyArray<OnDiskMigrationPackage>;
557
550
  /**
558
551
  * Optional app-space ref override. When provided, the app member's
559
552
  * graph-walk targets this hash instead of `contract.storage.storageHash`.
@@ -584,9 +577,9 @@ export interface MigrationApplyOptions {
584
577
 
585
578
  /**
586
579
  * A single on-disk migration package surfaced to the operation. The
587
- * SQL family already produces this shape via `loadMigrationPackages`;
588
- * the operation hands it through to the framework-neutral aggregate
589
- * loader's `appMigrationPackages` slot.
580
+ * SQL family surfaces this shape from the tolerant contract-space
581
+ * aggregate's app packages; the operation hands it through to the
582
+ * framework-neutral aggregate loader's `appMigrationPackages` slot.
590
583
  *
591
584
  * (Originally named `MigrationApplyStep` for the legacy single-space
592
585
  * apply path; the name is kept for compatibility with existing CLI
@@ -461,8 +461,8 @@ function writeStructuredError(stream: MigrationCliWritable, err: CliStructuredEr
461
461
  * `null` when the file is missing and throwing `MIGRATION.INVALID_JSON`
462
462
  * when the file is present but cannot be parsed as JSON. The CLI feeds
463
463
  * this into `buildMigrationArtifacts` so the pure builder can preserve
464
- * fields owned by `migration plan` (contract bookends, hints, labels,
465
- * `createdAt`) across re-emits.
464
+ * fields owned by `migration plan` (contract bookends, `createdAt`) across
465
+ * re-emits.
466
466
  *
467
467
  * Author-time path: this loader still does not verify the manifest hash
468
468
  * or schema — that is the apply-time loader's job. Hash mismatch is the
@@ -472,8 +472,8 @@ function writeStructuredError(stream: MigrationCliWritable, err: CliStructuredEr
472
472
  * however, is now surfaced rather than swallowed: a malformed
473
473
  * `migration.json` indicates either a hand-edit gone wrong or partial
474
474
  * write, and silently rebuilding from `describe()` would discard the
475
- * user's on-disk content (preserved bookends, hints, labels,
476
- * `createdAt`) without any indication something was wrong on disk.
475
+ * user's on-disk content (preserved bookends, `createdAt`) without any
476
+ * indication something was wrong on disk.
477
477
  * Apply-time consumers always route through the verifying
478
478
  * `readMigrationPackage` in `@prisma-next/migration-tools/io` instead.
479
479
  */
@@ -28,6 +28,7 @@ import {
28
28
  import { errorRuntime } from '@prisma-next/errors/execution';
29
29
  import type { MigrationToolsError } from '@prisma-next/migration-tools/errors';
30
30
  import type { RefResolutionError } from '@prisma-next/migration-tools/ref-resolution';
31
+ import type { MigrationApplyFailure } from '../control-api/types';
31
32
 
32
33
  export {
33
34
  ERROR_CODE_DESTRUCTIVE_CHANGES,
@@ -68,6 +69,239 @@ export {
68
69
  errorUnexpected,
69
70
  };
70
71
 
72
+ export function errorRefSetHashNotInGraph(
73
+ resolvedHash: string,
74
+ reachableHashes: readonly string[],
75
+ graphTipHash: string | null,
76
+ ): CliStructuredError {
77
+ const reachableList =
78
+ reachableHashes.length > 0 ? reachableHashes.join(', ') : '(none — migration graph is empty)';
79
+ const fix =
80
+ reachableHashes.length > 0
81
+ ? graphTipHash !== null
82
+ ? `Set the ref to a graph-node hash such as ${graphTipHash}, or run \`prisma-next migration plan\` to extend the graph.`
83
+ : 'Set the ref to a hash that appears in the migration graph.'
84
+ : 'Run `prisma-next migration plan` first.';
85
+ return errorRuntime(`Resolved contract hash is not in the migration graph: ${resolvedHash}`, {
86
+ why:
87
+ reachableHashes.length > 0
88
+ ? `The migration graph reaches ${reachableList}; resolved ${resolvedHash} isn't a graph node.`
89
+ : 'The migration graph is empty — no hashes reachable.',
90
+ fix,
91
+ meta: {
92
+ code: 'MIGRATION.HASH_NOT_IN_GRAPH',
93
+ resolvedHash,
94
+ reachableHashes: [...reachableHashes],
95
+ ...(graphTipHash !== null ? { graphTipHash } : {}),
96
+ },
97
+ });
98
+ }
99
+
100
+ export function errorRefSetEmptySentinel(hash: string): CliStructuredError {
101
+ return errorRuntime(`Cannot set ref to the empty-database sentinel: ${hash}`, {
102
+ why: 'The empty-database sentinel is a planner internal; it is not a valid ref target.',
103
+ fix: 'Set the ref to a contract hash from the migration graph, or use another ref name.',
104
+ meta: {
105
+ code: 'MIGRATION.REF_SET_EMPTY_SENTINEL',
106
+ hash,
107
+ },
108
+ });
109
+ }
110
+
111
+ /**
112
+ * `--space <id>` was given a value that doesn't satisfy the contract-space
113
+ * naming rule (`[a-z][a-z0-9_-]{0,63}` per `isValidSpaceId`). Fires before
114
+ * any fs work — the input is syntactically rejected the same way an on-disk
115
+ * directory with that name would be skipped by the enumerator.
116
+ */
117
+ export function errorInvalidSpaceId(spaceId: string): CliStructuredError {
118
+ return errorRuntime(`Invalid contract space id: ${spaceId}`, {
119
+ why: 'Contract space ids must match [a-z][a-z0-9_-]{0,63} (lowercase, starts with a letter, max 64 characters — the rule applied to every on-disk space directory).',
120
+ fix: 'Pass a space id that matches the directory naming rule, or omit --space to list every space.',
121
+ meta: {
122
+ code: 'MIGRATION.INVALID_SPACE_ID',
123
+ spaceId,
124
+ },
125
+ });
126
+ }
127
+
128
+ /**
129
+ * `migration list --space <id>` was given a contract-space id that has no
130
+ * directory under `migrations/`. Distinct from "the space exists but is
131
+ * empty" — that path renders the empty-state line and exits 0 per the
132
+ * slice spec § Empty-state. This error fires only when `<projectMigrationsDir>/<spaceId>`
133
+ * does not exist on disk.
134
+ *
135
+ * `availableSpaces` lists the contract-space directory names actually
136
+ * present, sorted lex-asc, so the diagnostic can suggest a near match
137
+ * without making the user reach for `ls`.
138
+ */
139
+ export function errorSpaceNotFound(
140
+ spaceId: string,
141
+ availableSpaces: readonly string[],
142
+ ): CliStructuredError {
143
+ const availableList =
144
+ availableSpaces.length > 0
145
+ ? availableSpaces.join(', ')
146
+ : '(none — no contract spaces on disk yet)';
147
+ const fix =
148
+ availableSpaces.length > 0
149
+ ? `Pick one of: ${availableList}. Run \`prisma-next migration list\` (no --space) to see every space's migrations.`
150
+ : 'Author a migration with `prisma-next migration new` to create the first contract-space directory.';
151
+ return errorRuntime(`Unknown contract space: ${spaceId}`, {
152
+ why: `No directory named "${spaceId}" exists under the migrations root.`,
153
+ fix,
154
+ meta: {
155
+ code: 'MIGRATION.SPACE_NOT_FOUND',
156
+ spaceId,
157
+ availableSpaces: [...availableSpaces],
158
+ },
159
+ });
160
+ }
161
+
162
+ export function errorRefSetBundleNotFound(hash: string): CliStructuredError {
163
+ return errorRuntime(`No migration bundle matches graph-node hash ${hash}`, {
164
+ why: `The hash is a graph node but no on-disk bundle has metadata.to = ${hash}.`,
165
+ fix: 'Run `pnpm fixtures:check`, or re-emit the migration that produces this hash so its bundle is restored.',
166
+ meta: {
167
+ code: 'MIGRATION.REF_SET_BUNDLE_NOT_FOUND',
168
+ hash,
169
+ },
170
+ });
171
+ }
172
+
173
+ export function errorPlanForgotTheFlag(
174
+ resolvedHash: string,
175
+ reachableRefs: ReadonlyArray<{ readonly name: string; readonly hash: string }>,
176
+ graphTipHash: string | null,
177
+ ): CliStructuredError {
178
+ const reachableList =
179
+ reachableRefs.length > 0
180
+ ? reachableRefs.map((r) => `${r.name} (${r.hash})`).join(', ')
181
+ : '(none)';
182
+ const refFix =
183
+ reachableRefs.length > 0
184
+ ? `Run migration plan with ${reachableRefs.map((r) => `--from ${r.name}`).join(' or ')}.`
185
+ : graphTipHash !== null
186
+ ? `Run migration plan --from ${graphTipHash}.`
187
+ : 'Commit pending migrations first, then run migration plan.';
188
+ return errorRuntime(`Resolved from-hash is not in the migration graph: ${resolvedHash}`, {
189
+ why: `The migration graph reaches ${reachableList}; resolved ${resolvedHash} isn't a graph node.`,
190
+ fix: refFix,
191
+ meta: {
192
+ code: 'MIGRATION.HASH_NOT_IN_GRAPH',
193
+ resolvedHash,
194
+ reachableRefs: reachableRefs.map((r) => r.name),
195
+ ...(graphTipHash !== null ? { graphTipHash } : {}),
196
+ },
197
+ });
198
+ }
199
+
200
+ export function errorSnapshotMissing(
201
+ identifier: string,
202
+ options?: { readonly viaRef?: boolean },
203
+ ): CliStructuredError {
204
+ const viaRef = options?.viaRef !== false;
205
+ const fix = viaRef
206
+ ? `Run "prisma-next db update --advance-ref ${identifier}" to repopulate the snapshot, or "prisma-next ref delete ${identifier}" to clear the orphan pointer.`
207
+ : `No contract source exists for hash "${identifier}" on an empty migration graph. Use --from with a ref name that has a paired snapshot, or run db update first.`;
208
+ return errorRuntime(
209
+ viaRef
210
+ ? `Ref "${identifier}" has no paired contract snapshot`
211
+ : `No contract source for from-hash "${identifier}"`,
212
+ {
213
+ why: viaRef
214
+ ? `Ref "${identifier}" exists but its paired snapshot files are missing.`
215
+ : `Hash "${identifier}" is not a graph node and no paired ref snapshot supplies a contract.`,
216
+ fix,
217
+ meta: {
218
+ code: 'MIGRATION.SNAPSHOT_MISSING',
219
+ identifier,
220
+ viaRef,
221
+ },
222
+ },
223
+ );
224
+ }
225
+
226
+ export function errorMarkerMismatch(
227
+ markerHash: string,
228
+ reachableHashes: readonly string[],
229
+ graphTip: string | null,
230
+ ): CliStructuredError {
231
+ const reachableList =
232
+ reachableHashes.length > 0 ? reachableHashes.join(', ') : '(none — migration graph is empty)';
233
+ const planFromFix =
234
+ graphTip !== null
235
+ ? `Run \`prisma-next migration plan --from ${graphTip}\` if the live marker is canonical and the on-disk graph needs catching up.`
236
+ : 'Run `prisma-next migration plan` if the live marker is canonical and the on-disk graph needs catching up.';
237
+ return errorRuntime('Database marker is not reachable in the on-disk migration graph', {
238
+ why: `DB marker is ${markerHash}, but the on-disk migration graph reaches: ${reachableList}.`,
239
+ fix: [
240
+ planFromFix,
241
+ `Run \`prisma-next ref set db ${markerHash}\` if the on-disk graph is canonical and the local \`db\` ref drifted.`,
242
+ 'Investigate whether the database was migrated by an out-of-band process.',
243
+ ].join('\n'),
244
+ meta: {
245
+ code: 'MIGRATION.MARKER_MISMATCH',
246
+ markerHash,
247
+ reachableHashes: [...reachableHashes],
248
+ ...(graphTip !== null ? { graphTip } : {}),
249
+ },
250
+ });
251
+ }
252
+
253
+ export function errorPathUnreachable(failure: MigrationApplyFailure): CliStructuredError {
254
+ const meta = failure.meta ?? {};
255
+ const fromHashMeta = typeof meta['fromHash'] === 'string' ? meta['fromHash'] : null;
256
+ // `buildPathNotFoundFailure` uses this sentinel in meta when the live marker is null.
257
+ const planFromHash = fromHashMeta === '<empty>' ? null : fromHashMeta;
258
+ const targetHash =
259
+ typeof meta['targetHash'] === 'string'
260
+ ? meta['targetHash']
261
+ : typeof meta['target'] === 'string'
262
+ ? meta['target']
263
+ : null;
264
+ const deadEnds = meta['deadEnds'];
265
+ const deadEndsSuffix =
266
+ Array.isArray(deadEnds) && deadEnds.length > 0
267
+ ? ` Dead-ends: ${deadEnds.map(String).join(', ')}.`
268
+ : '';
269
+ // Plan-then-apply recovery. The planner destination is the missing edge's
270
+ // target; `migration plan --to` (built for arbitrary targets) makes this a
271
+ // real command, so the diagnostic that sends you here is now honest.
272
+ const planCommand = (() => {
273
+ if (planFromHash !== null && targetHash !== null) {
274
+ return `prisma-next migration plan --from ${planFromHash} --to ${targetHash} --name <slug>`;
275
+ }
276
+ if (targetHash !== null) {
277
+ return `prisma-next migration plan --to ${targetHash} --name <slug>`;
278
+ }
279
+ if (planFromHash !== null) {
280
+ return `prisma-next migration plan --from ${planFromHash} --name <slug>`;
281
+ }
282
+ return 'prisma-next migration plan';
283
+ })();
284
+ const applyCommand =
285
+ targetHash !== null ? `prisma-next migrate --to ${targetHash}` : 'prisma-next migrate';
286
+ return errorRuntime(failure.summary, {
287
+ why:
288
+ failure.why ??
289
+ `Cannot reach target "${targetHash ?? '<unknown>'}" from current marker "${fromHashMeta ?? '<unknown>'}".${deadEndsSuffix}`,
290
+ fix: [
291
+ 'Plan the missing edge, then apply it:',
292
+ ` 1. ${planCommand}`,
293
+ ` 2. ${applyCommand}`,
294
+ 'A rollback (reverse) plan is expected to contain destructive (DROP) operations — review them before applying.',
295
+ 'Narrower cases (rename inference, re-adding a NOT NULL column without a safe default, or a type change that needs data) may additionally need a hint in the planned migration.',
296
+ 'Inspect the on-disk graph with `prisma-next migration list`, or `prisma-next migration show <bundle>` for any bundle in the path you expected.',
297
+ ].join('\n'),
298
+ meta: {
299
+ ...meta,
300
+ code: 'MIGRATION.PATH_UNREACHABLE',
301
+ },
302
+ });
303
+ }
304
+
71
305
  /**
72
306
  * Maps a `MigrationToolsError` raised by the migration-tools loader/graph
73
307
  * surface (`readMigrationPackage`, `readMigrationsDir`, `readRefs`,
@@ -3,10 +3,7 @@ import type { ControlTargetDescriptor } from '@prisma-next/framework-components/
3
3
  import { hasMigrations } from '@prisma-next/framework-components/control';
4
4
  import type { NoInvariantPathStructuralEdge } from '@prisma-next/migration-tools/errors';
5
5
  import type { MigrationEdge, MigrationGraph } from '@prisma-next/migration-tools/graph';
6
- import { readMigrationsDir } from '@prisma-next/migration-tools/io';
7
6
  import type { PathDecision } from '@prisma-next/migration-tools/migration-graph';
8
- import { reconstructGraph } from '@prisma-next/migration-tools/migration-graph';
9
- import type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';
10
7
  import { APP_SPACE_ID, spaceMigrationDirectory } from '@prisma-next/migration-tools/spaces';
11
8
  import { ifDefined } from '@prisma-next/utils/defined';
12
9
  import type { Command } from 'commander';
@@ -154,7 +151,7 @@ export function resolveMigrationPaths(
154
151
 
155
152
  /**
156
153
  * Slim representation of a PathDecision for CLI JSON output.
157
- * Strips internal fields (createdAt, labels) from path entries.
154
+ * Strips internal fields (createdAt) from path entries.
158
155
  */
159
156
  export interface PathDecisionResult {
160
157
  readonly fromHash: string;
@@ -231,22 +228,6 @@ export function getTargetMigrations(target: ControlTargetDescriptor<string, stri
231
228
  return hasMigrations(target) ? target.migrations : undefined;
232
229
  }
233
230
 
234
- /**
235
- * Reads the migrations directory and builds the migration graph from all
236
- * packages. Throws on I/O or graph errors — callers handle error mapping.
237
- *
238
- * Every on-disk package is content-addressed (`migrationHash` is always a
239
- * string); there is no draft state to filter out.
240
- */
241
- export async function loadMigrationPackages(migrationsDir: string): Promise<{
242
- bundles: readonly OnDiskMigrationPackage[];
243
- graph: MigrationGraph;
244
- }> {
245
- const bundles = await readMigrationsDir(migrationsDir);
246
- const graph = reconstructGraph(bundles);
247
- return { bundles, graph };
248
- }
249
-
250
231
  /**
251
232
  * The subset of the emitted contract.json that the framework layer can
252
233
  * safely type. The emitter adds these fields on top of the family-specific
@@ -0,0 +1,96 @@
1
+ import { MigrationToolsError } from '@prisma-next/migration-tools/errors';
2
+ import { notOk, type Result } from '@prisma-next/utils/result';
3
+ import { join } from 'pathe';
4
+ import {
5
+ CliStructuredError,
6
+ errorContractValidationFailed,
7
+ errorFileNotFound,
8
+ errorSnapshotMissing,
9
+ errorUnexpected,
10
+ mapMigrationToolsError,
11
+ } from './cli-errors';
12
+
13
+ export function mapContractAtError(
14
+ error: unknown,
15
+ options?: { readonly artifactRole?: 'from' | 'to' },
16
+ ): Result<never, CliStructuredError> {
17
+ if (MigrationToolsError.is(error)) {
18
+ switch (error.code) {
19
+ case 'MIGRATION.SNAPSHOT_MISSING': {
20
+ const refName =
21
+ typeof error.details?.['refName'] === 'string'
22
+ ? error.details['refName']
23
+ : typeof error.details?.['identifier'] === 'string'
24
+ ? error.details['identifier']
25
+ : 'unknown';
26
+ return notOk(errorSnapshotMissing(refName));
27
+ }
28
+ case 'MIGRATION.CONTRACT_DESERIALIZATION_FAILED': {
29
+ const filePath =
30
+ typeof error.details?.['filePath'] === 'string'
31
+ ? error.details['filePath']
32
+ : 'ref-snapshot';
33
+ const message =
34
+ typeof error.details?.['message'] === 'string' ? error.details['message'] : error.message;
35
+ const isRefSnapshot = filePath.endsWith('.contract.json');
36
+ return notOk(
37
+ errorContractValidationFailed(
38
+ isRefSnapshot
39
+ ? `Ref snapshot contract failed to deserialize: ${message}`
40
+ : `Predecessor contract at ${filePath} failed to deserialize: ${message}`,
41
+ { where: { path: isRefSnapshot ? 'ref-snapshot' : filePath } },
42
+ ),
43
+ );
44
+ }
45
+ case 'MIGRATION.INVALID_JSON': {
46
+ const filePath =
47
+ typeof error.details?.['filePath'] === 'string' ? error.details['filePath'] : 'unknown';
48
+ const message =
49
+ typeof error.details?.['parseError'] === 'string'
50
+ ? error.details['parseError']
51
+ : error.message;
52
+ const role = options?.artifactRole ?? 'from';
53
+ return notOk(
54
+ errorContractValidationFailed(
55
+ role === 'to'
56
+ ? `Target contract at ${filePath} failed to deserialize: ${message}`
57
+ : `Predecessor contract at ${filePath} failed to deserialize: ${message}`,
58
+ { where: { path: filePath } },
59
+ ),
60
+ );
61
+ }
62
+ case 'MIGRATION.BUNDLE_NOT_FOUND_FOR_GRAPH_NODE':
63
+ return notOk(
64
+ errorUnexpected(error.message, {
65
+ why: error.why,
66
+ fix: error.fix,
67
+ }),
68
+ );
69
+ case 'MIGRATION.FILE_MISSING': {
70
+ const file =
71
+ typeof error.details?.['file'] === 'string' ? error.details['file'] : 'end-contract.json';
72
+ const dir = typeof error.details?.['dir'] === 'string' ? error.details['dir'] : '';
73
+ const jsonPath = dir ? join(dir, 'end-contract.json') : file;
74
+ const role = options?.artifactRole ?? 'from';
75
+ return notOk(
76
+ errorFileNotFound(jsonPath, {
77
+ why:
78
+ role === 'to'
79
+ ? `Target migration is missing its destination contract snapshot at ${jsonPath}`
80
+ : `Predecessor migration is missing its destination contract snapshot at ${jsonPath}`,
81
+ fix:
82
+ role === 'to'
83
+ ? 'Re-emit the target migration so its sibling `end-contract.json` / `end-contract.d.ts` are restored, then re-run this command.'
84
+ : 'Re-emit the predecessor migration (`prisma-next migration plan` from its source) so its sibling `end-contract.json` is restored, then re-run this command.',
85
+ }),
86
+ );
87
+ }
88
+ default:
89
+ return notOk(mapMigrationToolsError(error));
90
+ }
91
+ }
92
+ if (CliStructuredError.is(error)) {
93
+ return notOk(error);
94
+ }
95
+ throw error;
96
+ }