@prisma-next/cli 0.1.0-pr.32.7 → 0.1.0-pr.32.9
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.
- package/README.md +16 -0
- package/dist/chunk-3EODSNGS.js +914 -0
- package/dist/chunk-3EODSNGS.js.map +1 -0
- package/dist/chunk-4Q3MO4TK.js +134 -0
- package/dist/chunk-4Q3MO4TK.js.map +1 -0
- package/dist/chunk-HWYQOCAJ.js +47 -0
- package/dist/chunk-HWYQOCAJ.js.map +1 -0
- package/dist/commands/contract-emit.d.ts +5 -0
- package/dist/commands/contract-emit.js +9 -0
- package/dist/commands/contract-emit.js.map +1 -0
- package/dist/commands/db-introspect.d.ts +5 -0
- package/dist/commands/db-introspect.js +181 -0
- package/dist/commands/db-introspect.js.map +1 -0
- package/dist/commands/db-schema-verify.d.ts +5 -0
- package/dist/commands/db-schema-verify.js +147 -0
- package/dist/commands/db-schema-verify.js.map +1 -0
- package/dist/commands/db-sign.d.ts +5 -0
- package/dist/commands/db-sign.js +186 -0
- package/dist/commands/db-sign.js.map +1 -0
- package/dist/commands/db-verify.d.ts +5 -0
- package/dist/commands/db-verify.js +164 -0
- package/dist/commands/db-verify.js.map +1 -0
- package/dist/config-loader.d.ts +14 -0
- package/dist/config-loader.js +7 -0
- package/dist/config-loader.js.map +1 -0
- package/dist/index.d.ts +3 -4
- package/dist/index.js +6 -631
- package/dist/index.js.map +1 -1
- package/package.json +33 -9
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-introspect.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport {\n errorDatabaseUrlRequired,\n errorDriverRequired,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { CoreSchemaView } from '@prisma-next/core-control-plane/schema-view';\nimport type { FamilyInstance, IntrospectSchemaResult } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatIntrospectJson,\n formatIntrospectOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { performAction } from '../utils/result';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbIntrospectOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | 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 createDbIntrospectCommand(): Command {\n const command = new Command('introspect');\n setCommandDescriptions(\n command,\n 'Inspect the database schema',\n 'Reads the live database schema and displays it as a tree structure. This command\\n' +\n 'does not check the schema against your contract - it only shows what exists in\\n' +\n 'the database. Use `db verify` or `db schema-verify` to compare against your contract.',\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('-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: DbIntrospectOptions) => {\n const flags = parseGlobalFlags(options);\n\n const result = await performAction(async () => {\n const startTime = Date.now();\n\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\n // Optionally load contract if contract config exists\n let contractIR: unknown | undefined;\n if (config.contract?.output) {\n const contractPath = resolve(config.contract.output);\n try {\n const contractJsonContent = await readFile(contractPath, 'utf-8');\n const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n // Validate contract using family instance (will be created later)\n // For now, we'll pass the raw JSON and let the family instance validate it\n contractIR = contractJson;\n } catch (error) {\n // Contract file is optional for introspection - don't fail if it doesn't exist\n if (error instanceof Error && (error as { code?: string }).code !== 'ENOENT') {\n throw errorUnexpected(error.message, {\n why: `Failed to read contract file: ${error.message}`,\n });\n }\n }\n }\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 ];\n if (options.db) {\n // Mask password in URL for security\n const maskedUrl = options.db.replace(/:([^:@]+)@/, ':****@');\n details.push({ label: 'database', value: maskedUrl });\n } else if (config.db?.url) {\n // Mask password in URL for security\n const maskedUrl = config.db.url.replace(/:([^:@]+)@/, ':****@');\n details.push({ label: 'database', value: maskedUrl });\n }\n const header = formatStyledHeader({\n command: 'db introspect',\n description: 'Inspect the database schema',\n url: 'https://pris.ly/db-introspect',\n details,\n flags,\n });\n console.log(header);\n }\n\n // Resolve database URL\n const dbUrl = options.db ?? config.db?.url;\n if (!dbUrl) {\n throw errorDatabaseUrlRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create driver\n const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n // Create family instance\n const familyInstance = config.family.create({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensions: config.extensions ?? [],\n });\n const typedFamilyInstance = familyInstance as FamilyInstance<string>;\n\n // Validate contract IR if we loaded it\n if (contractIR) {\n contractIR = typedFamilyInstance.validateContractIR(contractIR);\n }\n\n // Call family instance introspect method\n let schemaIR: unknown;\n try {\n schemaIR = await withSpinner(\n () =>\n typedFamilyInstance.introspect({\n driver,\n contractIR,\n }),\n {\n message: 'Introspecting database schema...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from introspect() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to introspect database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // Optionally call toSchemaView if available\n let schemaView: CoreSchemaView | undefined;\n if (typedFamilyInstance.toSchemaView) {\n try {\n schemaView = typedFamilyInstance.toSchemaView(schemaIR);\n } catch (error) {\n // Schema view projection is optional - log but don't fail\n if (flags.verbose) {\n console.error(\n `Warning: Failed to project schema to view: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n\n const totalTime = Date.now() - startTime;\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 // Build result envelope\n const introspectResult: IntrospectSchemaResult<unknown> = {\n ok: true,\n summary: 'Schema introspected successfully',\n target: {\n familyId: config.family.familyId,\n id: config.target.targetId,\n },\n schema: schemaIR,\n ...(configPath || options.db || config.db?.url\n ? {\n meta: {\n ...(configPath ? { configPath } : {}),\n ...(options.db || config.db?.url\n ? {\n dbUrl: (options.db ?? config.db?.url ?? '').replace(\n /:([^:@]+)@/,\n ':****@',\n ),\n }\n : {}),\n },\n }\n : {}),\n timings: {\n total: totalTime,\n },\n };\n\n return { introspectResult, schemaView };\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, (value) => {\n const { introspectResult, schemaView } = value;\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatIntrospectJson(introspectResult));\n } else {\n // Human-readable output to stdout\n const output = formatIntrospectOutput(introspectResult, schemaView, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,S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O;AAAA,UACT;AAAA,QACF;AAEA,eAAO,EAAE,kBAAkB,WAAW;AAAA,MACxC,UAAE;AAEA,cAAM,OAAO,MAAM;AAAA,MACrB;AAAA,IACF,CAAC;AAGD,UAAM,WAAW,aAAa,QAAQ,OAAO,CAAC,UAAU;AACtD,YAAM,EAAE,kBAAkB,WAAW,IAAI;AAEzC,UAAI,MAAM,SAAS,UAAU;AAE3B,gBAAQ,IAAI,qBAAqB,gBAAgB,CAAC;AAAA,MACpD,OAAO;AAEL,cAAM,SAAS,uBAAuB,kBAAkB,YAAY,KAAK;AACzE,YAAI,QAAQ;AACV,kBAAQ,IAAI,MAAM;AAAA,QACpB;AAAA,MACF;AAAA,IACF,CAAC;AACD,YAAQ,KAAK,QAAQ;AAAA,EACvB,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import {
|
|
2
|
+
formatCommandHelp,
|
|
3
|
+
formatSchemaVerifyJson,
|
|
4
|
+
formatSchemaVerifyOutput,
|
|
5
|
+
formatStyledHeader,
|
|
6
|
+
handleResult,
|
|
7
|
+
parseGlobalFlags,
|
|
8
|
+
performAction,
|
|
9
|
+
setCommandDescriptions,
|
|
10
|
+
withSpinner
|
|
11
|
+
} from "../chunk-3EODSNGS.js";
|
|
12
|
+
import {
|
|
13
|
+
loadConfig
|
|
14
|
+
} from "../chunk-HWYQOCAJ.js";
|
|
15
|
+
|
|
16
|
+
// src/commands/db-schema-verify.ts
|
|
17
|
+
import { readFile } from "fs/promises";
|
|
18
|
+
import { relative, resolve } from "path";
|
|
19
|
+
import {
|
|
20
|
+
errorDatabaseUrlRequired,
|
|
21
|
+
errorDriverRequired,
|
|
22
|
+
errorFileNotFound,
|
|
23
|
+
errorRuntime,
|
|
24
|
+
errorUnexpected
|
|
25
|
+
} from "@prisma-next/core-control-plane/errors";
|
|
26
|
+
import { Command } from "commander";
|
|
27
|
+
function createDbSchemaVerifyCommand() {
|
|
28
|
+
const command = new Command("schema-verify");
|
|
29
|
+
setCommandDescriptions(
|
|
30
|
+
command,
|
|
31
|
+
"Check whether the database schema satisfies your contract",
|
|
32
|
+
"Verifies that your database schema satisfies the emitted contract. Compares table structures,\ncolumn types, constraints, and extensions. Reports any mismatches via a contract-shaped\nverification tree. This is a read-only operation that does not modify the database."
|
|
33
|
+
);
|
|
34
|
+
command.configureHelp({
|
|
35
|
+
formatHelp: (cmd) => {
|
|
36
|
+
const flags = parseGlobalFlags({});
|
|
37
|
+
return formatCommandHelp({ command: cmd, flags });
|
|
38
|
+
}
|
|
39
|
+
}).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) => {
|
|
40
|
+
const flags = parseGlobalFlags(options);
|
|
41
|
+
const result = await performAction(async () => {
|
|
42
|
+
const config = await loadConfig(options.config);
|
|
43
|
+
const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
|
|
44
|
+
const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
|
|
45
|
+
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
46
|
+
if (flags.json !== "object" && !flags.quiet) {
|
|
47
|
+
const details = [
|
|
48
|
+
{ label: "config", value: configPath },
|
|
49
|
+
{ label: "contract", value: contractPath }
|
|
50
|
+
];
|
|
51
|
+
if (options.db) {
|
|
52
|
+
details.push({ label: "database", value: options.db });
|
|
53
|
+
}
|
|
54
|
+
const header = formatStyledHeader({
|
|
55
|
+
command: "db schema-verify",
|
|
56
|
+
description: "Check whether the database schema satisfies your contract",
|
|
57
|
+
url: "https://pris.ly/db-schema-verify",
|
|
58
|
+
details,
|
|
59
|
+
flags
|
|
60
|
+
});
|
|
61
|
+
console.log(header);
|
|
62
|
+
}
|
|
63
|
+
let contractJsonContent;
|
|
64
|
+
try {
|
|
65
|
+
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (error instanceof Error && error.code === "ENOENT") {
|
|
68
|
+
throw errorFileNotFound(contractPathAbsolute, {
|
|
69
|
+
why: `Contract file not found at ${contractPathAbsolute}`
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
throw errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
73
|
+
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
const contractJson = JSON.parse(contractJsonContent);
|
|
77
|
+
const dbUrl = options.db ?? config.db?.url;
|
|
78
|
+
if (!dbUrl) {
|
|
79
|
+
throw errorDatabaseUrlRequired();
|
|
80
|
+
}
|
|
81
|
+
if (!config.driver) {
|
|
82
|
+
throw errorDriverRequired();
|
|
83
|
+
}
|
|
84
|
+
const driverDescriptor = config.driver;
|
|
85
|
+
const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
|
|
86
|
+
message: "Connecting to database...",
|
|
87
|
+
flags
|
|
88
|
+
});
|
|
89
|
+
try {
|
|
90
|
+
const familyInstance = config.family.create({
|
|
91
|
+
target: config.target,
|
|
92
|
+
adapter: config.adapter,
|
|
93
|
+
driver: driverDescriptor,
|
|
94
|
+
extensions: config.extensions ?? []
|
|
95
|
+
});
|
|
96
|
+
const typedFamilyInstance = familyInstance;
|
|
97
|
+
const contractIR = typedFamilyInstance.validateContractIR(contractJson);
|
|
98
|
+
let schemaVerifyResult;
|
|
99
|
+
try {
|
|
100
|
+
schemaVerifyResult = await withSpinner(
|
|
101
|
+
() => typedFamilyInstance.schemaVerify({
|
|
102
|
+
driver,
|
|
103
|
+
contractIR,
|
|
104
|
+
strict: options.strict ?? false,
|
|
105
|
+
contractPath: contractPathAbsolute,
|
|
106
|
+
configPath
|
|
107
|
+
}),
|
|
108
|
+
{
|
|
109
|
+
message: "Verifying database schema...",
|
|
110
|
+
flags
|
|
111
|
+
}
|
|
112
|
+
);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
throw errorRuntime(error instanceof Error ? error.message : String(error), {
|
|
115
|
+
why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
119
|
+
console.log("");
|
|
120
|
+
}
|
|
121
|
+
return schemaVerifyResult;
|
|
122
|
+
} finally {
|
|
123
|
+
await driver.close();
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
const exitCode = handleResult(result, flags, (schemaVerifyResult) => {
|
|
127
|
+
if (flags.json === "object") {
|
|
128
|
+
console.log(formatSchemaVerifyJson(schemaVerifyResult));
|
|
129
|
+
} else {
|
|
130
|
+
const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
|
|
131
|
+
if (output) {
|
|
132
|
+
console.log(output);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
if (result.ok && !result.value.ok) {
|
|
137
|
+
process.exit(1);
|
|
138
|
+
} else {
|
|
139
|
+
process.exit(exitCode);
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
return command;
|
|
143
|
+
}
|
|
144
|
+
export {
|
|
145
|
+
createDbSchemaVerifyCommand
|
|
146
|
+
};
|
|
147
|
+
//# sourceMappingURL=db-schema-verify.js.map
|
|
@@ -0,0 +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 errorDatabaseUrlRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type {\n FamilyInstance,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { performAction } from '../utils/result';\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 // Resolve database URL\n const dbUrl = options.db ?? config.db?.url;\n if (!dbUrl) {\n throw errorDatabaseUrlRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create driver\n const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n // Create family instance\n const familyInstance = config.family.create({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensions: config.extensions ?? [],\n });\n const typedFamilyInstance = familyInstance as FamilyInstance<string>;\n\n // Validate contract using instance validator\n const contractIR = typedFamilyInstance.validateContractIR(contractJson) as ContractIR;\n\n // Call family instance schemaVerify method\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = (await withSpinner(\n () =>\n typedFamilyInstance.schemaVerify({\n driver,\n contractIR,\n strict: options.strict ?? false,\n contractPath: contractPathAbsolute,\n configPath,\n }),\n {\n message: 'Verifying database schema...',\n flags,\n },\n )) as VerifyDatabaseSchemaResult;\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;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,SAAS,eAAe;AA8BjB,SAAS,8BAAuC;AACrD,QAAM,UAAU,IAAI,QAAQ,eAAe;AAC3C;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EA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A,QACF,SAAS,OAAO;AAEd,gBAAM,aAAa,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;AAAA,YACzE,KAAK,qCAAqC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,UAClG,CAAC;AAAA,QACH;AAGA,YAAI,CAAC,MAAM,SAAS,MAAM,SAAS,YAAY,QAAQ,OAAO,OAAO;AACnE,kBAAQ,IAAI,EAAE;AAAA,QAChB;AAGA,eAAO;AAAA,MACT,UAAE;AAEA,cAAM,OAAO,MAAM;AAAA,MACrB;AAAA,IACF,CAAC;AAGD,UAAM,WAAW,aAAa,QAAQ,OAAO,CAAC,uBAAuB;AAEnE,UAAI,MAAM,SAAS,UAAU;AAE3B,gBAAQ,IAAI,uBAAuB,kBAAkB,CAAC;AAAA,MACxD,OAAO;AAEL,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":[]}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import {
|
|
2
|
+
formatCommandHelp,
|
|
3
|
+
formatSchemaVerifyJson,
|
|
4
|
+
formatSchemaVerifyOutput,
|
|
5
|
+
formatSignJson,
|
|
6
|
+
formatSignOutput,
|
|
7
|
+
formatStyledHeader,
|
|
8
|
+
handleResult,
|
|
9
|
+
parseGlobalFlags,
|
|
10
|
+
performAction,
|
|
11
|
+
setCommandDescriptions,
|
|
12
|
+
withSpinner
|
|
13
|
+
} from "../chunk-3EODSNGS.js";
|
|
14
|
+
import {
|
|
15
|
+
loadConfig
|
|
16
|
+
} from "../chunk-HWYQOCAJ.js";
|
|
17
|
+
|
|
18
|
+
// src/commands/db-sign.ts
|
|
19
|
+
import { readFile } from "fs/promises";
|
|
20
|
+
import { relative, resolve } from "path";
|
|
21
|
+
import {
|
|
22
|
+
errorDatabaseUrlRequired,
|
|
23
|
+
errorDriverRequired,
|
|
24
|
+
errorFileNotFound,
|
|
25
|
+
errorRuntime,
|
|
26
|
+
errorUnexpected
|
|
27
|
+
} from "@prisma-next/core-control-plane/errors";
|
|
28
|
+
import { Command } from "commander";
|
|
29
|
+
function createDbSignCommand() {
|
|
30
|
+
const command = new Command("sign");
|
|
31
|
+
setCommandDescriptions(
|
|
32
|
+
command,
|
|
33
|
+
"Sign the database with your contract so you can safely run queries",
|
|
34
|
+
"Verifies that your database schema satisfies the emitted contract, and if so, writes or\nupdates the contract marker in the database. This command is idempotent and safe to run\nin CI/deployment pipelines. The marker records that this database instance is aligned\nwith a specific contract version."
|
|
35
|
+
);
|
|
36
|
+
command.configureHelp({
|
|
37
|
+
formatHelp: (cmd) => {
|
|
38
|
+
const flags = parseGlobalFlags({});
|
|
39
|
+
return formatCommandHelp({ command: cmd, flags });
|
|
40
|
+
}
|
|
41
|
+
}).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) => {
|
|
42
|
+
const flags = parseGlobalFlags(options);
|
|
43
|
+
const result = await performAction(async () => {
|
|
44
|
+
const config = await loadConfig(options.config);
|
|
45
|
+
const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
|
|
46
|
+
const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
|
|
47
|
+
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
48
|
+
if (flags.json !== "object" && !flags.quiet) {
|
|
49
|
+
const details = [
|
|
50
|
+
{ label: "config", value: configPath },
|
|
51
|
+
{ label: "contract", value: contractPath }
|
|
52
|
+
];
|
|
53
|
+
if (options.db) {
|
|
54
|
+
details.push({ label: "database", value: options.db });
|
|
55
|
+
}
|
|
56
|
+
const header = formatStyledHeader({
|
|
57
|
+
command: "db sign",
|
|
58
|
+
description: "Sign the database with your contract so you can safely run queries",
|
|
59
|
+
url: "https://pris.ly/db-sign",
|
|
60
|
+
details,
|
|
61
|
+
flags
|
|
62
|
+
});
|
|
63
|
+
console.log(header);
|
|
64
|
+
}
|
|
65
|
+
let contractJsonContent;
|
|
66
|
+
try {
|
|
67
|
+
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error instanceof Error && error.code === "ENOENT") {
|
|
70
|
+
throw errorFileNotFound(contractPathAbsolute, {
|
|
71
|
+
why: `Contract file not found at ${contractPathAbsolute}`
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
throw errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
75
|
+
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
const contractJson = JSON.parse(contractJsonContent);
|
|
79
|
+
const dbUrl = options.db ?? config.db?.url;
|
|
80
|
+
if (!dbUrl) {
|
|
81
|
+
throw errorDatabaseUrlRequired();
|
|
82
|
+
}
|
|
83
|
+
if (!config.driver) {
|
|
84
|
+
throw errorDriverRequired();
|
|
85
|
+
}
|
|
86
|
+
const driverDescriptor = config.driver;
|
|
87
|
+
const driver = await driverDescriptor.create(dbUrl);
|
|
88
|
+
try {
|
|
89
|
+
const familyInstance = config.family.create({
|
|
90
|
+
target: config.target,
|
|
91
|
+
adapter: config.adapter,
|
|
92
|
+
driver: driverDescriptor,
|
|
93
|
+
extensions: config.extensions ?? []
|
|
94
|
+
});
|
|
95
|
+
const typedFamilyInstance = familyInstance;
|
|
96
|
+
const contractIR = typedFamilyInstance.validateContractIR(contractJson);
|
|
97
|
+
let schemaVerifyResult;
|
|
98
|
+
try {
|
|
99
|
+
schemaVerifyResult = await withSpinner(
|
|
100
|
+
async () => {
|
|
101
|
+
return await typedFamilyInstance.schemaVerify({
|
|
102
|
+
driver,
|
|
103
|
+
contractIR,
|
|
104
|
+
strict: false,
|
|
105
|
+
contractPath: contractPathAbsolute,
|
|
106
|
+
configPath
|
|
107
|
+
});
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
message: "Verifying database satisfies contract",
|
|
111
|
+
flags
|
|
112
|
+
}
|
|
113
|
+
);
|
|
114
|
+
} catch (error) {
|
|
115
|
+
throw errorRuntime(error instanceof Error ? error.message : String(error), {
|
|
116
|
+
why: `Failed to verify database schema: ${error instanceof Error ? error.message : String(error)}`
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
if (!schemaVerifyResult.ok) {
|
|
120
|
+
return { schemaVerifyResult, signResult: void 0 };
|
|
121
|
+
}
|
|
122
|
+
let signResult;
|
|
123
|
+
try {
|
|
124
|
+
signResult = await withSpinner(
|
|
125
|
+
async () => {
|
|
126
|
+
return await typedFamilyInstance.sign({
|
|
127
|
+
driver,
|
|
128
|
+
contractIR,
|
|
129
|
+
contractPath: contractPathAbsolute,
|
|
130
|
+
configPath
|
|
131
|
+
});
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
message: "Signing database...",
|
|
135
|
+
flags
|
|
136
|
+
}
|
|
137
|
+
);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
throw errorRuntime(error instanceof Error ? error.message : String(error), {
|
|
140
|
+
why: `Failed to sign database: ${error instanceof Error ? error.message : String(error)}`
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
144
|
+
console.log("");
|
|
145
|
+
}
|
|
146
|
+
return { schemaVerifyResult: void 0, signResult };
|
|
147
|
+
} finally {
|
|
148
|
+
await driver.close();
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
const exitCode = handleResult(result, flags, (value) => {
|
|
152
|
+
const { schemaVerifyResult, signResult } = value;
|
|
153
|
+
if (schemaVerifyResult && !schemaVerifyResult.ok) {
|
|
154
|
+
if (flags.json === "object") {
|
|
155
|
+
console.log(formatSchemaVerifyJson(schemaVerifyResult));
|
|
156
|
+
} else {
|
|
157
|
+
const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
|
|
158
|
+
if (output) {
|
|
159
|
+
console.log(output);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (signResult) {
|
|
165
|
+
if (flags.json === "object") {
|
|
166
|
+
console.log(formatSignJson(signResult));
|
|
167
|
+
} else {
|
|
168
|
+
const output = formatSignOutput(signResult, flags);
|
|
169
|
+
if (output) {
|
|
170
|
+
console.log(output);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.ok) {
|
|
176
|
+
process.exit(1);
|
|
177
|
+
} else {
|
|
178
|
+
process.exit(exitCode);
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
return command;
|
|
182
|
+
}
|
|
183
|
+
export {
|
|
184
|
+
createDbSignCommand
|
|
185
|
+
};
|
|
186
|
+
//# sourceMappingURL=db-sign.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-sign.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport {\n errorDatabaseUrlRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorRuntime,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type {\n FamilyInstance,\n SignDatabaseResult,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatSchemaVerifyJson,\n formatSchemaVerifyOutput,\n formatSignJson,\n formatSignOutput,\n formatStyledHeader,\n} from '../utils/output';\nimport { performAction } from '../utils/result';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbSignOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | 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 createDbSignCommand(): Command {\n const command = new Command('sign');\n setCommandDescriptions(\n command,\n 'Sign the database with your contract so you can safely run queries',\n 'Verifies that your database schema satisfies the emitted contract, and if so, writes or\\n' +\n 'updates the contract marker in the database. This command is idempotent and safe to run\\n' +\n 'in CI/deployment pipelines. The marker records that this database instance is aligned\\n' +\n 'with a specific contract version.',\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('-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: DbSignOptions) => {\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 sign',\n description: 'Sign the database with your contract so you can safely run queries',\n url: 'https://pris.ly/db-sign',\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 // Resolve database URL\n const dbUrl = options.db ?? config.db?.url;\n if (!dbUrl) {\n throw errorDatabaseUrlRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create driver\n const driver = await driverDescriptor.create(dbUrl);\n\n try {\n // Create family instance\n const familyInstance = config.family.create({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensions: config.extensions ?? [],\n });\n const typedFamilyInstance = familyInstance as FamilyInstance<string>;\n\n // Validate contract using instance validator\n const contractIR = typedFamilyInstance.validateContractIR(contractJson) as ContractIR;\n\n // Schema verification precondition with spinner\n let schemaVerifyResult: VerifyDatabaseSchemaResult;\n try {\n schemaVerifyResult = await withSpinner(\n async () => {\n return (await typedFamilyInstance.schemaVerify({\n driver,\n contractIR,\n strict: false,\n contractPath: contractPathAbsolute,\n configPath,\n })) as VerifyDatabaseSchemaResult;\n },\n {\n message: 'Verifying database satisfies contract',\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 // If schema verification failed, return both results for handling outside performAction\n if (!schemaVerifyResult.ok) {\n return { schemaVerifyResult, signResult: undefined };\n }\n\n // Schema verification passed - proceed with signing\n let signResult: SignDatabaseResult;\n try {\n signResult = await withSpinner(\n async () => {\n return (await typedFamilyInstance.sign({\n driver,\n contractIR,\n contractPath: contractPathAbsolute,\n configPath,\n })) as SignDatabaseResult;\n },\n {\n message: 'Signing database...',\n flags,\n },\n );\n } catch (error) {\n // Wrap errors from sign() in structured error\n throw errorRuntime(error instanceof Error ? error.message : String(error), {\n why: `Failed to sign database: ${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 { schemaVerifyResult: undefined, signResult };\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, (value) => {\n const { schemaVerifyResult, signResult } = value;\n\n // If schema verification failed, format and print schema verification output\n if (schemaVerifyResult && !schemaVerifyResult.ok) {\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 // Don't proceed to sign output formatting\n return;\n }\n\n // Schema verification passed - format sign output\n if (signResult) {\n if (flags.json === 'object') {\n console.log(formatSignJson(signResult));\n } else {\n const output = formatSignOutput(signResult, flags);\n if (output) {\n console.log(output);\n }\n }\n }\n });\n\n // For logical schema mismatches, check if schema verification passed\n // Infra errors already handled by handleResult (returns non-zero exit code)\n if (result.ok && result.value.schemaVerifyResult && !result.value.schemaVerifyResult.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;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,eAAe;AA+BjB,SAAS,sBAA+B;AAC7C,QAAM,UAAU,IAAI,QAAQ,MAAM;AAClC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAIF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,mBAAmB,qCAAqC,KAAK,EACpE,OAAO,eAAe,yBAAyB,EAC/C,OAAO,iBAAiB,qCAAqC,EAC7D,OAAO,gBAAgB,4CAA4C,EACnE,OAAO,gBAAgB,0BAA0B,EACjD,OAAO,WAAW,oBAAoB,EACtC,OAAO,cAAc,sBAAsB,EAC3C,OAAO,OAAO,YAA2B;AACxC,UAAM,QAAQ,iBAAiB,OAAO;AAEtC,UAAM,SAAS,MAAM,cAAc,YAAY;AAE7C,YAAM,SAAS,MAAM,WAAW,QAAQ,MAAM;AAE9C,YAAM,aAAa,QAAQ,SACvB,SAAS,QAAQ,IAAI,GAAG,QAAQ,QAAQ,MAAM,CAAC,IAC/C;AACJ,YAAM,uBAAuB,OAAO,UAAU,SAC1C,QAAQ,OAAO,SAAS,MAAM,IAC9B,QAAQ,0BAA0B;AAEtC,YAAM,eAAe,SAAS,QAAQ,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AE;AAEA,cAAM,OAAO,MAAM;AAAA,MACrB;AAAA,IACF,CAAC;AAGD,UAAM,WAAW,aAAa,QAAQ,OAAO,CAAC,UAAU;AACtD,YAAM,EAAE,oBAAoB,WAAW,IAAI;AAG3C,UAAI,sBAAsB,CAAC,mBAAmB,IAAI;AAChD,YAAI,MAAM,SAAS,UAAU;AAC3B,kBAAQ,IAAI,uBAAuB,kBAAkB,CAAC;AAAA,QACxD,OAAO;AACL,gBAAM,SAAS,yBAAyB,oBAAoB,KAAK;AACjE,cAAI,QAAQ;AACV,oBAAQ,IAAI,MAAM;AAAA,UACpB;AAAA,QACF;AAEA;AAAA,MACF;AAGA,UAAI,YAAY;AACd,YAAI,MAAM,SAAS,UAAU;AAC3B,kBAAQ,IAAI,eAAe,UAAU,CAAC;AAAA,QACxC,OAAO;AACL,gBAAM,SAAS,iBAAiB,YAAY,KAAK;AACjD,cAAI,QAAQ;AACV,oBAAQ,IAAI,MAAM;AAAA,UACpB;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAID,QAAI,OAAO,MAAM,OAAO,MAAM,sBAAsB,CAAC,OAAO,MAAM,mBAAmB,IAAI;AAEvF,cAAQ,KAAK,CAAC;AAAA,IAChB,OAAO;AAEL,cAAQ,KAAK,QAAQ;AAAA,IACvB;AAAA,EACF,CAAC;AAEH,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import {
|
|
2
|
+
formatCommandHelp,
|
|
3
|
+
formatStyledHeader,
|
|
4
|
+
formatVerifyJson,
|
|
5
|
+
formatVerifyOutput,
|
|
6
|
+
handleResult,
|
|
7
|
+
parseGlobalFlags,
|
|
8
|
+
performAction,
|
|
9
|
+
setCommandDescriptions,
|
|
10
|
+
withSpinner
|
|
11
|
+
} from "../chunk-3EODSNGS.js";
|
|
12
|
+
import {
|
|
13
|
+
loadConfig
|
|
14
|
+
} from "../chunk-HWYQOCAJ.js";
|
|
15
|
+
|
|
16
|
+
// src/commands/db-verify.ts
|
|
17
|
+
import { readFile } from "fs/promises";
|
|
18
|
+
import { relative, resolve } from "path";
|
|
19
|
+
import {
|
|
20
|
+
errorDatabaseUrlRequired,
|
|
21
|
+
errorDriverRequired,
|
|
22
|
+
errorFileNotFound,
|
|
23
|
+
errorHashMismatch,
|
|
24
|
+
errorMarkerMissing,
|
|
25
|
+
errorRuntime,
|
|
26
|
+
errorTargetMismatch,
|
|
27
|
+
errorUnexpected
|
|
28
|
+
} from "@prisma-next/core-control-plane/errors";
|
|
29
|
+
import { Command } from "commander";
|
|
30
|
+
function createDbVerifyCommand() {
|
|
31
|
+
const command = new Command("verify");
|
|
32
|
+
setCommandDescriptions(
|
|
33
|
+
command,
|
|
34
|
+
"Check whether the database has been signed with your contract",
|
|
35
|
+
"Verifies that your database schema matches the emitted contract. Checks table structures,\ncolumn types, constraints, and codec coverage. Reports any mismatches or missing codecs."
|
|
36
|
+
);
|
|
37
|
+
command.configureHelp({
|
|
38
|
+
formatHelp: (cmd) => {
|
|
39
|
+
const flags = parseGlobalFlags({});
|
|
40
|
+
return formatCommandHelp({ command: cmd, flags });
|
|
41
|
+
}
|
|
42
|
+
}).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) => {
|
|
43
|
+
const flags = parseGlobalFlags(options);
|
|
44
|
+
const result = await performAction(async () => {
|
|
45
|
+
const config = await loadConfig(options.config);
|
|
46
|
+
const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
|
|
47
|
+
const contractPathAbsolute = config.contract?.output ? resolve(config.contract.output) : resolve("src/prisma/contract.json");
|
|
48
|
+
const contractPath = relative(process.cwd(), contractPathAbsolute);
|
|
49
|
+
if (flags.json !== "object" && !flags.quiet) {
|
|
50
|
+
const details = [
|
|
51
|
+
{ label: "config", value: configPath },
|
|
52
|
+
{ label: "contract", value: contractPath }
|
|
53
|
+
];
|
|
54
|
+
if (options.db) {
|
|
55
|
+
details.push({ label: "database", value: options.db });
|
|
56
|
+
}
|
|
57
|
+
const header = formatStyledHeader({
|
|
58
|
+
command: "db verify",
|
|
59
|
+
description: "Check whether the database has been signed with your contract",
|
|
60
|
+
url: "https://pris.ly/db-verify",
|
|
61
|
+
details,
|
|
62
|
+
flags
|
|
63
|
+
});
|
|
64
|
+
console.log(header);
|
|
65
|
+
}
|
|
66
|
+
let contractJsonContent;
|
|
67
|
+
try {
|
|
68
|
+
contractJsonContent = await readFile(contractPathAbsolute, "utf-8");
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error instanceof Error && error.code === "ENOENT") {
|
|
71
|
+
throw errorFileNotFound(contractPathAbsolute, {
|
|
72
|
+
why: `Contract file not found at ${contractPathAbsolute}`
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
throw errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
76
|
+
why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const contractJson = JSON.parse(contractJsonContent);
|
|
80
|
+
const dbUrl = options.db ?? config.db?.url;
|
|
81
|
+
if (!dbUrl) {
|
|
82
|
+
throw errorDatabaseUrlRequired();
|
|
83
|
+
}
|
|
84
|
+
if (!config.driver) {
|
|
85
|
+
throw errorDriverRequired();
|
|
86
|
+
}
|
|
87
|
+
const driverDescriptor = config.driver;
|
|
88
|
+
const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
|
|
89
|
+
message: "Connecting to database...",
|
|
90
|
+
flags
|
|
91
|
+
});
|
|
92
|
+
try {
|
|
93
|
+
const familyInstance = config.family.create({
|
|
94
|
+
target: config.target,
|
|
95
|
+
adapter: config.adapter,
|
|
96
|
+
driver: driverDescriptor,
|
|
97
|
+
extensions: config.extensions ?? []
|
|
98
|
+
});
|
|
99
|
+
const typedFamilyInstance = familyInstance;
|
|
100
|
+
const contractIR = typedFamilyInstance.validateContractIR(contractJson);
|
|
101
|
+
let verifyResult;
|
|
102
|
+
try {
|
|
103
|
+
verifyResult = await withSpinner(
|
|
104
|
+
() => typedFamilyInstance.verify({
|
|
105
|
+
driver,
|
|
106
|
+
contractIR,
|
|
107
|
+
expectedTargetId: config.target.targetId,
|
|
108
|
+
contractPath: contractPathAbsolute,
|
|
109
|
+
configPath
|
|
110
|
+
}),
|
|
111
|
+
{
|
|
112
|
+
message: "Verifying database schema...",
|
|
113
|
+
flags
|
|
114
|
+
}
|
|
115
|
+
);
|
|
116
|
+
} catch (error) {
|
|
117
|
+
throw errorUnexpected(error instanceof Error ? error.message : String(error), {
|
|
118
|
+
why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
if (!verifyResult.ok && verifyResult.code) {
|
|
122
|
+
if (verifyResult.code === "PN-RTM-3001") {
|
|
123
|
+
throw errorMarkerMissing();
|
|
124
|
+
}
|
|
125
|
+
if (verifyResult.code === "PN-RTM-3002") {
|
|
126
|
+
throw errorHashMismatch({
|
|
127
|
+
expected: verifyResult.contract.coreHash,
|
|
128
|
+
...verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
if (verifyResult.code === "PN-RTM-3003") {
|
|
132
|
+
throw errorTargetMismatch(
|
|
133
|
+
verifyResult.target.expected,
|
|
134
|
+
verifyResult.target.actual ?? "unknown"
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
throw errorRuntime(verifyResult.summary);
|
|
138
|
+
}
|
|
139
|
+
if (!flags.quiet && flags.json !== "object" && process.stdout.isTTY) {
|
|
140
|
+
console.log("");
|
|
141
|
+
}
|
|
142
|
+
return verifyResult;
|
|
143
|
+
} finally {
|
|
144
|
+
await driver.close();
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
const exitCode = handleResult(result, flags, (verifyResult) => {
|
|
148
|
+
if (flags.json === "object") {
|
|
149
|
+
console.log(formatVerifyJson(verifyResult));
|
|
150
|
+
} else {
|
|
151
|
+
const output = formatVerifyOutput(verifyResult, flags);
|
|
152
|
+
if (output) {
|
|
153
|
+
console.log(output);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
process.exit(exitCode);
|
|
158
|
+
});
|
|
159
|
+
return command;
|
|
160
|
+
}
|
|
161
|
+
export {
|
|
162
|
+
createDbVerifyCommand
|
|
163
|
+
};
|
|
164
|
+
//# sourceMappingURL=db-verify.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/commands/db-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 errorDatabaseUrlRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorHashMismatch,\n errorMarkerMissing,\n errorRuntime,\n errorTargetMismatch,\n errorUnexpected,\n} from '@prisma-next/core-control-plane/errors';\nimport type { FamilyInstance, VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { setCommandDescriptions } from '../utils/command-helpers';\nimport { parseGlobalFlags } from '../utils/global-flags';\nimport {\n formatCommandHelp,\n formatStyledHeader,\n formatVerifyJson,\n formatVerifyOutput,\n} from '../utils/output';\nimport { performAction } from '../utils/result';\nimport { handleResult } from '../utils/result-handler';\nimport { withSpinner } from '../utils/spinner';\n\ninterface DbVerifyOptions {\n readonly db?: string;\n readonly config?: string;\n readonly json?: string | 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 createDbVerifyCommand(): Command {\n const command = new Command('verify');\n setCommandDescriptions(\n command,\n 'Check whether the database has been signed with your contract',\n 'Verifies that your database schema matches the emitted contract. Checks table structures,\\n' +\n 'column types, constraints, and codec coverage. Reports any mismatches or missing codecs.',\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('-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: DbVerifyOptions) => {\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 verify',\n description: 'Check whether the database has been signed with your contract',\n url: 'https://pris.ly/db-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 // Resolve database URL\n const dbUrl = options.db ?? config.db?.url;\n if (!dbUrl) {\n throw errorDatabaseUrlRequired();\n }\n\n // Check for driver\n if (!config.driver) {\n throw errorDriverRequired();\n }\n\n // Store driver descriptor after null check\n const driverDescriptor = config.driver;\n\n // Create driver\n const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {\n message: 'Connecting to database...',\n flags,\n });\n\n try {\n // Create family instance\n const familyInstance = config.family.create({\n target: config.target,\n adapter: config.adapter,\n driver: driverDescriptor,\n extensions: config.extensions ?? [],\n });\n const typedFamilyInstance = familyInstance as FamilyInstance<string>;\n\n // Validate contract using instance validator\n const contractIR = typedFamilyInstance.validateContractIR(contractJson) as ContractIR;\n\n // Call family instance verify method\n let verifyResult: VerifyDatabaseResult;\n try {\n verifyResult = (await withSpinner(\n () =>\n typedFamilyInstance.verify({\n driver,\n contractIR,\n expectedTargetId: config.target.targetId,\n contractPath: contractPathAbsolute,\n configPath,\n }),\n {\n message: 'Verifying database schema...',\n flags,\n },\n )) as VerifyDatabaseResult;\n } catch (error) {\n // Wrap errors from verify() in structured error\n throw errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n\n // If verification failed, throw structured error\n if (!verifyResult.ok && verifyResult.code) {\n if (verifyResult.code === 'PN-RTM-3001') {\n throw errorMarkerMissing();\n }\n if (verifyResult.code === 'PN-RTM-3002') {\n throw errorHashMismatch({\n expected: verifyResult.contract.coreHash,\n ...(verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}),\n });\n }\n if (verifyResult.code === 'PN-RTM-3003') {\n throw errorTargetMismatch(\n verifyResult.target.expected,\n verifyResult.target.actual ?? 'unknown',\n );\n }\n throw errorRuntime(verifyResult.summary);\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 verifyResult;\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, (verifyResult) => {\n // Output based on flags\n if (flags.json === 'object') {\n // JSON output to stdout\n console.log(formatVerifyJson(verifyResult));\n } else {\n // Human-readable output to stdout\n const output = formatVerifyOutput(verifyResult, flags);\n if (output) {\n console.log(output);\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,eAAe;AAElC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,eAAe;AA6BjB,SAAS,wBAAiC;AAC/C,QAAM,UAAU,IAAI,QAAQ,QAAQ;AACpC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EAEF;AACA,UACG,cAAc;AAAA,IACb,YAAY,CAAC,QAAQ;AACnB,YAAM,QAAQ,iBAAiB,CAAC,CAAC;AACjC,aAAO,kBAAkB,EAAE,SAAS,KAAK,MAAM,CAAC;AAAA,IAClD;AAAA,EACF,CAAC,EACA,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,mBAAmB,qCAAqC,KAAK,EACpE,OAAO,eAAe,yBAAyB,EAC/C,OAAO,iBAAiB,qCAAqC,EAC7D,OAAO,gBAAgB,4CAA4C,EACnE,OAAO,gBAAgB,0BAA0B,EACjD,OAAO,WAAW,oBAAoB,EACtC,OAAO,cAAc,sBAAsB,EAC3C,OAAO,OAAO,YAA6B;AAC1C,UAAM,QAAQ,iBAAiB,OAAO;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