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

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 (65) hide show
  1. package/dist/cli.d.ts +2 -0
  2. package/dist/cli.d.ts.map +1 -0
  3. package/dist/commands/contract-emit.d.ts +2 -4
  4. package/dist/commands/contract-emit.d.ts.map +1 -0
  5. package/dist/commands/db-init.d.ts +2 -4
  6. package/dist/commands/db-init.d.ts.map +1 -0
  7. package/dist/commands/db-introspect.d.ts +2 -4
  8. package/dist/commands/db-introspect.d.ts.map +1 -0
  9. package/dist/commands/db-schema-verify.d.ts +2 -4
  10. package/dist/commands/db-schema-verify.d.ts.map +1 -0
  11. package/dist/commands/db-sign.d.ts +2 -4
  12. package/dist/commands/db-sign.d.ts.map +1 -0
  13. package/dist/commands/db-verify.d.ts +2 -4
  14. package/dist/commands/db-verify.d.ts.map +1 -0
  15. package/dist/config-loader.d.ts +3 -5
  16. package/dist/config-loader.d.ts.map +1 -0
  17. package/dist/exports/config-types.d.ts +3 -0
  18. package/dist/exports/config-types.d.ts.map +1 -0
  19. package/dist/exports/config-types.js.map +1 -0
  20. package/dist/exports/index.d.ts +4 -0
  21. package/dist/exports/index.d.ts.map +1 -0
  22. package/dist/{index.js → exports/index.js} +3 -3
  23. package/dist/exports/index.js.map +1 -0
  24. package/dist/{index.d.ts → load-ts-contract.d.ts} +4 -8
  25. package/dist/load-ts-contract.d.ts.map +1 -0
  26. package/dist/utils/action.d.ts +16 -0
  27. package/dist/utils/action.d.ts.map +1 -0
  28. package/dist/utils/cli-errors.d.ts +7 -0
  29. package/dist/utils/cli-errors.d.ts.map +1 -0
  30. package/dist/utils/command-helpers.d.ts +12 -0
  31. package/dist/utils/command-helpers.d.ts.map +1 -0
  32. package/dist/utils/framework-components.d.ts +81 -0
  33. package/dist/utils/framework-components.d.ts.map +1 -0
  34. package/dist/utils/global-flags.d.ts +25 -0
  35. package/dist/utils/global-flags.d.ts.map +1 -0
  36. package/dist/utils/output.d.ts +142 -0
  37. package/dist/utils/output.d.ts.map +1 -0
  38. package/dist/utils/result-handler.d.ts +15 -0
  39. package/dist/utils/result-handler.d.ts.map +1 -0
  40. package/dist/utils/spinner.d.ts +29 -0
  41. package/dist/utils/spinner.d.ts.map +1 -0
  42. package/package.json +17 -16
  43. package/src/cli.ts +260 -0
  44. package/src/commands/contract-emit.ts +189 -0
  45. package/src/commands/db-init.ts +456 -0
  46. package/src/commands/db-introspect.ts +260 -0
  47. package/src/commands/db-schema-verify.ts +236 -0
  48. package/src/commands/db-sign.ts +277 -0
  49. package/src/commands/db-verify.ts +233 -0
  50. package/src/config-loader.ts +76 -0
  51. package/src/exports/config-types.ts +6 -0
  52. package/src/exports/index.ts +4 -0
  53. package/src/load-ts-contract.ts +217 -0
  54. package/src/utils/action.ts +43 -0
  55. package/src/utils/cli-errors.ts +26 -0
  56. package/src/utils/command-helpers.ts +26 -0
  57. package/src/utils/framework-components.ts +196 -0
  58. package/src/utils/global-flags.ts +75 -0
  59. package/src/utils/output.ts +1471 -0
  60. package/src/utils/result-handler.ts +44 -0
  61. package/src/utils/spinner.ts +67 -0
  62. package/dist/config-types.d.ts +0 -1
  63. package/dist/config-types.js.map +0 -1
  64. package/dist/index.js.map +0 -1
  65. /package/dist/{config-types.js → exports/config-types.js} +0 -0
@@ -0,0 +1,260 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import {
4
+ errorDatabaseUrlRequired,
5
+ errorDriverRequired,
6
+ errorRuntime,
7
+ errorUnexpected,
8
+ } from '@prisma-next/core-control-plane/errors';
9
+ import type { CoreSchemaView } from '@prisma-next/core-control-plane/schema-view';
10
+ import type { IntrospectSchemaResult } from '@prisma-next/core-control-plane/types';
11
+ import { Command } from 'commander';
12
+ import { loadConfig } from '../config-loader';
13
+ import { performAction } from '../utils/action';
14
+ import { setCommandDescriptions } from '../utils/command-helpers';
15
+ import { assertContractRequirementsSatisfied } from '../utils/framework-components';
16
+ import { parseGlobalFlags } from '../utils/global-flags';
17
+ import {
18
+ formatCommandHelp,
19
+ formatIntrospectJson,
20
+ formatIntrospectOutput,
21
+ formatStyledHeader,
22
+ } from '../utils/output';
23
+ import { handleResult } from '../utils/result-handler';
24
+ import { withSpinner } from '../utils/spinner';
25
+
26
+ interface DbIntrospectOptions {
27
+ readonly db?: string;
28
+ readonly config?: string;
29
+ readonly json?: string | boolean;
30
+ readonly quiet?: boolean;
31
+ readonly q?: boolean;
32
+ readonly verbose?: boolean;
33
+ readonly v?: boolean;
34
+ readonly vv?: boolean;
35
+ readonly trace?: boolean;
36
+ readonly timestamps?: boolean;
37
+ readonly color?: boolean;
38
+ readonly 'no-color'?: boolean;
39
+ }
40
+
41
+ export function createDbIntrospectCommand(): Command {
42
+ const command = new Command('introspect');
43
+ setCommandDescriptions(
44
+ command,
45
+ 'Inspect the database schema',
46
+ 'Reads the live database schema and displays it as a tree structure. This command\n' +
47
+ 'does not check the schema against your contract - it only shows what exists in\n' +
48
+ 'the database. Use `db verify` or `db schema-verify` to compare against your contract.',
49
+ );
50
+ command
51
+ .configureHelp({
52
+ formatHelp: (cmd) => {
53
+ const flags = parseGlobalFlags({});
54
+ return formatCommandHelp({ command: cmd, flags });
55
+ },
56
+ })
57
+ .option('--db <url>', 'Database connection string')
58
+ .option('--config <path>', 'Path to prisma-next.config.ts')
59
+ .option('--json [format]', 'Output as JSON (object or ndjson)', false)
60
+ .option('-q, --quiet', 'Quiet mode: errors only')
61
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
62
+ .option('-vv, --trace', 'Trace output: deep internals, stack traces')
63
+ .option('--timestamps', 'Add timestamps to output')
64
+ .option('--color', 'Force color output')
65
+ .option('--no-color', 'Disable color output')
66
+ .action(async (options: DbIntrospectOptions) => {
67
+ const flags = parseGlobalFlags(options);
68
+
69
+ const result = await performAction(async () => {
70
+ const startTime = Date.now();
71
+
72
+ // Load config (file I/O)
73
+ const config = await loadConfig(options.config);
74
+ // Normalize config path for display (match contract path format - no ./ prefix)
75
+ const configPath = options.config
76
+ ? relative(process.cwd(), resolve(options.config))
77
+ : 'prisma-next.config.ts';
78
+
79
+ // Optionally load contract if contract config exists
80
+ let contractIR: unknown | undefined;
81
+ if (config.contract?.output) {
82
+ const contractPath = resolve(config.contract.output);
83
+ try {
84
+ const contractJsonContent = await readFile(contractPath, 'utf-8');
85
+ contractIR = JSON.parse(contractJsonContent);
86
+ } catch (error) {
87
+ // Contract file is optional for introspection - don't fail if it doesn't exist
88
+ if (error instanceof Error && (error as { code?: string }).code !== 'ENOENT') {
89
+ throw errorUnexpected(error.message, {
90
+ why: `Failed to read contract file: ${error.message}`,
91
+ });
92
+ }
93
+ }
94
+ }
95
+
96
+ // Output header (only for human-readable output)
97
+ if (flags.json !== 'object' && !flags.quiet) {
98
+ const details: Array<{ label: string; value: string }> = [
99
+ { label: 'config', value: configPath },
100
+ ];
101
+ if (options.db) {
102
+ // Mask password in URL for security
103
+ const maskedUrl = options.db.replace(/:([^:@]+)@/, ':****@');
104
+ details.push({ label: 'database', value: maskedUrl });
105
+ } else if (config.db?.url) {
106
+ // Mask password in URL for security
107
+ const maskedUrl = config.db.url.replace(/:([^:@]+)@/, ':****@');
108
+ details.push({ label: 'database', value: maskedUrl });
109
+ }
110
+ const header = formatStyledHeader({
111
+ command: 'db introspect',
112
+ description: 'Inspect the database schema',
113
+ url: 'https://pris.ly/db-introspect',
114
+ details,
115
+ flags,
116
+ });
117
+ console.log(header);
118
+ }
119
+
120
+ // Resolve database URL
121
+ const dbUrl = options.db ?? config.db?.url;
122
+ if (!dbUrl) {
123
+ throw errorDatabaseUrlRequired();
124
+ }
125
+
126
+ // Check for driver
127
+ if (!config.driver) {
128
+ throw errorDriverRequired();
129
+ }
130
+
131
+ // Store driver descriptor after null check
132
+ const driverDescriptor = config.driver;
133
+
134
+ // Create driver
135
+ const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
136
+ message: 'Connecting to database...',
137
+ flags,
138
+ });
139
+
140
+ try {
141
+ // Create family instance
142
+ const familyInstance = config.family.create({
143
+ target: config.target,
144
+ adapter: config.adapter,
145
+ driver: driverDescriptor,
146
+ extensionPacks: config.extensionPacks ?? [],
147
+ });
148
+
149
+ // Validate contract IR if we loaded it
150
+ if (contractIR) {
151
+ const validatedContract = familyInstance.validateContractIR(contractIR);
152
+ assertContractRequirementsSatisfied({
153
+ contract: validatedContract,
154
+ family: config.family,
155
+ target: config.target,
156
+ adapter: config.adapter,
157
+ extensionPacks: config.extensionPacks,
158
+ });
159
+ contractIR = validatedContract;
160
+ }
161
+
162
+ // Call family instance introspect method
163
+ let schemaIR: unknown;
164
+ try {
165
+ schemaIR = await withSpinner(
166
+ () =>
167
+ familyInstance.introspect({
168
+ driver,
169
+ contractIR,
170
+ }),
171
+ {
172
+ message: 'Introspecting database schema...',
173
+ flags,
174
+ },
175
+ );
176
+ } catch (error) {
177
+ // Wrap errors from introspect() in structured error
178
+ throw errorRuntime(error instanceof Error ? error.message : String(error), {
179
+ why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`,
180
+ });
181
+ }
182
+
183
+ // Optionally call toSchemaView if available
184
+ let schemaView: CoreSchemaView | undefined;
185
+ if (familyInstance.toSchemaView) {
186
+ try {
187
+ schemaView = familyInstance.toSchemaView(schemaIR);
188
+ } catch (error) {
189
+ // Schema view projection is optional - log but don't fail
190
+ if (flags.verbose) {
191
+ console.error(
192
+ `Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`,
193
+ );
194
+ }
195
+ }
196
+ }
197
+
198
+ const totalTime = Date.now() - startTime;
199
+
200
+ // Add blank line after all async operations if spinners were shown
201
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
202
+ console.log('');
203
+ }
204
+
205
+ // Build result envelope
206
+ const introspectResult: IntrospectSchemaResult<unknown> = {
207
+ ok: true,
208
+ summary: 'Schema introspected successfully',
209
+ target: {
210
+ familyId: config.family.familyId,
211
+ id: config.target.targetId,
212
+ },
213
+ schema: schemaIR,
214
+ ...(configPath || options.db || config.db?.url
215
+ ? {
216
+ meta: {
217
+ ...(configPath ? { configPath } : {}),
218
+ ...(options.db || config.db?.url
219
+ ? {
220
+ dbUrl: (options.db ?? config.db?.url ?? '').replace(
221
+ /:([^:@]+)@/,
222
+ ':****@',
223
+ ),
224
+ }
225
+ : {}),
226
+ },
227
+ }
228
+ : {}),
229
+ timings: {
230
+ total: totalTime,
231
+ },
232
+ };
233
+
234
+ return { introspectResult, schemaView };
235
+ } finally {
236
+ // Ensure driver connection is closed
237
+ await driver.close();
238
+ }
239
+ });
240
+
241
+ // Handle result - formats output and returns exit code
242
+ const exitCode = handleResult(result, flags, (value) => {
243
+ const { introspectResult, schemaView } = value;
244
+ // Output based on flags
245
+ if (flags.json === 'object') {
246
+ // JSON output to stdout
247
+ console.log(formatIntrospectJson(introspectResult));
248
+ } else {
249
+ // Human-readable output to stdout
250
+ const output = formatIntrospectOutput(introspectResult, schemaView, flags);
251
+ if (output) {
252
+ console.log(output);
253
+ }
254
+ }
255
+ });
256
+ process.exit(exitCode);
257
+ });
258
+
259
+ return command;
260
+ }
@@ -0,0 +1,236 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { relative, resolve } from 'node:path';
3
+ import type { ContractIR } from '@prisma-next/contract/ir';
4
+ import {
5
+ errorDatabaseUrlRequired,
6
+ errorDriverRequired,
7
+ errorFileNotFound,
8
+ errorRuntime,
9
+ errorUnexpected,
10
+ } from '@prisma-next/core-control-plane/errors';
11
+ import type { VerifyDatabaseSchemaResult } from '@prisma-next/core-control-plane/types';
12
+ import { Command } from 'commander';
13
+ import { loadConfig } from '../config-loader';
14
+ import { performAction } from '../utils/action';
15
+ import { setCommandDescriptions } from '../utils/command-helpers';
16
+ import {
17
+ assertContractRequirementsSatisfied,
18
+ assertFrameworkComponentsCompatible,
19
+ } from '../utils/framework-components';
20
+ import { parseGlobalFlags } from '../utils/global-flags';
21
+ import {
22
+ formatCommandHelp,
23
+ formatSchemaVerifyJson,
24
+ formatSchemaVerifyOutput,
25
+ formatStyledHeader,
26
+ } from '../utils/output';
27
+ import { handleResult } from '../utils/result-handler';
28
+ import { withSpinner } from '../utils/spinner';
29
+
30
+ interface DbSchemaVerifyOptions {
31
+ readonly db?: string;
32
+ readonly config?: string;
33
+ readonly json?: string | boolean;
34
+ readonly strict?: boolean;
35
+ readonly quiet?: boolean;
36
+ readonly q?: boolean;
37
+ readonly verbose?: boolean;
38
+ readonly v?: boolean;
39
+ readonly vv?: boolean;
40
+ readonly trace?: boolean;
41
+ readonly timestamps?: boolean;
42
+ readonly color?: boolean;
43
+ readonly 'no-color'?: boolean;
44
+ }
45
+
46
+ export function createDbSchemaVerifyCommand(): Command {
47
+ const command = new Command('schema-verify');
48
+ setCommandDescriptions(
49
+ command,
50
+ 'Check whether the database schema satisfies your contract',
51
+ 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\n' +
52
+ 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\n' +
53
+ 'verification tree. This is a read-only operation that does not modify the database.',
54
+ );
55
+ command
56
+ .configureHelp({
57
+ formatHelp: (cmd) => {
58
+ const flags = parseGlobalFlags({});
59
+ return formatCommandHelp({ command: cmd, flags });
60
+ },
61
+ })
62
+ .option('--db <url>', 'Database connection string')
63
+ .option('--config <path>', 'Path to prisma-next.config.ts')
64
+ .option('--json [format]', 'Output as JSON (object or ndjson)', false)
65
+ .option('--strict', 'Strict mode: extra schema elements cause failures', false)
66
+ .option('-q, --quiet', 'Quiet mode: errors only')
67
+ .option('-v, --verbose', 'Verbose output: debug info, timings')
68
+ .option('-vv, --trace', 'Trace output: deep internals, stack traces')
69
+ .option('--timestamps', 'Add timestamps to output')
70
+ .option('--color', 'Force color output')
71
+ .option('--no-color', 'Disable color output')
72
+ .action(async (options: DbSchemaVerifyOptions) => {
73
+ const flags = parseGlobalFlags(options);
74
+
75
+ const result = await performAction(async () => {
76
+ // Load config (file I/O)
77
+ const config = await loadConfig(options.config);
78
+ // Normalize config path for display (match contract path format - no ./ prefix)
79
+ const configPath = options.config
80
+ ? relative(process.cwd(), resolve(options.config))
81
+ : 'prisma-next.config.ts';
82
+ const contractPathAbsolute = config.contract?.output
83
+ ? resolve(config.contract.output)
84
+ : resolve('src/prisma/contract.json');
85
+ // Convert to relative path for display
86
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
87
+
88
+ // Output header (only for human-readable output)
89
+ if (flags.json !== 'object' && !flags.quiet) {
90
+ const details: Array<{ label: string; value: string }> = [
91
+ { label: 'config', value: configPath },
92
+ { label: 'contract', value: contractPath },
93
+ ];
94
+ if (options.db) {
95
+ details.push({ label: 'database', value: options.db });
96
+ }
97
+ const header = formatStyledHeader({
98
+ command: 'db schema-verify',
99
+ description: 'Check whether the database schema satisfies your contract',
100
+ url: 'https://pris.ly/db-schema-verify',
101
+ details,
102
+ flags,
103
+ });
104
+ console.log(header);
105
+ }
106
+
107
+ // Load contract file (file I/O)
108
+ let contractJsonContent: string;
109
+ try {
110
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
111
+ } catch (error) {
112
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
113
+ throw errorFileNotFound(contractPathAbsolute, {
114
+ why: `Contract file not found at ${contractPathAbsolute}`,
115
+ });
116
+ }
117
+ throw errorUnexpected(error instanceof Error ? error.message : String(error), {
118
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
119
+ });
120
+ }
121
+ const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
122
+
123
+ // Check for driver (needed for family instance creation)
124
+ if (!config.driver) {
125
+ throw errorDriverRequired();
126
+ }
127
+
128
+ // Store driver descriptor after null check
129
+ const driverDescriptor = config.driver;
130
+
131
+ // Create family instance (needed for contract validation)
132
+ const familyInstance = config.family.create({
133
+ target: config.target,
134
+ adapter: config.adapter,
135
+ driver: driverDescriptor,
136
+ extensionPacks: config.extensionPacks ?? [],
137
+ });
138
+
139
+ // Validate contract using instance validator
140
+ const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;
141
+
142
+ // Validate contract requirements fail-fast before connecting to database
143
+ assertContractRequirementsSatisfied({
144
+ contract: contractIR,
145
+ family: config.family,
146
+ target: config.target,
147
+ adapter: config.adapter,
148
+ extensionPacks: config.extensionPacks,
149
+ });
150
+
151
+ // Resolve database URL
152
+ const dbUrl = options.db ?? config.db?.url;
153
+ if (!dbUrl) {
154
+ throw errorDatabaseUrlRequired();
155
+ }
156
+
157
+ // Create driver
158
+ const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
159
+ message: 'Connecting to database...',
160
+ flags,
161
+ });
162
+
163
+ try {
164
+ const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];
165
+ const frameworkComponents = assertFrameworkComponentsCompatible(
166
+ config.family.familyId,
167
+ config.target.targetId,
168
+ rawComponents,
169
+ );
170
+
171
+ // Call family instance schemaVerify method
172
+ let schemaVerifyResult: VerifyDatabaseSchemaResult;
173
+ try {
174
+ schemaVerifyResult = await withSpinner(
175
+ () =>
176
+ familyInstance.schemaVerify({
177
+ driver,
178
+ contractIR,
179
+ strict: options.strict ?? false,
180
+ contractPath: contractPathAbsolute,
181
+ configPath,
182
+ frameworkComponents,
183
+ }),
184
+ {
185
+ message: 'Verifying database schema...',
186
+ flags,
187
+ },
188
+ );
189
+ } catch (error) {
190
+ // Wrap errors from schemaVerify() in structured error
191
+ throw errorRuntime(error instanceof Error ? error.message : String(error), {
192
+ why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,
193
+ });
194
+ }
195
+
196
+ // Add blank line after all async operations if spinners were shown
197
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
198
+ console.log('');
199
+ }
200
+
201
+ // Return result (don't throw for logical mismatches - handle exit code separately)
202
+ return schemaVerifyResult;
203
+ } finally {
204
+ // Ensure driver connection is closed
205
+ await driver.close();
206
+ }
207
+ });
208
+
209
+ // Handle result - formats output and returns exit code
210
+ const exitCode = handleResult(result, flags, (schemaVerifyResult) => {
211
+ // Output based on flags
212
+ if (flags.json === 'object') {
213
+ // JSON output to stdout
214
+ console.log(formatSchemaVerifyJson(schemaVerifyResult));
215
+ } else {
216
+ // Human-readable output to stdout
217
+ const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
218
+ if (output) {
219
+ console.log(output);
220
+ }
221
+ }
222
+ });
223
+
224
+ // For logical schema mismatches, check if verification passed
225
+ // Infra errors already handled by handleResult (returns non-zero exit code)
226
+ if (result.ok && !result.value.ok) {
227
+ // Schema verification failed - exit with code 1
228
+ process.exit(1);
229
+ } else {
230
+ // Success or infra error - use exit code from handleResult
231
+ process.exit(exitCode);
232
+ }
233
+ });
234
+
235
+ return command;
236
+ }