@prisma-next/cli 0.11.0-dev.3 → 0.11.0-dev.30

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 (139) hide show
  1. package/dist/cli-errors-DFF1LlfU.mjs +215 -0
  2. package/dist/cli-errors-DFF1LlfU.mjs.map +1 -0
  3. package/dist/cli.mjs +8 -9
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/{client-oXO2WCPD.mjs → client-a5NJce0-.mjs} +5 -5
  6. package/dist/{client-oXO2WCPD.mjs.map → client-a5NJce0-.mjs.map} +1 -1
  7. package/dist/{command-helpers-DtavI0wJ.mjs → command-helpers-BnqwTptC.mjs} +380 -6
  8. package/dist/command-helpers-BnqwTptC.mjs.map +1 -0
  9. package/dist/commands/contract-emit.d.mts.map +1 -1
  10. package/dist/commands/contract-emit.mjs +1 -1
  11. package/dist/commands/contract-infer.d.mts.map +1 -1
  12. package/dist/commands/contract-infer.mjs +1 -1
  13. package/dist/commands/db-init.d.mts.map +1 -1
  14. package/dist/commands/db-init.mjs +33 -7
  15. package/dist/commands/db-init.mjs.map +1 -1
  16. package/dist/commands/db-schema.d.mts.map +1 -1
  17. package/dist/commands/db-schema.mjs +3 -4
  18. package/dist/commands/db-schema.mjs.map +1 -1
  19. package/dist/commands/db-sign.d.mts.map +1 -1
  20. package/dist/commands/db-sign.mjs +6 -7
  21. package/dist/commands/db-sign.mjs.map +1 -1
  22. package/dist/commands/db-update.d.mts.map +1 -1
  23. package/dist/commands/db-update.mjs +36 -8
  24. package/dist/commands/db-update.mjs.map +1 -1
  25. package/dist/commands/db-verify.d.mts.map +1 -1
  26. package/dist/commands/db-verify.mjs +1 -1
  27. package/dist/commands/migrate.d.mts +5 -1
  28. package/dist/commands/migrate.d.mts.map +1 -1
  29. package/dist/commands/migrate.mjs +44 -9
  30. package/dist/commands/migrate.mjs.map +1 -1
  31. package/dist/commands/migration-check.d.mts.map +1 -1
  32. package/dist/commands/migration-check.mjs +2 -3
  33. package/dist/commands/migration-check.mjs.map +1 -1
  34. package/dist/commands/migration-graph.d.mts.map +1 -1
  35. package/dist/commands/migration-graph.mjs +2 -3
  36. package/dist/commands/migration-graph.mjs.map +1 -1
  37. package/dist/commands/migration-list.d.mts +57 -13
  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.map +1 -1
  41. package/dist/commands/migration-log.mjs +3 -4
  42. package/dist/commands/migration-log.mjs.map +1 -1
  43. package/dist/commands/migration-new.d.mts.map +1 -1
  44. package/dist/commands/migration-new.mjs +3 -4
  45. package/dist/commands/migration-new.mjs.map +1 -1
  46. package/dist/commands/migration-plan.d.mts +1 -0
  47. package/dist/commands/migration-plan.d.mts.map +1 -1
  48. package/dist/commands/migration-plan.mjs +1 -1
  49. package/dist/commands/migration-show.d.mts +1 -1
  50. package/dist/commands/migration-show.d.mts.map +1 -1
  51. package/dist/commands/migration-show.mjs +6 -7
  52. package/dist/commands/migration-show.mjs.map +1 -1
  53. package/dist/commands/migration-status.d.mts.map +1 -1
  54. package/dist/commands/migration-status.mjs +6 -7
  55. package/dist/commands/migration-status.mjs.map +1 -1
  56. package/dist/commands/ref.d.mts +1 -1
  57. package/dist/commands/ref.d.mts.map +1 -1
  58. package/dist/commands/ref.mjs +34 -9
  59. package/dist/commands/ref.mjs.map +1 -1
  60. package/dist/config-loader-B6sJjXTv.mjs.map +1 -1
  61. package/dist/config-loader.d.mts.map +1 -1
  62. package/dist/{contract-emit-bcrpT-wD.mjs → contract-emit-DYBHfZqL.mjs} +8 -7
  63. package/dist/contract-emit-DYBHfZqL.mjs.map +1 -0
  64. package/dist/{contract-emit-uwT-Mj8-.mjs → contract-emit-aFcOi3aw.mjs} +20 -14
  65. package/dist/contract-emit-aFcOi3aw.mjs.map +1 -0
  66. package/dist/{contract-enrichment-Dani0mMW.mjs → contract-enrichment-XmUPhmsS.mjs} +4 -25
  67. package/dist/contract-enrichment-XmUPhmsS.mjs.map +1 -0
  68. package/dist/{contract-infer-pKkiCt7C.mjs → contract-infer-BpJeg-Eu.mjs} +3 -4
  69. package/dist/{contract-infer-pKkiCt7C.mjs.map → contract-infer-BpJeg-Eu.mjs.map} +1 -1
  70. package/dist/{contract-space-aggregate-loader-BmNQwlws.mjs → contract-space-aggregate-loader-EVU3n9YE.mjs} +2 -2
  71. package/dist/{contract-space-aggregate-loader-BmNQwlws.mjs.map → contract-space-aggregate-loader-EVU3n9YE.mjs.map} +1 -1
  72. package/dist/{db-verify-AoIUriL4.mjs → db-verify-CxtdGiL3.mjs} +6 -7
  73. package/dist/{db-verify-AoIUriL4.mjs.map → db-verify-CxtdGiL3.mjs.map} +1 -1
  74. package/dist/exports/control-api.d.mts +1 -1
  75. package/dist/exports/control-api.d.mts.map +1 -1
  76. package/dist/exports/control-api.mjs +3 -3
  77. package/dist/exports/index.d.mts.map +1 -1
  78. package/dist/exports/index.mjs +1 -1
  79. package/dist/exports/index.mjs.map +1 -1
  80. package/dist/exports/init-output.d.mts.map +1 -1
  81. package/dist/exports/init-output.mjs +1 -1
  82. package/dist/{framework-components-65gOHkHB.mjs → framework-components-DTcjouhS.mjs} +2 -2
  83. package/dist/{framework-components-65gOHkHB.mjs.map → framework-components-DTcjouhS.mjs.map} +1 -1
  84. package/dist/global-flags-CdE7M0d9.d.mts.map +1 -1
  85. package/dist/graph-render-DJVv0_uf.mjs.map +1 -1
  86. package/dist/{init-YX6lCJpG.mjs → init-eGkSo7hi.mjs} +5 -5
  87. package/dist/{init-YX6lCJpG.mjs.map → init-eGkSo7hi.mjs.map} +1 -1
  88. package/dist/{inspect-live-schema-LeWvkZVz.mjs → inspect-live-schema-B1GCyjAJ.mjs} +5 -5
  89. package/dist/{inspect-live-schema-LeWvkZVz.mjs.map → inspect-live-schema-B1GCyjAJ.mjs.map} +1 -1
  90. package/dist/migration-cli.d.mts.map +1 -1
  91. package/dist/migration-cli.mjs.map +1 -1
  92. package/dist/{migration-command-scaffold-BtkunvFQ.mjs → migration-command-scaffold-CNdZl60X.mjs} +5 -5
  93. package/dist/{migration-command-scaffold-BtkunvFQ.mjs.map → migration-command-scaffold-CNdZl60X.mjs.map} +1 -1
  94. package/dist/migration-list-CnYiHrNV.mjs +288 -0
  95. package/dist/migration-list-CnYiHrNV.mjs.map +1 -0
  96. package/dist/{migration-plan-C2jeH1J5.mjs → migration-plan-BnmP_yNz.mjs} +346 -88
  97. package/dist/migration-plan-BnmP_yNz.mjs.map +1 -0
  98. package/dist/{migrations-CwZMa1Ck.mjs → migrations-C7YTBnLy.mjs} +11 -2
  99. package/dist/migrations-C7YTBnLy.mjs.map +1 -0
  100. package/dist/{output-BlsrGMEF.mjs → output-CUIdfYo5.mjs} +1 -1
  101. package/dist/{output-BlsrGMEF.mjs.map → output-CUIdfYo5.mjs.map} +1 -1
  102. package/dist/{progress-adapter-DFfvZcYL.mjs → progress-adapter-xASh41wr.mjs} +1 -1
  103. package/dist/{progress-adapter-DFfvZcYL.mjs.map → progress-adapter-xASh41wr.mjs.map} +1 -1
  104. package/dist/ref-advancement-CHJ_8HxQ.mjs +50 -0
  105. package/dist/ref-advancement-CHJ_8HxQ.mjs.map +1 -0
  106. package/dist/{types--CqjMdk0.d.mts → types-UWB2-rrw.d.mts} +12 -4
  107. package/dist/types-UWB2-rrw.d.mts.map +1 -0
  108. package/dist/{verify-Bom75OYI.mjs → verify-DX4RQwq4.mjs} +2 -2
  109. package/dist/{verify-Bom75OYI.mjs.map → verify-DX4RQwq4.mjs.map} +1 -1
  110. package/package.json +20 -20
  111. package/src/commands/contract-emit.ts +19 -7
  112. package/src/commands/db-init.ts +48 -2
  113. package/src/commands/db-update.ts +45 -0
  114. package/src/commands/migrate.ts +73 -3
  115. package/src/commands/migration-list.ts +145 -74
  116. package/src/commands/migration-plan.ts +365 -128
  117. package/src/commands/ref.ts +46 -6
  118. package/src/control-api/contract-enrichment.ts +6 -42
  119. package/src/control-api/operations/contract-emit.ts +7 -4
  120. package/src/control-api/types.ts +7 -0
  121. package/src/utils/cli-errors.ts +224 -0
  122. package/src/utils/formatters/migration-list-render.ts +171 -0
  123. package/src/utils/formatters/migration-list-styler.ts +56 -0
  124. package/src/utils/formatters/migrations.ts +25 -0
  125. package/src/utils/plan-resolution.ts +257 -0
  126. package/src/utils/ref-advancement.ts +68 -0
  127. package/dist/cli-errors-Czmx92Zy.d.mts +0 -3
  128. package/dist/cli-errors-Djtz98Vm.mjs +0 -71
  129. package/dist/cli-errors-Djtz98Vm.mjs.map +0 -1
  130. package/dist/command-helpers-DtavI0wJ.mjs.map +0 -1
  131. package/dist/commands/migration-list.mjs.map +0 -1
  132. package/dist/contract-emit-bcrpT-wD.mjs.map +0 -1
  133. package/dist/contract-emit-uwT-Mj8-.mjs.map +0 -1
  134. package/dist/contract-enrichment-Dani0mMW.mjs.map +0 -1
  135. package/dist/migration-plan-C2jeH1J5.mjs.map +0 -1
  136. package/dist/migrations-CwZMa1Ck.mjs.map +0 -1
  137. package/dist/terminal-ui-BiB_8KNo.mjs +0 -379
  138. package/dist/terminal-ui-BiB_8KNo.mjs.map +0 -1
  139. package/dist/types--CqjMdk0.d.mts.map +0 -1
@@ -1,18 +1,26 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { EMPTY_CONTRACT_HASH } from '@prisma-next/migration-tools/constants';
1
3
  import { MigrationToolsError } from '@prisma-next/migration-tools/errors';
4
+ import { findLatestMigration, isGraphNode } from '@prisma-next/migration-tools/migration-graph';
2
5
  import { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';
3
6
  import type { RefEntry } from '@prisma-next/migration-tools/refs';
4
7
  import {
5
- deleteRef,
8
+ deleteRefPaired,
6
9
  readRefs,
7
10
  validateRefName,
8
11
  validateRefValue,
9
- writeRef,
12
+ writeRefPaired,
10
13
  } from '@prisma-next/migration-tools/refs';
11
14
  import { notOk, ok, type Result } from '@prisma-next/utils/result';
12
15
  import { Command } from 'commander';
16
+ import { join } from 'pathe';
13
17
  import { loadConfig } from '../config-loader';
14
18
  import {
15
19
  CliStructuredError,
20
+ errorFileNotFound,
21
+ errorRefSetBundleNotFound,
22
+ errorRefSetEmptySentinel,
23
+ errorRefSetHashNotInGraph,
16
24
  errorRuntime,
17
25
  errorUnexpected,
18
26
  mapMigrationToolsError,
@@ -26,6 +34,7 @@ import {
26
34
  } from '../utils/command-helpers';
27
35
  import { formatCommandHelp } from '../utils/formatters/help';
28
36
  import { parseGlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';
37
+ import { readContractIR } from '../utils/ref-advancement';
29
38
  import { handleResult } from '../utils/result-handler';
30
39
  import { createTerminalUI } from '../utils/terminal-ui';
31
40
 
@@ -73,13 +82,13 @@ export async function executeRefSetCommand(
73
82
  try {
74
83
  const config = await loadConfig(options.config);
75
84
  const { appMigrationsDir, refsDir } = resolveMigrationPaths(options.config, config);
85
+ const { graph, bundles } = await loadMigrationPackages(appMigrationsDir);
86
+ const refs = await readRefs(refsDir);
76
87
 
77
88
  let resolvedHash: string;
78
89
  if (validateRefValue(contractInput)) {
79
90
  resolvedHash = contractInput;
80
91
  } else {
81
- const { graph } = await loadMigrationPackages(appMigrationsDir);
82
- const refs = await readRefs(refsDir);
83
92
  const refResult = parseContractRef(contractInput, { graph, refs });
84
93
  if (!refResult.ok) {
85
94
  return notOk(mapRefResolutionError(refResult.failure));
@@ -87,8 +96,39 @@ export async function executeRefSetCommand(
87
96
  resolvedHash = refResult.value.hash;
88
97
  }
89
98
 
99
+ if (resolvedHash === EMPTY_CONTRACT_HASH) {
100
+ return notOk(errorRefSetEmptySentinel(resolvedHash));
101
+ }
102
+ if (!isGraphNode(resolvedHash, graph)) {
103
+ const graphTip = findLatestMigration(graph)?.to ?? null;
104
+ return notOk(errorRefSetHashNotInGraph(resolvedHash, [...graph.nodes].sort(), graphTip));
105
+ }
106
+
107
+ const matchingBundle = bundles.find((bundle) => bundle.metadata.to === resolvedHash);
108
+ if (!matchingBundle) {
109
+ return notOk(errorRefSetBundleNotFound(resolvedHash));
110
+ }
111
+
112
+ const contractJsonPath = join(matchingBundle.dirPath, 'end-contract.json');
113
+ let contractJson: Record<string, unknown>;
114
+ try {
115
+ const raw = await readFile(contractJsonPath, 'utf-8');
116
+ contractJson = JSON.parse(raw) as Record<string, unknown>;
117
+ } catch (readError) {
118
+ if (readError instanceof Error && (readError as NodeJS.ErrnoException).code === 'ENOENT') {
119
+ return notOk(
120
+ errorFileNotFound(contractJsonPath, {
121
+ why: `Migration bundle for hash ${resolvedHash} is missing its end-contract snapshot at ${contractJsonPath}`,
122
+ fix: 'Run `pnpm fixtures:check`, or re-emit the migration so its end-contract.json is restored.',
123
+ }),
124
+ );
125
+ }
126
+ throw readError;
127
+ }
128
+
129
+ const contractIR = await readContractIR(contractJson, contractJsonPath);
90
130
  const entry: RefEntry = { hash: resolvedHash, invariants: [] };
91
- await writeRef(refsDir, name, entry);
131
+ await writeRefPaired(refsDir, name, entry, contractIR);
92
132
  return ok({ ok: true as const, ref: name, hash: resolvedHash, invariants: [] });
93
133
  } catch (error) {
94
134
  if (error instanceof CliStructuredError) return notOk(error);
@@ -103,7 +143,7 @@ export async function executeRefDeleteCommand(
103
143
  try {
104
144
  const config = await loadConfig(options.config);
105
145
  const { refsDir } = resolveMigrationPaths(options.config, config);
106
- await deleteRef(refsDir, name);
146
+ await deleteRefPaired(refsDir, name);
107
147
  return ok({ ok: true as const, ref: name, deleted: true as const });
108
148
  } catch (error) {
109
149
  if (error instanceof CliStructuredError) return notOk(error);
@@ -1,7 +1,8 @@
1
1
  import type { Contract } from '@prisma-next/contract/types';
2
- import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';
3
-
4
- type CapabilityMatrix = Record<string, Record<string, boolean>>;
2
+ import {
3
+ mergeCapabilityMatrices,
4
+ type TargetBoundComponentDescriptor,
5
+ } from '@prisma-next/framework-components/components';
5
6
 
6
7
  function isPlainObject(value: unknown): value is Record<string, unknown> {
7
8
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -26,37 +27,6 @@ function sortDeepTyped<T>(value: T): T {
26
27
  return sortDeep(value) as T;
27
28
  }
28
29
 
29
- function extractCapabilityMatrix(value: unknown): CapabilityMatrix {
30
- if (!isPlainObject(value)) return {};
31
-
32
- const out: CapabilityMatrix = {};
33
- for (const [namespace, maybeCaps] of Object.entries(value)) {
34
- if (!isPlainObject(maybeCaps)) continue;
35
- const caps: Record<string, boolean> = {};
36
- for (const [key, flag] of Object.entries(maybeCaps)) {
37
- if (typeof flag === 'boolean') {
38
- caps[key] = flag;
39
- }
40
- }
41
- if (Object.keys(caps).length > 0) {
42
- out[namespace] = caps;
43
- }
44
- }
45
-
46
- return out;
47
- }
48
-
49
- function mergeCapabilities(left: CapabilityMatrix, right: CapabilityMatrix): CapabilityMatrix {
50
- const next: CapabilityMatrix = { ...left };
51
- for (const [namespace, capabilities] of Object.entries(right)) {
52
- next[namespace] = {
53
- ...(left[namespace] ?? {}),
54
- ...capabilities,
55
- };
56
- }
57
- return next;
58
- }
59
-
60
30
  function extractExtensionPackMeta(
61
31
  component: TargetBoundComponentDescriptor<string, string>,
62
32
  ): Record<string, unknown> {
@@ -93,16 +63,10 @@ export function enrichContract(
93
63
  ir: Contract,
94
64
  components: ReadonlyArray<TargetBoundComponentDescriptor<string, string>>,
95
65
  ): Contract {
96
- let mergedCapabilities = ir.capabilities;
97
- const extensionPacksMeta: Record<string, unknown> = {};
66
+ const mergedCapabilities = mergeCapabilityMatrices(ir.capabilities, components);
98
67
 
68
+ const extensionPacksMeta: Record<string, unknown> = {};
99
69
  for (const component of components) {
100
- if (component.capabilities) {
101
- mergedCapabilities = mergeCapabilities(
102
- mergedCapabilities,
103
- extractCapabilityMatrix(component.capabilities),
104
- );
105
- }
106
70
  if (component.kind === 'extension') {
107
71
  extensionPacksMeta[component.id] = extractExtensionPackMeta(component);
108
72
  }
@@ -5,7 +5,7 @@ import { createControlStack } from '@prisma-next/framework-components/control';
5
5
  import { abortable } from '@prisma-next/utils/abortable';
6
6
  import { ifDefined } from '@prisma-next/utils/defined';
7
7
  import type { JsonObject } from '@prisma-next/utils/json';
8
- import { dirname } from 'pathe';
8
+ import { dirname, join } from 'pathe';
9
9
  import { loadConfig } from '../../config-loader';
10
10
  import { errorContractConfigMissing, errorRuntime } from '../../utils/cli-errors';
11
11
  import { queueEmitByOutput } from '../../utils/emit-queue';
@@ -153,7 +153,7 @@ function validateProviderResult(providerResult: unknown): ValidatedProviderResul
153
153
  export async function executeContractEmit(
154
154
  options: ContractEmitOptions,
155
155
  ): Promise<ContractEmitResult> {
156
- const { configPath, signal = new AbortController().signal, onProgress } = options;
156
+ const { configPath, outputPath, signal = new AbortController().signal, onProgress } = options;
157
157
  const unlessAborted = abortable(signal);
158
158
 
159
159
  const config = await unlessAborted(loadConfig(configPath));
@@ -166,7 +166,10 @@ export async function executeContractEmit(
166
166
 
167
167
  const contractConfig = config.contract;
168
168
 
169
- if (!contractConfig.output) {
169
+ const effectiveOutput =
170
+ outputPath !== undefined ? join(outputPath, 'contract.json') : contractConfig.output;
171
+
172
+ if (!effectiveOutput) {
170
173
  throw errorContractConfigMissing({
171
174
  why: 'Contract config must have output path. This should not happen if defineConfig() was used.',
172
175
  });
@@ -180,7 +183,7 @@ export async function executeContractEmit(
180
183
 
181
184
  let outputPaths: ReturnType<typeof getEmittedArtifactPaths>;
182
185
  try {
183
- outputPaths = getEmittedArtifactPaths(contractConfig.output);
186
+ outputPaths = getEmittedArtifactPaths(effectiveOutput);
184
187
  } catch (error) {
185
188
  throw errorContractConfigMissing({
186
189
  why: error instanceof Error ? error.message : String(error),
@@ -719,6 +719,13 @@ export type MigrationApplyResult = Result<MigrationApplySuccess, MigrationApplyF
719
719
  export interface ContractEmitOptions {
720
720
  /** Path to the prisma-next.config.ts file */
721
721
  readonly configPath: string;
722
+ /**
723
+ * Directory to write contract artifacts into. When set, `contract.json` and
724
+ * `contract.d.ts` are written inside this directory, taking precedence over
725
+ * any output path from the loaded config. The value must be an absolute path;
726
+ * resolution against cwd is the caller's responsibility.
727
+ */
728
+ readonly outputPath?: string;
722
729
  /** Optional AbortSignal for cancelling the in-flight emit */
723
730
  readonly signal?: AbortSignal;
724
731
  /** Optional progress callback for observing source-resolution and emit spans */
@@ -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,229 @@ 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 fromHash = typeof meta['fromHash'] === 'string' ? meta['fromHash'] : null;
256
+ const targetHash =
257
+ typeof meta['targetHash'] === 'string'
258
+ ? meta['targetHash']
259
+ : typeof meta['target'] === 'string'
260
+ ? meta['target']
261
+ : null;
262
+ const deadEnds = meta['deadEnds'];
263
+ const deadEndsSuffix =
264
+ Array.isArray(deadEnds) && deadEnds.length > 0
265
+ ? ` Dead-ends: ${deadEnds.map(String).join(', ')}.`
266
+ : '';
267
+ const planFix = (() => {
268
+ if (fromHash !== null && targetHash !== null) {
269
+ return `Run \`prisma-next migration plan --from ${fromHash} --to ${targetHash}\` to introduce the missing path.`;
270
+ }
271
+ if (targetHash !== null) {
272
+ return `Run \`prisma-next migration plan --to ${targetHash}\` to introduce the missing path.`;
273
+ }
274
+ if (fromHash !== null) {
275
+ return `Run \`prisma-next migration plan --from ${fromHash}\` to introduce the missing path.`;
276
+ }
277
+ return 'Run `prisma-next migration plan` to introduce the missing path.';
278
+ })();
279
+ return errorRuntime(failure.summary, {
280
+ why:
281
+ failure.why ??
282
+ `Cannot reach target "${targetHash ?? '<unknown>'}" from current marker "${fromHash ?? '<unknown>'}".${deadEndsSuffix}`,
283
+ fix: [
284
+ 'Run `prisma-next migration list` to see the on-disk graph.',
285
+ planFix,
286
+ 'Run `prisma-next migration show <bundle>` for any bundle in the path you expected.',
287
+ ].join('\n'),
288
+ meta: {
289
+ ...meta,
290
+ code: 'MIGRATION.PATH_UNREACHABLE',
291
+ },
292
+ });
293
+ }
294
+
71
295
  /**
72
296
  * Maps a `MigrationToolsError` raised by the migration-tools loader/graph
73
297
  * surface (`readMigrationPackage`, `readMigrationsDir`, `readRefs`,
@@ -0,0 +1,171 @@
1
+ import type {
2
+ MigrationListEntry,
3
+ MigrationListResult,
4
+ } from '@prisma-next/migration-tools/migration-list-types';
5
+
6
+ export type {
7
+ MigrationListEntry,
8
+ MigrationListResult,
9
+ MigrationSpaceListEntry,
10
+ } from '@prisma-next/migration-tools/migration-list-types';
11
+
12
+ const HASH_WIDTH = 7;
13
+ const EMPTY_SOURCE = '∅';
14
+ const SELF_EDGE_GLYPH = '⟲';
15
+ const FORWARD_EDGE_GLYPH = '→';
16
+ const DECORATION_PREFIX = ' ';
17
+
18
+ /**
19
+ * Semantic styler for `migration list` output tokens. Token-typed so
20
+ * the renderer composes presentation-neutral fragments and the styler
21
+ * decides how each token kind is decorated (ANSI codes, plain text,
22
+ * etc.). The renderer pads with raw spaces *outside* styled tokens so
23
+ * visible column widths stay stable regardless of what the styler
24
+ * emits — adding ANSI escape sequences never disturbs alignment.
25
+ *
26
+ * `invariants` and `refs` receive the underlying string arrays rather
27
+ * than a pre-joined string so per-element styling (e.g. distinguishing
28
+ * the live-DB `db` marker from user-named refs) is possible without
29
+ * having to re-parse a joined block.
30
+ */
31
+ export interface MigrationListStyler {
32
+ dirName(text: string): string;
33
+ sourceHash(text: string): string;
34
+ destHash(text: string): string;
35
+ glyph(text: string): string;
36
+ invariants(ids: readonly string[]): string;
37
+ refs(names: readonly string[]): string;
38
+ spaceHeading(text: string): string;
39
+ summary(text: string): string;
40
+ emptyState(text: string): string;
41
+ }
42
+
43
+ export const IDENTITY_MIGRATION_LIST_STYLER: MigrationListStyler = {
44
+ dirName: (text) => text,
45
+ sourceHash: (text) => text,
46
+ destHash: (text) => text,
47
+ glyph: (text) => text,
48
+ invariants: (ids) => `{${ids.join(', ')}}`,
49
+ refs: (names) => `(${names.join(', ')})`,
50
+ spaceHeading: (text) => text,
51
+ summary: (text) => text,
52
+ emptyState: (text) => text,
53
+ };
54
+
55
+ function abbreviateContractHash(hash: string): string {
56
+ const stripped = hash.startsWith('sha256:') ? hash.slice(7) : hash;
57
+ return stripped.slice(0, HASH_WIDTH);
58
+ }
59
+
60
+ function formatSourceColumn(from: string | null, style: MigrationListStyler): string {
61
+ if (from === null) {
62
+ return style.glyph(EMPTY_SOURCE) + ' '.repeat(HASH_WIDTH - EMPTY_SOURCE.length);
63
+ }
64
+ return style.sourceHash(abbreviateContractHash(from));
65
+ }
66
+
67
+ function formatDestColumn(from: string | null, to: string, style: MigrationListStyler): string {
68
+ if (from !== null && from === to) {
69
+ return ' '.repeat(HASH_WIDTH);
70
+ }
71
+ return style.destHash(abbreviateContractHash(to));
72
+ }
73
+
74
+ function formatArrowGlyph(from: string | null, to: string, style: MigrationListStyler): string {
75
+ return style.glyph(from !== null && from === to ? SELF_EDGE_GLYPH : FORWARD_EDGE_GLYPH);
76
+ }
77
+
78
+ function formatDecorations(
79
+ providedInvariants: readonly string[],
80
+ refs: readonly string[],
81
+ style: MigrationListStyler,
82
+ ): string {
83
+ const blocks: string[] = [];
84
+ if (providedInvariants.length > 0) {
85
+ blocks.push(style.invariants(providedInvariants));
86
+ }
87
+ if (refs.length > 0) {
88
+ blocks.push(style.refs(refs));
89
+ }
90
+ if (blocks.length === 0) return '';
91
+ return `${DECORATION_PREFIX}${blocks.join(' ')}`;
92
+ }
93
+
94
+ function formatMigrationRow(
95
+ migration: MigrationListEntry,
96
+ dirNameWidth: number,
97
+ style: MigrationListStyler,
98
+ ): string {
99
+ const dirNamePadding = ' '.repeat(Math.max(0, dirNameWidth - migration.dirName.length));
100
+ const dirName = `${style.dirName(migration.dirName)}${dirNamePadding}`;
101
+ const source = formatSourceColumn(migration.from, style);
102
+ const arrow = formatArrowGlyph(migration.from, migration.to, style);
103
+ const dest = formatDestColumn(migration.from, migration.to, style);
104
+ const decorations = formatDecorations(migration.providedInvariants, migration.refs, style);
105
+ return `${dirName}${source} ${arrow} ${dest}${decorations}`;
106
+ }
107
+
108
+ function formatEmptyStateLine(spaceId: string, style: MigrationListStyler): string {
109
+ return style.emptyState(`There are no migrations in migrations/${spaceId}/ yet`);
110
+ }
111
+
112
+ function renderSpaceBlock(
113
+ spaceId: string,
114
+ migrations: readonly MigrationListEntry[],
115
+ multiSpace: boolean,
116
+ style: MigrationListStyler,
117
+ ): readonly string[] {
118
+ if (migrations.length === 0) {
119
+ const emptyLine = formatEmptyStateLine(spaceId, style);
120
+ if (!multiSpace) {
121
+ return [emptyLine];
122
+ }
123
+ return [style.spaceHeading(`${spaceId}:`), ` ${emptyLine}`];
124
+ }
125
+
126
+ const dirNameWidth = Math.max(...migrations.map((entry) => entry.dirName.length)) + 2;
127
+ const rows = migrations.map((entry) => formatMigrationRow(entry, dirNameWidth, style));
128
+ if (!multiSpace) {
129
+ return rows;
130
+ }
131
+ return [style.spaceHeading(`${spaceId}:`), ...rows.map((row) => ` ${row}`)];
132
+ }
133
+
134
+ /**
135
+ * Compose the styled `migration list` output. The renderer is
136
+ * presentation-neutral — every token passes through `style` before
137
+ * landing in the output, so the same composition serves the pure-text
138
+ * path ({@link renderMigrationList} via
139
+ * {@link IDENTITY_MIGRATION_LIST_STYLER}) and the ANSI-styled CLI path
140
+ * (via the ANSI styler the CLI shell wires up).
141
+ */
142
+ export function renderMigrationListWithStyle(
143
+ result: MigrationListResult,
144
+ style: MigrationListStyler,
145
+ ): string {
146
+ const multiSpace = result.spaces.length > 1;
147
+ const lines: string[] = [];
148
+
149
+ for (let index = 0; index < result.spaces.length; index++) {
150
+ const space = result.spaces[index]!;
151
+ if (index > 0) {
152
+ lines.push('');
153
+ }
154
+ lines.push(...renderSpaceBlock(space.spaceId, space.migrations, multiSpace, style));
155
+ }
156
+
157
+ const totalMigrations = result.spaces.reduce(
158
+ (count, space) => count + space.migrations.length,
159
+ 0,
160
+ );
161
+ if (totalMigrations > 0) {
162
+ lines.push('');
163
+ lines.push(style.summary(result.summary));
164
+ }
165
+
166
+ return lines.join('\n');
167
+ }
168
+
169
+ export function renderMigrationList(result: MigrationListResult): string {
170
+ return renderMigrationListWithStyle(result, IDENTITY_MIGRATION_LIST_STYLER);
171
+ }
@@ -0,0 +1,56 @@
1
+ import { bold, cyan, cyanBright, dim, green, greenBright, yellow } from 'colorette';
2
+ import { IDENTITY_MIGRATION_LIST_STYLER, type MigrationListStyler } from './migration-list-render';
3
+
4
+ /**
5
+ * The reserved ref name for the live-database marker. Treated as a
6
+ * structurally distinct token from user-named refs so the styler can
7
+ * make it visually pop in `(refs)` decorations.
8
+ */
9
+ const DB_REF_NAME = 'db';
10
+
11
+ function styleRefName(name: string): string {
12
+ return name === DB_REF_NAME ? bold(greenBright(name)) : green(name);
13
+ }
14
+
15
+ /**
16
+ * Build a {@link MigrationListStyler} that decorates `migration list`
17
+ * tokens with ANSI SGR codes. When `useColor` is `false` (non-TTY,
18
+ * `--no-color`, `NO_COLOR=1`, piped output) the function returns the
19
+ * shared identity styler so callers get plain text with zero ANSI
20
+ * bytes — pipe-friendly by construction.
21
+ *
22
+ * Palette:
23
+ *
24
+ * - `dirName`: bold
25
+ * - `sourceHash`: dim cyan
26
+ * - `destHash`: bright cyan
27
+ * - `glyph` (`→` / `⟲` / `∅`): dim
28
+ * - `invariants` (`{...}`): yellow
29
+ * - `refs` (`(...)`): green; the live-DB `db` marker inside is green-bold
30
+ * - `spaceHeading` (`<spaceId>:`): bold
31
+ * - `summary`: dim
32
+ * - `emptyState`: dim
33
+ */
34
+ export function createAnsiMigrationListStyler(opts: {
35
+ readonly useColor: boolean;
36
+ }): MigrationListStyler {
37
+ if (!opts.useColor) {
38
+ return IDENTITY_MIGRATION_LIST_STYLER;
39
+ }
40
+ return {
41
+ dirName: (text) => bold(text),
42
+ sourceHash: (text) => dim(cyan(text)),
43
+ destHash: (text) => cyanBright(text),
44
+ glyph: (text) => dim(text),
45
+ invariants: (ids) => yellow(`{${ids.join(', ')}}`),
46
+ refs: (names) => {
47
+ const open = green('(');
48
+ const close = green(')');
49
+ const separator = green(', ');
50
+ return open + names.map(styleRefName).join(separator) + close;
51
+ },
52
+ spaceHeading: (text) => bold(text),
53
+ summary: (text) => dim(text),
54
+ emptyState: (text) => dim(text),
55
+ };
56
+ }