@prisma-next/cli 0.10.0 → 0.11.0-dev.10

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 (166) hide show
  1. package/README.md +1 -1
  2. package/dist/cli-errors-Bw2GlweY.mjs +175 -0
  3. package/dist/cli-errors-Bw2GlweY.mjs.map +1 -0
  4. package/dist/cli.mjs +400 -13
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/{client-Brv4qlfB.mjs → client-UnIveZxZ.mjs} +6 -5
  7. package/dist/client-UnIveZxZ.mjs.map +1 -0
  8. package/dist/{command-helpers-D3vL5yi8.mjs → command-helpers-CRfjbZRz.mjs} +109 -12
  9. package/dist/command-helpers-CRfjbZRz.mjs.map +1 -0
  10. package/dist/commands/contract-emit.d.mts.map +1 -1
  11. package/dist/commands/contract-emit.mjs +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 +47 -21
  15. package/dist/commands/db-init.mjs.map +1 -1
  16. package/dist/commands/db-schema.mjs +6 -10
  17. package/dist/commands/db-schema.mjs.map +1 -1
  18. package/dist/commands/db-sign.mjs +8 -12
  19. package/dist/commands/db-sign.mjs.map +1 -1
  20. package/dist/commands/db-update.d.mts.map +1 -1
  21. package/dist/commands/db-update.mjs +47 -19
  22. package/dist/commands/db-update.mjs.map +1 -1
  23. package/dist/commands/db-verify.mjs +1 -1
  24. package/dist/commands/migrate.d.mts +5 -1
  25. package/dist/commands/migrate.d.mts.map +1 -1
  26. package/dist/commands/migrate.mjs +47 -15
  27. package/dist/commands/migrate.mjs.map +1 -1
  28. package/dist/commands/migration-check.mjs +5 -8
  29. package/dist/commands/migration-check.mjs.map +1 -1
  30. package/dist/commands/migration-graph.d.mts +1 -1
  31. package/dist/commands/migration-graph.mjs +6 -10
  32. package/dist/commands/migration-graph.mjs.map +1 -1
  33. package/dist/commands/migration-list.mjs +5 -9
  34. package/dist/commands/migration-list.mjs.map +1 -1
  35. package/dist/commands/migration-log.d.mts.map +1 -1
  36. package/dist/commands/migration-log.mjs +7 -10
  37. package/dist/commands/migration-log.mjs.map +1 -1
  38. package/dist/commands/migration-new.mjs +6 -10
  39. package/dist/commands/migration-new.mjs.map +1 -1
  40. package/dist/commands/migration-plan.d.mts +2 -1
  41. package/dist/commands/migration-plan.d.mts.map +1 -1
  42. package/dist/commands/migration-plan.mjs +1 -1
  43. package/dist/commands/migration-show.d.mts +1 -1
  44. package/dist/commands/migration-show.mjs +9 -13
  45. package/dist/commands/migration-show.mjs.map +1 -1
  46. package/dist/commands/migration-status.d.mts +1 -1
  47. package/dist/commands/migration-status.d.mts.map +1 -1
  48. package/dist/commands/migration-status.mjs +37 -15
  49. package/dist/commands/migration-status.mjs.map +1 -1
  50. package/dist/commands/ref.d.mts +1 -1
  51. package/dist/commands/ref.d.mts.map +1 -1
  52. package/dist/commands/ref.mjs +41 -25
  53. package/dist/commands/ref.mjs.map +1 -1
  54. package/dist/{contract-emit-iynA3BCA.mjs → contract-emit-C6rlsljO.mjs} +7 -6
  55. package/dist/contract-emit-C6rlsljO.mjs.map +1 -0
  56. package/dist/{contract-emit-C3STUIBg.mjs → contract-emit-mqXmapxB.mjs} +22 -20
  57. package/dist/contract-emit-mqXmapxB.mjs.map +1 -0
  58. package/dist/{contract-infer-Cnj8G1E2.mjs → contract-infer-C4jxc1aZ.mjs} +9 -14
  59. package/dist/contract-infer-C4jxc1aZ.mjs.map +1 -0
  60. package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs → contract-space-aggregate-loader-CGakRlKM.mjs} +2 -2
  61. package/dist/{contract-space-aggregate-loader-pAc8CDfY.mjs.map → contract-space-aggregate-loader-CGakRlKM.mjs.map} +1 -1
  62. package/dist/{db-verify-D7cyH_zz.mjs → db-verify-1d8tDoFN.mjs} +9 -13
  63. package/dist/db-verify-1d8tDoFN.mjs.map +1 -0
  64. package/dist/exports/control-api.d.mts +1 -1
  65. package/dist/exports/control-api.mjs +2 -2
  66. package/dist/exports/index.mjs +2 -2
  67. package/dist/exports/init-output.mjs +1 -1
  68. package/dist/{framework-components-xFLFpZUO.mjs → framework-components-Bexd0f4E.mjs} +2 -2
  69. package/dist/{framework-components-xFLFpZUO.mjs.map → framework-components-Bexd0f4E.mjs.map} +1 -1
  70. package/dist/{global-flags-DGmw6Kqg.d.mts → global-flags-CdE7M0d9.d.mts} +4 -1
  71. package/dist/global-flags-CdE7M0d9.d.mts.map +1 -0
  72. package/dist/{graph-render-eJDcLWny.mjs → graph-render-BE8vmJ_7.mjs} +1 -1
  73. package/dist/{graph-render-eJDcLWny.mjs.map → graph-render-BE8vmJ_7.mjs.map} +1 -1
  74. package/dist/{init-eh2z5Tl6.mjs → init-ByoeQphC.mjs} +528 -627
  75. package/dist/init-ByoeQphC.mjs.map +1 -0
  76. package/dist/{inspect-live-schema-CWLK_lgs.mjs → inspect-live-schema-B1Q49RF0.mjs} +4 -4
  77. package/dist/{inspect-live-schema-CWLK_lgs.mjs.map → inspect-live-schema-B1Q49RF0.mjs.map} +1 -1
  78. package/dist/{migration-command-scaffold-CmXXC1UZ.mjs → migration-command-scaffold-oY4P1Qto.mjs} +4 -4
  79. package/dist/{migration-command-scaffold-CmXXC1UZ.mjs.map → migration-command-scaffold-oY4P1Qto.mjs.map} +1 -1
  80. package/dist/{migration-plan-CHyUlBV0.mjs → migration-plan-jdAHg_gK.mjs} +349 -94
  81. package/dist/migration-plan-jdAHg_gK.mjs.map +1 -0
  82. package/dist/{migration-types-D2FW63pr.d.mts → migration-types-BXWvz12q.d.mts} +1 -1
  83. package/dist/{migration-types-D2FW63pr.d.mts.map → migration-types-BXWvz12q.d.mts.map} +1 -1
  84. package/dist/{migrations-DyUf5lTt.mjs → migrations-B7n518mT.mjs} +11 -2
  85. package/dist/migrations-B7n518mT.mjs.map +1 -0
  86. package/dist/{output-B60Gw5fu.mjs → output-CUIdfYo5.mjs} +1 -1
  87. package/dist/{output-B60Gw5fu.mjs.map → output-CUIdfYo5.mjs.map} +1 -1
  88. package/dist/quick-reference-mongo.md +1 -1
  89. package/dist/quick-reference-postgres.md +1 -1
  90. package/dist/readme-mongo.md +35 -0
  91. package/dist/readme-postgres.md +34 -0
  92. package/dist/ref-advancement-DRh5Nquq.mjs +50 -0
  93. package/dist/ref-advancement-DRh5Nquq.mjs.map +1 -0
  94. package/dist/{terminal-ui-XtOQsqe9.mjs → terminal-ui-BiB_8KNo.mjs} +131 -24
  95. package/dist/terminal-ui-BiB_8KNo.mjs.map +1 -0
  96. package/dist/{types-0aS865QN.d.mts → types-UWB2-rrw.d.mts} +12 -4
  97. package/dist/types-UWB2-rrw.d.mts.map +1 -0
  98. package/dist/{verify-D7ypCCe6.mjs → verify-C5UvbrF1.mjs} +2 -2
  99. package/dist/{verify-D7ypCCe6.mjs.map → verify-C5UvbrF1.mjs.map} +1 -1
  100. package/package.json +20 -18
  101. package/src/cli.ts +42 -0
  102. package/src/commands/contract-emit.ts +23 -11
  103. package/src/commands/contract-infer.ts +7 -7
  104. package/src/commands/db-init.ts +61 -7
  105. package/src/commands/db-schema.ts +4 -4
  106. package/src/commands/db-sign.ts +4 -4
  107. package/src/commands/db-update.ts +58 -5
  108. package/src/commands/db-verify.ts +5 -5
  109. package/src/commands/init/detect-package-manager.ts +15 -0
  110. package/src/commands/init/errors.ts +33 -2
  111. package/src/commands/init/hygiene-gitattributes.ts +2 -2
  112. package/src/commands/init/index.ts +15 -6
  113. package/src/commands/init/init.ts +61 -32
  114. package/src/commands/init/inputs.ts +82 -5
  115. package/src/commands/init/output.ts +1 -1
  116. package/src/commands/init/{agent-skill-install.ts → skill-install.ts} +42 -31
  117. package/src/commands/init/templates/code-templates.ts +26 -24
  118. package/src/commands/init/templates/env.ts +8 -1
  119. package/src/commands/init/templates/quick-reference-mongo.md +1 -1
  120. package/src/commands/init/templates/quick-reference-postgres.md +1 -1
  121. package/src/commands/init/templates/readme-mongo.md +35 -0
  122. package/src/commands/init/templates/readme-postgres.md +34 -0
  123. package/src/commands/init/templates/readme.ts +62 -0
  124. package/src/commands/migrate.ts +77 -10
  125. package/src/commands/migration-check.ts +4 -4
  126. package/src/commands/migration-graph.ts +4 -4
  127. package/src/commands/migration-list.ts +4 -4
  128. package/src/commands/migration-log.ts +6 -5
  129. package/src/commands/migration-new.ts +4 -4
  130. package/src/commands/migration-plan.ts +369 -132
  131. package/src/commands/migration-show.ts +4 -4
  132. package/src/commands/migration-status.ts +49 -6
  133. package/src/commands/ref.ts +54 -14
  134. package/src/control-api/operations/apply-aggregate.ts +1 -0
  135. package/src/control-api/operations/contract-emit.ts +7 -4
  136. package/src/control-api/types.ts +7 -0
  137. package/src/utils/cli-errors.ts +177 -0
  138. package/src/utils/command-helpers.ts +14 -6
  139. package/src/utils/formatters/migrations.ts +25 -0
  140. package/src/utils/global-flags.ts +105 -16
  141. package/src/utils/is-ci.ts +18 -0
  142. package/src/utils/plan-resolution.ts +257 -0
  143. package/src/utils/ref-advancement.ts +68 -0
  144. package/src/utils/telemetry.ts +141 -0
  145. package/src/utils/terminal-ui.ts +44 -23
  146. package/dist/cli-errors-CF60g2cG.mjs +0 -71
  147. package/dist/cli-errors-CF60g2cG.mjs.map +0 -1
  148. package/dist/cli-errors-DdcjVLJV.d.mts +0 -3
  149. package/dist/client-Brv4qlfB.mjs.map +0 -1
  150. package/dist/command-helpers-D3vL5yi8.mjs.map +0 -1
  151. package/dist/contract-emit-C3STUIBg.mjs.map +0 -1
  152. package/dist/contract-emit-iynA3BCA.mjs.map +0 -1
  153. package/dist/contract-infer-Cnj8G1E2.mjs.map +0 -1
  154. package/dist/db-verify-D7cyH_zz.mjs.map +0 -1
  155. package/dist/errors-Cw6kyTyV.mjs +0 -56
  156. package/dist/errors-Cw6kyTyV.mjs.map +0 -1
  157. package/dist/global-flags-DGmw6Kqg.d.mts.map +0 -1
  158. package/dist/helpers-eqdN8tH6.mjs +0 -25
  159. package/dist/helpers-eqdN8tH6.mjs.map +0 -1
  160. package/dist/init-eh2z5Tl6.mjs.map +0 -1
  161. package/dist/migration-plan-CHyUlBV0.mjs.map +0 -1
  162. package/dist/migrations-DyUf5lTt.mjs.map +0 -1
  163. package/dist/result-handler-Bm_6dDYg.mjs +0 -25
  164. package/dist/result-handler-Bm_6dDYg.mjs.map +0 -1
  165. package/dist/terminal-ui-XtOQsqe9.mjs.map +0 -1
  166. package/dist/types-0aS865QN.d.mts.map +0 -1
@@ -1,7 +1,17 @@
1
+ import { notOk } from '@prisma-next/utils/result';
2
+ import { CliStructuredError, errorInvalidOutputFormat, errorOutputFormatMutex } from './cli-errors';
3
+ import { isCI } from './is-ci';
4
+ import { handleResult } from './result-handler';
5
+ import { createTerminalUI } from './terminal-ui';
6
+
7
+ export type OutputFormat = 'pretty' | 'json';
8
+
1
9
  export interface GlobalFlags {
10
+ readonly format: OutputFormat;
11
+ readonly explicitFormat: boolean;
2
12
  readonly json?: boolean;
3
13
  readonly quiet?: boolean;
4
- readonly verbose?: number; // 0, 1, or 2
14
+ readonly verbose?: number;
5
15
  readonly color?: boolean;
6
16
  readonly interactive?: boolean;
7
17
  readonly yes?: boolean;
@@ -12,6 +22,7 @@ export interface GlobalFlags {
12
22
  * Extend this for command-specific options instead of duplicating these fields.
13
23
  */
14
24
  export interface CommonCommandOptions {
25
+ readonly format?: string;
15
26
  readonly json?: string | boolean;
16
27
  readonly quiet?: boolean;
17
28
  readonly q?: boolean;
@@ -26,33 +37,117 @@ export interface CommonCommandOptions {
26
37
  readonly y?: boolean;
27
38
  }
28
39
 
40
+ function isJsonFlagSet(json: string | boolean | undefined): boolean {
41
+ return json === true;
42
+ }
43
+
44
+ interface ResolvedOutputFormat {
45
+ readonly format: OutputFormat;
46
+ readonly explicitFormat: boolean;
47
+ }
48
+
49
+ function resolveOutputFormat(options: CommonCommandOptions): ResolvedOutputFormat {
50
+ const formatOption = options.format;
51
+ const jsonFlag = isJsonFlagSet(options.json);
52
+
53
+ if (formatOption !== undefined) {
54
+ if (formatOption !== 'pretty' && formatOption !== 'json') {
55
+ throw errorInvalidOutputFormat(formatOption);
56
+ }
57
+ if (jsonFlag && formatOption === 'pretty') {
58
+ throw errorOutputFormatMutex();
59
+ }
60
+ return { format: formatOption, explicitFormat: true };
61
+ }
62
+
63
+ if (jsonFlag) {
64
+ return { format: 'json', explicitFormat: false };
65
+ }
66
+
67
+ if (!process.stdout.isTTY) {
68
+ return { format: 'json', explicitFormat: false };
69
+ }
70
+
71
+ return { format: 'pretty', explicitFormat: false };
72
+ }
73
+
74
+ function inferJsonModeForParseError(options: CommonCommandOptions): boolean {
75
+ if (options.format === 'json') {
76
+ return true;
77
+ }
78
+ if (isJsonFlagSet(options.json) && options.format !== 'pretty') {
79
+ return true;
80
+ }
81
+ if (options.format !== undefined) {
82
+ return false;
83
+ }
84
+ return !process.stdout.isTTY;
85
+ }
86
+
87
+ function emitGlobalFlagParseError(error: CliStructuredError, options: CommonCommandOptions): never {
88
+ const jsonMode = inferJsonModeForParseError(options);
89
+ const flags: GlobalFlags = {
90
+ format: jsonMode ? 'json' : 'pretty',
91
+ explicitFormat: false,
92
+ ...(jsonMode ? { json: true } : {}),
93
+ color: false,
94
+ verbose: 0,
95
+ interactive: false,
96
+ };
97
+ const ui = createTerminalUI(flags);
98
+ const exitCode = handleResult(notOk(error), flags, ui);
99
+ process.exit(exitCode);
100
+ }
101
+
102
+ /**
103
+ * Parses global flags from CLI options.
104
+ * Handles verbosity flags (-v, --trace), output format (--format, --json),
105
+ * quiet mode, color, interactivity (--interactive/--no-interactive), and
106
+ * auto-accept (-y/--yes).
107
+ *
108
+ * On invalid or conflicting format flags, prints a structured CLI error
109
+ * envelope and exits with code 2.
110
+ */
111
+ export function parseGlobalFlagsOrExit(options: CommonCommandOptions): GlobalFlags {
112
+ try {
113
+ return parseGlobalFlags(options);
114
+ } catch (error) {
115
+ if (CliStructuredError.is(error)) {
116
+ emitGlobalFlagParseError(error, options);
117
+ }
118
+ throw error;
119
+ }
120
+ }
121
+
29
122
  /**
30
123
  * Parses global flags from CLI options.
31
- * Handles verbosity flags (-v, --trace), JSON output, quiet mode, color,
32
- * interactivity (--interactive/--no-interactive), and auto-accept (-y/--yes).
124
+ * Handles verbosity flags (-v, --trace), output format (--format, --json),
125
+ * quiet mode, color, interactivity (--interactive/--no-interactive), and
126
+ * auto-accept (-y/--yes).
127
+ *
128
+ * Throws {@link CliStructuredError} for invalid or conflicting format flags.
33
129
  */
34
130
  export function parseGlobalFlags(options: CommonCommandOptions): GlobalFlags {
131
+ const { format, explicitFormat } = resolveOutputFormat(options);
35
132
  const flags: {
133
+ format: OutputFormat;
134
+ explicitFormat: boolean;
36
135
  json?: boolean;
37
136
  quiet?: boolean;
38
137
  verbose?: number;
39
138
  color?: boolean;
40
139
  interactive?: boolean;
41
140
  yes?: boolean;
42
- } = {};
141
+ } = { format, explicitFormat };
43
142
 
44
- // JSON output: explicit --json flag or auto-detect piped stdout (Unix convention)
45
- if (options.json || !process.stdout.isTTY) {
143
+ if (format === 'json') {
46
144
  flags.json = true;
47
145
  }
48
146
 
49
- // Quiet mode
50
147
  if (options.quiet || options.q) {
51
148
  flags.quiet = true;
52
149
  }
53
150
 
54
- // Verbosity: -v = 1, --trace = 2
55
- // Env toggles: PRISMA_NEXT_TRACE=1 ≅ --trace, PRISMA_NEXT_DEBUG=1 ≅ -v
56
151
  if (options.trace || process.env['PRISMA_NEXT_TRACE'] === '1') {
57
152
  flags.verbose = 2;
58
153
  } else if (options.verbose || options.v || process.env['PRISMA_NEXT_DEBUG'] === '1') {
@@ -61,8 +156,6 @@ export function parseGlobalFlags(options: CommonCommandOptions): GlobalFlags {
61
156
  flags.verbose = 0;
62
157
  }
63
158
 
64
- // Color: respect NO_COLOR env var, --color/--no-color flags
65
- // When JSON output is enabled, disable color to ensure clean JSON output
66
159
  if (process.env['NO_COLOR'] || flags.json) {
67
160
  flags.color = false;
68
161
  } else if (options['no-color']) {
@@ -70,12 +163,9 @@ export function parseGlobalFlags(options: CommonCommandOptions): GlobalFlags {
70
163
  } else if (options.color !== undefined) {
71
164
  flags.color = options.color;
72
165
  } else {
73
- // Default: enable color if TTY
74
- flags.color = process.stdout.isTTY && !process.env['CI'];
166
+ flags.color = process.stdout.isTTY && !isCI();
75
167
  }
76
168
 
77
- // Interactivity: --interactive/--no-interactive
78
- // Default: interactive when stdout is a TTY
79
169
  if (options['no-interactive']) {
80
170
  flags.interactive = false;
81
171
  } else if (options.interactive !== undefined) {
@@ -84,7 +174,6 @@ export function parseGlobalFlags(options: CommonCommandOptions): GlobalFlags {
84
174
  flags.interactive = !!process.stdout.isTTY;
85
175
  }
86
176
 
87
- // Auto-accept prompts: -y/--yes
88
177
  if (options.yes || options.y) {
89
178
  flags.yes = true;
90
179
  }
@@ -0,0 +1,18 @@
1
+ import { isCI as ciInfoIsCI } from 'ci-info';
2
+
3
+ /**
4
+ * Returns true when the process is running in any CI environment recognised
5
+ * by the `ci-info` package. The single source of truth for CI detection
6
+ * across this CLI — colour-output suppression and telemetry-skip both call
7
+ * this helper, so neither path drifts from the other when a new CI provider
8
+ * is added upstream.
9
+ *
10
+ * `ci-info` checks the standard `CI=true` marker plus dozens of
11
+ * provider-specific environment variables (Buildkite, Jenkins, Drone,
12
+ * Bitbucket Pipelines, Azure Pipelines, AWS CodeBuild, …) that the raw
13
+ * `process.env.CI` read misses.
14
+ *
15
+ */
16
+ export function isCI(): boolean {
17
+ return ciInfoIsCI;
18
+ }
@@ -0,0 +1,257 @@
1
+ import type { Contract } from '@prisma-next/contract/types';
2
+ import type { ControlFamilyInstance } from '@prisma-next/framework-components/control';
3
+ import { MigrationToolsError } from '@prisma-next/migration-tools/errors';
4
+ import type { MigrationGraph } from '@prisma-next/migration-tools/graph';
5
+ import {
6
+ assertHashIsGraphNode,
7
+ findLatestMigration,
8
+ isGraphNode,
9
+ } from '@prisma-next/migration-tools/migration-graph';
10
+ import type { OnDiskMigrationPackage } from '@prisma-next/migration-tools/package';
11
+ import { parseContractRef } from '@prisma-next/migration-tools/ref-resolution';
12
+ import type { Refs } from '@prisma-next/migration-tools/refs';
13
+ import { readRefSnapshot, readRefs } from '@prisma-next/migration-tools/refs';
14
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
15
+ import {
16
+ CliStructuredError,
17
+ errorContractValidationFailed,
18
+ errorPlanForgotTheFlag,
19
+ errorSnapshotMissing,
20
+ errorUnexpected,
21
+ mapMigrationToolsError,
22
+ mapRefResolutionError,
23
+ } from './cli-errors';
24
+
25
+ const FULL_HASH_PATTERN = /^sha256:([0-9a-f]{64}|empty)$/;
26
+
27
+ export function looksLikeFullHash(input: string): boolean {
28
+ return FULL_HASH_PATTERN.test(input);
29
+ }
30
+
31
+ export type FromResolution =
32
+ | { kind: 'greenfield'; fromHash: null; fromContract: null }
33
+ | { kind: 'graph-node'; fromHash: string; fromContract: Contract; sourceDir: string }
34
+ | {
35
+ kind: 'snapshot';
36
+ fromHash: string;
37
+ fromContract: Contract;
38
+ contractDts: string;
39
+ contractJson: unknown;
40
+ }
41
+ | {
42
+ kind: 'auto-baseline';
43
+ fromHash: string;
44
+ fromContract: Contract;
45
+ contractDts: string;
46
+ contractJson: unknown;
47
+ };
48
+
49
+ export interface ResolveFromForPlanInput {
50
+ readonly optionsFrom?: string | undefined;
51
+ readonly refsDir: string;
52
+ readonly bundles: readonly OnDiskMigrationPackage[];
53
+ readonly graph: MigrationGraph;
54
+ readonly familyInstance: ControlFamilyInstance<string, unknown>;
55
+ readonly readBundleEndContract: (migrationDir: string) => Promise<Contract>;
56
+ }
57
+
58
+ function graphIsEmpty(bundles: readonly OnDiskMigrationPackage[]): boolean {
59
+ return bundles.length === 0;
60
+ }
61
+
62
+ function getReachableRefs(
63
+ refs: Refs,
64
+ graph: MigrationGraph,
65
+ ): ReadonlyArray<{ name: string; hash: string }> {
66
+ return Object.entries(refs)
67
+ .flatMap(([name, entry]) =>
68
+ entry && isGraphNode(entry.hash, graph) ? [{ name, hash: entry.hash }] : [],
69
+ )
70
+ .sort((a, b) => a.name.localeCompare(b.name));
71
+ }
72
+
73
+ export function assertFromIsGraphNode(
74
+ fromHash: string,
75
+ graph: MigrationGraph,
76
+ refs: Refs,
77
+ graphTipHash: string | null,
78
+ ): void {
79
+ try {
80
+ assertHashIsGraphNode(fromHash, graph);
81
+ } catch (error) {
82
+ if (MigrationToolsError.is(error) && error.code === 'MIGRATION.HASH_NOT_IN_GRAPH') {
83
+ throw errorPlanForgotTheFlag(fromHash, getReachableRefs(refs, graph), graphTipHash);
84
+ }
85
+ throw error;
86
+ }
87
+ }
88
+
89
+ async function deserializeSnapshotContract(
90
+ familyInstance: ControlFamilyInstance<string, unknown>,
91
+ contract: unknown,
92
+ ): Promise<Result<Contract, CliStructuredError>> {
93
+ try {
94
+ return ok(familyInstance.deserializeContract(contract));
95
+ } catch (error) {
96
+ if (CliStructuredError.is(error)) {
97
+ return notOk(error);
98
+ }
99
+ return notOk(
100
+ errorContractValidationFailed(
101
+ `Ref snapshot contract failed to deserialize: ${error instanceof Error ? error.message : String(error)}`,
102
+ { where: { path: 'ref-snapshot' } },
103
+ ),
104
+ );
105
+ }
106
+ }
107
+
108
+ async function resolveGraphNodeFromBundle(
109
+ fromHash: string,
110
+ bundles: readonly OnDiskMigrationPackage[],
111
+ readBundleEndContract: (migrationDir: string) => Promise<Contract>,
112
+ explicitFromLabel?: string,
113
+ ): Promise<Result<Extract<FromResolution, { kind: 'graph-node' }>, CliStructuredError>> {
114
+ const matchingBundle = bundles.find((pkg) => pkg.metadata.to === fromHash);
115
+ if (!matchingBundle) {
116
+ return notOk(
117
+ errorUnexpected(
118
+ explicitFromLabel
119
+ ? `No migration bundle found for --from "${explicitFromLabel}" (resolved hash: ${fromHash})`
120
+ : `No migration bundle found for graph node ${fromHash}`,
121
+ {
122
+ why: `The hash ${fromHash} is a graph node but no on-disk migration package has an end-contract hash matching it.`,
123
+ fix: 'Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.',
124
+ },
125
+ ),
126
+ );
127
+ }
128
+ try {
129
+ const fromContract = await readBundleEndContract(matchingBundle.dirPath);
130
+ return ok({
131
+ kind: 'graph-node',
132
+ fromHash,
133
+ fromContract,
134
+ sourceDir: matchingBundle.dirPath,
135
+ });
136
+ } catch (error) {
137
+ if (CliStructuredError.is(error)) {
138
+ return notOk(error);
139
+ }
140
+ throw error;
141
+ }
142
+ }
143
+
144
+ async function resolveFromRefName(
145
+ refName: string,
146
+ fromHash: string,
147
+ input: ResolveFromForPlanInput,
148
+ refs: Refs,
149
+ ): Promise<Result<FromResolution, CliStructuredError>> {
150
+ const { refsDir, bundles, graph, familyInstance, readBundleEndContract } = input;
151
+ const empty = graphIsEmpty(bundles);
152
+ const graphTip = findLatestMigration(graph)?.to ?? null;
153
+
154
+ let snapshot: Awaited<ReturnType<typeof readRefSnapshot>>;
155
+ try {
156
+ snapshot = await readRefSnapshot(refsDir, refName);
157
+ } catch (error) {
158
+ if (MigrationToolsError.is(error)) {
159
+ return notOk(mapMigrationToolsError(error));
160
+ }
161
+ throw error;
162
+ }
163
+
164
+ if (snapshot) {
165
+ const contractResult = await deserializeSnapshotContract(familyInstance, snapshot.contract);
166
+ if (!contractResult.ok) {
167
+ return contractResult;
168
+ }
169
+ const fromContract = contractResult.value;
170
+ const { contractDts, contract: contractJson } = snapshot;
171
+ if (empty) {
172
+ return ok({ kind: 'auto-baseline', fromHash, fromContract, contractDts, contractJson });
173
+ }
174
+ try {
175
+ assertFromIsGraphNode(fromHash, graph, refs, graphTip);
176
+ } catch (error) {
177
+ if (CliStructuredError.is(error)) {
178
+ return notOk(error);
179
+ }
180
+ throw error;
181
+ }
182
+ return ok({ kind: 'snapshot', fromHash, fromContract, contractDts, contractJson });
183
+ }
184
+
185
+ if (isGraphNode(fromHash, graph)) {
186
+ return resolveGraphNodeFromBundle(fromHash, bundles, readBundleEndContract);
187
+ }
188
+
189
+ return notOk(errorSnapshotMissing(refName));
190
+ }
191
+
192
+ async function resolveFromHashProvenance(
193
+ fromHash: string,
194
+ input: ResolveFromForPlanInput,
195
+ _refs: Refs,
196
+ explicitFromLabel?: string,
197
+ ): Promise<Result<FromResolution, CliStructuredError>> {
198
+ const { bundles, graph } = input;
199
+
200
+ if (isGraphNode(fromHash, graph)) {
201
+ return resolveGraphNodeFromBundle(
202
+ fromHash,
203
+ bundles,
204
+ input.readBundleEndContract,
205
+ explicitFromLabel,
206
+ );
207
+ }
208
+
209
+ throw new Error(
210
+ `resolveFromHashProvenance: non-graph-node hash ${fromHash} should be refused via looksLikeFullHash before this helper is called`,
211
+ );
212
+ }
213
+
214
+ export async function resolveFromForPlan(
215
+ input: ResolveFromForPlanInput,
216
+ ): Promise<Result<FromResolution, CliStructuredError>> {
217
+ const { optionsFrom, refsDir, graph } = input;
218
+
219
+ let refs: Refs;
220
+ try {
221
+ refs = await readRefs(refsDir);
222
+ } catch (error) {
223
+ if (MigrationToolsError.is(error)) {
224
+ return notOk(mapMigrationToolsError(error));
225
+ }
226
+ throw error;
227
+ }
228
+
229
+ if (optionsFrom === undefined) {
230
+ const dbRef = refs['db'];
231
+ if (!dbRef) {
232
+ return ok({ kind: 'greenfield', fromHash: null, fromContract: null });
233
+ }
234
+ return resolveFromRefName('db', dbRef.hash, input, refs);
235
+ }
236
+
237
+ const refResult = parseContractRef(optionsFrom, { graph, refs });
238
+ if (!refResult.ok) {
239
+ if (looksLikeFullHash(optionsFrom)) {
240
+ const empty = graphIsEmpty(input.bundles);
241
+ const graphTip = findLatestMigration(graph)?.to ?? null;
242
+ if (empty) {
243
+ return notOk(errorSnapshotMissing(optionsFrom, { viaRef: false }));
244
+ }
245
+ return notOk(errorPlanForgotTheFlag(optionsFrom, getReachableRefs(refs, graph), graphTip));
246
+ }
247
+ return notOk(mapRefResolutionError(refResult.failure));
248
+ }
249
+
250
+ const { hash: fromHash, provenance } = refResult.value;
251
+
252
+ if (provenance.kind === 'ref') {
253
+ return resolveFromRefName(provenance.refName, fromHash, input, refs);
254
+ }
255
+
256
+ return resolveFromHashProvenance(fromHash, input, refs, optionsFrom);
257
+ }
@@ -0,0 +1,68 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import type { ContractIR } from '@prisma-next/migration-tools/refs';
3
+ import { writeRefPaired } from '@prisma-next/migration-tools/refs';
4
+ import { ifDefined } from '@prisma-next/utils/defined';
5
+
6
+ export interface RefAdvancementFields {
7
+ readonly advancedRef: { readonly name: string; readonly hash: string } | null;
8
+ readonly plannedAdvanceRef: { readonly name: string; readonly hash: string } | null;
9
+ }
10
+
11
+ export function computeRefAdvancementName(options: {
12
+ readonly advanceRef?: string;
13
+ readonly db?: string;
14
+ }): string | null {
15
+ if (options.advanceRef !== undefined) {
16
+ return options.advanceRef;
17
+ }
18
+ if (options.db === undefined) {
19
+ return 'db';
20
+ }
21
+ return null;
22
+ }
23
+
24
+ export async function readContractIR(
25
+ contractJson: Record<string, unknown>,
26
+ contractJsonPath: string,
27
+ ): Promise<ContractIR> {
28
+ const contractDtsPath = contractJsonPath.replace(/\.json$/i, '.d.ts');
29
+ const contractDts = await readFile(contractDtsPath, 'utf-8');
30
+ return { contract: contractJson, contractDts };
31
+ }
32
+
33
+ export async function executeRefAdvancement(
34
+ refsDir: string,
35
+ name: string,
36
+ hash: string,
37
+ contractIR: ContractIR,
38
+ ): Promise<{ name: string; hash: string }> {
39
+ await writeRefPaired(refsDir, name, { hash, invariants: [] }, contractIR);
40
+ return { name, hash };
41
+ }
42
+
43
+ export async function buildRefAdvancementFields(options: {
44
+ readonly advanceRef?: string;
45
+ readonly db?: string;
46
+ readonly refsDir: string;
47
+ readonly contractIR: ContractIR;
48
+ readonly mode: 'plan' | 'apply';
49
+ readonly hash: string;
50
+ }): Promise<RefAdvancementFields> {
51
+ const name = computeRefAdvancementName({
52
+ ...ifDefined('advanceRef', options.advanceRef),
53
+ ...ifDefined('db', options.db),
54
+ });
55
+ if (name === null) {
56
+ return { advancedRef: null, plannedAdvanceRef: null };
57
+ }
58
+ if (options.mode === 'plan') {
59
+ return { advancedRef: null, plannedAdvanceRef: { name, hash: options.hash } };
60
+ }
61
+ const advancedRef = await executeRefAdvancement(
62
+ options.refsDir,
63
+ name,
64
+ options.hash,
65
+ options.contractIR,
66
+ );
67
+ return { advancedRef, plannedAdvanceRef: null };
68
+ }
@@ -0,0 +1,141 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import {
3
+ type CommanderOptionShape,
4
+ type CommanderResultShape,
5
+ readUserConfig,
6
+ resolveGating,
7
+ runTelemetry,
8
+ type TelemetryRunOutcome,
9
+ type UserConfig,
10
+ } from '@prisma-next/cli-telemetry';
11
+ import { ifDefined } from '@prisma-next/utils/defined';
12
+ import type { Command } from 'commander';
13
+ import { version as CLI_VERSION } from '../../package.json' with { type: 'json' };
14
+ import { isCI } from './is-ci';
15
+
16
+ type TelemetryGate =
17
+ | { readonly enabled: true; readonly userConfig: UserConfig }
18
+ | { readonly enabled: false; readonly outcome: TelemetryRunOutcome };
19
+
20
+ /**
21
+ * Resolve the commander command path from a leaf `Command`, walking up
22
+ * the parent chain. Result is rooted at the program name and ends at
23
+ * the leaf — `['prisma-next', 'migration', 'new']` for
24
+ * `prisma-next migration new …`.
25
+ */
26
+ function commandPathFor(actionCommand: Command): string[] {
27
+ const path: string[] = [];
28
+ let cursor: Command | null = actionCommand;
29
+ while (cursor !== null) {
30
+ path.unshift(cursor.name());
31
+ cursor = cursor.parent;
32
+ }
33
+ return path;
34
+ }
35
+
36
+ function commanderOptionSnapshots(actionCommand: Command): CommanderOptionShape[] {
37
+ return actionCommand.options.map((option) => {
38
+ const attributeName = option.attributeName();
39
+ return {
40
+ attributeName,
41
+ longName: option.long ?? null,
42
+ source: actionCommand.getOptionValueSource(attributeName) ?? null,
43
+ };
44
+ });
45
+ }
46
+
47
+ /**
48
+ * Project commander's leaf `Command` into the wire-shape snapshot the
49
+ * telemetry sanitiser consumes. Pure projection — no env, no I/O.
50
+ */
51
+ export function commanderSnapshotForTelemetry(actionCommand: Command): CommanderResultShape {
52
+ return {
53
+ commandPath: commandPathFor(actionCommand),
54
+ positionalArgs: actionCommand.args,
55
+ options: commanderOptionSnapshots(actionCommand),
56
+ };
57
+ }
58
+
59
+ function resolveTelemetryGate(): TelemetryGate {
60
+ if (isCI()) {
61
+ return { enabled: false, outcome: { spawned: false, reason: 'ci' } };
62
+ }
63
+ const userConfig = readUserConfig();
64
+ const gating = resolveGating({ env: process.env, config: userConfig });
65
+ if (!gating.enabled) {
66
+ return { enabled: false, outcome: { spawned: false, reason: 'gated-off' } };
67
+ }
68
+ return { enabled: true, userConfig };
69
+ }
70
+
71
+ /**
72
+ * Path to the compiled sender script inside `@prisma-next/cli-telemetry`'s
73
+ * `dist/`. Resolved off this module's `import.meta.url` via the package
74
+ * specifier `@prisma-next/cli-telemetry/sender`, so the consumer pays
75
+ * no attention to internal package layout.
76
+ */
77
+ function senderPath(): string {
78
+ return fileURLToPath(new URL(import.meta.resolve('@prisma-next/cli-telemetry/sender')));
79
+ }
80
+
81
+ function fireTelemetry(
82
+ actionCommand: Command,
83
+ userConfig: UserConfig,
84
+ overrides: { readonly databaseTarget?: string } = {},
85
+ ): TelemetryRunOutcome {
86
+ return runTelemetry({
87
+ command: commanderSnapshotForTelemetry(actionCommand),
88
+ version: CLI_VERSION,
89
+ projectRoot: process.cwd(),
90
+ senderPath: senderPath(),
91
+ isCI: isCI(),
92
+ env: process.env,
93
+ userConfig,
94
+ ...ifDefined('databaseTarget', overrides.databaseTarget),
95
+ });
96
+ }
97
+
98
+ /**
99
+ * preAction-stage entry point. Synchronous by construction: resolve
100
+ * env/CI/user-consent gates (cheap, all in-memory and a single tiny
101
+ * user-config read), then — only when enabled — `fork()` the detached
102
+ * sender script. The forked child loads `prisma-next.config.*` via
103
+ * c12 on its own (see `loadProjectConfig` in cli-telemetry); the
104
+ * parent does no project-config I/O on the command's hot path.
105
+ *
106
+ * Privacy invariant: gate resolution always happens before any project
107
+ * config touches disk. The child loading user TS code is acceptable
108
+ * only because it's gated behind the same resolved-enabled signal.
109
+ */
110
+ export function fireTelemetryFromPreAction(actionCommand: Command): TelemetryRunOutcome {
111
+ const gate = resolveTelemetryGate();
112
+ if (!gate.enabled) {
113
+ return gate.outcome;
114
+ }
115
+ return fireTelemetry(actionCommand, gate.userConfig);
116
+ }
117
+
118
+ /**
119
+ * Manual one-shot telemetry path for the first `init` run where the user
120
+ * explicitly answers Yes to the consent prompt. The preAction hook for
121
+ * that same run has already resolved before consent existed, so it is
122
+ * default-off. After consent is persisted, `runInit` calls this helper
123
+ * exactly for that first affirmative answer; subsequent init runs skip
124
+ * it because the prompt is not shown again.
125
+ *
126
+ * The child's c12 load would return `databaseTarget: null` for this
127
+ * specific invocation because `prisma-next.config.*` is not yet on
128
+ * disk (init writes it later in the same run). To preserve the
129
+ * prompt-chosen target in the first-init telemetry event, this
130
+ * helper forwards the value as a parent-side IPC override on
131
+ * `ParentToSenderPayload.databaseTarget` — the child consults the
132
+ * override first and falls back to its c12 result when absent.
133
+ */
134
+ export function fireTelemetryAfterInitConsent(
135
+ actionCommand: Command,
136
+ inputs: { readonly databaseTarget: string },
137
+ ): TelemetryRunOutcome {
138
+ return fireTelemetry(actionCommand, readUserConfig(), {
139
+ databaseTarget: inputs.databaseTarget,
140
+ });
141
+ }