@prisma-next/cli 0.3.0-dev.6 → 0.3.0-dev.64

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/LICENSE +201 -0
  2. package/README.md +314 -80
  3. package/dist/cli-errors-JlPTsazx.mjs +3 -0
  4. package/dist/cli.d.mts +1 -0
  5. package/dist/cli.js +1 -2376
  6. package/dist/cli.mjs +203 -0
  7. package/dist/cli.mjs.map +1 -0
  8. package/dist/client-PimzSD1f.mjs +981 -0
  9. package/dist/client-PimzSD1f.mjs.map +1 -0
  10. package/dist/commands/contract-emit.d.mts +7 -0
  11. package/dist/commands/contract-emit.d.mts.map +1 -0
  12. package/dist/commands/contract-emit.mjs +151 -0
  13. package/dist/commands/contract-emit.mjs.map +1 -0
  14. package/dist/commands/db-init.d.mts +7 -0
  15. package/dist/commands/db-init.d.mts.map +1 -0
  16. package/dist/commands/db-init.mjs +134 -0
  17. package/dist/commands/db-init.mjs.map +1 -0
  18. package/dist/commands/db-introspect.d.mts +7 -0
  19. package/dist/commands/db-introspect.d.mts.map +1 -0
  20. package/dist/commands/db-introspect.mjs +118 -0
  21. package/dist/commands/db-introspect.mjs.map +1 -0
  22. package/dist/commands/db-schema-verify.d.mts +7 -0
  23. package/dist/commands/db-schema-verify.d.mts.map +1 -0
  24. package/dist/commands/db-schema-verify.mjs +120 -0
  25. package/dist/commands/db-schema-verify.mjs.map +1 -0
  26. package/dist/commands/db-sign.d.mts +7 -0
  27. package/dist/commands/db-sign.d.mts.map +1 -0
  28. package/dist/commands/db-sign.mjs +142 -0
  29. package/dist/commands/db-sign.mjs.map +1 -0
  30. package/dist/commands/db-update.d.mts +7 -0
  31. package/dist/commands/db-update.d.mts.map +1 -0
  32. package/dist/commands/db-update.mjs +123 -0
  33. package/dist/commands/db-update.mjs.map +1 -0
  34. package/dist/commands/db-verify.d.mts +7 -0
  35. package/dist/commands/db-verify.d.mts.map +1 -0
  36. package/dist/commands/db-verify.mjs +133 -0
  37. package/dist/commands/db-verify.mjs.map +1 -0
  38. package/dist/commands/migration-apply.d.mts +23 -0
  39. package/dist/commands/migration-apply.d.mts.map +1 -0
  40. package/dist/commands/migration-apply.mjs +250 -0
  41. package/dist/commands/migration-apply.mjs.map +1 -0
  42. package/dist/commands/migration-plan.d.mts +25 -0
  43. package/dist/commands/migration-plan.d.mts.map +1 -0
  44. package/dist/commands/migration-plan.mjs +266 -0
  45. package/dist/commands/migration-plan.mjs.map +1 -0
  46. package/dist/commands/migration-show.d.mts +28 -0
  47. package/dist/commands/migration-show.d.mts.map +1 -0
  48. package/dist/commands/migration-show.mjs +138 -0
  49. package/dist/commands/migration-show.mjs.map +1 -0
  50. package/dist/commands/migration-status.d.mts +35 -0
  51. package/dist/commands/migration-status.d.mts.map +1 -0
  52. package/dist/commands/migration-status.mjs +260 -0
  53. package/dist/commands/migration-status.mjs.map +1 -0
  54. package/dist/commands/migration-verify.d.mts +16 -0
  55. package/dist/commands/migration-verify.d.mts.map +1 -0
  56. package/dist/commands/migration-verify.mjs +86 -0
  57. package/dist/commands/migration-verify.mjs.map +1 -0
  58. package/dist/config-loader-PPf4CtDj.mjs +43 -0
  59. package/dist/config-loader-PPf4CtDj.mjs.map +1 -0
  60. package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
  61. package/dist/config-loader.d.mts.map +1 -0
  62. package/dist/config-loader.mjs +3 -0
  63. package/dist/exports/config-types.d.mts +2 -0
  64. package/dist/exports/config-types.mjs +3 -0
  65. package/dist/exports/control-api.d.mts +621 -0
  66. package/dist/exports/control-api.d.mts.map +1 -0
  67. package/dist/exports/control-api.mjs +98 -0
  68. package/dist/exports/control-api.mjs.map +1 -0
  69. package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
  70. package/dist/exports/index.d.mts.map +1 -0
  71. package/dist/exports/index.mjs +135 -0
  72. package/dist/exports/index.mjs.map +1 -0
  73. package/dist/extract-sql-ddl-BmlKvk4o.mjs +26 -0
  74. package/dist/extract-sql-ddl-BmlKvk4o.mjs.map +1 -0
  75. package/dist/framework-components-CjV_jD8f.mjs +59 -0
  76. package/dist/framework-components-CjV_jD8f.mjs.map +1 -0
  77. package/dist/migration-command-scaffold-DfY_F3ev.mjs +97 -0
  78. package/dist/migration-command-scaffold-DfY_F3ev.mjs.map +1 -0
  79. package/dist/progress-adapter-DENrzF6I.mjs +49 -0
  80. package/dist/progress-adapter-DENrzF6I.mjs.map +1 -0
  81. package/dist/result-handler-iA9JtUC7.mjs +1186 -0
  82. package/dist/result-handler-iA9JtUC7.mjs.map +1 -0
  83. package/package.json +75 -38
  84. package/src/cli.ts +43 -0
  85. package/src/commands/contract-emit.ts +221 -111
  86. package/src/commands/db-init.ts +217 -426
  87. package/src/commands/db-introspect.ts +148 -185
  88. package/src/commands/db-schema-verify.ts +162 -149
  89. package/src/commands/db-sign.ts +215 -202
  90. package/src/commands/db-update.ts +220 -0
  91. package/src/commands/db-verify.ts +193 -156
  92. package/src/commands/migration-apply.ts +431 -0
  93. package/src/commands/migration-plan.ts +446 -0
  94. package/src/commands/migration-show.ts +255 -0
  95. package/src/commands/migration-status.ts +436 -0
  96. package/src/commands/migration-verify.ts +151 -0
  97. package/src/config-loader.ts +13 -3
  98. package/src/control-api/client.ts +605 -0
  99. package/src/control-api/errors.ts +9 -0
  100. package/src/control-api/operations/contract-emit.ts +161 -0
  101. package/src/control-api/operations/db-init.ts +286 -0
  102. package/src/control-api/operations/db-update.ts +221 -0
  103. package/src/control-api/operations/extract-sql-ddl.ts +47 -0
  104. package/src/control-api/operations/migration-apply.ts +195 -0
  105. package/src/control-api/operations/migration-helpers.ts +49 -0
  106. package/src/control-api/types.ts +687 -0
  107. package/src/exports/config-types.ts +3 -3
  108. package/src/exports/control-api.ts +53 -0
  109. package/src/load-ts-contract.ts +16 -11
  110. package/src/utils/cli-errors.ts +3 -1
  111. package/src/utils/command-helpers.ts +92 -3
  112. package/src/utils/framework-components.ts +11 -30
  113. package/src/utils/migration-command-scaffold.ts +190 -0
  114. package/src/utils/output.ts +363 -25
  115. package/src/utils/progress-adapter.ts +86 -0
  116. package/dist/chunk-464LNZCE.js +0 -134
  117. package/dist/chunk-464LNZCE.js.map +0 -1
  118. package/dist/chunk-BZMBKEEQ.js +0 -997
  119. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  120. package/dist/chunk-HWYQOCAJ.js +0 -47
  121. package/dist/chunk-HWYQOCAJ.js.map +0 -1
  122. package/dist/chunk-ZKYEJROM.js +0 -94
  123. package/dist/chunk-ZKYEJROM.js.map +0 -1
  124. package/dist/cli.d.ts +0 -2
  125. package/dist/cli.d.ts.map +0 -1
  126. package/dist/cli.js.map +0 -1
  127. package/dist/commands/contract-emit.d.ts +0 -3
  128. package/dist/commands/contract-emit.d.ts.map +0 -1
  129. package/dist/commands/contract-emit.js +0 -9
  130. package/dist/commands/contract-emit.js.map +0 -1
  131. package/dist/commands/db-init.d.ts +0 -3
  132. package/dist/commands/db-init.d.ts.map +0 -1
  133. package/dist/commands/db-init.js +0 -341
  134. package/dist/commands/db-init.js.map +0 -1
  135. package/dist/commands/db-introspect.d.ts +0 -3
  136. package/dist/commands/db-introspect.d.ts.map +0 -1
  137. package/dist/commands/db-introspect.js +0 -190
  138. package/dist/commands/db-introspect.js.map +0 -1
  139. package/dist/commands/db-schema-verify.d.ts +0 -3
  140. package/dist/commands/db-schema-verify.d.ts.map +0 -1
  141. package/dist/commands/db-schema-verify.js +0 -164
  142. package/dist/commands/db-schema-verify.js.map +0 -1
  143. package/dist/commands/db-sign.d.ts +0 -3
  144. package/dist/commands/db-sign.d.ts.map +0 -1
  145. package/dist/commands/db-sign.js +0 -199
  146. package/dist/commands/db-sign.js.map +0 -1
  147. package/dist/commands/db-verify.d.ts +0 -3
  148. package/dist/commands/db-verify.d.ts.map +0 -1
  149. package/dist/commands/db-verify.js +0 -173
  150. package/dist/commands/db-verify.js.map +0 -1
  151. package/dist/config-loader.d.ts.map +0 -1
  152. package/dist/config-loader.js +0 -7
  153. package/dist/config-loader.js.map +0 -1
  154. package/dist/exports/config-types.d.ts +0 -3
  155. package/dist/exports/config-types.d.ts.map +0 -1
  156. package/dist/exports/config-types.js +0 -6
  157. package/dist/exports/config-types.js.map +0 -1
  158. package/dist/exports/index.d.ts +0 -4
  159. package/dist/exports/index.d.ts.map +0 -1
  160. package/dist/exports/index.js +0 -175
  161. package/dist/exports/index.js.map +0 -1
  162. package/dist/load-ts-contract.d.ts.map +0 -1
  163. package/dist/utils/action.d.ts +0 -16
  164. package/dist/utils/action.d.ts.map +0 -1
  165. package/dist/utils/cli-errors.d.ts +0 -7
  166. package/dist/utils/cli-errors.d.ts.map +0 -1
  167. package/dist/utils/command-helpers.d.ts +0 -12
  168. package/dist/utils/command-helpers.d.ts.map +0 -1
  169. package/dist/utils/framework-components.d.ts +0 -81
  170. package/dist/utils/framework-components.d.ts.map +0 -1
  171. package/dist/utils/global-flags.d.ts +0 -25
  172. package/dist/utils/global-flags.d.ts.map +0 -1
  173. package/dist/utils/output.d.ts +0 -142
  174. package/dist/utils/output.d.ts.map +0 -1
  175. package/dist/utils/result-handler.d.ts +0 -15
  176. package/dist/utils/result-handler.d.ts.map +0 -1
  177. package/dist/utils/spinner.d.ts +0 -29
  178. package/dist/utils/spinner.d.ts.map +0 -1
  179. package/src/utils/action.ts +0 -43
  180. package/src/utils/spinner.ts +0 -67
package/dist/cli.js CHANGED
@@ -1,2377 +1,2 @@
1
1
  #!/usr/bin/env node
2
-
3
- // src/cli.ts
4
- import { Command as Command7 } from "commander";
5
-
6
- // src/commands/contract-emit.ts
7
- import { mkdirSync, writeFileSync } from "fs";
8
- import { dirname as dirname2, relative as relative2, resolve as resolve2 } from "path";
9
- import { errorContractConfigMissing as errorContractConfigMissing2 } from "@prisma-next/core-control-plane/errors";
10
- import { Command } from "commander";
11
-
12
- // src/config-loader.ts
13
- import { dirname, resolve } from "path";
14
- import { validateConfig } from "@prisma-next/core-control-plane/config-validation";
15
- import { errorConfigFileNotFound, errorUnexpected } from "@prisma-next/core-control-plane/errors";
16
- import { loadConfig as loadConfigC12 } from "c12";
17
- async function loadConfig(configPath) {
18
- try {
19
- const cwd = process.cwd();
20
- const resolvedConfigPath = configPath ? resolve(cwd, configPath) : void 0;
21
- const configCwd = resolvedConfigPath ? dirname(resolvedConfigPath) : cwd;
22
- const result = await loadConfigC12({
23
- name: "prisma-next",
24
- ...resolvedConfigPath ? { configFile: resolvedConfigPath } : {},
25
- cwd: configCwd
26
- });
27
- if (resolvedConfigPath && result.configFile !== resolvedConfigPath) {
28
- throw errorConfigFileNotFound(resolvedConfigPath);
29
- }
30
- if (!result.config || Object.keys(result.config).length === 0) {
31
- const displayPath = result.configFile || resolvedConfigPath || configPath;
32
- throw errorConfigFileNotFound(displayPath);
33
- }
34
- validateConfig(result.config);
35
- return result.config;
36
- } catch (error) {
37
- if (error instanceof Error && "code" in error && typeof error.code === "string") {
38
- throw error;
39
- }
40
- if (error instanceof Error) {
41
- if (error.message.includes("not found") || error.message.includes("Cannot find") || error.message.includes("ENOENT")) {
42
- const displayPath = configPath ? resolve(process.cwd(), configPath) : void 0;
43
- throw errorConfigFileNotFound(displayPath, {
44
- why: error.message
45
- });
46
- }
47
- throw errorUnexpected(error.message, {
48
- why: `Failed to load config: ${error.message}`
49
- });
50
- }
51
- throw errorUnexpected(String(error));
52
- }
53
- }
54
-
55
- // src/utils/action.ts
56
- import { notOk, ok } from "@prisma-next/utils/result";
57
-
58
- // src/utils/cli-errors.ts
59
- import {
60
- CliStructuredError,
61
- errorConfigFileNotFound as errorConfigFileNotFound2,
62
- errorConfigValidation,
63
- errorContractConfigMissing,
64
- errorContractMissingExtensionPacks,
65
- errorContractValidationFailed,
66
- errorDatabaseUrlRequired,
67
- errorDriverRequired,
68
- errorFamilyReadMarkerSqlRequired,
69
- errorFileNotFound,
70
- errorHashMismatch,
71
- errorJsonFormatNotSupported,
72
- errorMarkerMissing,
73
- errorMigrationPlanningFailed,
74
- errorQueryRunnerFactoryRequired,
75
- errorRuntime,
76
- errorTargetMigrationNotSupported,
77
- errorTargetMismatch,
78
- errorUnexpected as errorUnexpected2
79
- } from "@prisma-next/core-control-plane/errors";
80
-
81
- // src/utils/action.ts
82
- async function performAction(fn) {
83
- try {
84
- const value = await fn();
85
- return ok(value);
86
- } catch (error) {
87
- if (error instanceof CliStructuredError) {
88
- return notOk(error);
89
- }
90
- throw error;
91
- }
92
- }
93
-
94
- // src/utils/command-helpers.ts
95
- function setCommandDescriptions(command, shortDescription, longDescription) {
96
- command.description(shortDescription);
97
- if (longDescription) {
98
- command._longDescription = longDescription;
99
- }
100
- return command;
101
- }
102
- function getLongDescription(command) {
103
- return command._longDescription;
104
- }
105
-
106
- // src/utils/global-flags.ts
107
- function parseGlobalFlags(options) {
108
- const flags = {};
109
- if (options.json === true || options.json === "object") {
110
- flags.json = "object";
111
- } else if (options.json === "ndjson") {
112
- flags.json = "ndjson";
113
- }
114
- if (options.quiet || options.q) {
115
- flags.quiet = true;
116
- }
117
- if (options.vv || options.trace) {
118
- flags.verbose = 2;
119
- } else if (options.verbose || options.v) {
120
- flags.verbose = 1;
121
- } else {
122
- flags.verbose = 0;
123
- }
124
- if (options.timestamps) {
125
- flags.timestamps = true;
126
- }
127
- if (process.env["NO_COLOR"] || flags.json) {
128
- flags.color = false;
129
- } else if (options["no-color"]) {
130
- flags.color = false;
131
- } else if (options.color !== void 0) {
132
- flags.color = options.color;
133
- } else {
134
- flags.color = process.stdout.isTTY && !process.env["CI"];
135
- }
136
- return flags;
137
- }
138
-
139
- // src/utils/output.ts
140
- import { relative } from "path";
141
- import { bgGreen, blue, bold, cyan, dim, green, magenta, red, yellow } from "colorette";
142
- import stringWidth from "string-width";
143
- import stripAnsi from "strip-ansi";
144
- import wrapAnsi from "wrap-ansi";
145
- function formatTimestamp() {
146
- return (/* @__PURE__ */ new Date()).toISOString();
147
- }
148
- function createPrefix(flags) {
149
- return flags.timestamps ? `[${formatTimestamp()}] ` : "";
150
- }
151
- function isVerbose(flags, level) {
152
- return (flags.verbose ?? 0) >= level;
153
- }
154
- function createColorFormatter(useColor, colorFn) {
155
- return useColor ? colorFn : (text) => text;
156
- }
157
- function formatDim(useColor, text) {
158
- return useColor ? dim(text) : text;
159
- }
160
- function formatEmitOutput(result, flags) {
161
- if (flags.quiet) {
162
- return "";
163
- }
164
- const lines = [];
165
- const prefix = createPrefix(flags);
166
- const jsonPath = relative(process.cwd(), result.files.json);
167
- const dtsPath = relative(process.cwd(), result.files.dts);
168
- lines.push(`${prefix}\u2714 Emitted contract.json \u2192 ${jsonPath}`);
169
- lines.push(`${prefix}\u2714 Emitted contract.d.ts \u2192 ${dtsPath}`);
170
- lines.push(`${prefix} coreHash: ${result.coreHash}`);
171
- if (result.profileHash) {
172
- lines.push(`${prefix} profileHash: ${result.profileHash}`);
173
- }
174
- if (isVerbose(flags, 1)) {
175
- lines.push(`${prefix} Total time: ${result.timings.total}ms`);
176
- }
177
- return lines.join("\n");
178
- }
179
- function formatEmitJson(result) {
180
- const output = {
181
- ok: true,
182
- coreHash: result.coreHash,
183
- ...result.profileHash ? { profileHash: result.profileHash } : {},
184
- outDir: result.outDir,
185
- files: result.files,
186
- timings: result.timings
187
- };
188
- return JSON.stringify(output, null, 2);
189
- }
190
- function formatErrorOutput(error, flags) {
191
- const lines = [];
192
- const prefix = createPrefix(flags);
193
- const useColor = flags.color !== false;
194
- const formatRed = createColorFormatter(useColor, red);
195
- const formatDimText = (text) => formatDim(useColor, text);
196
- lines.push(`${prefix}${formatRed("\u2716")} ${error.summary} (${error.code})`);
197
- if (error.why) {
198
- lines.push(`${prefix}${formatDimText(` Why: ${error.why}`)}`);
199
- }
200
- if (error.fix) {
201
- lines.push(`${prefix}${formatDimText(` Fix: ${error.fix}`)}`);
202
- }
203
- if (error.where?.path) {
204
- const whereLine = error.where.line ? `${error.where.path}:${error.where.line}` : error.where.path;
205
- lines.push(`${prefix}${formatDimText(` Where: ${whereLine}`)}`);
206
- }
207
- if (error.meta?.["conflicts"]) {
208
- const conflicts = error.meta["conflicts"];
209
- if (conflicts.length > 0) {
210
- const maxToShow = isVerbose(flags, 1) ? conflicts.length : Math.min(3, conflicts.length);
211
- const header = isVerbose(flags, 1) ? " Conflicts:" : ` Conflicts (showing ${maxToShow} of ${conflicts.length}):`;
212
- lines.push(`${prefix}${formatDimText(header)}`);
213
- for (const conflict of conflicts.slice(0, maxToShow)) {
214
- lines.push(`${prefix}${formatDimText(` - [${conflict.kind}] ${conflict.summary}`)}`);
215
- }
216
- if (!isVerbose(flags, 1) && conflicts.length > maxToShow) {
217
- lines.push(`${prefix}${formatDimText(" Re-run with -v/--verbose to see all conflicts")}`);
218
- }
219
- }
220
- }
221
- if (error.meta?.["issues"]) {
222
- const issues = error.meta["issues"];
223
- if (issues.length > 0) {
224
- const maxToShow = isVerbose(flags, 1) ? issues.length : Math.min(3, issues.length);
225
- const header = isVerbose(flags, 1) ? " Issues:" : ` Issues (showing ${maxToShow} of ${issues.length}):`;
226
- lines.push(`${prefix}${formatDimText(header)}`);
227
- for (const issue of issues.slice(0, maxToShow)) {
228
- const kind = issue.kind ?? "issue";
229
- const message = issue.message ?? "";
230
- lines.push(`${prefix}${formatDimText(` - [${kind}] ${message}`)}`);
231
- }
232
- if (!isVerbose(flags, 1) && issues.length > maxToShow) {
233
- lines.push(`${prefix}${formatDimText(" Re-run with -v/--verbose to see all issues")}`);
234
- }
235
- }
236
- }
237
- if (error.docsUrl && isVerbose(flags, 1)) {
238
- lines.push(formatDimText(error.docsUrl));
239
- }
240
- if (isVerbose(flags, 2) && error.meta) {
241
- lines.push(`${prefix}${formatDimText(` Meta: ${JSON.stringify(error.meta, null, 2)}`)}`);
242
- }
243
- return lines.join("\n");
244
- }
245
- function formatErrorJson(error) {
246
- return JSON.stringify(error, null, 2);
247
- }
248
- function formatVerifyOutput(result, flags) {
249
- if (flags.quiet) {
250
- return "";
251
- }
252
- const lines = [];
253
- const prefix = createPrefix(flags);
254
- const useColor = flags.color !== false;
255
- const formatGreen = createColorFormatter(useColor, green);
256
- const formatRed = createColorFormatter(useColor, red);
257
- const formatDimText = (text) => formatDim(useColor, text);
258
- if (result.ok) {
259
- lines.push(`${prefix}${formatGreen("\u2714")} ${result.summary}`);
260
- lines.push(`${prefix}${formatDimText(` coreHash: ${result.contract.coreHash}`)}`);
261
- if (result.contract.profileHash) {
262
- lines.push(`${prefix}${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);
263
- }
264
- } else {
265
- lines.push(`${prefix}${formatRed("\u2716")} ${result.summary} (${result.code})`);
266
- }
267
- if (isVerbose(flags, 1)) {
268
- if (result.codecCoverageSkipped) {
269
- lines.push(
270
- `${prefix}${formatDimText(" Codec coverage check skipped (helper returned no supported types)")}`
271
- );
272
- }
273
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
274
- }
275
- return lines.join("\n");
276
- }
277
- function formatVerifyJson(result) {
278
- const output = {
279
- ok: result.ok,
280
- ...result.code ? { code: result.code } : {},
281
- summary: result.summary,
282
- contract: result.contract,
283
- ...result.marker ? { marker: result.marker } : {},
284
- target: result.target,
285
- ...result.missingCodecs ? { missingCodecs: result.missingCodecs } : {},
286
- ...result.meta ? { meta: result.meta } : {},
287
- timings: result.timings
288
- };
289
- return JSON.stringify(output, null, 2);
290
- }
291
- function formatIntrospectJson(result) {
292
- return JSON.stringify(result, null, 2);
293
- }
294
- function renderSchemaTree(node, flags, options) {
295
- const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;
296
- const lines = [];
297
- let formattedLabel = node.label;
298
- if (useColor) {
299
- switch (node.kind) {
300
- case "root":
301
- formattedLabel = bold(node.label);
302
- break;
303
- case "entity": {
304
- const tableMatch = node.label.match(/^table\s+(.+)$/);
305
- if (tableMatch?.[1]) {
306
- const tableName = tableMatch[1];
307
- formattedLabel = `${dim("table")} ${cyan(tableName)}`;
308
- } else {
309
- formattedLabel = cyan(node.label);
310
- }
311
- break;
312
- }
313
- case "collection": {
314
- formattedLabel = dim(node.label);
315
- break;
316
- }
317
- case "field": {
318
- const columnMatch = node.label.match(/^([^:]+):\s*(.+)$/);
319
- if (columnMatch?.[1] && columnMatch[2]) {
320
- const columnName = columnMatch[1];
321
- const rest = columnMatch[2];
322
- const typeMatch = rest.match(/^([^\s(]+)\s*(\([^)]+\))$/);
323
- if (typeMatch?.[1] && typeMatch[2]) {
324
- const typeDisplay = typeMatch[1];
325
- const nullability = typeMatch[2];
326
- formattedLabel = `${cyan(columnName)}: ${typeDisplay} ${dim(nullability)}`;
327
- } else {
328
- formattedLabel = `${cyan(columnName)}: ${rest}`;
329
- }
330
- } else {
331
- formattedLabel = node.label;
332
- }
333
- break;
334
- }
335
- case "index": {
336
- const pkMatch = node.label.match(/^primary key:\s*(.+)$/);
337
- if (pkMatch?.[1]) {
338
- const columnNames = pkMatch[1];
339
- formattedLabel = `${dim("primary key")}: ${cyan(columnNames)}`;
340
- } else {
341
- const uniqueMatch = node.label.match(/^unique\s+(.+)$/);
342
- if (uniqueMatch?.[1]) {
343
- const name = uniqueMatch[1];
344
- formattedLabel = `${dim("unique")} ${cyan(name)}`;
345
- } else {
346
- const indexMatch = node.label.match(/^(unique\s+)?index\s+(.+)$/);
347
- if (indexMatch?.[2]) {
348
- const prefix2 = indexMatch[1] ? `${dim("unique")} ` : "";
349
- const name = indexMatch[2];
350
- formattedLabel = `${prefix2}${dim("index")} ${cyan(name)}`;
351
- } else {
352
- formattedLabel = dim(node.label);
353
- }
354
- }
355
- }
356
- break;
357
- }
358
- case "extension": {
359
- const extMatch = node.label.match(/^([^\s]+)\s+(extension is enabled)$/);
360
- if (extMatch?.[1] && extMatch[2]) {
361
- const extName = extMatch[1];
362
- const rest = extMatch[2];
363
- formattedLabel = `${cyan(extName)} ${dim(rest)}`;
364
- } else {
365
- formattedLabel = magenta(node.label);
366
- }
367
- break;
368
- }
369
- default:
370
- formattedLabel = node.label;
371
- break;
372
- }
373
- }
374
- if (isRoot) {
375
- lines.push(formattedLabel);
376
- } else {
377
- const treeChar = isLast ? "\u2514" : "\u251C";
378
- const treePrefix = `${prefix}${formatDimText(treeChar)}\u2500 `;
379
- const isRootChild = prefix === "";
380
- const prefixWithoutAnsi = stripAnsi(prefix);
381
- const prefixHasVerticalBar = prefixWithoutAnsi.includes("\u2502");
382
- if (isRootChild) {
383
- lines.push(`${treePrefix}${formattedLabel}`);
384
- } else if (prefixHasVerticalBar) {
385
- lines.push(`${treePrefix}${formattedLabel}`);
386
- } else {
387
- lines.push(`${formatDimText("\u2502")} ${treePrefix}${formattedLabel}`);
388
- }
389
- }
390
- if (node.children && node.children.length > 0) {
391
- const childPrefix = isRoot ? "" : isLast ? `${prefix} ` : `${prefix}${formatDimText("\u2502")} `;
392
- for (let i = 0; i < node.children.length; i++) {
393
- const child = node.children[i];
394
- if (!child) continue;
395
- const isLastChild = i === node.children.length - 1;
396
- const childLines = renderSchemaTree(child, flags, {
397
- isLast: isLastChild,
398
- prefix: childPrefix,
399
- useColor,
400
- formatDimText,
401
- isRoot: false
402
- });
403
- lines.push(...childLines);
404
- }
405
- }
406
- return lines;
407
- }
408
- function formatIntrospectOutput(result, schemaView, flags) {
409
- if (flags.quiet) {
410
- return "";
411
- }
412
- const lines = [];
413
- const prefix = createPrefix(flags);
414
- const useColor = flags.color !== false;
415
- const formatDimText = (text) => formatDim(useColor, text);
416
- if (schemaView) {
417
- const treeLines = renderSchemaTree(schemaView.root, flags, {
418
- isLast: true,
419
- prefix: "",
420
- useColor,
421
- formatDimText,
422
- isRoot: true
423
- });
424
- const prefixedTreeLines = treeLines.map((line) => `${prefix}${line}`);
425
- lines.push(...prefixedTreeLines);
426
- } else {
427
- lines.push(`${prefix}\u2714 ${result.summary}`);
428
- if (isVerbose(flags, 1)) {
429
- lines.push(`${prefix} Target: ${result.target.familyId}/${result.target.id}`);
430
- if (result.meta?.dbUrl) {
431
- lines.push(`${prefix} Database: ${result.meta.dbUrl}`);
432
- }
433
- }
434
- }
435
- if (isVerbose(flags, 1)) {
436
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
437
- }
438
- return lines.join("\n");
439
- }
440
- function renderSchemaVerificationTree(node, flags, options) {
441
- const { isLast, prefix, useColor, formatDimText, isRoot = false } = options;
442
- const lines = [];
443
- let statusGlyph = "";
444
- let statusColor = (text) => text;
445
- if (useColor) {
446
- switch (node.status) {
447
- case "pass":
448
- statusGlyph = "\u2714";
449
- statusColor = green;
450
- break;
451
- case "warn":
452
- statusGlyph = "\u26A0";
453
- statusColor = (text) => useColor ? yellow(text) : text;
454
- break;
455
- case "fail":
456
- statusGlyph = "\u2716";
457
- statusColor = red;
458
- break;
459
- }
460
- } else {
461
- switch (node.status) {
462
- case "pass":
463
- statusGlyph = "\u2714";
464
- break;
465
- case "warn":
466
- statusGlyph = "\u26A0";
467
- break;
468
- case "fail":
469
- statusGlyph = "\u2716";
470
- break;
471
- }
472
- }
473
- let labelColor = (text) => text;
474
- let formattedLabel = node.name;
475
- if (useColor) {
476
- switch (node.kind) {
477
- case "contract":
478
- case "schema":
479
- labelColor = bold;
480
- formattedLabel = labelColor(node.name);
481
- break;
482
- case "table": {
483
- const tableMatch = node.name.match(/^table\s+(.+)$/);
484
- if (tableMatch?.[1]) {
485
- const tableName = tableMatch[1];
486
- formattedLabel = `${dim("table")} ${cyan(tableName)}`;
487
- } else {
488
- formattedLabel = dim(node.name);
489
- }
490
- break;
491
- }
492
- case "columns":
493
- labelColor = dim;
494
- formattedLabel = labelColor(node.name);
495
- break;
496
- case "column": {
497
- const columnMatch = node.name.match(/^([^:]+):\s*(.+)$/);
498
- if (columnMatch?.[1] && columnMatch[2]) {
499
- const columnName = columnMatch[1];
500
- const rest = columnMatch[2];
501
- const typeMatch = rest.match(/^([^\s→]+)\s*→\s*([^\s(]+)\s*(\([^)]+\))$/);
502
- if (typeMatch?.[1] && typeMatch[2] && typeMatch[3]) {
503
- const contractType = typeMatch[1];
504
- const nativeType = typeMatch[2];
505
- const nullability = typeMatch[3];
506
- formattedLabel = `${cyan(columnName)}: ${contractType} \u2192 ${dim(nativeType)} ${dim(nullability)}`;
507
- } else {
508
- formattedLabel = `${cyan(columnName)}: ${rest}`;
509
- }
510
- } else {
511
- formattedLabel = node.name;
512
- }
513
- break;
514
- }
515
- case "type":
516
- case "nullability":
517
- labelColor = (text) => text;
518
- formattedLabel = labelColor(node.name);
519
- break;
520
- case "primaryKey": {
521
- const pkMatch = node.name.match(/^primary key:\s*(.+)$/);
522
- if (pkMatch?.[1]) {
523
- const columnNames = pkMatch[1];
524
- formattedLabel = `${dim("primary key")}: ${cyan(columnNames)}`;
525
- } else {
526
- formattedLabel = dim(node.name);
527
- }
528
- break;
529
- }
530
- case "foreignKey":
531
- case "unique":
532
- case "index":
533
- labelColor = dim;
534
- formattedLabel = labelColor(node.name);
535
- break;
536
- case "extension": {
537
- const dbMatch = node.name.match(/^database is\s+(.+)$/);
538
- if (dbMatch?.[1]) {
539
- const dbName = dbMatch[1];
540
- formattedLabel = `${dim("database is")} ${cyan(dbName)}`;
541
- } else {
542
- const extMatch = node.name.match(/^([^\s]+)\s+(extension is enabled)$/);
543
- if (extMatch?.[1] && extMatch[2]) {
544
- const extName = extMatch[1];
545
- const rest = extMatch[2];
546
- formattedLabel = `${cyan(extName)} ${dim(rest)}`;
547
- } else {
548
- labelColor = magenta;
549
- formattedLabel = labelColor(node.name);
550
- }
551
- }
552
- break;
553
- }
554
- default:
555
- formattedLabel = node.name;
556
- break;
557
- }
558
- } else {
559
- formattedLabel = node.name;
560
- }
561
- const statusGlyphColored = statusColor(statusGlyph);
562
- let nodeLabel = formattedLabel;
563
- if ((node.status === "fail" || node.status === "warn") && node.message && node.message.length > 0) {
564
- const messageText = formatDimText(`(${node.message})`);
565
- nodeLabel = `${formattedLabel} ${messageText}`;
566
- }
567
- if (isRoot) {
568
- lines.push(`${statusGlyphColored} ${nodeLabel}`);
569
- } else {
570
- const treeChar = isLast ? "\u2514" : "\u251C";
571
- const treePrefix = `${prefix}${formatDimText(treeChar)}\u2500 `;
572
- const isRootChild = prefix === "";
573
- const prefixWithoutAnsi = stripAnsi(prefix);
574
- const prefixHasVerticalBar = prefixWithoutAnsi.includes("\u2502");
575
- if (isRootChild) {
576
- lines.push(`${treePrefix}${statusGlyphColored} ${nodeLabel}`);
577
- } else if (prefixHasVerticalBar) {
578
- lines.push(`${treePrefix}${statusGlyphColored} ${nodeLabel}`);
579
- } else {
580
- lines.push(`${formatDimText("\u2502")} ${treePrefix}${statusGlyphColored} ${nodeLabel}`);
581
- }
582
- }
583
- if (node.children && node.children.length > 0) {
584
- const childPrefix = isRoot ? "" : isLast ? `${prefix} ` : `${prefix}${formatDimText("\u2502")} `;
585
- for (let i = 0; i < node.children.length; i++) {
586
- const child = node.children[i];
587
- if (!child) continue;
588
- const isLastChild = i === node.children.length - 1;
589
- const childLines = renderSchemaVerificationTree(child, flags, {
590
- isLast: isLastChild,
591
- prefix: childPrefix,
592
- useColor,
593
- formatDimText,
594
- isRoot: false
595
- });
596
- lines.push(...childLines);
597
- }
598
- }
599
- return lines;
600
- }
601
- function formatSchemaVerifyOutput(result, flags) {
602
- if (flags.quiet) {
603
- return "";
604
- }
605
- const lines = [];
606
- const prefix = createPrefix(flags);
607
- const useColor = flags.color !== false;
608
- const formatGreen = createColorFormatter(useColor, green);
609
- const formatRed = createColorFormatter(useColor, red);
610
- const formatDimText = (text) => formatDim(useColor, text);
611
- const treeLines = renderSchemaVerificationTree(result.schema.root, flags, {
612
- isLast: true,
613
- prefix: "",
614
- useColor,
615
- formatDimText,
616
- isRoot: true
617
- });
618
- const prefixedTreeLines = treeLines.map((line) => `${prefix}${line}`);
619
- lines.push(...prefixedTreeLines);
620
- if (isVerbose(flags, 1)) {
621
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
622
- lines.push(
623
- `${prefix}${formatDimText(` pass=${result.schema.counts.pass} warn=${result.schema.counts.warn} fail=${result.schema.counts.fail}`)}`
624
- );
625
- }
626
- lines.push("");
627
- if (result.ok) {
628
- lines.push(`${prefix}${formatGreen("\u2714")} ${result.summary}`);
629
- } else {
630
- const codeText = result.code ? ` (${result.code})` : "";
631
- lines.push(`${prefix}${formatRed("\u2716")} ${result.summary}${codeText}`);
632
- }
633
- return lines.join("\n");
634
- }
635
- function formatSchemaVerifyJson(result) {
636
- return JSON.stringify(result, null, 2);
637
- }
638
- function formatSignOutput(result, flags) {
639
- if (flags.quiet) {
640
- return "";
641
- }
642
- const lines = [];
643
- const prefix = createPrefix(flags);
644
- const useColor = flags.color !== false;
645
- const formatGreen = createColorFormatter(useColor, green);
646
- const formatDimText = (text) => formatDim(useColor, text);
647
- if (result.ok) {
648
- lines.push(`${prefix}${formatGreen("\u2714")} Database signed`);
649
- const previousHash = result.marker.previous?.coreHash ?? "none";
650
- const currentHash = result.contract.coreHash;
651
- lines.push(`${prefix}${formatDimText(` from: ${previousHash}`)}`);
652
- lines.push(`${prefix}${formatDimText(` to: ${currentHash}`)}`);
653
- if (isVerbose(flags, 1)) {
654
- if (result.contract.profileHash) {
655
- lines.push(`${prefix}${formatDimText(` profileHash: ${result.contract.profileHash}`)}`);
656
- }
657
- if (result.marker.previous?.profileHash) {
658
- lines.push(
659
- `${prefix}${formatDimText(` previous profileHash: ${result.marker.previous.profileHash}`)}`
660
- );
661
- }
662
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
663
- }
664
- }
665
- return lines.join("\n");
666
- }
667
- function formatSignJson(result) {
668
- return JSON.stringify(result, null, 2);
669
- }
670
- function formatDbInitPlanOutput(result, flags) {
671
- if (flags.quiet) {
672
- return "";
673
- }
674
- const lines = [];
675
- const prefix = createPrefix(flags);
676
- const useColor = flags.color !== false;
677
- const formatGreen = createColorFormatter(useColor, green);
678
- const formatDimText = (text) => formatDim(useColor, text);
679
- const operationCount = result.plan?.operations.length ?? 0;
680
- lines.push(`${prefix}${formatGreen("\u2714")} Planned ${operationCount} operation(s)`);
681
- if (result.plan?.operations && result.plan.operations.length > 0) {
682
- lines.push(`${prefix}${formatDimText("\u2502")}`);
683
- for (let i = 0; i < result.plan.operations.length; i++) {
684
- const op = result.plan.operations[i];
685
- if (!op) continue;
686
- const isLast = i === result.plan.operations.length - 1;
687
- const treeChar = isLast ? "\u2514" : "\u251C";
688
- const opClass = formatDimText(`[${op.operationClass}]`);
689
- lines.push(`${prefix}${formatDimText(treeChar)}\u2500 ${op.label} ${opClass}`);
690
- }
691
- }
692
- if (result.plan?.destination) {
693
- lines.push(`${prefix}`);
694
- lines.push(
695
- `${prefix}${formatDimText(`Destination hash: ${result.plan.destination.coreHash}`)}`
696
- );
697
- }
698
- if (isVerbose(flags, 1)) {
699
- lines.push(`${prefix}${formatDimText(`Total time: ${result.timings.total}ms`)}`);
700
- }
701
- lines.push(`${prefix}`);
702
- lines.push(`${prefix}${formatDimText("This is a dry run. No changes were applied.")}`);
703
- lines.push(`${prefix}${formatDimText("Run without --plan to apply changes.")}`);
704
- return lines.join("\n");
705
- }
706
- function formatDbInitApplyOutput(result, flags) {
707
- if (flags.quiet) {
708
- return "";
709
- }
710
- const lines = [];
711
- const prefix = createPrefix(flags);
712
- const useColor = flags.color !== false;
713
- const formatGreen = createColorFormatter(useColor, green);
714
- const formatDimText = (text) => formatDim(useColor, text);
715
- if (result.ok) {
716
- const executed = result.execution?.operationsExecuted ?? 0;
717
- lines.push(`${prefix}${formatGreen("\u2714")} Applied ${executed} operation(s)`);
718
- if (result.marker) {
719
- lines.push(`${prefix}${formatDimText(` Marker written: ${result.marker.coreHash}`)}`);
720
- if (result.marker.profileHash) {
721
- lines.push(`${prefix}${formatDimText(` Profile hash: ${result.marker.profileHash}`)}`);
722
- }
723
- }
724
- if (isVerbose(flags, 1)) {
725
- lines.push(`${prefix}${formatDimText(` Total time: ${result.timings.total}ms`)}`);
726
- }
727
- }
728
- return lines.join("\n");
729
- }
730
- function formatDbInitJson(result) {
731
- return JSON.stringify(result, null, 2);
732
- }
733
- var LEFT_COLUMN_WIDTH = 20;
734
- var RIGHT_COLUMN_MIN_WIDTH = 40;
735
- var RIGHT_COLUMN_MAX_WIDTH = 90;
736
- function getTerminalWidth() {
737
- const terminalWidth = process.stdout.columns;
738
- const defaultWidth = Number.parseInt(process.env["CLI_WIDTH"] || "80", 10);
739
- return terminalWidth || defaultWidth;
740
- }
741
- function calculateRightColumnWidth() {
742
- const terminalWidth = getTerminalWidth();
743
- const availableWidth = terminalWidth - 2 - LEFT_COLUMN_WIDTH - 2;
744
- return Math.max(RIGHT_COLUMN_MIN_WIDTH, Math.min(availableWidth, RIGHT_COLUMN_MAX_WIDTH));
745
- }
746
- function createPrismaNextBadge(useColor) {
747
- if (!useColor) {
748
- return "prisma-next";
749
- }
750
- const text = " prisma-next ";
751
- const body = bgGreen(bold(text));
752
- const separator = "\uE0B0";
753
- const tip = green(separator);
754
- return `${body}${tip}`;
755
- }
756
- function createPadFunction() {
757
- return (s, w) => s + " ".repeat(Math.max(0, w - s.length));
758
- }
759
- function formatHeaderLine(options) {
760
- if (options.operation) {
761
- return `${options.brand} ${options.operation} \u2192 ${options.intent}`;
762
- }
763
- return `${options.brand} ${options.intent}`;
764
- }
765
- function formatReadMoreLine(options) {
766
- const pad = createPadFunction();
767
- const labelPadded = pad("Read more", options.maxLabelWidth);
768
- const valueColored = options.useColor ? blue(options.url) : options.url;
769
- return `${options.formatDimText("\u2502")} ${labelPadded} ${valueColored}`;
770
- }
771
- function padToFixedWidth(text, width) {
772
- const actualWidth = stringWidth(text);
773
- const padding = Math.max(0, width - actualWidth);
774
- return text + " ".repeat(padding);
775
- }
776
- function wrapTextAnsi(text, width) {
777
- const wrapped = wrapAnsi(text, width, { hard: false, trim: true });
778
- return wrapped.split("\n");
779
- }
780
- function formatDefaultValue(value, useColor) {
781
- const valueStr = String(value);
782
- const defaultText = `default: ${valueStr}`;
783
- return useColor ? dim(defaultText) : defaultText;
784
- }
785
- function renderCommandTree(options) {
786
- const { commands, useColor, formatDimText, hasItemsAfter, continuationPrefix } = options;
787
- const lines = [];
788
- if (commands.length === 0) {
789
- return lines;
790
- }
791
- for (let i = 0; i < commands.length; i++) {
792
- const cmd = commands[i];
793
- if (!cmd) continue;
794
- const subcommands = cmd.commands.filter((subcmd) => !subcmd.name().startsWith("_"));
795
- const isLastCommand = i === commands.length - 1;
796
- if (subcommands.length > 0) {
797
- const prefix = isLastCommand && !hasItemsAfter ? formatDimText("\u2514") : formatDimText("\u251C");
798
- const treePrefix = `${prefix}\u2500 `;
799
- const treePrefixWidth = stringWidth(stripAnsi(treePrefix));
800
- const remainingWidth = LEFT_COLUMN_WIDTH - treePrefixWidth;
801
- const commandNamePadded = padToFixedWidth(cmd.name(), remainingWidth);
802
- const commandNameColored = useColor ? cyan(commandNamePadded) : commandNamePadded;
803
- lines.push(`${formatDimText("\u2502")} ${treePrefix}${commandNameColored}`);
804
- for (let j = 0; j < subcommands.length; j++) {
805
- const subcmd = subcommands[j];
806
- if (!subcmd) continue;
807
- const isLastSubcommand = j === subcommands.length - 1;
808
- const shortDescription = subcmd.description() || "";
809
- const treeChar = isLastSubcommand ? "\u2514" : "\u251C";
810
- const continuation = continuationPrefix ?? (isLastCommand && isLastSubcommand && !hasItemsAfter ? " " : formatDimText("\u2502"));
811
- const continuationStr = continuation === " " ? " " : continuation;
812
- const subTreePrefix = `${continuationStr} ${formatDimText(treeChar)}\u2500 `;
813
- const subTreePrefixWidth = stringWidth(stripAnsi(subTreePrefix));
814
- const subRemainingWidth = LEFT_COLUMN_WIDTH - subTreePrefixWidth;
815
- const subcommandNamePadded = padToFixedWidth(subcmd.name(), subRemainingWidth);
816
- const subcommandNameColored = useColor ? cyan(subcommandNamePadded) : subcommandNamePadded;
817
- lines.push(
818
- `${formatDimText("\u2502")} ${subTreePrefix}${subcommandNameColored} ${shortDescription}`
819
- );
820
- }
821
- } else {
822
- const prefix = isLastCommand && !hasItemsAfter ? formatDimText("\u2514") : formatDimText("\u251C");
823
- const treePrefix = `${prefix}\u2500 `;
824
- const treePrefixWidth = stringWidth(stripAnsi(treePrefix));
825
- const remainingWidth = LEFT_COLUMN_WIDTH - treePrefixWidth;
826
- const commandNamePadded = padToFixedWidth(cmd.name(), remainingWidth);
827
- const commandNameColored = useColor ? cyan(commandNamePadded) : commandNamePadded;
828
- const shortDescription = cmd.description() || "";
829
- lines.push(`${formatDimText("\u2502")} ${treePrefix}${commandNameColored} ${shortDescription}`);
830
- }
831
- }
832
- return lines;
833
- }
834
- function formatMultilineDescription(options) {
835
- const lines = [];
836
- const formatGreen = (text) => options.useColor ? green(text) : text;
837
- const rightColumnWidth = calculateRightColumnWidth();
838
- const totalWidth = 2 + LEFT_COLUMN_WIDTH + 2 + rightColumnWidth;
839
- const wrapWidth = totalWidth - 2;
840
- for (const descLine of options.descriptionLines) {
841
- const formattedLine = descLine.replace(/Prisma Next/g, (match) => formatGreen(match));
842
- const wrappedLines = wrapTextAnsi(formattedLine, wrapWidth);
843
- for (const wrappedLine of wrappedLines) {
844
- lines.push(`${options.formatDimText("\u2502")} ${wrappedLine}`);
845
- }
846
- }
847
- return lines;
848
- }
849
- function formatStyledHeader(options) {
850
- const lines = [];
851
- const useColor = options.flags.color !== false;
852
- const formatDimText = (text) => formatDim(useColor, text);
853
- const brand = createPrismaNextBadge(useColor);
854
- const operation = useColor ? bold(options.command) : options.command;
855
- const intent = formatDimText(options.description);
856
- lines.push(formatHeaderLine({ brand, operation, intent }));
857
- lines.push(formatDimText("\u2502"));
858
- for (const detail of options.details) {
859
- const labelWithColon = `${detail.label}:`;
860
- const labelPadded = padToFixedWidth(labelWithColon, LEFT_COLUMN_WIDTH);
861
- const labelColored = useColor ? cyan(labelPadded) : labelPadded;
862
- lines.push(`${formatDimText("\u2502")} ${labelColored} ${detail.value}`);
863
- }
864
- if (options.url) {
865
- lines.push(formatDimText("\u2502"));
866
- lines.push(
867
- formatReadMoreLine({
868
- url: options.url,
869
- maxLabelWidth: LEFT_COLUMN_WIDTH,
870
- useColor,
871
- formatDimText
872
- })
873
- );
874
- }
875
- lines.push(formatDimText("\u2514"));
876
- return `${lines.join("\n")}
877
- `;
878
- }
879
- function formatSuccessMessage(flags) {
880
- const useColor = flags.color !== false;
881
- const formatGreen = createColorFormatter(useColor, green);
882
- return `${formatGreen("\u2714")} Success`;
883
- }
884
- function getCommandDocsUrl(commandPath) {
885
- const docsMap = {
886
- "contract emit": "https://pris.ly/contract-emit",
887
- "db verify": "https://pris.ly/db-verify"
888
- };
889
- return docsMap[commandPath];
890
- }
891
- function buildCommandPath(command) {
892
- const parts = [];
893
- let current = command;
894
- while (current && current.name() !== "prisma-next") {
895
- parts.unshift(current.name());
896
- current = current.parent ?? void 0;
897
- }
898
- return parts.join(" ");
899
- }
900
- function formatCommandHelp(options) {
901
- const { command, flags } = options;
902
- const lines = [];
903
- const useColor = flags.color !== false;
904
- const formatDimText = (text) => formatDim(useColor, text);
905
- const commandPath = buildCommandPath(command);
906
- const shortDescription = command.description() || "";
907
- const longDescription = getLongDescription(command);
908
- const brand = createPrismaNextBadge(useColor);
909
- const operation = useColor ? bold(commandPath) : commandPath;
910
- const intent = formatDimText(shortDescription);
911
- lines.push(formatHeaderLine({ brand, operation, intent }));
912
- lines.push(formatDimText("\u2502"));
913
- const optionsList = command.options.map((opt) => {
914
- const flags2 = opt.flags;
915
- const description = opt.description || "";
916
- const defaultValue = opt.defaultValue;
917
- return { flags: flags2, description, defaultValue };
918
- });
919
- const subcommands = command.commands.filter((cmd) => !cmd.name().startsWith("_"));
920
- if (subcommands.length > 0) {
921
- const hasItemsAfter = optionsList.length > 0;
922
- const treeLines = renderCommandTree({
923
- commands: subcommands,
924
- useColor,
925
- formatDimText,
926
- hasItemsAfter
927
- });
928
- lines.push(...treeLines);
929
- }
930
- if (subcommands.length > 0 && optionsList.length > 0) {
931
- lines.push(formatDimText("\u2502"));
932
- }
933
- if (optionsList.length > 0) {
934
- for (const opt of optionsList) {
935
- const flagsPadded = padToFixedWidth(opt.flags, LEFT_COLUMN_WIDTH);
936
- let flagsColored = flagsPadded;
937
- if (useColor) {
938
- flagsColored = flagsPadded.replace(/(<[^>]+>)/g, (match) => magenta(match));
939
- flagsColored = cyan(flagsColored);
940
- }
941
- const rightColumnWidth = calculateRightColumnWidth();
942
- const wrappedDescription = wrapTextAnsi(opt.description, rightColumnWidth);
943
- lines.push(`${formatDimText("\u2502")} ${flagsColored} ${wrappedDescription[0] || ""}`);
944
- for (let i = 1; i < wrappedDescription.length; i++) {
945
- const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
946
- lines.push(`${formatDimText("\u2502")} ${emptyLabel} ${wrappedDescription[i] || ""}`);
947
- }
948
- if (opt.defaultValue !== void 0) {
949
- const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
950
- const defaultText = formatDefaultValue(opt.defaultValue, useColor);
951
- lines.push(`${formatDimText("\u2502")} ${emptyLabel} ${defaultText}`);
952
- }
953
- }
954
- }
955
- const docsUrl = getCommandDocsUrl(commandPath);
956
- if (docsUrl) {
957
- lines.push(formatDimText("\u2502"));
958
- lines.push(
959
- formatReadMoreLine({
960
- url: docsUrl,
961
- maxLabelWidth: LEFT_COLUMN_WIDTH,
962
- useColor,
963
- formatDimText
964
- })
965
- );
966
- }
967
- if (longDescription) {
968
- lines.push(formatDimText("\u2502"));
969
- const descriptionLines = longDescription.split("\n").filter((line) => line.trim().length > 0);
970
- lines.push(...formatMultilineDescription({ descriptionLines, useColor, formatDimText }));
971
- }
972
- lines.push(formatDimText("\u2514"));
973
- return `${lines.join("\n")}
974
- `;
975
- }
976
- function formatRootHelp(options) {
977
- const { program: program2, flags } = options;
978
- const lines = [];
979
- const useColor = flags.color !== false;
980
- const formatDimText = (text) => formatDim(useColor, text);
981
- const brand = createPrismaNextBadge(useColor);
982
- const shortDescription = "Manage your data layer";
983
- const intent = formatDimText(shortDescription);
984
- lines.push(formatHeaderLine({ brand, operation: "", intent }));
985
- lines.push(formatDimText("\u2502"));
986
- const topLevelCommands = program2.commands.filter(
987
- (cmd) => !cmd.name().startsWith("_") && cmd.name() !== "help"
988
- );
989
- const globalOptions = program2.options.map((opt) => {
990
- const flags2 = opt.flags;
991
- const description = opt.description || "";
992
- const defaultValue = opt.defaultValue;
993
- return { flags: flags2, description, defaultValue };
994
- });
995
- if (topLevelCommands.length > 0) {
996
- const hasItemsAfter = globalOptions.length > 0;
997
- const treeLines = renderCommandTree({
998
- commands: topLevelCommands,
999
- useColor,
1000
- formatDimText,
1001
- hasItemsAfter
1002
- });
1003
- lines.push(...treeLines);
1004
- }
1005
- if (topLevelCommands.length > 0 && globalOptions.length > 0) {
1006
- lines.push(formatDimText("\u2502"));
1007
- }
1008
- if (globalOptions.length > 0) {
1009
- for (const opt of globalOptions) {
1010
- const flagsPadded = padToFixedWidth(opt.flags, LEFT_COLUMN_WIDTH);
1011
- let flagsColored = flagsPadded;
1012
- if (useColor) {
1013
- flagsColored = flagsPadded.replace(/(<[^>]+>)/g, (match) => magenta(match));
1014
- flagsColored = cyan(flagsColored);
1015
- }
1016
- const rightColumnWidth = calculateRightColumnWidth();
1017
- const wrappedDescription = wrapTextAnsi(opt.description, rightColumnWidth);
1018
- lines.push(`${formatDimText("\u2502")} ${flagsColored} ${wrappedDescription[0] || ""}`);
1019
- for (let i = 1; i < wrappedDescription.length; i++) {
1020
- const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
1021
- lines.push(`${formatDimText("\u2502")} ${emptyLabel} ${wrappedDescription[i] || ""}`);
1022
- }
1023
- if (opt.defaultValue !== void 0) {
1024
- const emptyLabel = " ".repeat(LEFT_COLUMN_WIDTH);
1025
- const defaultText = formatDefaultValue(opt.defaultValue, useColor);
1026
- lines.push(`${formatDimText("\u2502")} ${emptyLabel} ${defaultText}`);
1027
- }
1028
- }
1029
- }
1030
- const formatGreen = (text) => useColor ? green(text) : text;
1031
- const descriptionLines = [
1032
- `Use ${formatGreen("Prisma Next")} to define your data layer as a contract. Sign your database and application with the same contract to guarantee compatibility. Plan and apply migrations to safely evolve your schema.`
1033
- ];
1034
- if (descriptionLines.length > 0) {
1035
- lines.push(formatDimText("\u2502"));
1036
- lines.push(...formatMultilineDescription({ descriptionLines, useColor, formatDimText }));
1037
- }
1038
- lines.push(formatDimText("\u2514"));
1039
- return `${lines.join("\n")}
1040
- `;
1041
- }
1042
-
1043
- // src/utils/result-handler.ts
1044
- function handleResult(result, flags, onSuccess) {
1045
- if (result.ok) {
1046
- if (onSuccess) {
1047
- onSuccess(result.value);
1048
- }
1049
- return 0;
1050
- }
1051
- const envelope = result.failure.toEnvelope();
1052
- if (flags.json) {
1053
- console.error(formatErrorJson(envelope));
1054
- } else {
1055
- console.error(formatErrorOutput(envelope, flags));
1056
- }
1057
- const exitCode = result.failure.domain === "CLI" ? 2 : 1;
1058
- return exitCode;
1059
- }
1060
-
1061
- // src/utils/spinner.ts
1062
- import ora from "ora";
1063
- async function withSpinner(operation, options) {
1064
- const { message, flags } = options;
1065
- const shouldShowSpinner = !flags.quiet && flags.json !== "object" && process.stdout.isTTY;
1066
- if (!shouldShowSpinner) {
1067
- return operation();
1068
- }
1069
- const startTime = Date.now();
1070
- const spinner = ora({
1071
- text: message,
1072
- color: flags.color !== false ? "cyan" : false
1073
- }).start();
1074
- try {
1075
- const result = await operation();
1076
- const elapsed = Date.now() - startTime;
1077
- spinner.succeed(`${message} (${elapsed}ms)`);
1078
- return result;
1079
- } catch (error) {
1080
- spinner.fail(`${message} failed: ${error instanceof Error ? error.message : String(error)}`);
1081
- throw error;
1082
- }
1083
- }
1084
-
1085
- // src/commands/contract-emit.ts
1086
- function createContractEmitCommand() {
1087
- const command = new Command("emit");
1088
- setCommandDescriptions(
1089
- command,
1090
- "Write your contract to JSON and sign it",
1091
- "Reads your contract source (TypeScript or Prisma schema) and emits contract.json and\ncontract.d.ts. The contract.json contains the canonical contract structure, and\ncontract.d.ts provides TypeScript types for type-safe query building."
1092
- );
1093
- command.configureHelp({
1094
- formatHelp: (cmd) => {
1095
- const flags = parseGlobalFlags({});
1096
- return formatCommandHelp({ command: cmd, flags });
1097
- }
1098
- }).option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1099
- const flags = parseGlobalFlags(options);
1100
- const result = await performAction(async () => {
1101
- const config = await loadConfig(options.config);
1102
- if (!config.contract) {
1103
- throw errorContractConfigMissing2({
1104
- why: "Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ..., types: ... }"
1105
- });
1106
- }
1107
- const contractConfig = config.contract;
1108
- if (!contractConfig.output || !contractConfig.types) {
1109
- throw errorContractConfigMissing2({
1110
- why: "Contract config must have output and types paths. This should not happen if defineConfig() was used."
1111
- });
1112
- }
1113
- const outputJsonPath = resolve2(contractConfig.output);
1114
- const outputDtsPath = resolve2(contractConfig.types);
1115
- if (flags.json !== "object" && !flags.quiet) {
1116
- const configPath = options.config ? relative2(process.cwd(), resolve2(options.config)) : "prisma-next.config.ts";
1117
- const contractPath = relative2(process.cwd(), outputJsonPath);
1118
- const typesPath = relative2(process.cwd(), outputDtsPath);
1119
- const header = formatStyledHeader({
1120
- command: "contract emit",
1121
- description: "Write your contract to JSON and sign it",
1122
- url: "https://pris.ly/contract-emit",
1123
- details: [
1124
- { label: "config", value: configPath },
1125
- { label: "contract", value: contractPath },
1126
- { label: "types", value: typesPath }
1127
- ],
1128
- flags
1129
- });
1130
- console.log(header);
1131
- }
1132
- if (!config.driver) {
1133
- throw errorContractConfigMissing2({
1134
- why: "Config.driver is required. Even though emit does not use the driver, it is required by ControlFamilyDescriptor.create()"
1135
- });
1136
- }
1137
- const familyInstance = config.family.create({
1138
- target: config.target,
1139
- adapter: config.adapter,
1140
- driver: config.driver,
1141
- extensionPacks: config.extensionPacks ?? []
1142
- });
1143
- let contractRaw;
1144
- if (typeof contractConfig.source === "function") {
1145
- contractRaw = await contractConfig.source();
1146
- } else {
1147
- contractRaw = contractConfig.source;
1148
- }
1149
- const emitResult = await withSpinner(
1150
- () => familyInstance.emitContract({ contractIR: contractRaw }),
1151
- {
1152
- message: "Emitting contract...",
1153
- flags
1154
- }
1155
- );
1156
- mkdirSync(dirname2(outputJsonPath), { recursive: true });
1157
- mkdirSync(dirname2(outputDtsPath), { recursive: true });
1158
- writeFileSync(outputJsonPath, emitResult.contractJson, "utf-8");
1159
- writeFileSync(outputDtsPath, emitResult.contractDts, "utf-8");
1160
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
1161
- console.log("");
1162
- }
1163
- return {
1164
- coreHash: emitResult.coreHash,
1165
- profileHash: emitResult.profileHash,
1166
- outDir: dirname2(outputJsonPath),
1167
- files: {
1168
- json: outputJsonPath,
1169
- dts: outputDtsPath
1170
- },
1171
- timings: {
1172
- total: 0
1173
- // Timing is handled by emitContract internally if needed
1174
- }
1175
- };
1176
- });
1177
- const exitCode = handleResult(result, flags, (emitResult) => {
1178
- if (flags.json === "object") {
1179
- console.log(formatEmitJson(emitResult));
1180
- } else {
1181
- const output = formatEmitOutput(emitResult, flags);
1182
- if (output) {
1183
- console.log(output);
1184
- }
1185
- if (!flags.quiet) {
1186
- console.log(formatSuccessMessage(flags));
1187
- }
1188
- }
1189
- });
1190
- process.exit(exitCode);
1191
- });
1192
- return command;
1193
- }
1194
-
1195
- // src/commands/db-init.ts
1196
- import { readFile } from "fs/promises";
1197
- import { relative as relative3, resolve as resolve3 } from "path";
1198
- import { redactDatabaseUrl } from "@prisma-next/utils/redact-db-url";
1199
- import { Command as Command2 } from "commander";
1200
-
1201
- // src/utils/framework-components.ts
1202
- import {
1203
- checkContractComponentRequirements
1204
- } from "@prisma-next/contract/framework-components";
1205
- function assertFrameworkComponentsCompatible(expectedFamilyId, expectedTargetId, frameworkComponents) {
1206
- for (let i = 0; i < frameworkComponents.length; i++) {
1207
- const component = frameworkComponents[i];
1208
- if (typeof component !== "object" || component === null) {
1209
- throw errorConfigValidation("frameworkComponents[]", {
1210
- why: `Framework component at index ${i} must be an object`
1211
- });
1212
- }
1213
- const record = component;
1214
- if (!Object.hasOwn(record, "kind")) {
1215
- throw errorConfigValidation("frameworkComponents[].kind", {
1216
- why: `Framework component at index ${i} must have 'kind' property`
1217
- });
1218
- }
1219
- const kind = record["kind"];
1220
- if (kind !== "target" && kind !== "adapter" && kind !== "extension" && kind !== "driver") {
1221
- throw errorConfigValidation("frameworkComponents[].kind", {
1222
- why: `Framework component at index ${i} has invalid kind '${String(kind)}' (must be 'target', 'adapter', 'extension', or 'driver')`
1223
- });
1224
- }
1225
- if (!Object.hasOwn(record, "familyId")) {
1226
- throw errorConfigValidation("frameworkComponents[].familyId", {
1227
- why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'familyId' property`
1228
- });
1229
- }
1230
- const familyId = record["familyId"];
1231
- if (familyId !== expectedFamilyId) {
1232
- throw errorConfigValidation("frameworkComponents[].familyId", {
1233
- why: `Framework component at index ${i} (kind: ${String(kind)}) has familyId '${String(familyId)}' but expected '${expectedFamilyId}'`
1234
- });
1235
- }
1236
- if (!Object.hasOwn(record, "targetId")) {
1237
- throw errorConfigValidation("frameworkComponents[].targetId", {
1238
- why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'targetId' property`
1239
- });
1240
- }
1241
- const targetId = record["targetId"];
1242
- if (targetId !== expectedTargetId) {
1243
- throw errorConfigValidation("frameworkComponents[].targetId", {
1244
- why: `Framework component at index ${i} (kind: ${String(kind)}) has targetId '${String(targetId)}' but expected '${expectedTargetId}'`
1245
- });
1246
- }
1247
- }
1248
- return frameworkComponents;
1249
- }
1250
- function assertContractRequirementsSatisfied({
1251
- contract,
1252
- family,
1253
- target,
1254
- adapter,
1255
- extensionPacks
1256
- }) {
1257
- const providedComponentIds = /* @__PURE__ */ new Set([target.id, adapter.id]);
1258
- for (const extension of extensionPacks ?? []) {
1259
- providedComponentIds.add(extension.id);
1260
- }
1261
- const result = checkContractComponentRequirements({
1262
- contract,
1263
- expectedTargetFamily: family.familyId,
1264
- expectedTargetId: target.targetId,
1265
- providedComponentIds
1266
- });
1267
- if (result.familyMismatch) {
1268
- throw errorConfigValidation("contract.targetFamily", {
1269
- why: `Contract was emitted for family '${result.familyMismatch.actual}' but CLI config is wired to '${result.familyMismatch.expected}'.`
1270
- });
1271
- }
1272
- if (result.targetMismatch) {
1273
- throw errorConfigValidation("contract.target", {
1274
- why: `Contract target '${result.targetMismatch.actual}' does not match CLI target '${result.targetMismatch.expected}'.`
1275
- });
1276
- }
1277
- if (result.missingExtensionPackIds.length > 0) {
1278
- throw errorContractMissingExtensionPacks({
1279
- missingExtensionPacks: result.missingExtensionPackIds,
1280
- providedComponentIds: [...providedComponentIds]
1281
- });
1282
- }
1283
- }
1284
-
1285
- // src/commands/db-init.ts
1286
- function createDbInitCommand() {
1287
- const command = new Command2("init");
1288
- setCommandDescriptions(
1289
- command,
1290
- "Bootstrap a database to match the current contract and write the contract marker",
1291
- "Initializes a database to match your emitted contract using additive-only operations.\nCreates any missing tables, columns, indexes, and constraints defined in your contract.\nLeaves existing compatible structures in place, surfaces conflicts when destructive changes\nwould be required, and writes a contract marker to track the database state. Use --plan to\npreview changes without applying."
1292
- );
1293
- command.configureHelp({
1294
- formatHelp: (cmd) => {
1295
- const flags = parseGlobalFlags({});
1296
- return formatCommandHelp({ command: cmd, flags });
1297
- }
1298
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--plan", "Preview planned operations without applying", false).option("--json [format]", "Output as JSON (object)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1299
- const flags = parseGlobalFlags(options);
1300
- const startTime = Date.now();
1301
- const result = await performAction(async () => {
1302
- if (flags.json === "ndjson") {
1303
- throw errorJsonFormatNotSupported({
1304
- command: "db init",
1305
- format: "ndjson",
1306
- supportedFormats: ["object"]
1307
- });
1308
- }
1309
- const config = await loadConfig(options.config);
1310
- const configPath = options.config ? relative3(process.cwd(), resolve3(options.config)) : "prisma-next.config.ts";
1311
- const contractPathAbsolute = config.contract?.output ? resolve3(config.contract.output) : resolve3("src/prisma/contract.json");
1312
- const contractPath = relative3(process.cwd(), contractPathAbsolute);
1313
- if (flags.json !== "object" && !flags.quiet) {
1314
- const details = [
1315
- { label: "config", value: configPath },
1316
- { label: "contract", value: contractPath }
1317
- ];
1318
- if (options.db) {
1319
- details.push({ label: "database", value: options.db });
1320
- }
1321
- if (options.plan) {
1322
- details.push({ label: "mode", value: "plan (dry run)" });
1323
- }
1324
- const header = formatStyledHeader({
1325
- command: "db init",
1326
- description: "Bootstrap a database to match the current contract",
1327
- url: "https://pris.ly/db-init",
1328
- details,
1329
- flags
1330
- });
1331
- console.log(header);
1332
- }
1333
- let contractJsonContent;
1334
- try {
1335
- contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
1336
- } catch (error) {
1337
- if (error instanceof Error && error.code === "ENOENT") {
1338
- throw errorFileNotFound(contractPathAbsolute, {
1339
- why: `Contract file not found at ${contractPathAbsolute}`,
1340
- fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
1341
- });
1342
- }
1343
- throw errorUnexpected2(error instanceof Error ? error.message : String(error), {
1344
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
1345
- });
1346
- }
1347
- let contractJson;
1348
- try {
1349
- contractJson = JSON.parse(contractJsonContent);
1350
- } catch (error) {
1351
- throw errorContractValidationFailed(
1352
- `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
1353
- { where: { path: contractPathAbsolute } }
1354
- );
1355
- }
1356
- const dbUrl = options.db ?? config.db?.url;
1357
- if (!dbUrl) {
1358
- throw errorDatabaseUrlRequired({
1359
- why: `Database URL is required for db init (set db.url in ${configPath}, or pass --db <url>)`
1360
- });
1361
- }
1362
- if (!config.driver) {
1363
- throw errorDriverRequired({ why: "Config.driver is required for db init" });
1364
- }
1365
- const driverDescriptor = config.driver;
1366
- if (!config.target.migrations) {
1367
- throw errorTargetMigrationNotSupported({
1368
- why: `Target "${config.target.id}" does not support migrations`
1369
- });
1370
- }
1371
- const migrations = config.target.migrations;
1372
- let driver;
1373
- try {
1374
- driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
1375
- message: "Connecting to database...",
1376
- flags
1377
- });
1378
- } catch (error) {
1379
- const message = error instanceof Error ? error.message : String(error);
1380
- const code = error.code;
1381
- const redacted = redactDatabaseUrl(dbUrl);
1382
- throw errorRuntime("Database connection failed", {
1383
- why: message,
1384
- fix: "Verify the database URL, ensure the database is reachable, and confirm credentials/permissions",
1385
- meta: {
1386
- ...typeof code !== "undefined" ? { code } : {},
1387
- ...redacted
1388
- }
1389
- });
1390
- }
1391
- try {
1392
- const familyInstance = config.family.create({
1393
- target: config.target,
1394
- adapter: config.adapter,
1395
- driver: driverDescriptor,
1396
- extensionPacks: config.extensionPacks ?? []
1397
- });
1398
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
1399
- const frameworkComponents = assertFrameworkComponentsCompatible(
1400
- config.family.familyId,
1401
- config.target.targetId,
1402
- rawComponents
1403
- );
1404
- const contractIR = familyInstance.validateContractIR(contractJson);
1405
- assertContractRequirementsSatisfied({
1406
- contract: contractIR,
1407
- family: config.family,
1408
- target: config.target,
1409
- adapter: config.adapter,
1410
- extensionPacks: config.extensionPacks
1411
- });
1412
- const planner = migrations.createPlanner(familyInstance);
1413
- const runner = migrations.createRunner(familyInstance);
1414
- const schemaIR = await withSpinner(() => familyInstance.introspect({ driver }), {
1415
- message: "Introspecting database schema...",
1416
- flags
1417
- });
1418
- const policy = { allowedOperationClasses: ["additive"] };
1419
- const plannerResult = await withSpinner(
1420
- async () => planner.plan({
1421
- contract: contractIR,
1422
- schema: schemaIR,
1423
- policy,
1424
- frameworkComponents
1425
- }),
1426
- {
1427
- message: "Planning migration...",
1428
- flags
1429
- }
1430
- );
1431
- if (plannerResult.kind === "failure") {
1432
- throw errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts });
1433
- }
1434
- const migrationPlan = plannerResult.plan;
1435
- const existingMarker = await familyInstance.readMarker({ driver });
1436
- if (existingMarker) {
1437
- const markerMatchesDestination = existingMarker.coreHash === migrationPlan.destination.coreHash && (!migrationPlan.destination.profileHash || existingMarker.profileHash === migrationPlan.destination.profileHash);
1438
- if (markerMatchesDestination) {
1439
- const dbInitResult2 = {
1440
- ok: true,
1441
- mode: options.plan ? "plan" : "apply",
1442
- plan: {
1443
- targetId: migrationPlan.targetId,
1444
- destination: migrationPlan.destination,
1445
- operations: []
1446
- },
1447
- ...options.plan ? {} : {
1448
- execution: { operationsPlanned: 0, operationsExecuted: 0 },
1449
- marker: {
1450
- coreHash: existingMarker.coreHash,
1451
- profileHash: existingMarker.profileHash
1452
- }
1453
- },
1454
- summary: "Database already at target contract state",
1455
- timings: { total: Date.now() - startTime }
1456
- };
1457
- return dbInitResult2;
1458
- }
1459
- const coreHashMismatch = existingMarker.coreHash !== migrationPlan.destination.coreHash;
1460
- const profileHashMismatch = migrationPlan.destination.profileHash && existingMarker.profileHash !== migrationPlan.destination.profileHash;
1461
- const mismatchParts = [];
1462
- if (coreHashMismatch) {
1463
- mismatchParts.push(
1464
- `coreHash (marker: ${existingMarker.coreHash}, destination: ${migrationPlan.destination.coreHash})`
1465
- );
1466
- }
1467
- if (profileHashMismatch) {
1468
- mismatchParts.push(
1469
- `profileHash (marker: ${existingMarker.profileHash}, destination: ${migrationPlan.destination.profileHash})`
1470
- );
1471
- }
1472
- throw errorRuntime(
1473
- `Existing contract marker does not match plan destination. Mismatch in ${mismatchParts.join(" and ")}.`,
1474
- {
1475
- why: "Database has an existing contract marker that does not match the target contract",
1476
- fix: "If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow",
1477
- meta: {
1478
- code: "MARKER_ORIGIN_MISMATCH",
1479
- markerCoreHash: existingMarker.coreHash,
1480
- destinationCoreHash: migrationPlan.destination.coreHash,
1481
- ...existingMarker.profileHash ? { markerProfileHash: existingMarker.profileHash } : {},
1482
- ...migrationPlan.destination.profileHash ? { destinationProfileHash: migrationPlan.destination.profileHash } : {}
1483
- }
1484
- }
1485
- );
1486
- }
1487
- if (options.plan) {
1488
- const dbInitResult2 = {
1489
- ok: true,
1490
- mode: "plan",
1491
- plan: {
1492
- targetId: migrationPlan.targetId,
1493
- destination: migrationPlan.destination,
1494
- operations: migrationPlan.operations.map((op) => ({
1495
- id: op.id,
1496
- label: op.label,
1497
- operationClass: op.operationClass
1498
- }))
1499
- },
1500
- summary: `Planned ${migrationPlan.operations.length} operation(s)`,
1501
- timings: { total: Date.now() - startTime }
1502
- };
1503
- return dbInitResult2;
1504
- }
1505
- if (!flags.quiet && flags.json !== "object") {
1506
- console.log("Applying migration plan and verifying schema...");
1507
- }
1508
- const callbacks = {
1509
- onOperationStart: (op) => {
1510
- if (!flags.quiet && flags.json !== "object") {
1511
- console.log(` \u2192 ${op.label}...`);
1512
- }
1513
- },
1514
- onOperationComplete: (_op) => {
1515
- }
1516
- };
1517
- const runnerResult = await runner.execute({
1518
- plan: migrationPlan,
1519
- driver,
1520
- destinationContract: contractIR,
1521
- policy,
1522
- callbacks,
1523
- // db init plans and applies back-to-back from a fresh introspection, so per-operation
1524
- // pre/postchecks and the idempotency probe are usually redundant overhead. We still
1525
- // enforce marker/origin compatibility and a full schema verification after apply.
1526
- executionChecks: {
1527
- prechecks: false,
1528
- postchecks: false,
1529
- idempotencyChecks: false
1530
- },
1531
- frameworkComponents
1532
- });
1533
- if (!runnerResult.ok) {
1534
- const meta = {
1535
- code: runnerResult.failure.code,
1536
- ...runnerResult.failure.meta ?? {}
1537
- };
1538
- const sqlState = typeof meta["sqlState"] === "string" ? meta["sqlState"] : void 0;
1539
- const fix = sqlState === "42501" ? "Grant the database user sufficient privileges (insufficient_privilege), or run db init as a more privileged role" : runnerResult.failure.code === "SCHEMA_VERIFY_FAILED" ? "Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`" : void 0;
1540
- throw errorRuntime(runnerResult.failure.summary, {
1541
- why: runnerResult.failure.why ?? `Migration runner failed: ${runnerResult.failure.code}`,
1542
- ...fix ? { fix } : {},
1543
- meta
1544
- });
1545
- }
1546
- const execution = runnerResult.value;
1547
- const dbInitResult = {
1548
- ok: true,
1549
- mode: "apply",
1550
- plan: {
1551
- targetId: migrationPlan.targetId,
1552
- destination: migrationPlan.destination,
1553
- operations: migrationPlan.operations.map((op) => ({
1554
- id: op.id,
1555
- label: op.label,
1556
- operationClass: op.operationClass
1557
- }))
1558
- },
1559
- execution: {
1560
- operationsPlanned: execution.operationsPlanned,
1561
- operationsExecuted: execution.operationsExecuted
1562
- },
1563
- marker: migrationPlan.destination.profileHash ? {
1564
- coreHash: migrationPlan.destination.coreHash,
1565
- profileHash: migrationPlan.destination.profileHash
1566
- } : { coreHash: migrationPlan.destination.coreHash },
1567
- summary: `Applied ${execution.operationsExecuted} operation(s), marker written`,
1568
- timings: { total: Date.now() - startTime }
1569
- };
1570
- return dbInitResult;
1571
- } finally {
1572
- await driver.close();
1573
- }
1574
- });
1575
- const exitCode = handleResult(result, flags, (dbInitResult) => {
1576
- if (flags.json === "object") {
1577
- console.log(formatDbInitJson(dbInitResult));
1578
- } else {
1579
- const output = dbInitResult.mode === "plan" ? formatDbInitPlanOutput(dbInitResult, flags) : formatDbInitApplyOutput(dbInitResult, flags);
1580
- if (output) {
1581
- console.log(output);
1582
- }
1583
- }
1584
- });
1585
- process.exit(exitCode);
1586
- });
1587
- return command;
1588
- }
1589
-
1590
- // src/commands/db-introspect.ts
1591
- import { readFile as readFile2 } from "fs/promises";
1592
- import { relative as relative4, resolve as resolve4 } from "path";
1593
- import {
1594
- errorDatabaseUrlRequired as errorDatabaseUrlRequired2,
1595
- errorDriverRequired as errorDriverRequired2,
1596
- errorRuntime as errorRuntime2,
1597
- errorUnexpected as errorUnexpected3
1598
- } from "@prisma-next/core-control-plane/errors";
1599
- import { Command as Command3 } from "commander";
1600
- function createDbIntrospectCommand() {
1601
- const command = new Command3("introspect");
1602
- setCommandDescriptions(
1603
- command,
1604
- "Inspect the database schema",
1605
- "Reads the live database schema and displays it as a tree structure. This command\ndoes not check the schema against your contract - it only shows what exists in\nthe database. Use `db verify` or `db schema-verify` to compare against your contract."
1606
- );
1607
- command.configureHelp({
1608
- formatHelp: (cmd) => {
1609
- const flags = parseGlobalFlags({});
1610
- return formatCommandHelp({ command: cmd, flags });
1611
- }
1612
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1613
- const flags = parseGlobalFlags(options);
1614
- const result = await performAction(async () => {
1615
- const startTime = Date.now();
1616
- const config = await loadConfig(options.config);
1617
- const configPath = options.config ? relative4(process.cwd(), resolve4(options.config)) : "prisma-next.config.ts";
1618
- let contractIR;
1619
- if (config.contract?.output) {
1620
- const contractPath = resolve4(config.contract.output);
1621
- try {
1622
- const contractJsonContent = await readFile2(contractPath, "utf-8");
1623
- contractIR = JSON.parse(contractJsonContent);
1624
- } catch (error) {
1625
- if (error instanceof Error && error.code !== "ENOENT") {
1626
- throw errorUnexpected3(error.message, {
1627
- why: `Failed to read contract file: ${error.message}`
1628
- });
1629
- }
1630
- }
1631
- }
1632
- if (flags.json !== "object" && !flags.quiet) {
1633
- const details = [
1634
- { label: "config", value: configPath }
1635
- ];
1636
- if (options.db) {
1637
- const maskedUrl = options.db.replace(/:([^:@]+)@/, ":****@");
1638
- details.push({ label: "database", value: maskedUrl });
1639
- } else if (config.db?.url) {
1640
- const maskedUrl = config.db.url.replace(/:([^:@]+)@/, ":****@");
1641
- details.push({ label: "database", value: maskedUrl });
1642
- }
1643
- const header = formatStyledHeader({
1644
- command: "db introspect",
1645
- description: "Inspect the database schema",
1646
- url: "https://pris.ly/db-introspect",
1647
- details,
1648
- flags
1649
- });
1650
- console.log(header);
1651
- }
1652
- const dbUrl = options.db ?? config.db?.url;
1653
- if (!dbUrl) {
1654
- throw errorDatabaseUrlRequired2();
1655
- }
1656
- if (!config.driver) {
1657
- throw errorDriverRequired2();
1658
- }
1659
- const driverDescriptor = config.driver;
1660
- const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
1661
- message: "Connecting to database...",
1662
- flags
1663
- });
1664
- try {
1665
- const familyInstance = config.family.create({
1666
- target: config.target,
1667
- adapter: config.adapter,
1668
- driver: driverDescriptor,
1669
- extensionPacks: config.extensionPacks ?? []
1670
- });
1671
- if (contractIR) {
1672
- const validatedContract = familyInstance.validateContractIR(contractIR);
1673
- assertContractRequirementsSatisfied({
1674
- contract: validatedContract,
1675
- family: config.family,
1676
- target: config.target,
1677
- adapter: config.adapter,
1678
- extensionPacks: config.extensionPacks
1679
- });
1680
- contractIR = validatedContract;
1681
- }
1682
- let schemaIR;
1683
- try {
1684
- schemaIR = await withSpinner(
1685
- () => familyInstance.introspect({
1686
- driver,
1687
- contractIR
1688
- }),
1689
- {
1690
- message: "Introspecting database schema...",
1691
- flags
1692
- }
1693
- );
1694
- } catch (error) {
1695
- throw errorRuntime2(error instanceof Error ? error.message : String(error), {
1696
- why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`
1697
- });
1698
- }
1699
- let schemaView;
1700
- if (familyInstance.toSchemaView) {
1701
- try {
1702
- schemaView = familyInstance.toSchemaView(schemaIR);
1703
- } catch (error) {
1704
- if (flags.verbose) {
1705
- console.error(
1706
- `Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`
1707
- );
1708
- }
1709
- }
1710
- }
1711
- const totalTime = Date.now() - startTime;
1712
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
1713
- console.log("");
1714
- }
1715
- const introspectResult = {
1716
- ok: true,
1717
- summary: "Schema introspected successfully",
1718
- target: {
1719
- familyId: config.family.familyId,
1720
- id: config.target.targetId
1721
- },
1722
- schema: schemaIR,
1723
- ...configPath || options.db || config.db?.url ? {
1724
- meta: {
1725
- ...configPath ? { configPath } : {},
1726
- ...options.db || config.db?.url ? {
1727
- dbUrl: (options.db ?? config.db?.url ?? "").replace(
1728
- /:([^:@]+)@/,
1729
- ":****@"
1730
- )
1731
- } : {}
1732
- }
1733
- } : {},
1734
- timings: {
1735
- total: totalTime
1736
- }
1737
- };
1738
- return { introspectResult, schemaView };
1739
- } finally {
1740
- await driver.close();
1741
- }
1742
- });
1743
- const exitCode = handleResult(result, flags, (value) => {
1744
- const { introspectResult, schemaView } = value;
1745
- if (flags.json === "object") {
1746
- console.log(formatIntrospectJson(introspectResult));
1747
- } else {
1748
- const output = formatIntrospectOutput(introspectResult, schemaView, flags);
1749
- if (output) {
1750
- console.log(output);
1751
- }
1752
- }
1753
- });
1754
- process.exit(exitCode);
1755
- });
1756
- return command;
1757
- }
1758
-
1759
- // src/commands/db-schema-verify.ts
1760
- import { readFile as readFile3 } from "fs/promises";
1761
- import { relative as relative5, resolve as resolve5 } from "path";
1762
- import {
1763
- errorDatabaseUrlRequired as errorDatabaseUrlRequired3,
1764
- errorDriverRequired as errorDriverRequired3,
1765
- errorFileNotFound as errorFileNotFound2,
1766
- errorRuntime as errorRuntime3,
1767
- errorUnexpected as errorUnexpected4
1768
- } from "@prisma-next/core-control-plane/errors";
1769
- import { Command as Command4 } from "commander";
1770
- function createDbSchemaVerifyCommand() {
1771
- const command = new Command4("schema-verify");
1772
- setCommandDescriptions(
1773
- command,
1774
- "Check whether the database schema satisfies your contract",
1775
- "Verifies that your database schema satisfies the emitted contract. Compares table structures,\ncolumn types, constraints, and extensions. Reports any mismatches via a contract-shaped\nverification tree. This is a read-only operation that does not modify the database."
1776
- );
1777
- command.configureHelp({
1778
- formatHelp: (cmd) => {
1779
- const flags = parseGlobalFlags({});
1780
- return formatCommandHelp({ command: cmd, flags });
1781
- }
1782
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("--strict", "Strict mode: extra schema elements cause failures", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1783
- const flags = parseGlobalFlags(options);
1784
- const result = await performAction(async () => {
1785
- const config = await loadConfig(options.config);
1786
- const configPath = options.config ? relative5(process.cwd(), resolve5(options.config)) : "prisma-next.config.ts";
1787
- const contractPathAbsolute = config.contract?.output ? resolve5(config.contract.output) : resolve5("src/prisma/contract.json");
1788
- const contractPath = relative5(process.cwd(), contractPathAbsolute);
1789
- if (flags.json !== "object" && !flags.quiet) {
1790
- const details = [
1791
- { label: "config", value: configPath },
1792
- { label: "contract", value: contractPath }
1793
- ];
1794
- if (options.db) {
1795
- details.push({ label: "database", value: options.db });
1796
- }
1797
- const header = formatStyledHeader({
1798
- command: "db schema-verify",
1799
- description: "Check whether the database schema satisfies your contract",
1800
- url: "https://pris.ly/db-schema-verify",
1801
- details,
1802
- flags
1803
- });
1804
- console.log(header);
1805
- }
1806
- let contractJsonContent;
1807
- try {
1808
- contractJsonContent = await readFile3(contractPathAbsolute, "utf-8");
1809
- } catch (error) {
1810
- if (error instanceof Error && error.code === "ENOENT") {
1811
- throw errorFileNotFound2(contractPathAbsolute, {
1812
- why: `Contract file not found at ${contractPathAbsolute}`
1813
- });
1814
- }
1815
- throw errorUnexpected4(error instanceof Error ? error.message : String(error), {
1816
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
1817
- });
1818
- }
1819
- const contractJson = JSON.parse(contractJsonContent);
1820
- if (!config.driver) {
1821
- throw errorDriverRequired3();
1822
- }
1823
- const driverDescriptor = config.driver;
1824
- const familyInstance = config.family.create({
1825
- target: config.target,
1826
- adapter: config.adapter,
1827
- driver: driverDescriptor,
1828
- extensionPacks: config.extensionPacks ?? []
1829
- });
1830
- const contractIR = familyInstance.validateContractIR(contractJson);
1831
- assertContractRequirementsSatisfied({
1832
- contract: contractIR,
1833
- family: config.family,
1834
- target: config.target,
1835
- adapter: config.adapter,
1836
- extensionPacks: config.extensionPacks
1837
- });
1838
- const dbUrl = options.db ?? config.db?.url;
1839
- if (!dbUrl) {
1840
- throw errorDatabaseUrlRequired3();
1841
- }
1842
- const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
1843
- message: "Connecting to database...",
1844
- flags
1845
- });
1846
- try {
1847
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
1848
- const frameworkComponents = assertFrameworkComponentsCompatible(
1849
- config.family.familyId,
1850
- config.target.targetId,
1851
- rawComponents
1852
- );
1853
- let schemaVerifyResult;
1854
- try {
1855
- schemaVerifyResult = await withSpinner(
1856
- () => familyInstance.schemaVerify({
1857
- driver,
1858
- contractIR,
1859
- strict: options.strict ?? false,
1860
- contractPath: contractPathAbsolute,
1861
- configPath,
1862
- frameworkComponents
1863
- }),
1864
- {
1865
- message: "Verifying database schema...",
1866
- flags
1867
- }
1868
- );
1869
- } catch (error) {
1870
- throw errorRuntime3(error instanceof Error ? error.message : String(error), {
1871
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
1872
- });
1873
- }
1874
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
1875
- console.log("");
1876
- }
1877
- return schemaVerifyResult;
1878
- } finally {
1879
- await driver.close();
1880
- }
1881
- });
1882
- const exitCode = handleResult(result, flags, (schemaVerifyResult) => {
1883
- if (flags.json === "object") {
1884
- console.log(formatSchemaVerifyJson(schemaVerifyResult));
1885
- } else {
1886
- const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
1887
- if (output) {
1888
- console.log(output);
1889
- }
1890
- }
1891
- });
1892
- if (result.ok && !result.value.ok) {
1893
- process.exit(1);
1894
- } else {
1895
- process.exit(exitCode);
1896
- }
1897
- });
1898
- return command;
1899
- }
1900
-
1901
- // src/commands/db-sign.ts
1902
- import { readFile as readFile4 } from "fs/promises";
1903
- import { relative as relative6, resolve as resolve6 } from "path";
1904
- import {
1905
- errorDatabaseUrlRequired as errorDatabaseUrlRequired4,
1906
- errorDriverRequired as errorDriverRequired4,
1907
- errorFileNotFound as errorFileNotFound3,
1908
- errorRuntime as errorRuntime4,
1909
- errorUnexpected as errorUnexpected5
1910
- } from "@prisma-next/core-control-plane/errors";
1911
- import { Command as Command5 } from "commander";
1912
- function createDbSignCommand() {
1913
- const command = new Command5("sign");
1914
- setCommandDescriptions(
1915
- command,
1916
- "Sign the database with your contract so you can safely run queries",
1917
- "Verifies that your database schema satisfies the emitted contract, and if so, writes or\nupdates the contract marker in the database. This command is idempotent and safe to run\nin CI/deployment pipelines. The marker records that this database instance is aligned\nwith a specific contract version."
1918
- );
1919
- command.configureHelp({
1920
- formatHelp: (cmd) => {
1921
- const flags = parseGlobalFlags({});
1922
- return formatCommandHelp({ command: cmd, flags });
1923
- }
1924
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
1925
- const flags = parseGlobalFlags(options);
1926
- const result = await performAction(async () => {
1927
- const config = await loadConfig(options.config);
1928
- const configPath = options.config ? relative6(process.cwd(), resolve6(options.config)) : "prisma-next.config.ts";
1929
- const contractPathAbsolute = config.contract?.output ? resolve6(config.contract.output) : resolve6("src/prisma/contract.json");
1930
- const contractPath = relative6(process.cwd(), contractPathAbsolute);
1931
- if (flags.json !== "object" && !flags.quiet) {
1932
- const details = [
1933
- { label: "config", value: configPath },
1934
- { label: "contract", value: contractPath }
1935
- ];
1936
- if (options.db) {
1937
- details.push({ label: "database", value: options.db });
1938
- }
1939
- const header = formatStyledHeader({
1940
- command: "db sign",
1941
- description: "Sign the database with your contract so you can safely run queries",
1942
- url: "https://pris.ly/db-sign",
1943
- details,
1944
- flags
1945
- });
1946
- console.log(header);
1947
- }
1948
- let contractJsonContent;
1949
- try {
1950
- contractJsonContent = await readFile4(contractPathAbsolute, "utf-8");
1951
- } catch (error) {
1952
- if (error instanceof Error && error.code === "ENOENT") {
1953
- throw errorFileNotFound3(contractPathAbsolute, {
1954
- why: `Contract file not found at ${contractPathAbsolute}`
1955
- });
1956
- }
1957
- throw errorUnexpected5(error instanceof Error ? error.message : String(error), {
1958
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
1959
- });
1960
- }
1961
- const contractJson = JSON.parse(contractJsonContent);
1962
- const dbUrl = options.db ?? config.db?.url;
1963
- if (!dbUrl) {
1964
- throw errorDatabaseUrlRequired4();
1965
- }
1966
- if (!config.driver) {
1967
- throw errorDriverRequired4();
1968
- }
1969
- const driverDescriptor = config.driver;
1970
- const familyInstance = config.family.create({
1971
- target: config.target,
1972
- adapter: config.adapter,
1973
- driver: driverDescriptor,
1974
- extensionPacks: config.extensionPacks ?? []
1975
- });
1976
- const contractIR = familyInstance.validateContractIR(contractJson);
1977
- assertContractRequirementsSatisfied({
1978
- contract: contractIR,
1979
- family: config.family,
1980
- target: config.target,
1981
- adapter: config.adapter,
1982
- extensionPacks: config.extensionPacks
1983
- });
1984
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
1985
- const frameworkComponents = assertFrameworkComponentsCompatible(
1986
- config.family.familyId,
1987
- config.target.targetId,
1988
- rawComponents
1989
- );
1990
- const driver = await driverDescriptor.create(dbUrl);
1991
- try {
1992
- let schemaVerifyResult;
1993
- try {
1994
- schemaVerifyResult = await withSpinner(
1995
- () => familyInstance.schemaVerify({
1996
- driver,
1997
- contractIR,
1998
- strict: false,
1999
- contractPath: contractPathAbsolute,
2000
- configPath,
2001
- frameworkComponents
2002
- }),
2003
- {
2004
- message: "Verifying database satisfies contract",
2005
- flags
2006
- }
2007
- );
2008
- } catch (error) {
2009
- throw errorRuntime4(error instanceof Error ? error.message : String(error), {
2010
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
2011
- });
2012
- }
2013
- if (!schemaVerifyResult.ok) {
2014
- return { schemaVerifyResult, signResult: void 0 };
2015
- }
2016
- let signResult;
2017
- try {
2018
- signResult = await withSpinner(
2019
- () => familyInstance.sign({
2020
- driver,
2021
- contractIR,
2022
- contractPath: contractPathAbsolute,
2023
- configPath
2024
- }),
2025
- {
2026
- message: "Signing database...",
2027
- flags
2028
- }
2029
- );
2030
- } catch (error) {
2031
- throw errorRuntime4(error instanceof Error ? error.message : String(error), {
2032
- why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`
2033
- });
2034
- }
2035
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
2036
- console.log("");
2037
- }
2038
- return { schemaVerifyResult: void 0, signResult };
2039
- } finally {
2040
- await driver.close();
2041
- }
2042
- });
2043
- const exitCode = handleResult(result, flags, (value) => {
2044
- const { schemaVerifyResult, signResult } = value;
2045
- if (schemaVerifyResult && !schemaVerifyResult.ok) {
2046
- if (flags.json === "object") {
2047
- console.log(formatSchemaVerifyJson(schemaVerifyResult));
2048
- } else {
2049
- const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
2050
- if (output) {
2051
- console.log(output);
2052
- }
2053
- }
2054
- return;
2055
- }
2056
- if (signResult) {
2057
- if (flags.json === "object") {
2058
- console.log(formatSignJson(signResult));
2059
- } else {
2060
- const output = formatSignOutput(signResult, flags);
2061
- if (output) {
2062
- console.log(output);
2063
- }
2064
- }
2065
- }
2066
- });
2067
- if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {
2068
- process.exit(1);
2069
- } else {
2070
- process.exit(exitCode);
2071
- }
2072
- });
2073
- return command;
2074
- }
2075
-
2076
- // src/commands/db-verify.ts
2077
- import { readFile as readFile5 } from "fs/promises";
2078
- import { relative as relative7, resolve as resolve7 } from "path";
2079
- import {
2080
- errorDatabaseUrlRequired as errorDatabaseUrlRequired5,
2081
- errorDriverRequired as errorDriverRequired5,
2082
- errorFileNotFound as errorFileNotFound4,
2083
- errorHashMismatch as errorHashMismatch2,
2084
- errorMarkerMissing as errorMarkerMissing2,
2085
- errorRuntime as errorRuntime5,
2086
- errorTargetMismatch as errorTargetMismatch2,
2087
- errorUnexpected as errorUnexpected6
2088
- } from "@prisma-next/core-control-plane/errors";
2089
- import { Command as Command6 } from "commander";
2090
- function createDbVerifyCommand() {
2091
- const command = new Command6("verify");
2092
- setCommandDescriptions(
2093
- command,
2094
- "Check whether the database has been signed with your contract",
2095
- "Verifies that your database schema matches the emitted contract. Checks table structures,\ncolumn types, constraints, and codec coverage. Reports any mismatches or missing codecs."
2096
- );
2097
- command.configureHelp({
2098
- formatHelp: (cmd) => {
2099
- const flags = parseGlobalFlags({});
2100
- return formatCommandHelp({ command: cmd, flags });
2101
- }
2102
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
2103
- const flags = parseGlobalFlags(options);
2104
- const result = await performAction(async () => {
2105
- const config = await loadConfig(options.config);
2106
- const configPath = options.config ? relative7(process.cwd(), resolve7(options.config)) : "prisma-next.config.ts";
2107
- const contractPathAbsolute = config.contract?.output ? resolve7(config.contract.output) : resolve7("src/prisma/contract.json");
2108
- const contractPath = relative7(process.cwd(), contractPathAbsolute);
2109
- if (flags.json !== "object" && !flags.quiet) {
2110
- const details = [
2111
- { label: "config", value: configPath },
2112
- { label: "contract", value: contractPath }
2113
- ];
2114
- if (options.db) {
2115
- details.push({ label: "database", value: options.db });
2116
- }
2117
- const header = formatStyledHeader({
2118
- command: "db verify",
2119
- description: "Check whether the database has been signed with your contract",
2120
- url: "https://pris.ly/db-verify",
2121
- details,
2122
- flags
2123
- });
2124
- console.log(header);
2125
- }
2126
- let contractJsonContent;
2127
- try {
2128
- contractJsonContent = await readFile5(contractPathAbsolute, "utf-8");
2129
- } catch (error) {
2130
- if (error instanceof Error && error.code === "ENOENT") {
2131
- throw errorFileNotFound4(contractPathAbsolute, {
2132
- why: `Contract file not found at ${contractPathAbsolute}`
2133
- });
2134
- }
2135
- throw errorUnexpected6(error instanceof Error ? error.message : String(error), {
2136
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
2137
- });
2138
- }
2139
- const contractJson = JSON.parse(contractJsonContent);
2140
- const dbUrl = options.db ?? config.db?.url;
2141
- if (!dbUrl) {
2142
- throw errorDatabaseUrlRequired5();
2143
- }
2144
- if (!config.driver) {
2145
- throw errorDriverRequired5();
2146
- }
2147
- const driverDescriptor = config.driver;
2148
- const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
2149
- message: "Connecting to database...",
2150
- flags
2151
- });
2152
- try {
2153
- const familyInstance = config.family.create({
2154
- target: config.target,
2155
- adapter: config.adapter,
2156
- driver: driverDescriptor,
2157
- extensionPacks: config.extensionPacks ?? []
2158
- });
2159
- const contractIR = familyInstance.validateContractIR(contractJson);
2160
- assertContractRequirementsSatisfied({
2161
- contract: contractIR,
2162
- family: config.family,
2163
- target: config.target,
2164
- adapter: config.adapter,
2165
- extensionPacks: config.extensionPacks
2166
- });
2167
- let verifyResult;
2168
- try {
2169
- verifyResult = await withSpinner(
2170
- () => familyInstance.verify({
2171
- driver,
2172
- contractIR,
2173
- expectedTargetId: config.target.targetId,
2174
- contractPath: contractPathAbsolute,
2175
- configPath
2176
- }),
2177
- {
2178
- message: "Verifying database schema...",
2179
- flags
2180
- }
2181
- );
2182
- } catch (error) {
2183
- throw errorUnexpected6(error instanceof Error ? error.message : String(error), {
2184
- why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`
2185
- });
2186
- }
2187
- if (!verifyResult.ok && verifyResult.code) {
2188
- if (verifyResult.code === "PN-RTM-3001") {
2189
- throw errorMarkerMissing2();
2190
- }
2191
- if (verifyResult.code === "PN-RTM-3002") {
2192
- throw errorHashMismatch2({
2193
- expected: verifyResult.contract.coreHash,
2194
- ...verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}
2195
- });
2196
- }
2197
- if (verifyResult.code === "PN-RTM-3003") {
2198
- throw errorTargetMismatch2(
2199
- verifyResult.target.expected,
2200
- verifyResult.target.actual ?? "unknown"
2201
- );
2202
- }
2203
- throw errorRuntime5(verifyResult.summary);
2204
- }
2205
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
2206
- console.log("");
2207
- }
2208
- return verifyResult;
2209
- } finally {
2210
- await driver.close();
2211
- }
2212
- });
2213
- const exitCode = handleResult(result, flags, (verifyResult) => {
2214
- if (flags.json === "object") {
2215
- console.log(formatVerifyJson(verifyResult));
2216
- } else {
2217
- const output = formatVerifyOutput(verifyResult, flags);
2218
- if (output) {
2219
- console.log(output);
2220
- }
2221
- }
2222
- });
2223
- process.exit(exitCode);
2224
- });
2225
- return command;
2226
- }
2227
-
2228
- // src/cli.ts
2229
- var program = new Command7();
2230
- program.name("prisma-next").description("Prisma Next CLI").version("0.0.1");
2231
- var versionOption = program.options.find((opt) => opt.flags.includes("--version"));
2232
- if (versionOption) {
2233
- versionOption.description = "Output the version number";
2234
- }
2235
- program.configureOutput({
2236
- writeErr: () => {
2237
- },
2238
- writeOut: () => {
2239
- }
2240
- });
2241
- var rootHelpFormatter = (cmd) => {
2242
- const flags = parseGlobalFlags({});
2243
- return formatRootHelp({ program: cmd, flags });
2244
- };
2245
- program.configureHelp({
2246
- formatHelp: rootHelpFormatter,
2247
- subcommandDescription: () => ""
2248
- });
2249
- program.exitOverride((err) => {
2250
- if (err) {
2251
- const errorCode = err.code;
2252
- const errorMessage = String(err.message ?? "");
2253
- const errorName = err.name ?? "";
2254
- const isUnknownCommandError = errorCode === "commander.unknownCommand" || errorCode === "commander.unknownArgument" || errorName === "CommanderError" && (errorMessage.includes("unknown command") || errorMessage.includes("unknown argument"));
2255
- if (isUnknownCommandError) {
2256
- const flags = parseGlobalFlags({});
2257
- const match = errorMessage.match(/unknown command ['"]([^'"]+)['"]/);
2258
- const commandName = match ? match[1] : process.argv[3] || process.argv[2] || "unknown";
2259
- const firstArg = process.argv[2];
2260
- const parentCommand = firstArg ? program.commands.find((cmd) => cmd.name() === firstArg) : void 0;
2261
- if (parentCommand && commandName !== firstArg) {
2262
- console.error(`Unknown command: ${commandName}`);
2263
- console.error("");
2264
- const helpText = formatCommandHelp({ command: parentCommand, flags });
2265
- console.log(helpText);
2266
- } else {
2267
- console.error(`Unknown command: ${commandName}`);
2268
- console.error("");
2269
- const helpText = formatRootHelp({ program, flags });
2270
- console.log(helpText);
2271
- }
2272
- process.exit(1);
2273
- return;
2274
- }
2275
- const isHelpError = errorCode === "commander.help" || errorCode === "commander.helpDisplayed" || errorCode === "outputHelp" || errorMessage === "(outputHelp)" || errorMessage.includes("outputHelp") || errorName === "CommanderError" && errorMessage.includes("outputHelp");
2276
- if (isHelpError) {
2277
- process.exit(0);
2278
- return;
2279
- }
2280
- const isMissingArgumentError = errorCode === "commander.missingArgument" || errorCode === "commander.missingMandatoryOptionValue" || errorName === "CommanderError" && (errorMessage.includes("missing") || errorMessage.includes("required"));
2281
- if (isMissingArgumentError) {
2282
- process.exit(0);
2283
- return;
2284
- }
2285
- console.error(`Unhandled error: ${err.message}`);
2286
- if (err.stack) {
2287
- console.error(err.stack);
2288
- }
2289
- process.exit(1);
2290
- }
2291
- process.exit(0);
2292
- });
2293
- var contractCommand = new Command7("contract");
2294
- setCommandDescriptions(
2295
- contractCommand,
2296
- "Contract management commands",
2297
- "Define and emit your application data contract. The contract describes your schema as a\ndeclarative data structure that can be signed and verified against your database."
2298
- );
2299
- contractCommand.configureHelp({
2300
- formatHelp: (cmd) => {
2301
- const flags = parseGlobalFlags({});
2302
- return formatCommandHelp({ command: cmd, flags });
2303
- },
2304
- subcommandDescription: () => ""
2305
- });
2306
- var contractEmitCommand = createContractEmitCommand();
2307
- contractCommand.addCommand(contractEmitCommand);
2308
- program.addCommand(contractCommand);
2309
- var dbCommand = new Command7("db");
2310
- setCommandDescriptions(
2311
- dbCommand,
2312
- "Database management commands",
2313
- "Verify and sign your database with your contract. Ensure your database schema matches\nyour contract, and sign it to record the contract hash for future verification."
2314
- );
2315
- dbCommand.configureHelp({
2316
- formatHelp: (cmd) => {
2317
- const flags = parseGlobalFlags({});
2318
- return formatCommandHelp({ command: cmd, flags });
2319
- },
2320
- subcommandDescription: () => ""
2321
- });
2322
- var dbVerifyCommand = createDbVerifyCommand();
2323
- dbCommand.addCommand(dbVerifyCommand);
2324
- var dbInitCommand = createDbInitCommand();
2325
- dbCommand.addCommand(dbInitCommand);
2326
- var dbIntrospectCommand = createDbIntrospectCommand();
2327
- dbCommand.addCommand(dbIntrospectCommand);
2328
- var dbSchemaVerifyCommand = createDbSchemaVerifyCommand();
2329
- dbCommand.addCommand(dbSchemaVerifyCommand);
2330
- var dbSignCommand = createDbSignCommand();
2331
- dbCommand.addCommand(dbSignCommand);
2332
- program.addCommand(dbCommand);
2333
- var helpCommand = new Command7("help").description("Show usage instructions").configureHelp({
2334
- formatHelp: (cmd) => {
2335
- const flags = parseGlobalFlags({});
2336
- return formatCommandHelp({ command: cmd, flags });
2337
- }
2338
- }).action(() => {
2339
- const flags = parseGlobalFlags({});
2340
- const helpText = formatRootHelp({ program, flags });
2341
- console.log(helpText);
2342
- process.exit(0);
2343
- });
2344
- program.addCommand(helpCommand);
2345
- program.action(() => {
2346
- const flags = parseGlobalFlags({});
2347
- const helpText = formatRootHelp({ program, flags });
2348
- console.log(helpText);
2349
- process.exit(0);
2350
- });
2351
- var args = process.argv.slice(2);
2352
- if (args.length > 0) {
2353
- const commandName = args[0];
2354
- if (commandName === "--version" || commandName === "-V") {
2355
- console.log(program.version());
2356
- process.exit(0);
2357
- }
2358
- const isGlobalOption = commandName === "--help" || commandName === "-h";
2359
- if (!isGlobalOption) {
2360
- const command = program.commands.find((cmd) => cmd.name() === commandName);
2361
- if (!command) {
2362
- const flags = parseGlobalFlags({});
2363
- console.error(`Unknown command: ${commandName}`);
2364
- console.error("");
2365
- const helpText = formatRootHelp({ program, flags });
2366
- console.log(helpText);
2367
- process.exit(1);
2368
- } else if (command.commands.length > 0 && args.length === 1) {
2369
- const flags = parseGlobalFlags({});
2370
- const helpText = formatCommandHelp({ command, flags });
2371
- console.log(helpText);
2372
- process.exit(0);
2373
- }
2374
- }
2375
- }
2376
- program.parse();
2377
- //# sourceMappingURL=cli.js.map
2
+ import './cli.mjs';