@prisma-next/cli 0.3.0-dev.1 → 0.3.0-dev.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +2 -2
  2. package/dist/{chunk-ZKYEJROM.js → chunk-CVNWLFXO.js} +6 -9
  3. package/dist/chunk-CVNWLFXO.js.map +1 -0
  4. package/dist/{chunk-464LNZCE.js → chunk-QUPBU4KV.js} +5 -8
  5. package/dist/chunk-QUPBU4KV.js.map +1 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +34 -60
  9. package/dist/cli.js.map +1 -1
  10. package/dist/commands/contract-emit.d.ts +2 -4
  11. package/dist/commands/contract-emit.d.ts.map +1 -0
  12. package/dist/commands/contract-emit.js +1 -1
  13. package/dist/commands/db-init.d.ts +2 -4
  14. package/dist/commands/db-init.d.ts.map +1 -0
  15. package/dist/commands/db-init.js +6 -10
  16. package/dist/commands/db-init.js.map +1 -1
  17. package/dist/commands/db-introspect.d.ts +2 -4
  18. package/dist/commands/db-introspect.d.ts.map +1 -0
  19. package/dist/commands/db-introspect.js +6 -10
  20. package/dist/commands/db-introspect.js.map +1 -1
  21. package/dist/commands/db-schema-verify.d.ts +2 -4
  22. package/dist/commands/db-schema-verify.d.ts.map +1 -0
  23. package/dist/commands/db-schema-verify.js +6 -10
  24. package/dist/commands/db-schema-verify.js.map +1 -1
  25. package/dist/commands/db-sign.d.ts +2 -4
  26. package/dist/commands/db-sign.d.ts.map +1 -0
  27. package/dist/commands/db-sign.js +6 -10
  28. package/dist/commands/db-sign.js.map +1 -1
  29. package/dist/commands/db-verify.d.ts +2 -4
  30. package/dist/commands/db-verify.d.ts.map +1 -0
  31. package/dist/commands/db-verify.js +6 -10
  32. package/dist/commands/db-verify.js.map +1 -1
  33. package/dist/config-loader.d.ts +3 -5
  34. package/dist/config-loader.d.ts.map +1 -0
  35. package/dist/exports/config-types.d.ts +3 -0
  36. package/dist/exports/config-types.d.ts.map +1 -0
  37. package/dist/exports/config-types.js.map +1 -0
  38. package/dist/exports/index.d.ts +4 -0
  39. package/dist/exports/index.d.ts.map +1 -0
  40. package/dist/{index.js → exports/index.js} +3 -3
  41. package/dist/exports/index.js.map +1 -0
  42. package/dist/{index.d.ts → load-ts-contract.d.ts} +4 -8
  43. package/dist/load-ts-contract.d.ts.map +1 -0
  44. package/dist/utils/action.d.ts +16 -0
  45. package/dist/utils/action.d.ts.map +1 -0
  46. package/dist/utils/cli-errors.d.ts +7 -0
  47. package/dist/utils/cli-errors.d.ts.map +1 -0
  48. package/dist/utils/command-helpers.d.ts +12 -0
  49. package/dist/utils/command-helpers.d.ts.map +1 -0
  50. package/dist/utils/framework-components.d.ts +70 -0
  51. package/dist/utils/framework-components.d.ts.map +1 -0
  52. package/dist/utils/global-flags.d.ts +25 -0
  53. package/dist/utils/global-flags.d.ts.map +1 -0
  54. package/dist/utils/output.d.ts +142 -0
  55. package/dist/utils/output.d.ts.map +1 -0
  56. package/dist/utils/result-handler.d.ts +15 -0
  57. package/dist/utils/result-handler.d.ts.map +1 -0
  58. package/dist/utils/spinner.d.ts +29 -0
  59. package/dist/utils/spinner.d.ts.map +1 -0
  60. package/package.json +21 -21
  61. package/src/cli.ts +260 -0
  62. package/src/commands/contract-emit.ts +182 -0
  63. package/src/commands/db-init.ts +452 -0
  64. package/src/commands/db-introspect.ts +256 -0
  65. package/src/commands/db-schema-verify.ts +232 -0
  66. package/src/commands/db-sign.ts +273 -0
  67. package/src/commands/db-verify.ts +229 -0
  68. package/src/config-loader.ts +76 -0
  69. package/src/exports/config-types.ts +6 -0
  70. package/src/exports/index.ts +4 -0
  71. package/src/load-ts-contract.ts +217 -0
  72. package/src/utils/action.ts +43 -0
  73. package/src/utils/cli-errors.ts +26 -0
  74. package/src/utils/command-helpers.ts +26 -0
  75. package/src/utils/framework-components.ts +177 -0
  76. package/src/utils/global-flags.ts +75 -0
  77. package/src/utils/output.ts +1471 -0
  78. package/src/utils/result-handler.ts +44 -0
  79. package/src/utils/spinner.ts +67 -0
  80. package/dist/chunk-464LNZCE.js.map +0 -1
  81. package/dist/chunk-ZKYEJROM.js.map +0 -1
  82. package/dist/config-types.d.ts +0 -1
  83. package/dist/config-types.js.map +0 -1
  84. package/dist/index.js.map +0 -1
  85. /package/dist/{config-types.js → exports/config-types.js} +0 -0
@@ -0,0 +1,452 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import type {
4
+ MigrationPlan,
5
+ MigrationPlannerResult,
6
+ MigrationPlanOperation,
7
+ MigrationRunnerResult,
8
+ } from '@prisma-next/core-control-plane/types';
9
+ import { createControlPlaneStack } from '@prisma-next/core-control-plane/types';
10
+ import { redactDatabaseUrl } from '@prisma-next/utils/redact-db-url';
11
+ import { Command } from 'commander';
12
+ import { loadConfig } from '../config-loader';
13
+ import { performAction } from '../utils/action';
14
+ import {
15
+ errorContractValidationFailed,
16
+ errorDatabaseUrlRequired,
17
+ errorDriverRequired,
18
+ errorFileNotFound,
19
+ errorJsonFormatNotSupported,
20
+ errorMigrationPlanningFailed,
21
+ errorRuntime,
22
+ errorTargetMigrationNotSupported,
23
+ errorUnexpected,
24
+ } from '../utils/cli-errors';
25
+ import { setCommandDescriptions } from '../utils/command-helpers';
26
+ import {
27
+ assertContractRequirementsSatisfied,
28
+ assertFrameworkComponentsCompatible,
29
+ } from '../utils/framework-components';
30
+ import { parseGlobalFlags } from '../utils/global-flags';
31
+ import {
32
+ type DbInitResult,
33
+ formatCommandHelp,
34
+ formatDbInitApplyOutput,
35
+ formatDbInitJson,
36
+ formatDbInitPlanOutput,
37
+ formatStyledHeader,
38
+ } from '../utils/output';
39
+ import { handleResult } from '../utils/result-handler';
40
+ import { withSpinner } from '../utils/spinner';
41
+
42
+ interface DbInitOptions {
43
+ readonly db?: string;
44
+ readonly config?: string;
45
+ readonly plan?: boolean;
46
+ readonly json?: string | boolean;
47
+ readonly quiet?: boolean;
48
+ readonly q?: boolean;
49
+ readonly verbose?: boolean;
50
+ readonly v?: boolean;
51
+ readonly vv?: boolean;
52
+ readonly trace?: boolean;
53
+ readonly timestamps?: boolean;
54
+ readonly color?: boolean;
55
+ readonly 'no-color'?: boolean;
56
+ }
57
+
58
+ export function createDbInitCommand(): Command {
59
+ const command = new Command('init');
60
+ setCommandDescriptions(
61
+ command,
62
+ 'Bootstrap a database to match the current contract and write the contract marker',
63
+ 'Initializes a database to match your emitted contract using additive-only operations.\n' +
64
+ 'Creates any missing tables, columns, indexes, and constraints defined in your contract.\n' +
65
+ 'Leaves existing compatible structures in place, surfaces conflicts when destructive changes\n' +
66
+ 'would be required, and writes a contract marker to track the database state. Use --plan to\n' +
67
+ 'preview changes without applying.',
68
+ );
69
+ command
70
+ .configureHelp({
71
+ formatHelp: (cmd) => {
72
+ const flags = parseGlobalFlags({});
73
+ return formatCommandHelp({ command: cmd, flags });
74
+ },
75
+ })
76
+ .option('--db <url>', 'Database connection string')
77
+ .option('--config <path>', 'Path to prisma-next.config.ts')
78
+ .option('--plan', 'Preview planned operations without applying', false)
79
+ .option('--json [format]', 'Output as JSON (object)', false)
80
+ .option('-q, --quiet', 'Quiet mode: errors only')
81
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
82
+ .option('-vv, --trace', 'Trace output: deep internals, stack traces')
83
+ .option('--timestamps', 'Add timestamps to output')
84
+ .option('--color', 'Force color output')
85
+ .option('--no-color', 'Disable color output')
86
+ .action(async (options: DbInitOptions) => {
87
+ const flags = parseGlobalFlags(options);
88
+ const startTime = Date.now();
89
+
90
+ const result = await performAction(async () => {
91
+ if (flags.json === 'ndjson') {
92
+ throw errorJsonFormatNotSupported({
93
+ command: 'db init',
94
+ format: 'ndjson',
95
+ supportedFormats: ['object'],
96
+ });
97
+ }
98
+
99
+ // Load config
100
+ const config = await loadConfig(options.config);
101
+ const configPath = options.config
102
+ ? relative(process.cwd(), resolve(options.config))
103
+ : 'prisma-next.config.ts';
104
+ const contractPathAbsolute = config.contract?.output
105
+ ? resolve(config.contract.output)
106
+ : resolve('src/prisma/contract.json');
107
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
108
+
109
+ // Output header
110
+ if (flags.json !== 'object' && !flags.quiet) {
111
+ const details: Array<{ label: string; value: string }> = [
112
+ { label: 'config', value: configPath },
113
+ { label: 'contract', value: contractPath },
114
+ ];
115
+ if (options.db) {
116
+ details.push({ label: 'database', value: options.db });
117
+ }
118
+ if (options.plan) {
119
+ details.push({ label: 'mode', value: 'plan (dry run)' });
120
+ }
121
+ const header = formatStyledHeader({
122
+ command: 'db init',
123
+ description: 'Bootstrap a database to match the current contract',
124
+ url: 'https://pris.ly/db-init',
125
+ details,
126
+ flags,
127
+ });
128
+ console.log(header);
129
+ }
130
+
131
+ // Load contract file
132
+ let contractJsonContent: string;
133
+ try {
134
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
135
+ } catch (error) {
136
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
137
+ throw errorFileNotFound(contractPathAbsolute, {
138
+ why: `Contract file not found at ${contractPathAbsolute}`,
139
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
140
+ });
141
+ }
142
+ throw errorUnexpected(error instanceof Error ? error.message : String(error), {
143
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
144
+ });
145
+ }
146
+
147
+ let contractJson: Record<string, unknown>;
148
+ try {
149
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
150
+ } catch (error) {
151
+ throw errorContractValidationFailed(
152
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
153
+ { where: { path: contractPathAbsolute } },
154
+ );
155
+ }
156
+
157
+ // Resolve database URL
158
+ const dbUrl = options.db ?? config.db?.url;
159
+ if (!dbUrl) {
160
+ throw errorDatabaseUrlRequired({
161
+ why: `Database URL is required for db init (set db.url in ${configPath}, or pass --db <url>)`,
162
+ });
163
+ }
164
+
165
+ // Check for driver
166
+ if (!config.driver) {
167
+ throw errorDriverRequired({ why: 'Config.driver is required for db init' });
168
+ }
169
+ const driverDescriptor = config.driver;
170
+
171
+ // Check target supports migrations via the migrations capability
172
+ if (!config.target.migrations) {
173
+ throw errorTargetMigrationNotSupported({
174
+ why: `Target "${config.target.id}" does not support migrations`,
175
+ });
176
+ }
177
+ const migrations = config.target.migrations;
178
+
179
+ // Create driver
180
+ let driver: Awaited<ReturnType<(typeof driverDescriptor)['create']>>;
181
+ try {
182
+ driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
183
+ message: 'Connecting to database...',
184
+ flags,
185
+ });
186
+ } catch (error) {
187
+ const message = error instanceof Error ? error.message : String(error);
188
+ const code = (error as { code?: unknown }).code;
189
+ const redacted = redactDatabaseUrl(dbUrl);
190
+ throw errorRuntime('Database connection failed', {
191
+ why: message,
192
+ fix: 'Verify the database URL, ensure the database is reachable, and confirm credentials/permissions',
193
+ meta: {
194
+ ...(typeof code !== 'undefined' ? { code } : {}),
195
+ ...redacted,
196
+ },
197
+ });
198
+ }
199
+
200
+ try {
201
+ // Create family instance
202
+ const stack = createControlPlaneStack({
203
+ target: config.target,
204
+ adapter: config.adapter,
205
+ driver: driverDescriptor,
206
+ extensionPacks: config.extensionPacks,
207
+ });
208
+ const familyInstance = config.family.create(stack);
209
+ const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];
210
+ const frameworkComponents = assertFrameworkComponentsCompatible(
211
+ config.family.familyId,
212
+ config.target.targetId,
213
+ rawComponents,
214
+ );
215
+
216
+ // Validate contract
217
+ const contractIR = familyInstance.validateContractIR(contractJson);
218
+ assertContractRequirementsSatisfied({ contract: contractIR, stack });
219
+
220
+ // Create planner and runner from target migrations capability
221
+ const planner = migrations.createPlanner(familyInstance);
222
+ const runner = migrations.createRunner(familyInstance);
223
+
224
+ // Introspect live schema
225
+ const schemaIR = await withSpinner(() => familyInstance.introspect({ driver }), {
226
+ message: 'Introspecting database schema...',
227
+ flags,
228
+ });
229
+
230
+ // Policy for init mode (additive only)
231
+ const policy = { allowedOperationClasses: ['additive'] as const };
232
+
233
+ // Plan migration
234
+ const plannerResult: MigrationPlannerResult = await withSpinner(
235
+ async () =>
236
+ planner.plan({
237
+ contract: contractIR,
238
+ schema: schemaIR,
239
+ policy,
240
+ frameworkComponents,
241
+ }),
242
+ {
243
+ message: 'Planning migration...',
244
+ flags,
245
+ },
246
+ );
247
+
248
+ if (plannerResult.kind === 'failure') {
249
+ throw errorMigrationPlanningFailed({ conflicts: plannerResult.conflicts });
250
+ }
251
+
252
+ const migrationPlan: MigrationPlan = plannerResult.plan;
253
+
254
+ // Check for existing marker - handle idempotency and mismatch errors
255
+ const existingMarker = await familyInstance.readMarker({ driver });
256
+ if (existingMarker) {
257
+ const markerMatchesDestination =
258
+ existingMarker.coreHash === migrationPlan.destination.coreHash &&
259
+ (!migrationPlan.destination.profileHash ||
260
+ existingMarker.profileHash === migrationPlan.destination.profileHash);
261
+
262
+ if (markerMatchesDestination) {
263
+ // Already at destination - return success with no operations
264
+ const dbInitResult: DbInitResult = {
265
+ ok: true,
266
+ mode: options.plan ? 'plan' : 'apply',
267
+ plan: {
268
+ targetId: migrationPlan.targetId,
269
+ destination: migrationPlan.destination,
270
+ operations: [],
271
+ },
272
+ ...(options.plan
273
+ ? {}
274
+ : {
275
+ execution: { operationsPlanned: 0, operationsExecuted: 0 },
276
+ marker: {
277
+ coreHash: existingMarker.coreHash,
278
+ profileHash: existingMarker.profileHash,
279
+ },
280
+ }),
281
+ summary: 'Database already at target contract state',
282
+ timings: { total: Date.now() - startTime },
283
+ };
284
+ return dbInitResult;
285
+ }
286
+
287
+ // Marker exists but doesn't match destination - fail
288
+ const coreHashMismatch = existingMarker.coreHash !== migrationPlan.destination.coreHash;
289
+ const profileHashMismatch =
290
+ migrationPlan.destination.profileHash &&
291
+ existingMarker.profileHash !== migrationPlan.destination.profileHash;
292
+
293
+ const mismatchParts: string[] = [];
294
+ if (coreHashMismatch) {
295
+ mismatchParts.push(
296
+ `coreHash (marker: ${existingMarker.coreHash}, destination: ${migrationPlan.destination.coreHash})`,
297
+ );
298
+ }
299
+ if (profileHashMismatch) {
300
+ mismatchParts.push(
301
+ `profileHash (marker: ${existingMarker.profileHash}, destination: ${migrationPlan.destination.profileHash})`,
302
+ );
303
+ }
304
+
305
+ throw errorRuntime(
306
+ `Existing contract marker does not match plan destination. Mismatch in ${mismatchParts.join(' and ')}.`,
307
+ {
308
+ why: 'Database has an existing contract marker that does not match the target contract',
309
+ fix: 'If bootstrapping, drop/reset the database then re-run `prisma-next db init`; otherwise reconcile schema/marker using your migration workflow',
310
+ meta: {
311
+ code: 'MARKER_ORIGIN_MISMATCH',
312
+ markerCoreHash: existingMarker.coreHash,
313
+ destinationCoreHash: migrationPlan.destination.coreHash,
314
+ ...(existingMarker.profileHash
315
+ ? { markerProfileHash: existingMarker.profileHash }
316
+ : {}),
317
+ ...(migrationPlan.destination.profileHash
318
+ ? { destinationProfileHash: migrationPlan.destination.profileHash }
319
+ : {}),
320
+ },
321
+ },
322
+ );
323
+ }
324
+
325
+ // Plan mode - don't execute
326
+ if (options.plan) {
327
+ const dbInitResult: DbInitResult = {
328
+ ok: true,
329
+ mode: 'plan',
330
+ plan: {
331
+ targetId: migrationPlan.targetId,
332
+ destination: migrationPlan.destination,
333
+ operations: migrationPlan.operations.map((op) => ({
334
+ id: op.id,
335
+ label: op.label,
336
+ operationClass: op.operationClass,
337
+ })),
338
+ },
339
+ summary: `Planned ${migrationPlan.operations.length} operation(s)`,
340
+ timings: { total: Date.now() - startTime },
341
+ };
342
+ return dbInitResult;
343
+ }
344
+
345
+ // Apply mode - execute runner
346
+ // Log main message once, then show individual operations via callbacks
347
+ if (!flags.quiet && flags.json !== 'object') {
348
+ console.log('Applying migration plan and verifying schema...');
349
+ }
350
+
351
+ const callbacks = {
352
+ onOperationStart: (op: MigrationPlanOperation) => {
353
+ if (!flags.quiet && flags.json !== 'object') {
354
+ console.log(` → ${op.label}...`);
355
+ }
356
+ },
357
+ onOperationComplete: (_op: MigrationPlanOperation) => {
358
+ // Could log completion if needed
359
+ },
360
+ };
361
+
362
+ const runnerResult: MigrationRunnerResult = await runner.execute({
363
+ plan: migrationPlan,
364
+ driver,
365
+ destinationContract: contractIR,
366
+ policy,
367
+ callbacks,
368
+ // db init plans and applies back-to-back from a fresh introspection, so per-operation
369
+ // pre/postchecks and the idempotency probe are usually redundant overhead. We still
370
+ // enforce marker/origin compatibility and a full schema verification after apply.
371
+ executionChecks: {
372
+ prechecks: false,
373
+ postchecks: false,
374
+ idempotencyChecks: false,
375
+ },
376
+ frameworkComponents,
377
+ });
378
+
379
+ if (!runnerResult.ok) {
380
+ const meta: Record<string, unknown> = {
381
+ code: runnerResult.failure.code,
382
+ ...(runnerResult.failure.meta ?? {}),
383
+ };
384
+ const sqlState = typeof meta['sqlState'] === 'string' ? meta['sqlState'] : undefined;
385
+ const fix =
386
+ sqlState === '42501'
387
+ ? 'Grant the database user sufficient privileges (insufficient_privilege), or run db init as a more privileged role'
388
+ : runnerResult.failure.code === 'SCHEMA_VERIFY_FAILED'
389
+ ? 'Fix the schema mismatch (db init is additive-only), or drop/reset the database and re-run `prisma-next db init`'
390
+ : undefined;
391
+
392
+ throw errorRuntime(runnerResult.failure.summary, {
393
+ why:
394
+ runnerResult.failure.why ?? `Migration runner failed: ${runnerResult.failure.code}`,
395
+ ...(fix ? { fix } : {}),
396
+ meta,
397
+ });
398
+ }
399
+
400
+ const execution = runnerResult.value;
401
+
402
+ const dbInitResult: DbInitResult = {
403
+ ok: true,
404
+ mode: 'apply',
405
+ plan: {
406
+ targetId: migrationPlan.targetId,
407
+ destination: migrationPlan.destination,
408
+ operations: migrationPlan.operations.map((op) => ({
409
+ id: op.id,
410
+ label: op.label,
411
+ operationClass: op.operationClass,
412
+ })),
413
+ },
414
+ execution: {
415
+ operationsPlanned: execution.operationsPlanned,
416
+ operationsExecuted: execution.operationsExecuted,
417
+ },
418
+ marker: migrationPlan.destination.profileHash
419
+ ? {
420
+ coreHash: migrationPlan.destination.coreHash,
421
+ profileHash: migrationPlan.destination.profileHash,
422
+ }
423
+ : { coreHash: migrationPlan.destination.coreHash },
424
+ summary: `Applied ${execution.operationsExecuted} operation(s), marker written`,
425
+ timings: { total: Date.now() - startTime },
426
+ };
427
+ return dbInitResult;
428
+ } finally {
429
+ await driver.close();
430
+ }
431
+ });
432
+
433
+ // Handle result
434
+ const exitCode = handleResult(result, flags, (dbInitResult) => {
435
+ if (flags.json === 'object') {
436
+ console.log(formatDbInitJson(dbInitResult));
437
+ } else {
438
+ const output =
439
+ dbInitResult.mode === 'plan'
440
+ ? formatDbInitPlanOutput(dbInitResult, flags)
441
+ : formatDbInitApplyOutput(dbInitResult, flags);
442
+ if (output) {
443
+ console.log(output);
444
+ }
445
+ }
446
+ });
447
+
448
+ process.exit(exitCode);
449
+ });
450
+
451
+ return command;
452
+ }