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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,259 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname, relative, resolve } from 'node:path';
3
+ import { errorContractConfigMissing } from '@prisma-next/core-control-plane/errors';
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 type { EmitContractSource, EmitFailure } from '../control-api/types';
9
+ import { CliStructuredError, errorRuntime, errorUnexpected } from '../utils/cli-errors';
10
+ import { setCommandDescriptions } from '../utils/command-helpers';
11
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
12
+ import {
13
+ type EmitContractResult,
14
+ formatCommandHelp,
15
+ formatEmitJson,
16
+ formatEmitOutput,
17
+ formatStyledHeader,
18
+ formatSuccessMessage,
19
+ } from '../utils/output';
20
+ import { createProgressAdapter } from '../utils/progress-adapter';
21
+ import { handleResult } from '../utils/result-handler';
22
+
23
+ interface ContractEmitOptions {
24
+ readonly config?: string;
25
+ readonly json?: string | boolean;
26
+ readonly quiet?: boolean;
27
+ readonly q?: boolean;
28
+ readonly verbose?: boolean;
29
+ readonly v?: boolean;
30
+ readonly vv?: boolean;
31
+ readonly trace?: boolean;
32
+ readonly timestamps?: boolean;
33
+ readonly color?: boolean;
34
+ readonly 'no-color'?: boolean;
35
+ }
36
+
37
+ /**
38
+ * Maps an EmitFailure to a CliStructuredError for consistent error handling.
39
+ */
40
+ function mapEmitFailure(failure: EmitFailure): CliStructuredError {
41
+ if (failure.code === 'CONTRACT_SOURCE_INVALID') {
42
+ return errorRuntime(failure.summary, {
43
+ why: failure.why ?? 'Contract source is invalid',
44
+ fix: 'Check your contract source configuration in prisma-next.config.ts',
45
+ });
46
+ }
47
+
48
+ if (failure.code === 'EMIT_FAILED') {
49
+ return errorRuntime(failure.summary, {
50
+ why: failure.why ?? 'Failed to emit contract',
51
+ fix: 'Check your contract configuration and ensure the source is valid',
52
+ });
53
+ }
54
+
55
+ // Exhaustive check - TypeScript will error if a new code is added but not handled
56
+ const exhaustive: never = failure.code;
57
+ throw new Error(`Unhandled EmitFailure code: ${exhaustive}`);
58
+ }
59
+
60
+ /**
61
+ * Executes the contract emit command and returns a structured Result.
62
+ */
63
+ async function executeContractEmitCommand(
64
+ options: ContractEmitOptions,
65
+ flags: GlobalFlags,
66
+ startTime: number,
67
+ ): Promise<Result<EmitContractResult, CliStructuredError>> {
68
+ // Load config
69
+ let config: Awaited<ReturnType<typeof loadConfig>>;
70
+ try {
71
+ config = await loadConfig(options.config);
72
+ } catch (error) {
73
+ // Convert thrown CliStructuredError to Result
74
+ if (error instanceof CliStructuredError) {
75
+ return notOk(error);
76
+ }
77
+ return notOk(
78
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
79
+ why: 'Failed to load config',
80
+ }),
81
+ );
82
+ }
83
+
84
+ // Resolve contract from config
85
+ if (!config.contract) {
86
+ return notOk(
87
+ errorContractConfigMissing({
88
+ why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ..., types: ... }',
89
+ }),
90
+ );
91
+ }
92
+
93
+ // Contract config is already normalized by defineConfig() with defaults applied
94
+ const contractConfig = config.contract;
95
+
96
+ // Resolve artifact paths from config (already normalized by defineConfig() with defaults)
97
+ if (!contractConfig.output || !contractConfig.types) {
98
+ return notOk(
99
+ errorContractConfigMissing({
100
+ why: 'Contract config must have output and types paths. This should not happen if defineConfig() was used.',
101
+ }),
102
+ );
103
+ }
104
+ const outputJsonPath = resolve(contractConfig.output);
105
+ const outputDtsPath = resolve(contractConfig.types);
106
+
107
+ // Output header (only for human-readable output)
108
+ if (flags.json !== 'object' && !flags.quiet) {
109
+ // Normalize config path for display (match contract path format - no ./ prefix)
110
+ const configPath = options.config
111
+ ? relative(process.cwd(), resolve(options.config))
112
+ : 'prisma-next.config.ts';
113
+ // Convert absolute paths to relative paths for display
114
+ const contractPath = relative(process.cwd(), outputJsonPath);
115
+ const typesPath = relative(process.cwd(), outputDtsPath);
116
+ const header = formatStyledHeader({
117
+ command: 'contract emit',
118
+ description: 'Write your contract to JSON and sign it',
119
+ url: 'https://pris.ly/contract-emit',
120
+ details: [
121
+ { label: 'config', value: configPath },
122
+ { label: 'contract', value: contractPath },
123
+ { label: 'types', value: typesPath },
124
+ ],
125
+ flags,
126
+ });
127
+ console.log(header);
128
+ }
129
+
130
+ // Create control client (no driver needed for emit)
131
+ const client = createControlClient({
132
+ family: config.family,
133
+ target: config.target,
134
+ adapter: config.adapter,
135
+ extensionPacks: config.extensionPacks ?? [],
136
+ });
137
+
138
+ // Create progress adapter
139
+ const onProgress = createProgressAdapter({ flags });
140
+
141
+ try {
142
+ // Convert user config source to discriminated union
143
+ // Type assertion is safe: we check typeof to determine if it's a function
144
+ const source: EmitContractSource =
145
+ typeof contractConfig.source === 'function'
146
+ ? { kind: 'loader', load: contractConfig.source as () => unknown | Promise<unknown> }
147
+ : { kind: 'value', value: contractConfig.source };
148
+
149
+ // Call emit with progress callback
150
+ const result = await client.emit({
151
+ contractConfig: {
152
+ source,
153
+ output: outputJsonPath,
154
+ types: outputDtsPath,
155
+ },
156
+ onProgress,
157
+ });
158
+
159
+ // Handle failures by mapping to CLI structured error
160
+ if (!result.ok) {
161
+ return notOk(mapEmitFailure(result.failure));
162
+ }
163
+
164
+ // Create directories if needed
165
+ mkdirSync(dirname(outputJsonPath), { recursive: true });
166
+ mkdirSync(dirname(outputDtsPath), { recursive: true });
167
+
168
+ // Write the results to files
169
+ writeFileSync(outputJsonPath, result.value.contractJson, 'utf-8');
170
+ writeFileSync(outputDtsPath, result.value.contractDts, 'utf-8');
171
+
172
+ // Add blank line after all async operations if spinners were shown
173
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
174
+ console.log('');
175
+ }
176
+
177
+ // Convert success result to CLI output format
178
+ const emitResult: EmitContractResult = {
179
+ coreHash: result.value.coreHash,
180
+ profileHash: result.value.profileHash,
181
+ outDir: dirname(outputJsonPath),
182
+ files: {
183
+ json: outputJsonPath,
184
+ dts: outputDtsPath,
185
+ },
186
+ timings: { total: Date.now() - startTime },
187
+ };
188
+
189
+ return ok(emitResult);
190
+ } catch (error) {
191
+ // Use static type guard to work across module boundaries
192
+ if (CliStructuredError.is(error)) {
193
+ return notOk(error);
194
+ }
195
+
196
+ // Wrap unexpected errors
197
+ return notOk(
198
+ errorUnexpected('Unexpected error during contract emit', {
199
+ why: error instanceof Error ? error.message : String(error),
200
+ }),
201
+ );
202
+ } finally {
203
+ await client.close();
204
+ }
205
+ }
206
+
207
+ export function createContractEmitCommand(): Command {
208
+ const command = new Command('emit');
209
+ setCommandDescriptions(
210
+ command,
211
+ 'Write your contract to JSON and sign it',
212
+ 'Reads your contract source (TypeScript or Prisma schema) and emits contract.json and\n' +
213
+ 'contract.d.ts. The contract.json contains the canonical contract structure, and\n' +
214
+ 'contract.d.ts provides TypeScript types for type-safe query building.',
215
+ );
216
+ command
217
+ .configureHelp({
218
+ formatHelp: (cmd) => {
219
+ const flags = parseGlobalFlags({});
220
+ return formatCommandHelp({ command: cmd, flags });
221
+ },
222
+ })
223
+ .option('--config <path>', 'Path to prisma-next.config.ts')
224
+ .option('--json [format]', 'Output as JSON (object or ndjson)', false)
225
+ .option('-q, --quiet', 'Quiet mode: errors only')
226
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
227
+ .option('-vv, --trace', 'Trace output: deep internals, stack traces')
228
+ .option('--timestamps', 'Add timestamps to output')
229
+ .option('--color', 'Force color output')
230
+ .option('--no-color', 'Disable color output')
231
+ .action(async (options: ContractEmitOptions) => {
232
+ const flags = parseGlobalFlags(options);
233
+ const startTime = Date.now();
234
+
235
+ const result = await executeContractEmitCommand(options, flags, startTime);
236
+
237
+ // Handle result - formats output and returns exit code
238
+ const exitCode = handleResult(result, flags, (emitResult) => {
239
+ // Output based on flags
240
+ if (flags.json === 'object') {
241
+ // JSON output to stdout
242
+ console.log(formatEmitJson(emitResult));
243
+ } else {
244
+ // Human-readable output to stdout
245
+ const output = formatEmitOutput(emitResult, flags);
246
+ if (output) {
247
+ console.log(output);
248
+ }
249
+ // Output success message
250
+ if (!flags.quiet) {
251
+ console.log(formatSuccessMessage(flags));
252
+ }
253
+ }
254
+ });
255
+ process.exit(exitCode);
256
+ });
257
+
258
+ return command;
259
+ }
@@ -0,0 +1,360 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
4
+ import { Command } from 'commander';
5
+ import { loadConfig } from '../config-loader';
6
+ import { createControlClient } from '../control-api/client';
7
+ import type { DbInitFailure } from '../control-api/types';
8
+ import {
9
+ CliStructuredError,
10
+ errorContractValidationFailed,
11
+ errorDatabaseConnectionRequired,
12
+ errorDriverRequired,
13
+ errorFileNotFound,
14
+ errorJsonFormatNotSupported,
15
+ errorMigrationPlanningFailed,
16
+ errorRuntime,
17
+ errorTargetMigrationNotSupported,
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
+ type DbInitResult,
24
+ formatCommandHelp,
25
+ formatDbInitApplyOutput,
26
+ formatDbInitJson,
27
+ formatDbInitPlanOutput,
28
+ formatStyledHeader,
29
+ } from '../utils/output';
30
+ import { createProgressAdapter } from '../utils/progress-adapter';
31
+ import { handleResult } from '../utils/result-handler';
32
+
33
+ interface DbInitOptions {
34
+ readonly db?: string;
35
+ readonly config?: string;
36
+ readonly plan?: boolean;
37
+ readonly json?: string | boolean;
38
+ readonly quiet?: boolean;
39
+ readonly q?: boolean;
40
+ readonly verbose?: boolean;
41
+ readonly v?: boolean;
42
+ readonly vv?: boolean;
43
+ readonly trace?: boolean;
44
+ readonly timestamps?: boolean;
45
+ readonly color?: boolean;
46
+ readonly 'no-color'?: boolean;
47
+ }
48
+
49
+ /**
50
+ * Maps a DbInitFailure to a CliStructuredError for consistent error handling.
51
+ */
52
+ function mapDbInitFailure(failure: DbInitFailure): CliStructuredError {
53
+ if (failure.code === 'PLANNING_FAILED') {
54
+ return errorMigrationPlanningFailed({ conflicts: failure.conflicts ?? [] });
55
+ }
56
+
57
+ if (failure.code === 'MARKER_ORIGIN_MISMATCH') {
58
+ const mismatchParts: string[] = [];
59
+ if (
60
+ failure.marker?.coreHash !== failure.destination?.coreHash &&
61
+ failure.marker?.coreHash &&
62
+ failure.destination?.coreHash
63
+ ) {
64
+ mismatchParts.push(
65
+ `coreHash (marker: ${failure.marker.coreHash}, destination: ${failure.destination.coreHash})`,
66
+ );
67
+ }
68
+ if (
69
+ failure.marker?.profileHash !== failure.destination?.profileHash &&
70
+ failure.marker?.profileHash &&
71
+ failure.destination?.profileHash
72
+ ) {
73
+ mismatchParts.push(
74
+ `profileHash (marker: ${failure.marker.profileHash}, destination: ${failure.destination.profileHash})`,
75
+ );
76
+ }
77
+
78
+ return errorRuntime(
79
+ `Existing contract marker does not match plan destination.${mismatchParts.length > 0 ? ` Mismatch in ${mismatchParts.join(' and ')}.` : ''}`,
80
+ {
81
+ why: 'Database has an existing contract marker that does not match the target contract',
82
+ fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',
83
+ meta: {
84
+ code: 'MARKER_ORIGIN_MISMATCH',
85
+ ...(failure.marker?.coreHash ? { markerCoreHash: failure.marker.coreHash } : {}),
86
+ ...(failure.destination?.coreHash
87
+ ? { destinationCoreHash: failure.destination.coreHash }
88
+ : {}),
89
+ ...(failure.marker?.profileHash ? { markerProfileHash: failure.marker.profileHash } : {}),
90
+ ...(failure.destination?.profileHash
91
+ ? { destinationProfileHash: failure.destination.profileHash }
92
+ : {}),
93
+ },
94
+ },
95
+ );
96
+ }
97
+
98
+ if (failure.code === 'RUNNER_FAILED') {
99
+ return errorRuntime(failure.summary, {
100
+ why: failure.why ?? 'Migration runner failed',
101
+ fix: 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`',
102
+ meta: {
103
+ code: 'RUNNER_FAILED',
104
+ ...(failure.meta ?? {}),
105
+ },
106
+ });
107
+ }
108
+
109
+ // Exhaustive check - TypeScript will error if a new code is added but not handled
110
+ const exhaustive: never = failure.code;
111
+ throw new Error(`Unhandled DbInitFailure code: ${exhaustive}`);
112
+ }
113
+
114
+ /**
115
+ * Executes the db init command and returns a structured Result.
116
+ */
117
+ async function executeDbInitCommand(
118
+ options: DbInitOptions,
119
+ flags: GlobalFlags,
120
+ startTime: number,
121
+ ): Promise<Result<DbInitResult, CliStructuredError>> {
122
+ // Load config
123
+ const config = await loadConfig(options.config);
124
+ const configPath = options.config
125
+ ? relative(process.cwd(), resolve(options.config))
126
+ : 'prisma-next.config.ts';
127
+ const contractPathAbsolute = config.contract?.output
128
+ ? resolve(config.contract.output)
129
+ : resolve('src/prisma/contract.json');
130
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
131
+
132
+ // Output header
133
+ if (flags.json !== 'object' && !flags.quiet) {
134
+ const details: Array<{ label: string; value: string }> = [
135
+ { label: 'config', value: configPath },
136
+ { label: 'contract', value: contractPath },
137
+ ];
138
+ if (options.db) {
139
+ details.push({ label: 'database', value: options.db });
140
+ }
141
+ if (options.plan) {
142
+ details.push({ label: 'mode', value: 'plan (dry run)' });
143
+ }
144
+ const header = formatStyledHeader({
145
+ command: 'db init',
146
+ description: 'Bootstrap a database to match the current contract',
147
+ url: 'https://pris.ly/db-init',
148
+ details,
149
+ flags,
150
+ });
151
+ console.log(header);
152
+ }
153
+
154
+ // Load contract file
155
+ let contractJsonContent: string;
156
+ try {
157
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
158
+ } catch (error) {
159
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
160
+ return notOk(
161
+ errorFileNotFound(contractPathAbsolute, {
162
+ why: `Contract file not found at ${contractPathAbsolute}`,
163
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
164
+ }),
165
+ );
166
+ }
167
+ return notOk(
168
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
169
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
170
+ }),
171
+ );
172
+ }
173
+
174
+ let contractJson: Record<string, unknown>;
175
+ try {
176
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
177
+ } catch (error) {
178
+ return notOk(
179
+ errorContractValidationFailed(
180
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
181
+ { where: { path: contractPathAbsolute } },
182
+ ),
183
+ );
184
+ }
185
+
186
+ // Resolve database connection (--db flag or config.db.connection)
187
+ const dbConnection = options.db ?? config.db?.connection;
188
+ if (!dbConnection) {
189
+ return notOk(
190
+ errorDatabaseConnectionRequired({
191
+ why: `Database connection is required for db init (set db.connection in ${configPath}, or pass --db <url>)`,
192
+ }),
193
+ );
194
+ }
195
+
196
+ // Check for driver
197
+ if (!config.driver) {
198
+ return notOk(errorDriverRequired({ why: 'Config.driver is required for db init' }));
199
+ }
200
+
201
+ // Check target supports migrations via the migrations capability
202
+ if (!config.target.migrations) {
203
+ return notOk(
204
+ errorTargetMigrationNotSupported({
205
+ why: `Target "${config.target.id}" does not support migrations`,
206
+ }),
207
+ );
208
+ }
209
+
210
+ // Create control client
211
+ const client = createControlClient({
212
+ family: config.family,
213
+ target: config.target,
214
+ adapter: config.adapter,
215
+ driver: config.driver,
216
+ extensionPacks: config.extensionPacks ?? [],
217
+ });
218
+
219
+ // Create progress adapter
220
+ const onProgress = createProgressAdapter({ flags });
221
+
222
+ try {
223
+ // Call dbInit with connection and progress callback
224
+ // Connection happens inside dbInit with a 'connect' progress span
225
+ const result = await client.dbInit({
226
+ contractIR: contractJson,
227
+ mode: options.plan ? 'plan' : 'apply',
228
+ connection: dbConnection,
229
+ onProgress,
230
+ });
231
+
232
+ // Handle failures by mapping to CLI structured error
233
+ if (!result.ok) {
234
+ return notOk(mapDbInitFailure(result.failure));
235
+ }
236
+
237
+ // Convert success result to CLI output format
238
+ const profileHash = result.value.marker?.profileHash;
239
+ const dbInitResult: DbInitResult = {
240
+ ok: true,
241
+ mode: result.value.mode,
242
+ plan: {
243
+ targetId: config.target.targetId,
244
+ destination: {
245
+ coreHash: result.value.marker?.coreHash ?? '',
246
+ ...(profileHash ? { profileHash } : {}),
247
+ },
248
+ operations: result.value.plan.operations.map((op) => ({
249
+ id: op.id,
250
+ label: op.label,
251
+ operationClass: op.operationClass,
252
+ })),
253
+ },
254
+ ...(result.value.execution
255
+ ? {
256
+ execution: {
257
+ operationsPlanned: result.value.execution.operationsPlanned,
258
+ operationsExecuted: result.value.execution.operationsExecuted,
259
+ },
260
+ }
261
+ : {}),
262
+ ...(result.value.marker
263
+ ? {
264
+ marker: {
265
+ coreHash: result.value.marker.coreHash,
266
+ ...(result.value.marker.profileHash
267
+ ? { profileHash: result.value.marker.profileHash }
268
+ : {}),
269
+ },
270
+ }
271
+ : {}),
272
+ summary: result.value.summary,
273
+ timings: { total: Date.now() - startTime },
274
+ };
275
+
276
+ return ok(dbInitResult);
277
+ } catch (error) {
278
+ // Driver already throws CliStructuredError for connection failures
279
+ // Use static type guard to work across module boundaries
280
+ if (CliStructuredError.is(error)) {
281
+ return notOk(error);
282
+ }
283
+
284
+ // Wrap unexpected errors
285
+ return notOk(
286
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
287
+ why: `Unexpected error during db init: ${error instanceof Error ? error.message : String(error)}`,
288
+ }),
289
+ );
290
+ } finally {
291
+ await client.close();
292
+ }
293
+ }
294
+
295
+ export function createDbInitCommand(): Command {
296
+ const command = new Command('init');
297
+ setCommandDescriptions(
298
+ command,
299
+ 'Bootstrap a database to match the current contract and write the contract marker',
300
+ 'Initializes a database to match your emitted contract using additive-only operations.\n' +
301
+ 'Creates any missing tables, columns, indexes, and constraints defined in your contract.\n' +
302
+ 'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\n' +
303
+ 'would be required, and writes a contract marker to track the database state. Use --plan to\n' +
304
+ 'preview changes without applying.',
305
+ );
306
+ command
307
+ .configureHelp({
308
+ formatHelp: (cmd) => {
309
+ const flags = parseGlobalFlags({});
310
+ return formatCommandHelp({ command: cmd, flags });
311
+ },
312
+ })
313
+ .option('--db <url>', 'Database connection string')
314
+ .option('--config <path>', 'Path to prisma-next.config.ts')
315
+ .option('--plan', 'Preview planned operations without applying', false)
316
+ .option('--json [format]', 'Output as JSON (object)', false)
317
+ .option('-q, --quiet', 'Quiet mode: errors only')
318
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
319
+ .option('-vv, --trace', 'Trace output: deep internals, stack traces')
320
+ .option('--timestamps', 'Add timestamps to output')
321
+ .option('--color', 'Force color output')
322
+ .option('--no-color', 'Disable color output')
323
+ .action(async (options: DbInitOptions) => {
324
+ const flags = parseGlobalFlags(options);
325
+ const startTime = Date.now();
326
+
327
+ // Validate JSON format option
328
+ if (flags.json === 'ndjson') {
329
+ const result = notOk(
330
+ errorJsonFormatNotSupported({
331
+ command: 'db init',
332
+ format: 'ndjson',
333
+ supportedFormats: ['object'],
334
+ }),
335
+ );
336
+ const exitCode = handleResult(result, flags);
337
+ process.exit(exitCode);
338
+ }
339
+
340
+ const result = await executeDbInitCommand(options, flags, startTime);
341
+
342
+ const exitCode = handleResult(result, flags, (dbInitResult) => {
343
+ if (flags.json === 'object') {
344
+ console.log(formatDbInitJson(dbInitResult));
345
+ } else {
346
+ const output =
347
+ dbInitResult.mode === 'plan'
348
+ ? formatDbInitPlanOutput(dbInitResult, flags)
349
+ : formatDbInitApplyOutput(dbInitResult, flags);
350
+ if (output) {
351
+ console.log(output);
352
+ }
353
+ }
354
+ });
355
+
356
+ process.exit(exitCode);
357
+ });
358
+
359
+ return command;
360
+ }