@prisma-next/cli 0.3.0-dev.8 → 0.3.0-pr.100.1

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 (66) 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.js +1502 -942
  9. package/dist/cli.js.map +1 -1
  10. package/dist/commands/contract-emit.d.ts.map +1 -1
  11. package/dist/commands/contract-emit.js +3 -2
  12. package/dist/commands/db-init.d.ts.map +1 -1
  13. package/dist/commands/db-init.js +205 -285
  14. package/dist/commands/db-init.js.map +1 -1
  15. package/dist/commands/db-introspect.d.ts.map +1 -1
  16. package/dist/commands/db-introspect.js +108 -139
  17. package/dist/commands/db-introspect.js.map +1 -1
  18. package/dist/commands/db-schema-verify.d.ts.map +1 -1
  19. package/dist/commands/db-schema-verify.js +120 -109
  20. package/dist/commands/db-schema-verify.js.map +1 -1
  21. package/dist/commands/db-sign.d.ts.map +1 -1
  22. package/dist/commands/db-sign.js +152 -152
  23. package/dist/commands/db-sign.js.map +1 -1
  24. package/dist/commands/db-verify.d.ts.map +1 -1
  25. package/dist/commands/db-verify.js +142 -118
  26. package/dist/commands/db-verify.js.map +1 -1
  27. package/dist/control-api/client.d.ts +13 -0
  28. package/dist/control-api/client.d.ts.map +1 -0
  29. package/dist/control-api/operations/db-init.d.ts +29 -0
  30. package/dist/control-api/operations/db-init.d.ts.map +1 -0
  31. package/dist/control-api/types.d.ts +387 -0
  32. package/dist/control-api/types.d.ts.map +1 -0
  33. package/dist/exports/control-api.d.ts +13 -0
  34. package/dist/exports/control-api.d.ts.map +1 -0
  35. package/dist/exports/control-api.js +7 -0
  36. package/dist/exports/control-api.js.map +1 -0
  37. package/dist/exports/index.js +3 -2
  38. package/dist/exports/index.js.map +1 -1
  39. package/dist/utils/cli-errors.d.ts +1 -1
  40. package/dist/utils/cli-errors.d.ts.map +1 -1
  41. package/dist/utils/progress-adapter.d.ts +26 -0
  42. package/dist/utils/progress-adapter.d.ts.map +1 -0
  43. package/package.json +20 -16
  44. package/src/commands/contract-emit.ts +179 -102
  45. package/src/commands/db-init.ts +263 -355
  46. package/src/commands/db-introspect.ts +151 -180
  47. package/src/commands/db-schema-verify.ts +151 -145
  48. package/src/commands/db-sign.ts +202 -196
  49. package/src/commands/db-verify.ts +180 -151
  50. package/src/control-api/client.ts +589 -0
  51. package/src/control-api/operations/db-init.ts +281 -0
  52. package/src/control-api/types.ts +461 -0
  53. package/src/exports/control-api.ts +46 -0
  54. package/src/utils/cli-errors.ts +1 -1
  55. package/src/utils/progress-adapter.ts +86 -0
  56. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  57. package/dist/chunk-CVNWLFXO.js +0 -91
  58. package/dist/chunk-CVNWLFXO.js.map +0 -1
  59. package/dist/chunk-QUPBU4KV.js +0 -131
  60. package/dist/chunk-QUPBU4KV.js.map +0 -1
  61. package/dist/utils/action.d.ts +0 -16
  62. package/dist/utils/action.d.ts.map +0 -1
  63. package/dist/utils/spinner.d.ts +0 -29
  64. package/dist/utils/spinner.d.ts.map +0 -1
  65. package/src/utils/action.ts +0 -43
  66. package/src/utils/spinner.ts +0 -67
@@ -1,32 +1,33 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { relative, resolve } from 'node:path';
3
- import type { ContractIR } from '@prisma-next/contract/ir';
3
+ import type { VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';
4
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
5
+ import { Command } from 'commander';
6
+ import { loadConfig } from '../config-loader';
7
+ import { createControlClient } from '../control-api/client';
4
8
  import {
5
- errorDatabaseUrlRequired,
9
+ CliStructuredError,
10
+ errorContractValidationFailed,
11
+ errorDatabaseConnectionRequired,
6
12
  errorDriverRequired,
7
13
  errorFileNotFound,
8
14
  errorHashMismatch,
15
+ errorJsonFormatNotSupported,
9
16
  errorMarkerMissing,
10
17
  errorRuntime,
11
18
  errorTargetMismatch,
12
19
  errorUnexpected,
13
- } from '@prisma-next/core-control-plane/errors';
14
- import type { VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';
15
- import { createControlPlaneStack } from '@prisma-next/core-control-plane/types';
16
- import { Command } from 'commander';
17
- import { loadConfig } from '../config-loader';
18
- import { performAction } from '../utils/action';
20
+ } from '../utils/cli-errors';
19
21
  import { setCommandDescriptions } from '../utils/command-helpers';
20
- import { assertContractRequirementsSatisfied } from '../utils/framework-components';
21
- import { parseGlobalFlags } from '../utils/global-flags';
22
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
22
23
  import {
23
24
  formatCommandHelp,
24
25
  formatStyledHeader,
25
26
  formatVerifyJson,
26
27
  formatVerifyOutput,
27
28
  } from '../utils/output';
29
+ import { createProgressAdapter } from '../utils/progress-adapter';
28
30
  import { handleResult } from '../utils/result-handler';
29
- import { withSpinner } from '../utils/spinner';
30
31
 
31
32
  interface DbVerifyOptions {
32
33
  readonly db?: string;
@@ -43,6 +44,161 @@ interface DbVerifyOptions {
43
44
  readonly 'no-color'?: boolean;
44
45
  }
45
46
 
47
+ /**
48
+ * Maps a VerifyDatabaseResult failure to a CliStructuredError.
49
+ */
50
+ function mapVerifyFailure(verifyResult: VerifyDatabaseResult): CliStructuredError {
51
+ if (!verifyResult.ok && verifyResult.code) {
52
+ if (verifyResult.code === 'PN-RTM-3001') {
53
+ return errorMarkerMissing();
54
+ }
55
+ if (verifyResult.code === 'PN-RTM-3002') {
56
+ return errorHashMismatch({
57
+ expected: verifyResult.contract.coreHash,
58
+ ...(verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}),
59
+ });
60
+ }
61
+ if (verifyResult.code === 'PN-RTM-3003') {
62
+ return errorTargetMismatch(
63
+ verifyResult.target.expected,
64
+ verifyResult.target.actual ?? 'unknown',
65
+ );
66
+ }
67
+ // Unknown code - fall through to runtime error
68
+ }
69
+ return errorRuntime(verifyResult.summary);
70
+ }
71
+
72
+ /**
73
+ * Executes the db verify command and returns a structured Result.
74
+ */
75
+ async function executeDbVerifyCommand(
76
+ options: DbVerifyOptions,
77
+ flags: GlobalFlags,
78
+ ): Promise<Result<VerifyDatabaseResult, CliStructuredError>> {
79
+ // Load config
80
+ const config = await loadConfig(options.config);
81
+ const configPath = options.config
82
+ ? relative(process.cwd(), resolve(options.config))
83
+ : 'prisma-next.config.ts';
84
+ const contractPathAbsolute = config.contract?.output
85
+ ? resolve(config.contract.output)
86
+ : resolve('src/prisma/contract.json');
87
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
88
+
89
+ // Output header
90
+ if (flags.json !== 'object' && !flags.quiet) {
91
+ const details: Array<{ label: string; value: string }> = [
92
+ { label: 'config', value: configPath },
93
+ { label: 'contract', value: contractPath },
94
+ ];
95
+ if (options.db) {
96
+ details.push({ label: 'database', value: options.db });
97
+ }
98
+ const header = formatStyledHeader({
99
+ command: 'db verify',
100
+ description: 'Check whether the database has been signed with your contract',
101
+ url: 'https://pris.ly/db-verify',
102
+ details,
103
+ flags,
104
+ });
105
+ console.log(header);
106
+ }
107
+
108
+ // Load contract file
109
+ let contractJsonContent: string;
110
+ try {
111
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
112
+ } catch (error) {
113
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
114
+ return notOk(
115
+ errorFileNotFound(contractPathAbsolute, {
116
+ why: `Contract file not found at ${contractPathAbsolute}`,
117
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
118
+ }),
119
+ );
120
+ }
121
+ return notOk(
122
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
123
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
124
+ }),
125
+ );
126
+ }
127
+
128
+ let contractJson: Record<string, unknown>;
129
+ try {
130
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
131
+ } catch (error) {
132
+ return notOk(
133
+ errorContractValidationFailed(
134
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
135
+ { where: { path: contractPathAbsolute } },
136
+ ),
137
+ );
138
+ }
139
+
140
+ // Resolve database connection (--db flag or config.db.connection)
141
+ const dbConnection = options.db ?? config.db?.connection;
142
+ if (!dbConnection) {
143
+ return notOk(
144
+ errorDatabaseConnectionRequired({
145
+ why: `Database connection is required for db verify (set db.connection in ${configPath}, or pass --db <url>)`,
146
+ }),
147
+ );
148
+ }
149
+
150
+ // Check for driver
151
+ if (!config.driver) {
152
+ return notOk(errorDriverRequired({ why: 'Config.driver is required for db verify' }));
153
+ }
154
+
155
+ // Create control client
156
+ const client = createControlClient({
157
+ family: config.family,
158
+ target: config.target,
159
+ adapter: config.adapter,
160
+ driver: config.driver,
161
+ extensionPacks: config.extensionPacks ?? [],
162
+ });
163
+
164
+ // Create progress adapter
165
+ const onProgress = createProgressAdapter({ flags });
166
+
167
+ try {
168
+ const verifyResult = await client.verify({
169
+ contractIR: contractJson,
170
+ connection: dbConnection,
171
+ onProgress,
172
+ });
173
+
174
+ // Add blank line after all async operations if spinners were shown
175
+ if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
176
+ console.log('');
177
+ }
178
+
179
+ // If verification failed, map to CLI structured error
180
+ if (!verifyResult.ok) {
181
+ return notOk(mapVerifyFailure(verifyResult));
182
+ }
183
+
184
+ return ok(verifyResult);
185
+ } catch (error) {
186
+ // Driver already throws CliStructuredError for connection failures
187
+ if (error instanceof CliStructuredError) {
188
+ return notOk(error);
189
+ }
190
+
191
+ // Wrap unexpected errors
192
+ return notOk(
193
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
194
+ why: `Unexpected error during db verify: ${error instanceof Error ? error.message : String(error)}`,
195
+ }),
196
+ );
197
+ } finally {
198
+ await client.close();
199
+ }
200
+ }
201
+
46
202
  export function createDbVerifyCommand(): Command {
47
203
  const command = new Command('verify');
48
204
  setCommandDescriptions(
@@ -60,7 +216,7 @@ export function createDbVerifyCommand(): Command {
60
216
  })
61
217
  .option('--db <url>', 'Database connection string')
62
218
  .option('--config <path>', 'Path to prisma-next.config.ts')
63
- .option('--json [format]', 'Output as JSON (object or ndjson)', false)
219
+ .option('--json [format]', 'Output as JSON (object)', false)
64
220
  .option('-q, --quiet', 'Quiet mode: errors only')
65
221
  .option('-v, --verbose', 'Verbose output: debug info, timings')
66
222
  .option('-vv, --trace', 'Trace output: deep internals, stack traces')
@@ -70,152 +226,25 @@ export function createDbVerifyCommand(): Command {
70
226
  .action(async (options: DbVerifyOptions) => {
71
227
  const flags = parseGlobalFlags(options);
72
228
 
73
- const result = await performAction(async () => {
74
- // Load config (file I/O)
75
- const config = await loadConfig(options.config);
76
- // Normalize config path for display (match contract path format - no ./ prefix)
77
- const configPath = options.config
78
- ? relative(process.cwd(), resolve(options.config))
79
- : 'prisma-next.config.ts';
80
- const contractPathAbsolute = config.contract?.output
81
- ? resolve(config.contract.output)
82
- : resolve('src/prisma/contract.json');
83
- // Convert to relative path for display
84
- const contractPath = relative(process.cwd(), contractPathAbsolute);
85
-
86
- // Output header (only for human-readable output)
87
- if (flags.json !== 'object' && !flags.quiet) {
88
- const details: Array<{ label: string; value: string }> = [
89
- { label: 'config', value: configPath },
90
- { label: 'contract', value: contractPath },
91
- ];
92
- if (options.db) {
93
- details.push({ label: 'database', value: options.db });
94
- }
95
- const header = formatStyledHeader({
229
+ // Validate JSON format option
230
+ if (flags.json === 'ndjson') {
231
+ const result = notOk(
232
+ errorJsonFormatNotSupported({
96
233
  command: 'db verify',
97
- description: 'Check whether the database has been signed with your contract',
98
- url: 'https://pris.ly/db-verify',
99
- details,
100
- flags,
101
- });
102
- console.log(header);
103
- }
104
-
105
- // Load contract file (file I/O)
106
- let contractJsonContent: string;
107
- try {
108
- contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
109
- } catch (error) {
110
- if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
111
- throw errorFileNotFound(contractPathAbsolute, {
112
- why: `Contract file not found at ${contractPathAbsolute}`,
113
- });
114
- }
115
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
116
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
117
- });
118
- }
119
- const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
120
-
121
- // Resolve database URL
122
- const dbUrl = options.db ?? config.db?.url;
123
- if (!dbUrl) {
124
- throw errorDatabaseUrlRequired();
125
- }
234
+ format: 'ndjson',
235
+ supportedFormats: ['object'],
236
+ }),
237
+ );
238
+ const exitCode = handleResult(result, flags);
239
+ process.exit(exitCode);
240
+ }
126
241
 
127
- // Check for driver
128
- if (!config.driver) {
129
- throw errorDriverRequired();
130
- }
131
-
132
- // Store driver descriptor after null check
133
- const driverDescriptor = config.driver;
134
-
135
- // Create driver
136
- const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
137
- message: 'Connecting to database...',
138
- flags,
139
- });
140
-
141
- try {
142
- // Create family instance
143
- const stack = createControlPlaneStack({
144
- target: config.target,
145
- adapter: config.adapter,
146
- driver: driverDescriptor,
147
- extensionPacks: config.extensionPacks,
148
- });
149
- const familyInstance = config.family.create(stack);
150
-
151
- // Validate contract using instance validator
152
- const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;
153
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
154
-
155
- // Call family instance verify method
156
- let verifyResult: VerifyDatabaseResult;
157
- try {
158
- verifyResult = await withSpinner(
159
- () =>
160
- familyInstance.verify({
161
- driver,
162
- contractIR,
163
- expectedTargetId: config.target.targetId,
164
- contractPath: contractPathAbsolute,
165
- configPath,
166
- }),
167
- {
168
- message: 'Verifying database schema...',
169
- flags,
170
- },
171
- );
172
- } catch (error) {
173
- // Wrap errors from verify() in structured error
174
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
175
- why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`,
176
- });
177
- }
178
-
179
- // If verification failed, throw structured error
180
- if (!verifyResult.ok && verifyResult.code) {
181
- if (verifyResult.code === 'PN-RTM-3001') {
182
- throw errorMarkerMissing();
183
- }
184
- if (verifyResult.code === 'PN-RTM-3002') {
185
- throw errorHashMismatch({
186
- expected: verifyResult.contract.coreHash,
187
- ...(verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}),
188
- });
189
- }
190
- if (verifyResult.code === 'PN-RTM-3003') {
191
- throw errorTargetMismatch(
192
- verifyResult.target.expected,
193
- verifyResult.target.actual ?? 'unknown',
194
- );
195
- }
196
- throw errorRuntime(verifyResult.summary);
197
- }
198
-
199
- // Add blank line after all async operations if spinners were shown
200
- if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
201
- console.log('');
202
- }
203
-
204
- return verifyResult;
205
- } finally {
206
- // Ensure driver connection is closed
207
- await driver.close();
208
- }
209
- });
242
+ const result = await executeDbVerifyCommand(options, flags);
210
243
 
211
- // Handle result - formats output and returns exit code
212
244
  const exitCode = handleResult(result, flags, (verifyResult) => {
213
- // Output based on flags
214
245
  if (flags.json === 'object') {
215
- // JSON output to stdout
216
246
  console.log(formatVerifyJson(verifyResult));
217
247
  } else {
218
- // Human-readable output to stdout
219
248
  const output = formatVerifyOutput(verifyResult, flags);
220
249
  if (output) {
221
250
  console.log(output);