@prisma-next/cli 0.0.1 → 0.1.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;A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-control-plane/config-types';
2
+
3
+ /**
4
+ * Loads the Prisma Next config from a TypeScript file.
5
+ * Supports both default export and named export.
6
+ * Uses c12 to automatically handle TypeScript compilation and config file discovery.
7
+ *
8
+ * @param configPath - Optional path to config file. Defaults to `./prisma-next.config.ts` in current directory.
9
+ * @returns The loaded config object.
10
+ * @throws Error if config file doesn't exist or is invalid.
11
+ */
12
+ declare function loadConfig(configPath?: string): Promise<PrismaNextConfig>;
13
+
14
+ export { loadConfig };
@@ -0,0 +1,7 @@
1
+ import {
2
+ loadConfig
3
+ } from "./chunk-HWYQOCAJ.js";
4
+ export {
5
+ loadConfig
6
+ };
7
+ //# sourceMappingURL=config-loader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,10 +1,9 @@
1
- import { Command } from 'commander';
1
+ export { createContractEmitCommand } from './commands/contract-emit.js';
2
2
  import { ContractIR } from '@prisma-next/contract/ir';
3
3
  export { loadExtensionPackManifest, loadExtensionPacks } from './pack-loading.js';
4
+ import 'commander';
4
5
  import '@prisma-next/contract/pack-manifest-types';
5
6
 
6
- declare function createContractEmitCommand(): Command;
7
-
8
7
  interface LoadTsContractOptions {
9
8
  readonly allowlist?: ReadonlyArray<string>;
10
9
  }
@@ -25,4 +24,4 @@ interface LoadTsContractOptions {
25
24
  */
26
25
  declare function loadContractFromTs(entryPath: string, options?: LoadTsContractOptions): Promise<ContractIR>;
27
26
 
28
- export { type LoadTsContractOptions, createContractEmitCommand, loadContractFromTs };
27
+ export { type LoadTsContractOptions, loadContractFromTs };