@prisma-next/cli 0.3.0-dev.17 → 0.3.0-dev.18

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 (45) hide show
  1. package/dist/chunk-BO73VO4I.js +45 -0
  2. package/dist/chunk-BO73VO4I.js.map +1 -0
  3. package/dist/{chunk-VI2YETW7.js → chunk-MPSJAVF6.js} +4 -2
  4. package/dist/{chunk-U6QI3AZ3.js → chunk-RIONCN4I.js} +45 -6
  5. package/dist/chunk-RIONCN4I.js.map +1 -0
  6. package/dist/{chunk-74IELXRA.js → chunk-RPYY5SM7.js} +273 -19
  7. package/dist/chunk-RPYY5SM7.js.map +1 -0
  8. package/dist/cli.js +708 -551
  9. package/dist/cli.js.map +1 -1
  10. package/dist/commands/contract-emit.js +2 -3
  11. package/dist/commands/db-init.js +5 -46
  12. package/dist/commands/db-init.js.map +1 -1
  13. package/dist/commands/db-introspect.d.ts.map +1 -1
  14. package/dist/commands/db-introspect.js +107 -133
  15. package/dist/commands/db-introspect.js.map +1 -1
  16. package/dist/commands/db-schema-verify.d.ts.map +1 -1
  17. package/dist/commands/db-schema-verify.js +119 -107
  18. package/dist/commands/db-schema-verify.js.map +1 -1
  19. package/dist/commands/db-sign.d.ts.map +1 -1
  20. package/dist/commands/db-sign.js +151 -150
  21. package/dist/commands/db-sign.js.map +1 -1
  22. package/dist/commands/db-verify.d.ts.map +1 -1
  23. package/dist/commands/db-verify.js +141 -116
  24. package/dist/commands/db-verify.js.map +1 -1
  25. package/dist/control-api/client.d.ts.map +1 -1
  26. package/dist/control-api/types.d.ts +41 -0
  27. package/dist/control-api/types.d.ts.map +1 -1
  28. package/dist/exports/control-api.js +2 -3
  29. package/dist/exports/index.js +2 -3
  30. package/dist/exports/index.js.map +1 -1
  31. package/package.json +10 -10
  32. package/src/commands/contract-emit.ts +1 -1
  33. package/src/commands/db-introspect.ts +151 -178
  34. package/src/commands/db-schema-verify.ts +150 -143
  35. package/src/commands/db-sign.ts +202 -196
  36. package/src/commands/db-verify.ts +179 -149
  37. package/src/control-api/client.ts +256 -22
  38. package/src/control-api/types.ts +42 -0
  39. package/dist/chunk-5MPKZYVI.js +0 -47
  40. package/dist/chunk-5MPKZYVI.js.map +0 -1
  41. package/dist/chunk-6EPKRATC.js +0 -91
  42. package/dist/chunk-6EPKRATC.js.map +0 -1
  43. package/dist/chunk-74IELXRA.js.map +0 -1
  44. package/dist/chunk-U6QI3AZ3.js.map +0 -1
  45. /package/dist/{chunk-VI2YETW7.js.map → chunk-MPSJAVF6.js.map} +0 -0
@@ -1,11 +1,9 @@
1
1
  import {
2
- assertContractRequirementsSatisfied,
3
- assertFrameworkComponentsCompatible
4
- } from "../chunk-6EPKRATC.js";
2
+ createProgressAdapter
3
+ } from "../chunk-BO73VO4I.js";
5
4
  import {
6
- performAction,
7
- withSpinner
8
- } from "../chunk-5MPKZYVI.js";
5
+ createControlClient
6
+ } from "../chunk-RPYY5SM7.js";
9
7
  import {
10
8
  formatCommandHelp,
11
9
  formatSchemaVerifyJson,
@@ -18,20 +16,115 @@ import {
18
16
  import {
19
17
  loadConfig
20
18
  } from "../chunk-HWYQOCAJ.js";
21
- import "../chunk-VI2YETW7.js";
22
-
23
- // src/commands/db-schema-verify.ts
24
- import { readFile } from "fs/promises";
25
- import { relative, resolve } from "path";
26
19
  import {
20
+ CliStructuredError,
21
+ errorContractValidationFailed,
27
22
  errorDatabaseConnectionRequired,
28
23
  errorDriverRequired,
29
24
  errorFileNotFound,
30
- errorRuntime,
25
+ errorJsonFormatNotSupported,
31
26
  errorUnexpected
32
- } from "@prisma-next/core-control-plane/errors";
33
- import { createControlPlaneStack } from "@prisma-next/core-control-plane/types";
27
+ } from "../chunk-MPSJAVF6.js";
28
+
29
+ // src/commands/db-schema-verify.ts
30
+ import { readFile } from "fs/promises";
31
+ import { relative, resolve } from "path";
32
+ import { notOk, ok } from "@prisma-next/utils/result";
34
33
  import { Command } from "commander";
34
+ async function executeDbSchemaVerifyCommand(options, flags) {
35
+ const config = await loadConfig(options.config);
36
+ const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
37
+ const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
38
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
39
+ if (flags.json !== "object" && !flags.quiet) {
40
+ const details = [
41
+ { label: "config", value: configPath },
42
+ { label: "contract", value: contractPath }
43
+ ];
44
+ if (options.db) {
45
+ details.push({ label: "database", value: options.db });
46
+ }
47
+ const header = formatStyledHeader({
48
+ command: "db schema-verify",
49
+ description: "Check whether the database schema satisfies your contract",
50
+ url: "https://pris.ly/db-schema-verify",
51
+ details,
52
+ flags
53
+ });
54
+ console.log(header);
55
+ }
56
+ let contractJsonContent;
57
+ try {
58
+ contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
59
+ } catch (error) {
60
+ if (error instanceof Error && error.code === "ENOENT") {
61
+ return notOk(
62
+ errorFileNotFound(contractPathAbsolute, {
63
+ why: `Contract file not found at ${contractPathAbsolute}`,
64
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
65
+ })
66
+ );
67
+ }
68
+ return notOk(
69
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
70
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
71
+ })
72
+ );
73
+ }
74
+ let contractJson;
75
+ try {
76
+ contractJson = JSON.parse(contractJsonContent);
77
+ } catch (error) {
78
+ return notOk(
79
+ errorContractValidationFailed(
80
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
81
+ { where: { path: contractPathAbsolute } }
82
+ )
83
+ );
84
+ }
85
+ const dbConnection = options.db ?? config.db?.connection;
86
+ if (!dbConnection) {
87
+ return notOk(
88
+ errorDatabaseConnectionRequired({
89
+ why: `Database connection is required for db schema-verify (set db.connection in ${configPath}, or pass --db <url>)`
90
+ })
91
+ );
92
+ }
93
+ if (!config.driver) {
94
+ return notOk(errorDriverRequired({ why: "Config.driver is required for db schema-verify" }));
95
+ }
96
+ const client = createControlClient({
97
+ family: config.family,
98
+ target: config.target,
99
+ adapter: config.adapter,
100
+ driver: config.driver,
101
+ extensionPacks: config.extensionPacks ?? []
102
+ });
103
+ const onProgress = createProgressAdapter({ flags });
104
+ try {
105
+ const schemaVerifyResult = await client.schemaVerify({
106
+ contractIR: contractJson,
107
+ strict: options.strict ?? false,
108
+ connection: dbConnection,
109
+ onProgress
110
+ });
111
+ if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
112
+ console.log("");
113
+ }
114
+ return ok(schemaVerifyResult);
115
+ } catch (error) {
116
+ if (error instanceof CliStructuredError) {
117
+ return notOk(error);
118
+ }
119
+ return notOk(
120
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
121
+ why: `Unexpected error during db schema-verify: ${error instanceof Error ? error.message : String(error)}`
122
+ })
123
+ );
124
+ } finally {
125
+ await client.close();
126
+ }
127
+ }
35
128
  function createDbSchemaVerifyCommand() {
36
129
  const command = new Command("schema-verify");
37
130
  setCommandDescriptions(
@@ -44,101 +137,20 @@ function createDbSchemaVerifyCommand() {
44
137
  const flags = parseGlobalFlags({});
45
138
  return formatCommandHelp({ command: cmd, flags });
46
139
  }
47
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("--strict", "Strict mode: extra schema elements cause failures", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
140
+ }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object)", false).option("--strict", "Strict mode: extra schema elements cause failures", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
48
141
  const flags = parseGlobalFlags(options);
49
- const result = await performAction(async () => {
50
- const config = await loadConfig(options.config);
51
- const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
52
- const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
53
- const contractPath = relative(process.cwd(), contractPathAbsolute);
54
- if (flags.json !== "object" && !flags.quiet) {
55
- const details = [
56
- { label: "config", value: configPath },
57
- { label: "contract", value: contractPath }
58
- ];
59
- if (options.db) {
60
- details.push({ label: "database", value: options.db });
61
- }
62
- const header = formatStyledHeader({
142
+ if (flags.json === "ndjson") {
143
+ const result2 = notOk(
144
+ errorJsonFormatNotSupported({
63
145
  command: "db schema-verify",
64
- description: "Check whether the database schema satisfies your contract",
65
- url: "https://pris.ly/db-schema-verify",
66
- details,
67
- flags
68
- });
69
- console.log(header);
70
- }
71
- let contractJsonContent;
72
- try {
73
- contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
74
- } catch (error) {
75
- if (error instanceof Error && error.code === "ENOENT") {
76
- throw errorFileNotFound(contractPathAbsolute, {
77
- why: `Contract file not found at ${contractPathAbsolute}`
78
- });
79
- }
80
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
81
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
82
- });
83
- }
84
- const contractJson = JSON.parse(contractJsonContent);
85
- if (!config.driver) {
86
- throw errorDriverRequired();
87
- }
88
- const driverDescriptor = config.driver;
89
- const stack = createControlPlaneStack({
90
- target: config.target,
91
- adapter: config.adapter,
92
- driver: driverDescriptor,
93
- extensionPacks: config.extensionPacks
94
- });
95
- const familyInstance = config.family.create(stack);
96
- const contractIR = familyInstance.validateContractIR(contractJson);
97
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
98
- const dbConnection = options.db ?? config.db?.connection;
99
- if (!dbConnection) {
100
- throw errorDatabaseConnectionRequired();
101
- }
102
- const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {
103
- message: "Connecting to database...",
104
- flags
105
- });
106
- try {
107
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
108
- const frameworkComponents = assertFrameworkComponentsCompatible(
109
- config.family.familyId,
110
- config.target.targetId,
111
- rawComponents
112
- );
113
- let schemaVerifyResult;
114
- try {
115
- schemaVerifyResult = await withSpinner(
116
- () => familyInstance.schemaVerify({
117
- driver,
118
- contractIR,
119
- strict: options.strict ?? false,
120
- contractPath: contractPathAbsolute,
121
- configPath,
122
- frameworkComponents
123
- }),
124
- {
125
- message: "Verifying database schema...",
126
- flags
127
- }
128
- );
129
- } catch (error) {
130
- throw errorRuntime(error instanceof Error ? error.message : String(error), {
131
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
132
- });
133
- }
134
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
135
- console.log("");
136
- }
137
- return schemaVerifyResult;
138
- } finally {
139
- await driver.close();
140
- }
141
- });
146
+ format: "ndjson",
147
+ supportedFormats: ["object"]
148
+ })
149
+ );
150
+ const exitCode2 = handleResult(result2, flags);
151
+ process.exit(exitCode2);
152
+ }
153
+ const result = await executeDbSchemaVerifyCommand(options, flags);
142
154
  const exitCode = handleResult(result, flags, (schemaVerifyResult) => {
143
155
  if (flags.json === "object") {
144
156
  console.log(formatSchemaVerifyJson(schemaVerifyResult));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commands/db-schema-verify.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport {\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { VerifyDatabaseSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { createControlPlaneStack } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { performAction } from '../utils/action';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport {\n assertContractRequirementsSatisfied,\n assertFrameworkComponentsCompatible,\n} from '../utils/framework-components';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbSchemaVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly strict?: boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\nexport function createDbSchemaVerifyCommand(): Command {\n const command = new Command('schema-verify');\n setCommandDescriptions(\n command,\n 'Check whether the database schema satisfies your contract',\n 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\\n' +\n 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\\n' +\n 'verification tree. This is a read-only operation that does not modify the database.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object or ndjson)', false)\n .option('--strict', 'Strict mode: extra schema elements cause failures', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSchemaVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n // Load config (file I/O)\n const config = await loadConfig(options.config);\n // Normalize config path for display (match contract path format - no ./ prefix)\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n // Convert to relative path for display\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header (only for human-readable output)\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db schema-verify',\n description: 'Check whether the database schema satisfies your contract',\n url: 'https://pris.ly/db-schema-verify',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file (file I/O)\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n });\n }\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n\n // Check for driver (needed for family instance creation)\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create family instance (needed for contract validation)\n const stack = createControlPlaneStack({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensionPacks: config.extensionPacks,\n });\n const familyInstance = config.family.create(stack);\n\n // Validate contract using instance validator\n const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;\n\n // Validate contract requirements fail-fast before connecting to database\n assertContractRequirementsSatisfied({ contract: contractIR, stack });\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n throw errorDatabaseConnectionRequired();\n }\n\n const driver = await withSpinner(() => driverDescriptor.create(dbConnection), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n\n // Call family instance schemaVerify method\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = await withSpinner(\n () =>\n familyInstance.schemaVerify({\n driver,\n contractIR,\n strict: options.strict ?? false,\n contractPath: contractPathAbsolute,\n configPath,\n frameworkComponents,\n }),\n {\n message: 'Verifying database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from schemaVerify() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n // Return result (don't throw for logical mismatches - handle exit code separately)\n return schemaVerifyResult;\n } finally {\n // Ensure driver connection is closed\n await driver.close();\n }\n });\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (schemaVerifyResult) => {\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n // Human-readable output to stdout\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n // For logical schema mismatches, check if verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && !result.value.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC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AAEH,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/commands/db-schema-verify.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { VerifyDatabaseSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorJsonFormatNotSupported,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\n\ninterface DbSchemaVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | boolean;\n readonly strict?: boolean;\n readonly quiet?: boolean;\n readonly q?: boolean;\n readonly verbose?: boolean;\n readonly v?: boolean;\n readonly vv?: boolean;\n readonly trace?: boolean;\n readonly timestamps?: boolean;\n readonly color?: boolean;\n readonly 'no-color'?: boolean;\n}\n\n/**\n * Executes the db schema-verify command and returns a structured Result.\n */\nasync function executeDbSchemaVerifyCommand(\n options: DbSchemaVerifyOptions,\n flags: GlobalFlags,\n): Promise<Result<VerifyDatabaseSchemaResult, CliStructuredError>> {\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = config.contract?.output\n ? resolve(config.contract.output)\n : resolve('src/prisma/contract.json');\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header\n if (flags.json !== 'object' && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: options.db });\n }\n const header = formatStyledHeader({\n command: 'db schema-verify',\n description: 'Check whether the database schema satisfies your contract',\n url: 'https://pris.ly/db-schema-verify',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for db schema-verify (set db.connection in ${configPath}, or pass --db <url>)`,\n }),\n );\n }\n\n // Check for driver\n if (!config.driver) {\n return notOk(errorDriverRequired({ why: 'Config.driver is required for db schema-verify' }));\n }\n\n // Create control client\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Create progress adapter\n const onProgress = createProgressAdapter({ flags });\n\n try {\n const schemaVerifyResult = await client.schemaVerify({\n contractIR: contractJson,\n strict: options.strict ?? false,\n connection: dbConnection,\n onProgress,\n });\n\n // Add blank line after all async operations if spinners were shown\n if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {\n console.log('');\n }\n\n return ok(schemaVerifyResult);\n } catch (error) {\n // Driver already throws CliStructuredError for connection failures\n if (error instanceof CliStructuredError) {\n return notOk(error);\n }\n\n // Wrap unexpected errors\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Unexpected error during db schema-verify: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n\nexport function createDbSchemaVerifyCommand(): Command {\n const command = new Command('schema-verify');\n setCommandDescriptions(\n command,\n 'Check whether the database schema satisfies your contract',\n 'Verifies that your database schema satisfies the emitted contract. Compares table structures,\\n' +\n 'column types, constraints, and extensions. Reports any mismatches via a contract-shaped\\n' +\n 'verification tree. This is a read-only operation that does not modify the database.',\n );\n command\n .configureHelp({\n formatHelp: (cmd) => {\n const flags = parseGlobalFlags({});\n return formatCommandHelp({ command: cmd, flags });\n },\n })\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--json [format]', 'Output as JSON (object)', false)\n .option('--strict', 'Strict mode: extra schema elements cause failures', false)\n .option('-q, --quiet', 'Quiet mode: errors only')\n .option('-v, --verbose', 'Verbose output: debug info, timings')\n .option('-vv, --trace', 'Trace output: deep internals, stack traces')\n .option('--timestamps', 'Add timestamps to output')\n .option('--color', 'Force color output')\n .option('--no-color', 'Disable color output')\n .action(async (options: DbSchemaVerifyOptions) => {\n const flags = parseGlobalFlags(options);\n\n // Validate JSON format option\n if (flags.json === 'ndjson') {\n const result = notOk(\n errorJsonFormatNotSupported({\n command: 'db schema-verify',\n format: 'ndjson',\n supportedFormats: ['object'],\n }),\n );\n const exitCode = handleResult(result, flags);\n process.exit(exitCode);\n }\n\n const result = await executeDbSchemaVerifyCommand(options, flags);\n\n // Handle result - formats output and returns exit code\n const exitCode = handleResult(result, flags, (schemaVerifyResult) => {\n if (flags.json === 'object') {\n console.log(formatSchemaVerifyJson(schemaVerifyResult));\n } else {\n const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n\n // For logical schema mismatches, check if verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && !result.value.ok) {\n // Schema verification failed - exit with code 1\n process.exit(1);\n } else {\n // Success or infra error - use exit code from handleResult\n process.exit(exitCode);\n }\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC,SAAS,OAAO,UAAuB;AACvC,SAAS,eAAe;AA0CxB,eAAe,6BACb,SACA,OACiE;AAEjE,QAAM,SAAS,MAAM,WAAW,QAAQ,MAAM;AAC9C,QAAM,aAAa,QAAQ,SACvB,SAAS,QAAQ,IAAI,GAAG,QAAQ,QAAQ,MAAM,CAAC,IAC/C;AACJ,QAAM,uBAAuB,OAAO,UAAU,SAC1C,QAAQ,OAAO,SAAS,MAAM,IAC9B,QAAQ,0BAA0B;AACtC,QAAM,eAAe,SAAS,QAAQ,IAAI,GAAG,oBAAoB;AAGjE,MAAI,MAAM,SAAS,YAAY,CAAC,MAAM,OAAO;AAC3C,UAAM,UAAmD;AAAA,MACvD,EAAE,OAAO,UAAU,OAAO,WAAW;AAAA,MACrC,EAAE,OAAO,YAAY,OAAO,aAAa;AAAA,IAC3C;AACA,QAAI,QAAQ,IAAI;AACd,cAAQ,KAAK,EAAE,OAAO,YAAY,OAAO,QAAQ,GAAG,CAAC;AAAA,IACvD;AACA,UAAM,SAAS,mBAAmB;AAAA,MAChC,SAAS;AAAA,MACT,aAAa;AAAA,MACb,KAAK;AAAA,MACL;AAAA,MACA;AAAA,IACF,CAAC;AACD,YAAQ,IAAI,MAAM;AAAA,EACpB;AAGA,MAAI;AACJ,MAAI;AACF,0BAAsB,MAAM,SAAS,sBAAsB,OAAO;AAAA,EACpE,SAAS,OAAO;AACd,QAAI,iBAAiB,SAAU,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QAAQ;AAAA,UACR,kBAAkB,CAAC,QAAQ;AAAA,QAC7B,CAAC;AAAA,MACH;AACA,YAAMC,YAAW,aAAaD,SAAQ,KAAK;AAC3C,cAAQ,KAAKC,SAAQ;AAAA,IACvB;AAEA,UAAM,SAAS,MAAM,6BAA6B,SAAS,KAAK;AAGhE,UAAM,WAAW,aAAa,QAAQ,OAAO,CAAC,uBAAuB;AACnE,UAAI,MAAM,SAAS,UAAU;AAC3B,gBAAQ,IAAI,uBAAuB,kBAAkB,CAAC;AAAA,MACxD,OAAO;AACL,cAAM,SAAS,yBAAyB,oBAAoB,KAAK;AACjE,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AAID,QAAI,OAAO,MAAM,CAAC,OAAO,MAAM,IAAI;AAEjC,cAAQ,KAAK,CAAC;AAAA,IAChB,OAAO;AAEL,cAAQ,KAAK,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;","names":["result","exitCode"]}
@@ -1 +1 @@
1
- {"version":3,"file":"db-sign.d.ts","sourceRoot":"","sources":["../../src/commands/db-sign.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAmCpC,wBAAgB,mBAAmB,IAAI,OAAO,CA+N7C"}
1
+ {"version":3,"file":"db-sign.d.ts","sourceRoot":"","sources":["../../src/commands/db-sign.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAgMpC,wBAAgB,mBAAmB,IAAI,OAAO,CA+E7C"}
@@ -1,11 +1,9 @@
1
1
  import {
2
- assertContractRequirementsSatisfied,
3
- assertFrameworkComponentsCompatible
4
- } from "../chunk-6EPKRATC.js";
2
+ createProgressAdapter
3
+ } from "../chunk-BO73VO4I.js";
5
4
  import {
6
- performAction,
7
- withSpinner
8
- } from "../chunk-5MPKZYVI.js";
5
+ createControlClient
6
+ } from "../chunk-RPYY5SM7.js";
9
7
  import {
10
8
  formatCommandHelp,
11
9
  formatSchemaVerifyJson,
@@ -20,20 +18,127 @@ import {
20
18
  import {
21
19
  loadConfig
22
20
  } from "../chunk-HWYQOCAJ.js";
23
- import "../chunk-VI2YETW7.js";
24
-
25
- // src/commands/db-sign.ts
26
- import { readFile } from "fs/promises";
27
- import { relative, resolve } from "path";
28
21
  import {
22
+ CliStructuredError,
23
+ errorContractValidationFailed,
29
24
  errorDatabaseConnectionRequired,
30
25
  errorDriverRequired,
31
26
  errorFileNotFound,
32
- errorRuntime,
27
+ errorJsonFormatNotSupported,
33
28
  errorUnexpected
34
- } from "@prisma-next/core-control-plane/errors";
35
- import { createControlPlaneStack } from "@prisma-next/core-control-plane/types";
29
+ } from "../chunk-MPSJAVF6.js";
30
+
31
+ // src/commands/db-sign.ts
32
+ import { readFile } from "fs/promises";
33
+ import { relative, resolve } from "path";
34
+ import { notOk, ok } from "@prisma-next/utils/result";
36
35
  import { Command } from "commander";
36
+ async function executeDbSignCommand(options, flags) {
37
+ const config = await loadConfig(options.config);
38
+ const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
39
+ const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
40
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
41
+ if (flags.json !== "object" && !flags.quiet) {
42
+ const details = [
43
+ { label: "config", value: configPath },
44
+ { label: "contract", value: contractPath }
45
+ ];
46
+ if (options.db) {
47
+ details.push({ label: "database", value: options.db });
48
+ }
49
+ const header = formatStyledHeader({
50
+ command: "db sign",
51
+ description: "Sign the database with your contract so you can safely run queries",
52
+ url: "https://pris.ly/db-sign",
53
+ details,
54
+ flags
55
+ });
56
+ console.log(header);
57
+ }
58
+ let contractJsonContent;
59
+ try {
60
+ contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
61
+ } catch (error) {
62
+ if (error instanceof Error && error.code === "ENOENT") {
63
+ return notOk(
64
+ errorFileNotFound(contractPathAbsolute, {
65
+ why: `Contract file not found at ${contractPathAbsolute}`,
66
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`
67
+ })
68
+ );
69
+ }
70
+ return notOk(
71
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
72
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
73
+ })
74
+ );
75
+ }
76
+ let contractJson;
77
+ try {
78
+ contractJson = JSON.parse(contractJsonContent);
79
+ } catch (error) {
80
+ return notOk(
81
+ errorContractValidationFailed(
82
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
83
+ { where: { path: contractPathAbsolute } }
84
+ )
85
+ );
86
+ }
87
+ const dbConnection = options.db ?? config.db?.connection;
88
+ if (!dbConnection) {
89
+ return notOk(
90
+ errorDatabaseConnectionRequired({
91
+ why: `Database connection is required for db sign (set db.connection in ${configPath}, or pass --db <url>)`
92
+ })
93
+ );
94
+ }
95
+ if (!config.driver) {
96
+ return notOk(errorDriverRequired({ why: "Config.driver is required for db sign" }));
97
+ }
98
+ const client = createControlClient({
99
+ family: config.family,
100
+ target: config.target,
101
+ adapter: config.adapter,
102
+ driver: config.driver,
103
+ extensionPacks: config.extensionPacks ?? []
104
+ });
105
+ const onProgress = createProgressAdapter({ flags });
106
+ try {
107
+ const schemaVerifyResult = await client.schemaVerify({
108
+ contractIR: contractJson,
109
+ strict: false,
110
+ connection: dbConnection,
111
+ onProgress
112
+ });
113
+ if (!schemaVerifyResult.ok) {
114
+ if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
115
+ console.log("");
116
+ }
117
+ return notOk(schemaVerifyResult);
118
+ }
119
+ const signResult = await client.sign({
120
+ contractIR: contractJson,
121
+ contractPath,
122
+ configPath,
123
+ onProgress
124
+ });
125
+ if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
126
+ console.log("");
127
+ }
128
+ return ok(signResult);
129
+ } catch (error) {
130
+ if (error instanceof CliStructuredError) {
131
+ return notOk(error);
132
+ }
133
+ return notOk(
134
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
135
+ why: `Unexpected error during db sign: ${error instanceof Error ? error.message : String(error)}`
136
+ })
137
+ );
138
+ } finally {
139
+ await client.close();
140
+ }
141
+ }
37
142
  function createDbSignCommand() {
38
143
  const command = new Command("sign");
39
144
  setCommandDescriptions(
@@ -46,149 +151,45 @@ function createDbSignCommand() {
46
151
  const flags = parseGlobalFlags({});
47
152
  return formatCommandHelp({ command: cmd, flags });
48
153
  }
49
- }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object or ndjson)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
154
+ }).option("--db <url>", "Database connection string").option("--config <path>", "Path to prisma-next.config.ts").option("--json [format]", "Output as JSON (object)", false).option("-q, --quiet", "Quiet mode: errors only").option("-v, --verbose", "Verbose output: debug info, timings").option("-vv, --trace", "Trace output: deep internals, stack traces").option("--timestamps", "Add timestamps to output").option("--color", "Force color output").option("--no-color", "Disable color output").action(async (options) => {
50
155
  const flags = parseGlobalFlags(options);
51
- const result = await performAction(async () => {
52
- const config = await loadConfig(options.config);
53
- const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
54
- const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
55
- const contractPath = relative(process.cwd(), contractPathAbsolute);
56
- if (flags.json !== "object" && !flags.quiet) {
57
- const details = [
58
- { label: "config", value: configPath },
59
- { label: "contract", value: contractPath }
60
- ];
61
- if (options.db) {
62
- details.push({ label: "database", value: options.db });
63
- }
64
- const header = formatStyledHeader({
156
+ if (flags.json === "ndjson") {
157
+ const result2 = notOk(
158
+ errorJsonFormatNotSupported({
65
159
  command: "db sign",
66
- description: "Sign the database with your contract so you can safely run queries",
67
- url: "https://pris.ly/db-sign",
68
- details,
69
- flags
70
- });
71
- console.log(header);
72
- }
73
- let contractJsonContent;
74
- try {
75
- contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
76
- } catch (error) {
77
- if (error instanceof Error && error.code === "ENOENT") {
78
- throw errorFileNotFound(contractPathAbsolute, {
79
- why: `Contract file not found at ${contractPathAbsolute}`
80
- });
81
- }
82
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
83
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
84
- });
85
- }
86
- const contractJson = JSON.parse(contractJsonContent);
87
- const dbConnection = options.db ?? config.db?.connection;
88
- if (!dbConnection) {
89
- throw errorDatabaseConnectionRequired();
90
- }
91
- if (!config.driver) {
92
- throw errorDriverRequired();
93
- }
94
- const driverDescriptor = config.driver;
95
- const stack = createControlPlaneStack({
96
- target: config.target,
97
- adapter: config.adapter,
98
- driver: driverDescriptor,
99
- extensionPacks: config.extensionPacks
100
- });
101
- const familyInstance = config.family.create(stack);
102
- const contractIR = familyInstance.validateContractIR(contractJson);
103
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
104
- const rawComponents = [config.target, config.adapter, ...config.extensionPacks ?? []];
105
- const frameworkComponents = assertFrameworkComponentsCompatible(
106
- config.family.familyId,
107
- config.target.targetId,
108
- rawComponents
160
+ format: "ndjson",
161
+ supportedFormats: ["object"]
162
+ })
109
163
  );
110
- const driver = await driverDescriptor.create(dbConnection);
111
- try {
112
- let schemaVerifyResult;
113
- try {
114
- schemaVerifyResult = await withSpinner(
115
- () => familyInstance.schemaVerify({
116
- driver,
117
- contractIR,
118
- strict: false,
119
- contractPath: contractPathAbsolute,
120
- configPath,
121
- frameworkComponents
122
- }),
123
- {
124
- message: "Verifying database satisfies contract",
125
- flags
126
- }
127
- );
128
- } catch (error) {
129
- throw errorRuntime(error instanceof Error ? error.message : String(error), {
130
- why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
131
- });
132
- }
133
- if (!schemaVerifyResult.ok) {
134
- return { schemaVerifyResult, signResult: void 0 };
135
- }
136
- let signResult;
137
- try {
138
- signResult = await withSpinner(
139
- () => familyInstance.sign({
140
- driver,
141
- contractIR,
142
- contractPath: contractPathAbsolute,
143
- configPath
144
- }),
145
- {
146
- message: "Signing database...",
147
- flags
148
- }
149
- );
150
- } catch (error) {
151
- throw errorRuntime(error instanceof Error ? error.message : String(error), {
152
- why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`
153
- });
154
- }
155
- if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
156
- console.log("");
157
- }
158
- return { schemaVerifyResult: void 0, signResult };
159
- } finally {
160
- await driver.close();
161
- }
162
- });
163
- const exitCode = handleResult(result, flags, (value) => {
164
- const { schemaVerifyResult, signResult } = value;
165
- if (schemaVerifyResult && !schemaVerifyResult.ok) {
166
- if (flags.json === "object") {
167
- console.log(formatSchemaVerifyJson(schemaVerifyResult));
168
- } else {
169
- const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
170
- if (output) {
171
- console.log(output);
172
- }
173
- }
174
- return;
175
- }
176
- if (signResult) {
177
- if (flags.json === "object") {
178
- console.log(formatSignJson(signResult));
179
- } else {
180
- const output = formatSignOutput(signResult, flags);
181
- if (output) {
182
- console.log(output);
183
- }
164
+ const exitCode = handleResult(result2, flags);
165
+ process.exit(exitCode);
166
+ }
167
+ const result = await executeDbSignCommand(options, flags);
168
+ if (result.ok) {
169
+ if (flags.json === "object") {
170
+ console.log(formatSignJson(result.value));
171
+ } else {
172
+ const output = formatSignOutput(result.value, flags);
173
+ if (output) {
174
+ console.log(output);
184
175
  }
185
176
  }
186
- });
187
- if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {
188
- process.exit(1);
189
- } else {
177
+ process.exit(0);
178
+ }
179
+ const failure = result.failure;
180
+ if (failure instanceof CliStructuredError) {
181
+ const exitCode = handleResult(result, flags);
190
182
  process.exit(exitCode);
191
183
  }
184
+ if (flags.json === "object") {
185
+ console.log(formatSchemaVerifyJson(failure));
186
+ } else {
187
+ const output = formatSchemaVerifyOutput(failure, flags);
188
+ if (output) {
189
+ console.log(output);
190
+ }
191
+ }
192
+ process.exit(1);
192
193
  });
193
194
  return command;
194
195
  }