@prisma-next/cli 0.3.0-dev.4 → 0.3.0-dev.41

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