@prisma-next/cli 0.3.0-dev.3 → 0.3.0-dev.31

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 (101) hide show
  1. package/README.md +111 -27
  2. package/dist/{chunk-BZMBKEEQ.js → chunk-AGOTG4L3.js} +44 -76
  3. package/dist/chunk-AGOTG4L3.js.map +1 -0
  4. package/dist/chunk-HLLI4YL7.js +180 -0
  5. package/dist/chunk-HLLI4YL7.js.map +1 -0
  6. package/dist/chunk-VG2R7DGF.js +735 -0
  7. package/dist/chunk-VG2R7DGF.js.map +1 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.d.ts.map +1 -0
  10. package/dist/cli.js +1502 -968
  11. package/dist/cli.js.map +1 -1
  12. package/dist/commands/contract-emit.d.ts +2 -4
  13. package/dist/commands/contract-emit.d.ts.map +1 -0
  14. package/dist/commands/contract-emit.js +3 -2
  15. package/dist/commands/db-init.d.ts +2 -4
  16. package/dist/commands/db-init.d.ts.map +1 -0
  17. package/dist/commands/db-init.js +205 -289
  18. package/dist/commands/db-init.js.map +1 -1
  19. package/dist/commands/db-introspect.d.ts +2 -4
  20. package/dist/commands/db-introspect.d.ts.map +1 -0
  21. package/dist/commands/db-introspect.js +108 -143
  22. package/dist/commands/db-introspect.js.map +1 -1
  23. package/dist/commands/db-schema-verify.d.ts +2 -4
  24. package/dist/commands/db-schema-verify.d.ts.map +1 -0
  25. package/dist/commands/db-schema-verify.js +120 -113
  26. package/dist/commands/db-schema-verify.js.map +1 -1
  27. package/dist/commands/db-sign.d.ts +2 -4
  28. package/dist/commands/db-sign.d.ts.map +1 -0
  29. package/dist/commands/db-sign.js +152 -156
  30. package/dist/commands/db-sign.js.map +1 -1
  31. package/dist/commands/db-verify.d.ts +2 -4
  32. package/dist/commands/db-verify.d.ts.map +1 -0
  33. package/dist/commands/db-verify.js +142 -122
  34. package/dist/commands/db-verify.js.map +1 -1
  35. package/dist/config-loader.d.ts +3 -5
  36. package/dist/config-loader.d.ts.map +1 -0
  37. package/dist/control-api/client.d.ts +13 -0
  38. package/dist/control-api/client.d.ts.map +1 -0
  39. package/dist/control-api/operations/db-init.d.ts +29 -0
  40. package/dist/control-api/operations/db-init.d.ts.map +1 -0
  41. package/dist/control-api/types.d.ts +387 -0
  42. package/dist/control-api/types.d.ts.map +1 -0
  43. package/dist/exports/config-types.d.ts +3 -0
  44. package/dist/exports/config-types.d.ts.map +1 -0
  45. package/dist/exports/config-types.js.map +1 -0
  46. package/dist/exports/control-api.d.ts +13 -0
  47. package/dist/exports/control-api.d.ts.map +1 -0
  48. package/dist/exports/control-api.js +7 -0
  49. package/dist/exports/control-api.js.map +1 -0
  50. package/dist/exports/index.d.ts +4 -0
  51. package/dist/exports/index.d.ts.map +1 -0
  52. package/dist/{index.js → exports/index.js} +4 -3
  53. package/dist/exports/index.js.map +1 -0
  54. package/dist/{index.d.ts → load-ts-contract.d.ts} +4 -8
  55. package/dist/load-ts-contract.d.ts.map +1 -0
  56. package/dist/utils/cli-errors.d.ts +7 -0
  57. package/dist/utils/cli-errors.d.ts.map +1 -0
  58. package/dist/utils/command-helpers.d.ts +12 -0
  59. package/dist/utils/command-helpers.d.ts.map +1 -0
  60. package/dist/utils/framework-components.d.ts +70 -0
  61. package/dist/utils/framework-components.d.ts.map +1 -0
  62. package/dist/utils/global-flags.d.ts +25 -0
  63. package/dist/utils/global-flags.d.ts.map +1 -0
  64. package/dist/utils/output.d.ts +142 -0
  65. package/dist/utils/output.d.ts.map +1 -0
  66. package/dist/utils/progress-adapter.d.ts +26 -0
  67. package/dist/utils/progress-adapter.d.ts.map +1 -0
  68. package/dist/utils/result-handler.d.ts +15 -0
  69. package/dist/utils/result-handler.d.ts.map +1 -0
  70. package/package.json +30 -26
  71. package/src/cli.ts +260 -0
  72. package/src/commands/contract-emit.ts +259 -0
  73. package/src/commands/db-init.ts +360 -0
  74. package/src/commands/db-introspect.ts +227 -0
  75. package/src/commands/db-schema-verify.ts +238 -0
  76. package/src/commands/db-sign.ts +279 -0
  77. package/src/commands/db-verify.ts +258 -0
  78. package/src/config-loader.ts +76 -0
  79. package/src/control-api/client.ts +589 -0
  80. package/src/control-api/operations/db-init.ts +281 -0
  81. package/src/control-api/types.ts +461 -0
  82. package/src/exports/config-types.ts +6 -0
  83. package/src/exports/control-api.ts +46 -0
  84. package/src/exports/index.ts +4 -0
  85. package/src/load-ts-contract.ts +217 -0
  86. package/src/utils/cli-errors.ts +26 -0
  87. package/src/utils/command-helpers.ts +26 -0
  88. package/src/utils/framework-components.ts +177 -0
  89. package/src/utils/global-flags.ts +75 -0
  90. package/src/utils/output.ts +1471 -0
  91. package/src/utils/progress-adapter.ts +86 -0
  92. package/src/utils/result-handler.ts +44 -0
  93. package/dist/chunk-464LNZCE.js +0 -134
  94. package/dist/chunk-464LNZCE.js.map +0 -1
  95. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  96. package/dist/chunk-ZKYEJROM.js +0 -94
  97. package/dist/chunk-ZKYEJROM.js.map +0 -1
  98. package/dist/config-types.d.ts +0 -1
  99. package/dist/config-types.js.map +0 -1
  100. package/dist/index.js.map +0 -1
  101. /package/dist/{config-types.js → exports/config-types.js} +0 -0
@@ -0,0 +1,279 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import type {
4
+ SignDatabaseResult,
5
+ VerifyDatabaseSchemaResult,
6
+ } from '@prisma-next/core-control-plane/types';
7
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
8
+ import { Command } from 'commander';
9
+ import { loadConfig } from '../config-loader';
10
+ import { createControlClient } from '../control-api/client';
11
+ import {
12
+ CliStructuredError,
13
+ errorContractValidationFailed,
14
+ errorDatabaseConnectionRequired,
15
+ errorDriverRequired,
16
+ errorFileNotFound,
17
+ errorJsonFormatNotSupported,
18
+ errorUnexpected,
19
+ } from '../utils/cli-errors';
20
+ import { setCommandDescriptions } from '../utils/command-helpers';
21
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
22
+ import {
23
+ formatCommandHelp,
24
+ formatSchemaVerifyJson,
25
+ formatSchemaVerifyOutput,
26
+ formatSignJson,
27
+ formatSignOutput,
28
+ formatStyledHeader,
29
+ } from '../utils/output';
30
+ import { createProgressAdapter } from '../utils/progress-adapter';
31
+ import { handleResult } from '../utils/result-handler';
32
+
33
+ interface DbSignOptions {
34
+ readonly db?: string;
35
+ readonly config?: string;
36
+ readonly json?: string | boolean;
37
+ readonly quiet?: boolean;
38
+ readonly q?: boolean;
39
+ readonly verbose?: boolean;
40
+ readonly v?: boolean;
41
+ readonly vv?: boolean;
42
+ readonly trace?: boolean;
43
+ readonly timestamps?: boolean;
44
+ readonly color?: boolean;
45
+ readonly 'no-color'?: boolean;
46
+ }
47
+
48
+ /**
49
+ * Failure type for db sign command.
50
+ * Either an infrastructure error (CliStructuredError) or a logical failure (schema verification failed).
51
+ */
52
+ type DbSignFailure = CliStructuredError | VerifyDatabaseSchemaResult;
53
+
54
+ /**
55
+ * Executes the db sign command and returns a structured Result.
56
+ * Success: SignDatabaseResult (sign happened)
57
+ * Failure: CliStructuredError (infra error) or VerifyDatabaseSchemaResult (schema mismatch)
58
+ */
59
+ async function executeDbSignCommand(
60
+ options: DbSignOptions,
61
+ flags: GlobalFlags,
62
+ ): Promise<Result<SignDatabaseResult, DbSignFailure>> {
63
+ // Load config
64
+ const config = await loadConfig(options.config);
65
+ const configPath = options.config
66
+ ? relative(process.cwd(), resolve(options.config))
67
+ : 'prisma-next.config.ts';
68
+ const contractPathAbsolute = config.contract?.output
69
+ ? resolve(config.contract.output)
70
+ : resolve('src/prisma/contract.json');
71
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
72
+
73
+ // Output header
74
+ if (flags.json !== 'object' && !flags.quiet) {
75
+ const details: Array<{ label: string; value: string }> = [
76
+ { label: 'config', value: configPath },
77
+ { label: 'contract', value: contractPath },
78
+ ];
79
+ if (options.db) {
80
+ details.push({ label: 'database', value: options.db });
81
+ }
82
+ const header = formatStyledHeader({
83
+ command: 'db sign',
84
+ description: 'Sign the database with your contract so you can safely run queries',
85
+ url: 'https://pris.ly/db-sign',
86
+ details,
87
+ flags,
88
+ });
89
+ console.log(header);
90
+ }
91
+
92
+ // Load contract file
93
+ let contractJsonContent: string;
94
+ try {
95
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
96
+ } catch (error) {
97
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
98
+ return notOk(
99
+ errorFileNotFound(contractPathAbsolute, {
100
+ why: `Contract file not found at ${contractPathAbsolute}`,
101
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
102
+ }),
103
+ );
104
+ }
105
+ return notOk(
106
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
107
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
108
+ }),
109
+ );
110
+ }
111
+
112
+ let contractJson: Record<string, unknown>;
113
+ try {
114
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
115
+ } catch (error) {
116
+ return notOk(
117
+ errorContractValidationFailed(
118
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
119
+ { where: { path: contractPathAbsolute } },
120
+ ),
121
+ );
122
+ }
123
+
124
+ // Resolve database connection (--db flag or config.db.connection)
125
+ const dbConnection = options.db ?? config.db?.connection;
126
+ if (!dbConnection) {
127
+ return notOk(
128
+ errorDatabaseConnectionRequired({
129
+ why: `Database connection is required for db sign (set db.connection in ${configPath}, or pass --db <url>)`,
130
+ }),
131
+ );
132
+ }
133
+
134
+ // Check for driver
135
+ if (!config.driver) {
136
+ return notOk(errorDriverRequired({ why: 'Config.driver is required for db sign' }));
137
+ }
138
+
139
+ // Create control client
140
+ const client = createControlClient({
141
+ family: config.family,
142
+ target: config.target,
143
+ adapter: config.adapter,
144
+ driver: config.driver,
145
+ extensionPacks: config.extensionPacks ?? [],
146
+ });
147
+
148
+ // Create progress adapter
149
+ const onProgress = createProgressAdapter({ flags });
150
+
151
+ try {
152
+ // Step 1: Schema verification - connect here
153
+ const schemaVerifyResult = await client.schemaVerify({
154
+ contractIR: contractJson,
155
+ strict: false,
156
+ connection: dbConnection,
157
+ onProgress,
158
+ });
159
+
160
+ // If schema verification failed, return as failure
161
+ if (!schemaVerifyResult.ok) {
162
+ // Add blank line after all async operations if spinners were shown
163
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
164
+ console.log('');
165
+ }
166
+ return notOk(schemaVerifyResult);
167
+ }
168
+
169
+ // Step 2: Sign (already connected from schemaVerify)
170
+ const signResult = await client.sign({
171
+ contractIR: contractJson,
172
+ contractPath,
173
+ configPath,
174
+ onProgress,
175
+ });
176
+
177
+ // Add blank line after all async operations if spinners were shown
178
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
179
+ console.log('');
180
+ }
181
+
182
+ return ok(signResult);
183
+ } catch (error) {
184
+ // Driver already throws CliStructuredError for connection failures
185
+ if (error instanceof CliStructuredError) {
186
+ return notOk(error);
187
+ }
188
+
189
+ // Wrap unexpected errors
190
+ return notOk(
191
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
192
+ why: `Unexpected error during db sign: ${error instanceof Error ? error.message : String(error)}`,
193
+ }),
194
+ );
195
+ } finally {
196
+ await client.close();
197
+ }
198
+ }
199
+
200
+ export function createDbSignCommand(): Command {
201
+ const command = new Command('sign');
202
+ setCommandDescriptions(
203
+ command,
204
+ 'Sign the database with your contract so you can safely run queries',
205
+ 'Verifies that your database schema satisfies the emitted contract, and if so, writes or\n' +
206
+ 'updates the contract marker in the database. This command is idempotent and safe to run\n' +
207
+ 'in CI/deployment pipelines. The marker records that this database instance is aligned\n' +
208
+ 'with a specific contract version.',
209
+ );
210
+ command
211
+ .configureHelp({
212
+ formatHelp: (cmd) => {
213
+ const flags = parseGlobalFlags({});
214
+ return formatCommandHelp({ command: cmd, flags });
215
+ },
216
+ })
217
+ .option('--db <url>', 'Database connection string')
218
+ .option('--config <path>', 'Path to prisma-next.config.ts')
219
+ .option('--json [format]', 'Output as JSON (object)', false)
220
+ .option('-q, --quiet', 'Quiet mode: errors only')
221
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
222
+ .option('-vv, --trace', 'Trace output: deep internals, stack traces')
223
+ .option('--timestamps', 'Add timestamps to output')
224
+ .option('--color', 'Force color output')
225
+ .option('--no-color', 'Disable color output')
226
+ .action(async (options: DbSignOptions) => {
227
+ const flags = parseGlobalFlags(options);
228
+
229
+ // Validate JSON format option
230
+ if (flags.json === 'ndjson') {
231
+ const result = notOk(
232
+ errorJsonFormatNotSupported({
233
+ command: 'db sign',
234
+ format: 'ndjson',
235
+ supportedFormats: ['object'],
236
+ }),
237
+ );
238
+ const exitCode = handleResult(result, flags);
239
+ process.exit(exitCode);
240
+ }
241
+
242
+ const result = await executeDbSignCommand(options, flags);
243
+
244
+ if (result.ok) {
245
+ // Success - format sign output
246
+ if (flags.json === 'object') {
247
+ console.log(formatSignJson(result.value));
248
+ } else {
249
+ const output = formatSignOutput(result.value, flags);
250
+ if (output) {
251
+ console.log(output);
252
+ }
253
+ }
254
+ process.exit(0);
255
+ }
256
+
257
+ // Failure - determine type and handle appropriately
258
+ const failure = result.failure;
259
+
260
+ if (failure instanceof CliStructuredError) {
261
+ // Infrastructure error - use standard handler
262
+ const exitCode = handleResult(result as Result<never, CliStructuredError>, flags);
263
+ process.exit(exitCode);
264
+ }
265
+
266
+ // Schema verification failed - format and print schema verification output
267
+ if (flags.json === 'object') {
268
+ console.log(formatSchemaVerifyJson(failure));
269
+ } else {
270
+ const output = formatSchemaVerifyOutput(failure, flags);
271
+ if (output) {
272
+ console.log(output);
273
+ }
274
+ }
275
+ process.exit(1);
276
+ });
277
+
278
+ return command;
279
+ }
@@ -0,0 +1,258 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import type { VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';
4
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
5
+ import { Command } from 'commander';
6
+ import { loadConfig } from '../config-loader';
7
+ import { createControlClient } from '../control-api/client';
8
+ import {
9
+ CliStructuredError,
10
+ errorContractValidationFailed,
11
+ errorDatabaseConnectionRequired,
12
+ errorDriverRequired,
13
+ errorFileNotFound,
14
+ errorHashMismatch,
15
+ errorJsonFormatNotSupported,
16
+ errorMarkerMissing,
17
+ errorRuntime,
18
+ errorTargetMismatch,
19
+ errorUnexpected,
20
+ } from '../utils/cli-errors';
21
+ import { setCommandDescriptions } from '../utils/command-helpers';
22
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
23
+ import {
24
+ formatCommandHelp,
25
+ formatStyledHeader,
26
+ formatVerifyJson,
27
+ formatVerifyOutput,
28
+ } from '../utils/output';
29
+ import { createProgressAdapter } from '../utils/progress-adapter';
30
+ import { handleResult } from '../utils/result-handler';
31
+
32
+ interface DbVerifyOptions {
33
+ readonly db?: string;
34
+ readonly config?: string;
35
+ readonly json?: string | boolean;
36
+ readonly quiet?: boolean;
37
+ readonly q?: boolean;
38
+ readonly verbose?: boolean;
39
+ readonly v?: boolean;
40
+ readonly vv?: boolean;
41
+ readonly trace?: boolean;
42
+ readonly timestamps?: boolean;
43
+ readonly color?: boolean;
44
+ readonly 'no-color'?: boolean;
45
+ }
46
+
47
+ /**
48
+ * Maps a VerifyDatabaseResult failure to a CliStructuredError.
49
+ */
50
+ function mapVerifyFailure(verifyResult: VerifyDatabaseResult): CliStructuredError {
51
+ if (!verifyResult.ok && verifyResult.code) {
52
+ if (verifyResult.code === 'PN-RTM-3001') {
53
+ return errorMarkerMissing();
54
+ }
55
+ if (verifyResult.code === 'PN-RTM-3002') {
56
+ return errorHashMismatch({
57
+ expected: verifyResult.contract.coreHash,
58
+ ...(verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}),
59
+ });
60
+ }
61
+ if (verifyResult.code === 'PN-RTM-3003') {
62
+ return errorTargetMismatch(
63
+ verifyResult.target.expected,
64
+ verifyResult.target.actual ?? 'unknown',
65
+ );
66
+ }
67
+ // Unknown code - fall through to runtime error
68
+ }
69
+ return errorRuntime(verifyResult.summary);
70
+ }
71
+
72
+ /**
73
+ * Executes the db verify command and returns a structured Result.
74
+ */
75
+ async function executeDbVerifyCommand(
76
+ options: DbVerifyOptions,
77
+ flags: GlobalFlags,
78
+ ): Promise<Result<VerifyDatabaseResult, CliStructuredError>> {
79
+ // Load config
80
+ const config = await loadConfig(options.config);
81
+ const configPath = options.config
82
+ ? relative(process.cwd(), resolve(options.config))
83
+ : 'prisma-next.config.ts';
84
+ const contractPathAbsolute = config.contract?.output
85
+ ? resolve(config.contract.output)
86
+ : resolve('src/prisma/contract.json');
87
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
88
+
89
+ // Output header
90
+ if (flags.json !== 'object' && !flags.quiet) {
91
+ const details: Array<{ label: string; value: string }> = [
92
+ { label: 'config', value: configPath },
93
+ { label: 'contract', value: contractPath },
94
+ ];
95
+ if (options.db) {
96
+ details.push({ label: 'database', value: options.db });
97
+ }
98
+ const header = formatStyledHeader({
99
+ command: 'db verify',
100
+ description: 'Check whether the database has been signed with your contract',
101
+ url: 'https://pris.ly/db-verify',
102
+ details,
103
+ flags,
104
+ });
105
+ console.log(header);
106
+ }
107
+
108
+ // Load contract file
109
+ let contractJsonContent: string;
110
+ try {
111
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
112
+ } catch (error) {
113
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
114
+ return notOk(
115
+ errorFileNotFound(contractPathAbsolute, {
116
+ why: `Contract file not found at ${contractPathAbsolute}`,
117
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
118
+ }),
119
+ );
120
+ }
121
+ return notOk(
122
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
123
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
124
+ }),
125
+ );
126
+ }
127
+
128
+ let contractJson: Record<string, unknown>;
129
+ try {
130
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
131
+ } catch (error) {
132
+ return notOk(
133
+ errorContractValidationFailed(
134
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
135
+ { where: { path: contractPathAbsolute } },
136
+ ),
137
+ );
138
+ }
139
+
140
+ // Resolve database connection (--db flag or config.db.connection)
141
+ const dbConnection = options.db ?? config.db?.connection;
142
+ if (!dbConnection) {
143
+ return notOk(
144
+ errorDatabaseConnectionRequired({
145
+ why: `Database connection is required for db verify (set db.connection in ${configPath}, or pass --db <url>)`,
146
+ }),
147
+ );
148
+ }
149
+
150
+ // Check for driver
151
+ if (!config.driver) {
152
+ return notOk(errorDriverRequired({ why: 'Config.driver is required for db verify' }));
153
+ }
154
+
155
+ // Create control client
156
+ const client = createControlClient({
157
+ family: config.family,
158
+ target: config.target,
159
+ adapter: config.adapter,
160
+ driver: config.driver,
161
+ extensionPacks: config.extensionPacks ?? [],
162
+ });
163
+
164
+ // Create progress adapter
165
+ const onProgress = createProgressAdapter({ flags });
166
+
167
+ try {
168
+ const verifyResult = await client.verify({
169
+ contractIR: contractJson,
170
+ connection: dbConnection,
171
+ onProgress,
172
+ });
173
+
174
+ // Add blank line after all async operations if spinners were shown
175
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
176
+ console.log('');
177
+ }
178
+
179
+ // If verification failed, map to CLI structured error
180
+ if (!verifyResult.ok) {
181
+ return notOk(mapVerifyFailure(verifyResult));
182
+ }
183
+
184
+ return ok(verifyResult);
185
+ } catch (error) {
186
+ // Driver already throws CliStructuredError for connection failures
187
+ if (error instanceof CliStructuredError) {
188
+ return notOk(error);
189
+ }
190
+
191
+ // Wrap unexpected errors
192
+ return notOk(
193
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
194
+ why: `Unexpected error during db verify: ${error instanceof Error ? error.message : String(error)}`,
195
+ }),
196
+ );
197
+ } finally {
198
+ await client.close();
199
+ }
200
+ }
201
+
202
+ export function createDbVerifyCommand(): Command {
203
+ const command = new Command('verify');
204
+ setCommandDescriptions(
205
+ command,
206
+ 'Check whether the database has been signed with your contract',
207
+ 'Verifies that your database schema matches the emitted contract. Checks table structures,\n' +
208
+ 'column types, constraints, and codec coverage. Reports any mismatches or missing codecs.',
209
+ );
210
+ command
211
+ .configureHelp({
212
+ formatHelp: (cmd) => {
213
+ const flags = parseGlobalFlags({});
214
+ return formatCommandHelp({ command: cmd, flags });
215
+ },
216
+ })
217
+ .option('--db <url>', 'Database connection string')
218
+ .option('--config <path>', 'Path to prisma-next.config.ts')
219
+ .option('--json [format]', 'Output as JSON (object)', false)
220
+ .option('-q, --quiet', 'Quiet mode: errors only')
221
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
222
+ .option('-vv, --trace', 'Trace output: deep internals, stack traces')
223
+ .option('--timestamps', 'Add timestamps to output')
224
+ .option('--color', 'Force color output')
225
+ .option('--no-color', 'Disable color output')
226
+ .action(async (options: DbVerifyOptions) => {
227
+ const flags = parseGlobalFlags(options);
228
+
229
+ // Validate JSON format option
230
+ if (flags.json === 'ndjson') {
231
+ const result = notOk(
232
+ errorJsonFormatNotSupported({
233
+ command: 'db verify',
234
+ format: 'ndjson',
235
+ supportedFormats: ['object'],
236
+ }),
237
+ );
238
+ const exitCode = handleResult(result, flags);
239
+ process.exit(exitCode);
240
+ }
241
+
242
+ const result = await executeDbVerifyCommand(options, flags);
243
+
244
+ const exitCode = handleResult(result, flags, (verifyResult) => {
245
+ if (flags.json === 'object') {
246
+ console.log(formatVerifyJson(verifyResult));
247
+ } else {
248
+ const output = formatVerifyOutput(verifyResult, flags);
249
+ if (output) {
250
+ console.log(output);
251
+ }
252
+ }
253
+ });
254
+ process.exit(exitCode);
255
+ });
256
+
257
+ return command;
258
+ }
@@ -0,0 +1,76 @@
1
+ import { dirname, resolve } from 'node:path';
2
+ import type { PrismaNextConfig } from '@prisma-next/core-control-plane/config-types';
3
+ import { validateConfig } from '@prisma-next/core-control-plane/config-validation';
4
+ import { errorConfigFileNotFound, errorUnexpected } from '@prisma-next/core-control-plane/errors';
5
+ import { loadConfig as loadConfigC12 } from 'c12';
6
+
7
+ /**
8
+ * Loads the Prisma Next config from a TypeScript file.
9
+ * Supports both default export and named export.
10
+ * Uses c12 to automatically handle TypeScript compilation and config file discovery.
11
+ *
12
+ * @param configPath - Optional path to config file. Defaults to `./prisma-next.config.ts` in current directory.
13
+ * @returns The loaded config object.
14
+ * @throws Error if config file doesn't exist or is invalid.
15
+ */
16
+ export async function loadConfig(configPath?: string): Promise<PrismaNextConfig> {
17
+ try {
18
+ const cwd = process.cwd();
19
+ // Resolve config path to absolute path and set cwd to config directory when path is provided
20
+ const resolvedConfigPath = configPath ? resolve(cwd, configPath) : undefined;
21
+ const configCwd = resolvedConfigPath ? dirname(resolvedConfigPath) : cwd;
22
+
23
+ const result = await loadConfigC12<PrismaNextConfig>({
24
+ name: 'prisma-next',
25
+ ...(resolvedConfigPath ? { configFile: resolvedConfigPath } : {}),
26
+ cwd: configCwd,
27
+ });
28
+
29
+ // When a specific config file was requested, verify it was actually loaded
30
+ // (c12 falls back to searching by name if the specified file doesn't exist)
31
+ if (resolvedConfigPath && result.configFile !== resolvedConfigPath) {
32
+ throw errorConfigFileNotFound(resolvedConfigPath);
33
+ }
34
+
35
+ // Check if config is missing or empty (c12 may return empty object when file doesn't exist)
36
+ if (!result.config || Object.keys(result.config).length === 0) {
37
+ // Use c12's configFile if available, otherwise use explicit configPath, otherwise omit path
38
+ const displayPath = result.configFile || resolvedConfigPath || configPath;
39
+ throw errorConfigFileNotFound(displayPath);
40
+ }
41
+
42
+ // Validate config structure
43
+ validateConfig(result.config);
44
+
45
+ return result.config;
46
+ } catch (error) {
47
+ // Re-throw structured errors as-is
48
+ if (
49
+ error instanceof Error &&
50
+ 'code' in error &&
51
+ typeof (error as { code: string }).code === 'string'
52
+ ) {
53
+ throw error;
54
+ }
55
+
56
+ if (error instanceof Error) {
57
+ // Check for file not found errors
58
+ if (
59
+ error.message.includes('not found') ||
60
+ error.message.includes('Cannot find') ||
61
+ error.message.includes('ENOENT')
62
+ ) {
63
+ // Use resolved path if available, otherwise use original configPath
64
+ const displayPath = configPath ? resolve(process.cwd(), configPath) : undefined;
65
+ throw errorConfigFileNotFound(displayPath, {
66
+ why: error.message,
67
+ });
68
+ }
69
+ // For other errors, wrap in unexpected error
70
+ throw errorUnexpected(error.message, {
71
+ why: `Failed to load config: ${error.message}`,
72
+ });
73
+ }
74
+ throw errorUnexpected(String(error));
75
+ }
76
+ }