@prisma-next/cli 0.3.0-dev.11 → 0.3.0-dev.113

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 (215) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +470 -134
  3. package/dist/cli-errors-ByGuoqNj.mjs +3 -0
  4. package/dist/cli-errors-D6HxRn3A.d.mts +2 -0
  5. package/dist/cli.d.mts +1 -0
  6. package/dist/cli.js +1 -2350
  7. package/dist/cli.mjs +235 -0
  8. package/dist/cli.mjs.map +1 -0
  9. package/dist/client-612RJJD_.mjs +1069 -0
  10. package/dist/client-612RJJD_.mjs.map +1 -0
  11. package/dist/commands/contract-emit.d.mts +7 -0
  12. package/dist/commands/contract-emit.d.mts.map +1 -0
  13. package/dist/commands/contract-emit.mjs +4 -0
  14. package/dist/commands/contract-infer.d.mts +7 -0
  15. package/dist/commands/contract-infer.d.mts.map +1 -0
  16. package/dist/commands/contract-infer.mjs +4 -0
  17. package/dist/commands/db-init.d.mts +7 -0
  18. package/dist/commands/db-init.d.mts.map +1 -0
  19. package/dist/commands/db-init.mjs +124 -0
  20. package/dist/commands/db-init.mjs.map +1 -0
  21. package/dist/commands/db-schema.d.mts +7 -0
  22. package/dist/commands/db-schema.d.mts.map +1 -0
  23. package/dist/commands/db-schema.mjs +52 -0
  24. package/dist/commands/db-schema.mjs.map +1 -0
  25. package/dist/commands/db-sign.d.mts +7 -0
  26. package/dist/commands/db-sign.d.mts.map +1 -0
  27. package/dist/commands/db-sign.mjs +135 -0
  28. package/dist/commands/db-sign.mjs.map +1 -0
  29. package/dist/commands/db-update.d.mts +7 -0
  30. package/dist/commands/db-update.d.mts.map +1 -0
  31. package/dist/commands/db-update.mjs +121 -0
  32. package/dist/commands/db-update.mjs.map +1 -0
  33. package/dist/commands/db-verify.d.mts +7 -0
  34. package/dist/commands/db-verify.d.mts.map +1 -0
  35. package/dist/commands/db-verify.mjs +310 -0
  36. package/dist/commands/db-verify.mjs.map +1 -0
  37. package/dist/commands/migration-apply.d.mts +36 -0
  38. package/dist/commands/migration-apply.d.mts.map +1 -0
  39. package/dist/commands/migration-apply.mjs +240 -0
  40. package/dist/commands/migration-apply.mjs.map +1 -0
  41. package/dist/commands/migration-plan.d.mts +47 -0
  42. package/dist/commands/migration-plan.d.mts.map +1 -0
  43. package/dist/commands/migration-plan.mjs +288 -0
  44. package/dist/commands/migration-plan.mjs.map +1 -0
  45. package/dist/commands/migration-ref.d.mts +43 -0
  46. package/dist/commands/migration-ref.d.mts.map +1 -0
  47. package/dist/commands/migration-ref.mjs +194 -0
  48. package/dist/commands/migration-ref.mjs.map +1 -0
  49. package/dist/commands/migration-show.d.mts +28 -0
  50. package/dist/commands/migration-show.d.mts.map +1 -0
  51. package/dist/commands/migration-show.mjs +139 -0
  52. package/dist/commands/migration-show.mjs.map +1 -0
  53. package/dist/commands/migration-status.d.mts +85 -0
  54. package/dist/commands/migration-status.d.mts.map +1 -0
  55. package/dist/commands/migration-status.mjs +4 -0
  56. package/dist/commands/migration-verify.d.mts +16 -0
  57. package/dist/commands/migration-verify.d.mts.map +1 -0
  58. package/dist/commands/migration-verify.mjs +87 -0
  59. package/dist/commands/migration-verify.mjs.map +1 -0
  60. package/dist/config-loader-d_KF19Tw.mjs +43 -0
  61. package/dist/config-loader-d_KF19Tw.mjs.map +1 -0
  62. package/dist/{config-loader.d.ts → config-loader.d.mts} +8 -3
  63. package/dist/config-loader.d.mts.map +1 -0
  64. package/dist/config-loader.mjs +3 -0
  65. package/dist/contract-emit-CVv7dbQ9.mjs +187 -0
  66. package/dist/contract-emit-CVv7dbQ9.mjs.map +1 -0
  67. package/dist/contract-infer-Bvw8u8Eu.mjs +83 -0
  68. package/dist/contract-infer-Bvw8u8Eu.mjs.map +1 -0
  69. package/dist/exports/config-types.d.mts +2 -0
  70. package/dist/exports/config-types.mjs +3 -0
  71. package/dist/exports/control-api.d.mts +626 -0
  72. package/dist/exports/control-api.d.mts.map +1 -0
  73. package/dist/exports/control-api.mjs +107 -0
  74. package/dist/exports/control-api.mjs.map +1 -0
  75. package/dist/{load-ts-contract.d.ts → exports/index.d.mts} +10 -5
  76. package/dist/exports/index.d.mts.map +1 -0
  77. package/dist/exports/index.mjs +130 -0
  78. package/dist/exports/index.mjs.map +1 -0
  79. package/dist/extract-sql-ddl-Jf5blEO0.mjs +26 -0
  80. package/dist/extract-sql-ddl-Jf5blEO0.mjs.map +1 -0
  81. package/dist/framework-components-M2j-qPfr.mjs +59 -0
  82. package/dist/framework-components-M2j-qPfr.mjs.map +1 -0
  83. package/dist/inspect-live-schema-BQe5i4YE.mjs +90 -0
  84. package/dist/inspect-live-schema-BQe5i4YE.mjs.map +1 -0
  85. package/dist/migration-command-scaffold-SLrjcKXS.mjs +104 -0
  86. package/dist/migration-command-scaffold-SLrjcKXS.mjs.map +1 -0
  87. package/dist/migration-status-DAQKsmWW.mjs +1576 -0
  88. package/dist/migration-status-DAQKsmWW.mjs.map +1 -0
  89. package/dist/migrations-Db_ea9eE.mjs +173 -0
  90. package/dist/migrations-Db_ea9eE.mjs.map +1 -0
  91. package/dist/progress-adapter-DRNe2idZ.mjs +43 -0
  92. package/dist/progress-adapter-DRNe2idZ.mjs.map +1 -0
  93. package/dist/terminal-ui-DAcMBRKf.mjs +980 -0
  94. package/dist/terminal-ui-DAcMBRKf.mjs.map +1 -0
  95. package/dist/verify-DXKxBFvU.mjs +385 -0
  96. package/dist/verify-DXKxBFvU.mjs.map +1 -0
  97. package/package.json +88 -43
  98. package/src/cli.ts +109 -58
  99. package/src/commands/contract-emit.ts +236 -143
  100. package/src/commands/contract-infer-paths.ts +32 -0
  101. package/src/commands/contract-infer.ts +131 -0
  102. package/src/commands/db-init.ts +211 -425
  103. package/src/commands/db-schema.ts +77 -0
  104. package/src/commands/db-sign.ts +207 -228
  105. package/src/commands/db-update.ts +236 -0
  106. package/src/commands/db-verify.ts +484 -186
  107. package/src/commands/inspect-live-schema.ts +171 -0
  108. package/src/commands/migration-apply.ts +416 -0
  109. package/src/commands/migration-plan.ts +451 -0
  110. package/src/commands/migration-ref.ts +305 -0
  111. package/src/commands/migration-show.ts +246 -0
  112. package/src/commands/migration-status.ts +838 -0
  113. package/src/commands/migration-verify.ts +134 -0
  114. package/src/config-loader.ts +13 -3
  115. package/src/control-api/client.ts +614 -0
  116. package/src/control-api/contract-enrichment.ts +135 -0
  117. package/src/control-api/errors.ts +9 -0
  118. package/src/control-api/operations/contract-emit.ts +173 -0
  119. package/src/control-api/operations/db-init.ts +286 -0
  120. package/src/control-api/operations/db-update.ts +221 -0
  121. package/src/control-api/operations/extract-sql-ddl.ts +47 -0
  122. package/src/control-api/operations/migration-apply.ts +194 -0
  123. package/src/control-api/operations/migration-helpers.ts +49 -0
  124. package/src/control-api/types.ts +683 -0
  125. package/src/exports/config-types.ts +4 -3
  126. package/src/exports/control-api.ts +56 -0
  127. package/src/load-ts-contract.ts +16 -11
  128. package/src/utils/cli-errors.ts +5 -2
  129. package/src/utils/command-helpers.ts +293 -3
  130. package/src/utils/formatters/emit.ts +67 -0
  131. package/src/utils/formatters/errors.ts +82 -0
  132. package/src/utils/formatters/graph-migration-mapper.ts +220 -0
  133. package/src/utils/formatters/graph-render.ts +1317 -0
  134. package/src/utils/formatters/graph-types.ts +114 -0
  135. package/src/utils/formatters/help.ts +380 -0
  136. package/src/utils/formatters/helpers.ts +28 -0
  137. package/src/utils/formatters/migrations.ts +346 -0
  138. package/src/utils/formatters/styled.ts +212 -0
  139. package/src/utils/formatters/verify.ts +620 -0
  140. package/src/utils/global-flags.ts +41 -23
  141. package/src/utils/migration-command-scaffold.ts +187 -0
  142. package/src/utils/migration-types.ts +12 -0
  143. package/src/utils/progress-adapter.ts +75 -0
  144. package/src/utils/result-handler.ts +12 -13
  145. package/src/utils/shutdown.ts +92 -0
  146. package/src/utils/suggest-command.ts +31 -0
  147. package/src/utils/terminal-ui.ts +276 -0
  148. package/dist/chunk-BZMBKEEQ.js +0 -997
  149. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  150. package/dist/chunk-CVNWLFXO.js +0 -91
  151. package/dist/chunk-CVNWLFXO.js.map +0 -1
  152. package/dist/chunk-HWYQOCAJ.js +0 -47
  153. package/dist/chunk-HWYQOCAJ.js.map +0 -1
  154. package/dist/chunk-QUPBU4KV.js +0 -131
  155. package/dist/chunk-QUPBU4KV.js.map +0 -1
  156. package/dist/cli.d.ts +0 -2
  157. package/dist/cli.d.ts.map +0 -1
  158. package/dist/cli.js.map +0 -1
  159. package/dist/commands/contract-emit.d.ts +0 -3
  160. package/dist/commands/contract-emit.d.ts.map +0 -1
  161. package/dist/commands/contract-emit.js +0 -9
  162. package/dist/commands/contract-emit.js.map +0 -1
  163. package/dist/commands/db-init.d.ts +0 -3
  164. package/dist/commands/db-init.d.ts.map +0 -1
  165. package/dist/commands/db-init.js +0 -337
  166. package/dist/commands/db-init.js.map +0 -1
  167. package/dist/commands/db-introspect.d.ts +0 -3
  168. package/dist/commands/db-introspect.d.ts.map +0 -1
  169. package/dist/commands/db-introspect.js +0 -186
  170. package/dist/commands/db-introspect.js.map +0 -1
  171. package/dist/commands/db-schema-verify.d.ts +0 -3
  172. package/dist/commands/db-schema-verify.d.ts.map +0 -1
  173. package/dist/commands/db-schema-verify.js +0 -160
  174. package/dist/commands/db-schema-verify.js.map +0 -1
  175. package/dist/commands/db-sign.d.ts +0 -3
  176. package/dist/commands/db-sign.d.ts.map +0 -1
  177. package/dist/commands/db-sign.js +0 -195
  178. package/dist/commands/db-sign.js.map +0 -1
  179. package/dist/commands/db-verify.d.ts +0 -3
  180. package/dist/commands/db-verify.d.ts.map +0 -1
  181. package/dist/commands/db-verify.js +0 -169
  182. package/dist/commands/db-verify.js.map +0 -1
  183. package/dist/config-loader.d.ts.map +0 -1
  184. package/dist/config-loader.js +0 -7
  185. package/dist/config-loader.js.map +0 -1
  186. package/dist/exports/config-types.d.ts +0 -3
  187. package/dist/exports/config-types.d.ts.map +0 -1
  188. package/dist/exports/config-types.js +0 -6
  189. package/dist/exports/config-types.js.map +0 -1
  190. package/dist/exports/index.d.ts +0 -4
  191. package/dist/exports/index.d.ts.map +0 -1
  192. package/dist/exports/index.js +0 -175
  193. package/dist/exports/index.js.map +0 -1
  194. package/dist/load-ts-contract.d.ts.map +0 -1
  195. package/dist/utils/action.d.ts +0 -16
  196. package/dist/utils/action.d.ts.map +0 -1
  197. package/dist/utils/cli-errors.d.ts +0 -7
  198. package/dist/utils/cli-errors.d.ts.map +0 -1
  199. package/dist/utils/command-helpers.d.ts +0 -12
  200. package/dist/utils/command-helpers.d.ts.map +0 -1
  201. package/dist/utils/framework-components.d.ts +0 -70
  202. package/dist/utils/framework-components.d.ts.map +0 -1
  203. package/dist/utils/global-flags.d.ts +0 -25
  204. package/dist/utils/global-flags.d.ts.map +0 -1
  205. package/dist/utils/output.d.ts +0 -142
  206. package/dist/utils/output.d.ts.map +0 -1
  207. package/dist/utils/result-handler.d.ts +0 -15
  208. package/dist/utils/result-handler.d.ts.map +0 -1
  209. package/dist/utils/spinner.d.ts +0 -29
  210. package/dist/utils/spinner.d.ts.map +0 -1
  211. package/src/commands/db-introspect.ts +0 -256
  212. package/src/commands/db-schema-verify.ts +0 -232
  213. package/src/utils/action.ts +0 -43
  214. package/src/utils/output.ts +0 -1471
  215. package/src/utils/spinner.ts +0 -67
@@ -1,8 +1,19 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { relative, resolve } from 'node:path';
3
- import type { ContractIR } from '@prisma-next/contract/ir';
2
+ import type {
3
+ VerifyDatabaseResult,
4
+ VerifyDatabaseSchemaResult,
5
+ } from '@prisma-next/core-control-plane/types';
6
+ import { ifDefined } from '@prisma-next/utils/defined';
7
+ import { notOk, ok, type Result } from '@prisma-next/utils/result';
8
+ import { Command } from 'commander';
9
+ import { relative, resolve } from 'pathe';
10
+ import { loadConfig } from '../config-loader';
11
+ import { createControlClient } from '../control-api/client';
12
+ import { ContractValidationError } from '../control-api/errors';
4
13
  import {
5
- errorDatabaseUrlRequired,
14
+ CliStructuredError,
15
+ errorContractValidationFailed,
16
+ errorDatabaseConnectionRequired,
6
17
  errorDriverRequired,
7
18
  errorFileNotFound,
8
19
  errorHashMismatch,
@@ -10,219 +21,506 @@ import {
10
21
  errorRuntime,
11
22
  errorTargetMismatch,
12
23
  errorUnexpected,
13
- } from '@prisma-next/core-control-plane/errors';
14
- import type { VerifyDatabaseResult } from '@prisma-next/core-control-plane/types';
15
- import { createControlPlaneStack } from '@prisma-next/core-control-plane/types';
16
- import { Command } from 'commander';
17
- import { loadConfig } from '../config-loader';
18
- import { performAction } from '../utils/action';
19
- import { setCommandDescriptions } from '../utils/command-helpers';
20
- import { assertContractRequirementsSatisfied } from '../utils/framework-components';
21
- import { parseGlobalFlags } from '../utils/global-flags';
24
+ } from '../utils/cli-errors';
22
25
  import {
23
- formatCommandHelp,
24
- formatStyledHeader,
26
+ addGlobalOptions,
27
+ maskConnectionUrl,
28
+ resolveContractPath,
29
+ setCommandDescriptions,
30
+ setCommandExamples,
31
+ } from '../utils/command-helpers';
32
+ import { formatStyledHeader } from '../utils/formatters/styled';
33
+ import {
34
+ type DbVerifyCommandSuccessResult,
35
+ formatSchemaVerifyJson,
36
+ formatSchemaVerifyOutput,
25
37
  formatVerifyJson,
26
38
  formatVerifyOutput,
27
- } from '../utils/output';
39
+ } from '../utils/formatters/verify';
40
+ import type { CommonCommandOptions } from '../utils/global-flags';
41
+ import { type GlobalFlags, parseGlobalFlags } from '../utils/global-flags';
42
+ import { createProgressAdapter } from '../utils/progress-adapter';
28
43
  import { handleResult } from '../utils/result-handler';
29
- import { withSpinner } from '../utils/spinner';
44
+ import { TerminalUI } from '../utils/terminal-ui';
30
45
 
31
- interface DbVerifyOptions {
46
+ interface DbVerifyOptions extends CommonCommandOptions {
32
47
  readonly db?: string;
33
48
  readonly config?: string;
34
- readonly json?: string | boolean;
35
- readonly quiet?: boolean;
36
- readonly q?: boolean;
37
- readonly verbose?: boolean;
38
- readonly v?: boolean;
39
- readonly vv?: boolean;
40
- readonly trace?: boolean;
41
- readonly timestamps?: boolean;
42
- readonly color?: boolean;
43
- readonly 'no-color'?: boolean;
49
+ readonly markerOnly?: boolean;
50
+ readonly schemaOnly?: boolean;
51
+ readonly strict?: boolean;
52
+ }
53
+
54
+ type DbVerifyMode = 'full' | 'marker-only' | 'schema-only';
55
+
56
+ /**
57
+ * Maps a VerifyDatabaseResult failure to a CliStructuredError.
58
+ */
59
+ function mapVerifyFailure(verifyResult: VerifyDatabaseResult): CliStructuredError {
60
+ if (!verifyResult.ok && verifyResult.code) {
61
+ if (verifyResult.code === 'PN-RUN-3001') {
62
+ return errorMarkerMissing();
63
+ }
64
+ if (verifyResult.code === 'PN-RUN-3002') {
65
+ return errorHashMismatch({
66
+ expected: verifyResult.contract.storageHash,
67
+ ...ifDefined('actual', verifyResult.marker?.storageHash),
68
+ });
69
+ }
70
+ if (verifyResult.code === 'PN-RUN-3003') {
71
+ return errorTargetMismatch(
72
+ verifyResult.target.expected,
73
+ verifyResult.target.actual ?? 'unknown',
74
+ );
75
+ }
76
+ // Unknown code - fall through to runtime error
77
+ }
78
+ return errorRuntime(verifyResult.summary);
79
+ }
80
+
81
+ type DbVerifyFailure = CliStructuredError | VerifyDatabaseSchemaResult;
82
+
83
+ function errorInvalidVerifyMode(options: {
84
+ readonly why: string;
85
+ readonly fix: string;
86
+ }): CliStructuredError {
87
+ return new CliStructuredError('4012', 'Invalid verify mode', {
88
+ domain: 'CLI',
89
+ why: options.why,
90
+ fix: options.fix,
91
+ docsUrl: 'https://pris.ly/db-verify',
92
+ });
93
+ }
94
+
95
+ function resolveDbVerifyMode(options: DbVerifyOptions): Result<DbVerifyMode, CliStructuredError> {
96
+ if (options.markerOnly && options.schemaOnly) {
97
+ return notOk(
98
+ errorInvalidVerifyMode({
99
+ why: '`--marker-only` and `--schema-only` cannot be used together',
100
+ fix: 'Choose one mode: omit both to check the marker and schema, use `--marker-only` to check only the marker, or use `--schema-only` to check only the live schema.',
101
+ }),
102
+ );
103
+ }
104
+
105
+ if (options.markerOnly && options.strict) {
106
+ return notOk(
107
+ errorInvalidVerifyMode({
108
+ why: '`--strict` requires schema verification, but `--marker-only` skips it',
109
+ fix: 'Remove `--strict`, or use `db verify` / `db verify --schema-only` when you want to check the live schema in strict mode.',
110
+ }),
111
+ );
112
+ }
113
+
114
+ if (options.schemaOnly) {
115
+ return ok('schema-only');
116
+ }
117
+
118
+ if (options.markerOnly) {
119
+ return ok('marker-only');
120
+ }
121
+
122
+ return ok('full');
123
+ }
124
+
125
+ function formatDbVerifyModeLabel(mode: DbVerifyMode, strict: boolean): string {
126
+ if (mode === 'marker-only') {
127
+ return 'marker only';
128
+ }
129
+
130
+ if (mode === 'schema-only') {
131
+ return `schema only (${strict ? 'strict' : 'tolerant'})`;
132
+ }
133
+
134
+ return `full (marker + schema, ${strict ? 'strict' : 'tolerant'})`;
135
+ }
136
+
137
+ function formatDbVerifyInvocation(mode: DbVerifyMode, strict: boolean): string {
138
+ const args = ['db verify'];
139
+
140
+ if (mode === 'marker-only') {
141
+ args.push('--marker-only');
142
+ }
143
+
144
+ if (mode === 'schema-only') {
145
+ args.push('--schema-only');
146
+ }
147
+
148
+ if (strict) {
149
+ args.push('--strict');
150
+ }
151
+
152
+ return args.join(' ');
153
+ }
154
+
155
+ function createDbVerifyConnectionRequiredError(options: {
156
+ readonly configPath: string;
157
+ readonly mode: DbVerifyMode;
158
+ readonly strict: boolean;
159
+ }): CliStructuredError {
160
+ const invocation = formatDbVerifyInvocation(options.mode, options.strict);
161
+ return errorDatabaseConnectionRequired({
162
+ why: `Database connection is required for ${invocation} (set db.connection in ${options.configPath}, or pass --db <url>)`,
163
+ retryCommand: `prisma-next ${invocation} --db <url>`,
164
+ });
165
+ }
166
+
167
+ function renderVerifyHeader(
168
+ paths: { configPath: string; contractPath: string },
169
+ options: DbVerifyOptions,
170
+ mode: DbVerifyMode,
171
+ flags: GlobalFlags,
172
+ ui: TerminalUI,
173
+ ): void {
174
+ if (flags.json || flags.quiet) return;
175
+
176
+ const description =
177
+ mode === 'schema-only'
178
+ ? 'Check whether the live database schema matches your contract'
179
+ : mode === 'marker-only'
180
+ ? 'Check whether the database marker matches your contract'
181
+ : 'Check whether the database marker and live schema match your contract';
182
+
183
+ const details: Array<{ label: string; value: string }> = [
184
+ { label: 'config', value: paths.configPath },
185
+ { label: 'contract', value: paths.contractPath },
186
+ { label: 'mode', value: formatDbVerifyModeLabel(mode, options.strict ?? false) },
187
+ ];
188
+ if (options.db) {
189
+ details.push({ label: 'database', value: maskConnectionUrl(options.db) });
190
+ }
191
+
192
+ ui.stderr(
193
+ formatStyledHeader({
194
+ command: 'db verify',
195
+ description,
196
+ url: 'https://pris.ly/db-verify',
197
+ details,
198
+ flags,
199
+ }),
200
+ );
201
+ }
202
+
203
+ async function resolveVerifyPaths(options: DbVerifyOptions) {
204
+ const config = await loadConfig(options.config);
205
+ const configPath = options.config
206
+ ? relative(process.cwd(), resolve(options.config))
207
+ : 'prisma-next.config.ts';
208
+ const contractPathAbsolute = resolveContractPath(config);
209
+ const contractPath = relative(process.cwd(), contractPathAbsolute);
210
+ return { config, configPath, contractPathAbsolute, contractPath };
211
+ }
212
+
213
+ type VerifyPaths = Awaited<ReturnType<typeof resolveVerifyPaths>>;
214
+
215
+ interface VerifySetup extends VerifyPaths {
216
+ readonly contractJson: Record<string, unknown>;
217
+ readonly dbConnection: string;
218
+ }
219
+
220
+ async function resolveVerifySetup(
221
+ paths: VerifyPaths,
222
+ options: DbVerifyOptions,
223
+ mode: DbVerifyMode,
224
+ ): Promise<Result<VerifySetup, CliStructuredError>> {
225
+ const { config, configPath, contractPathAbsolute, contractPath } = paths;
226
+
227
+ let contractJsonContent: string;
228
+ try {
229
+ contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
230
+ } catch (error) {
231
+ if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
232
+ return notOk(
233
+ errorFileNotFound(contractPathAbsolute, {
234
+ why: `Contract file not found at ${contractPathAbsolute}`,
235
+ fix: `Run \`prisma-next contract emit\` to generate ${contractPath}, or update \`config.contract.output\` in ${configPath}`,
236
+ }),
237
+ );
238
+ }
239
+ return notOk(
240
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
241
+ why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
242
+ }),
243
+ );
244
+ }
245
+
246
+ let contractJson: Record<string, unknown>;
247
+ try {
248
+ contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
249
+ } catch (error) {
250
+ return notOk(
251
+ errorContractValidationFailed(
252
+ `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,
253
+ { where: { path: contractPathAbsolute } },
254
+ ),
255
+ );
256
+ }
257
+
258
+ const dbConnection = options.db ?? config.db?.connection;
259
+ if (typeof dbConnection !== 'string' || dbConnection.length === 0) {
260
+ return notOk(
261
+ createDbVerifyConnectionRequiredError({
262
+ configPath,
263
+ mode,
264
+ strict: options.strict ?? false,
265
+ }),
266
+ );
267
+ }
268
+
269
+ if (!config.driver) {
270
+ return notOk(
271
+ errorDriverRequired({
272
+ why: `Config.driver is required for ${formatDbVerifyInvocation(mode, options.strict ?? false)}`,
273
+ }),
274
+ );
275
+ }
276
+
277
+ return ok({ ...paths, contractJson, dbConnection });
278
+ }
279
+
280
+ function createVerifyClient(setup: VerifySetup) {
281
+ return createControlClient({
282
+ family: setup.config.family,
283
+ target: setup.config.target,
284
+ adapter: setup.config.adapter,
285
+ driver: setup.config.driver!,
286
+ extensionPacks: setup.config.extensionPacks ?? [],
287
+ });
288
+ }
289
+
290
+ function wrapVerifyError(
291
+ error: unknown,
292
+ contractPathAbsolute: string,
293
+ modeLabel: string,
294
+ ): Result<never, CliStructuredError> {
295
+ if (error instanceof CliStructuredError) {
296
+ return notOk(error);
297
+ }
298
+ if (error instanceof ContractValidationError) {
299
+ return notOk(
300
+ errorContractValidationFailed(`Contract validation failed: ${error.message}`, {
301
+ where: { path: contractPathAbsolute },
302
+ }),
303
+ );
304
+ }
305
+ return notOk(
306
+ errorUnexpected(error instanceof Error ? error.message : String(error), {
307
+ why: `Unexpected error during ${modeLabel}: ${error instanceof Error ? error.message : String(error)}`,
308
+ }),
309
+ );
310
+ }
311
+
312
+ /**
313
+ * Executes the db verify command and returns a structured Result.
314
+ */
315
+ async function executeDbVerifyCommand(
316
+ options: DbVerifyOptions,
317
+ flags: GlobalFlags,
318
+ ui: TerminalUI,
319
+ mode: Extract<DbVerifyMode, 'full' | 'marker-only'>,
320
+ ): Promise<Result<DbVerifyCommandSuccessResult, DbVerifyFailure>> {
321
+ const startTime = Date.now();
322
+ const paths = await resolveVerifyPaths(options);
323
+ renderVerifyHeader(paths, options, mode, flags, ui);
324
+
325
+ const setupResult = await resolveVerifySetup(paths, options, mode);
326
+ if (!setupResult.ok) return setupResult;
327
+ const { contractJson, dbConnection, contractPathAbsolute } = setupResult.value;
328
+
329
+ const client = createVerifyClient(setupResult.value);
330
+ const onProgress = createProgressAdapter({ ui, flags });
331
+
332
+ try {
333
+ const verifyResult = await client.verify({
334
+ contractIR: contractJson,
335
+ connection: dbConnection,
336
+ onProgress,
337
+ });
338
+
339
+ // If verification failed, map to CLI structured error
340
+ if (!verifyResult.ok) {
341
+ return notOk(mapVerifyFailure(verifyResult));
342
+ }
343
+
344
+ if (mode === 'marker-only') {
345
+ return ok({
346
+ ok: true,
347
+ mode: 'marker-only',
348
+ summary: 'Database marker matches contract',
349
+ contract: verifyResult.contract,
350
+ marker: verifyResult.marker,
351
+ target: verifyResult.target,
352
+ ...ifDefined('missingCodecs', verifyResult.missingCodecs),
353
+ ...ifDefined('codecCoverageSkipped', verifyResult.codecCoverageSkipped),
354
+ warning: 'Schema verification skipped because --marker-only was provided',
355
+ meta: {
356
+ ...(verifyResult.meta ?? {}),
357
+ schemaVerification: 'skipped',
358
+ },
359
+ timings: { total: Date.now() - startTime },
360
+ });
361
+ }
362
+
363
+ const schemaVerifyResult = await client.schemaVerify({
364
+ contractIR: contractJson,
365
+ strict: options.strict ?? false,
366
+ onProgress,
367
+ });
368
+
369
+ if (!schemaVerifyResult.ok) {
370
+ return notOk(schemaVerifyResult);
371
+ }
372
+
373
+ return ok({
374
+ ok: true,
375
+ mode: 'full',
376
+ summary: 'Database marker and schema match contract',
377
+ contract: verifyResult.contract,
378
+ marker: verifyResult.marker,
379
+ target: verifyResult.target,
380
+ ...ifDefined('missingCodecs', verifyResult.missingCodecs),
381
+ ...ifDefined('codecCoverageSkipped', verifyResult.codecCoverageSkipped),
382
+ schema: {
383
+ summary: schemaVerifyResult.summary,
384
+ counts: schemaVerifyResult.schema.counts,
385
+ strict: schemaVerifyResult.meta?.strict ?? false,
386
+ },
387
+ meta: {
388
+ ...(verifyResult.meta ?? {}),
389
+ schemaVerification: 'performed',
390
+ },
391
+ timings: { total: Date.now() - startTime },
392
+ });
393
+ } catch (error) {
394
+ return wrapVerifyError(error, contractPathAbsolute, 'db verify');
395
+ } finally {
396
+ await client.close();
397
+ }
398
+ }
399
+
400
+ async function executeDbSchemaOnlyVerifyCommand(
401
+ options: DbVerifyOptions,
402
+ flags: GlobalFlags,
403
+ ui: TerminalUI,
404
+ ): Promise<Result<VerifyDatabaseSchemaResult, CliStructuredError>> {
405
+ const paths = await resolveVerifyPaths(options);
406
+ renderVerifyHeader(paths, options, 'schema-only', flags, ui);
407
+
408
+ const setupResult = await resolveVerifySetup(paths, options, 'schema-only');
409
+ if (!setupResult.ok) return setupResult;
410
+ const { contractJson, dbConnection, contractPathAbsolute } = setupResult.value;
411
+
412
+ const client = createVerifyClient(setupResult.value);
413
+ const onProgress = createProgressAdapter({ ui, flags });
414
+
415
+ try {
416
+ const schemaVerifyResult = await client.schemaVerify({
417
+ contractIR: contractJson,
418
+ strict: options.strict ?? false,
419
+ connection: dbConnection,
420
+ onProgress,
421
+ });
422
+
423
+ return ok(schemaVerifyResult);
424
+ } catch (error) {
425
+ return wrapVerifyError(error, contractPathAbsolute, 'db verify --schema-only');
426
+ } finally {
427
+ await client.close();
428
+ }
44
429
  }
45
430
 
46
431
  export function createDbVerifyCommand(): Command {
47
432
  const command = new Command('verify');
48
433
  setCommandDescriptions(
49
434
  command,
50
- 'Check whether the database has been signed with your contract',
51
- 'Verifies that your database schema matches the emitted contract. Checks table structures,\n' +
52
- 'column types, constraints, and codec coverage. Reports any mismatches or missing codecs.',
435
+ 'Check whether the database marker and live schema match your contract',
436
+ 'Verifies the database marker first, then checks the database schema matches your contract.\n' +
437
+ 'Use `--marker-only` for marker-only verification, `--schema-only` to skip marker checks and\n' +
438
+ 'inspect only the live schema, and `--strict` to fail if the database includes elements\n' +
439
+ 'not present in the contract.',
53
440
  );
54
- command
55
- .configureHelp({
56
- formatHelp: (cmd) => {
57
- const flags = parseGlobalFlags({});
58
- return formatCommandHelp({ command: cmd, flags });
59
- },
60
- })
441
+ setCommandExamples(command, [
442
+ 'prisma-next db verify --db $DATABASE_URL',
443
+ 'prisma-next db verify --db $DATABASE_URL --strict',
444
+ 'prisma-next db verify --db $DATABASE_URL --schema-only',
445
+ 'prisma-next db verify --db $DATABASE_URL --schema-only --strict',
446
+ 'prisma-next db verify --db $DATABASE_URL --marker-only',
447
+ 'prisma-next db verify --db $DATABASE_URL --json',
448
+ ]);
449
+ addGlobalOptions(command)
61
450
  .option('--db <url>', 'Database connection string')
62
451
  .option('--config <path>', 'Path to prisma-next.config.ts')
63
- .option('--json [format]', 'Output as JSON (object or ndjson)', false)
64
- .option('-q, --quiet', 'Quiet mode: errors only')
65
- .option('-v, --verbose', 'Verbose output: debug info, timings')
66
- .option('-vv, --trace', 'Trace output: deep internals, stack traces')
67
- .option('--timestamps', 'Add timestamps to output')
68
- .option('--color', 'Force color output')
69
- .option('--no-color', 'Disable color output')
452
+ .option('--marker-only', 'Skip schema verification and only check the database marker')
453
+ .option(
454
+ '--schema-only',
455
+ 'Skip marker verification and only check whether the live schema satisfies the contract',
456
+ )
457
+ .option(
458
+ '--strict',
459
+ 'Strict mode: schema elements not present in the contract are considered an error',
460
+ false,
461
+ )
70
462
  .action(async (options: DbVerifyOptions) => {
71
463
  const flags = parseGlobalFlags(options);
464
+ const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });
72
465
 
73
- const result = await performAction(async () => {
74
- // Load config (file I/O)
75
- const config = await loadConfig(options.config);
76
- // Normalize config path for display (match contract path format - no ./ prefix)
77
- const configPath = options.config
78
- ? relative(process.cwd(), resolve(options.config))
79
- : 'prisma-next.config.ts';
80
- const contractPathAbsolute = config.contract?.output
81
- ? resolve(config.contract.output)
82
- : resolve('src/prisma/contract.json');
83
- // Convert to relative path for display
84
- const contractPath = relative(process.cwd(), contractPathAbsolute);
85
-
86
- // Output header (only for human-readable output)
87
- if (flags.json !== 'object' && !flags.quiet) {
88
- const details: Array<{ label: string; value: string }> = [
89
- { label: 'config', value: configPath },
90
- { label: 'contract', value: contractPath },
91
- ];
92
- if (options.db) {
93
- details.push({ label: 'database', value: options.db });
94
- }
95
- const header = formatStyledHeader({
96
- command: 'db verify',
97
- description: 'Check whether the database has been signed with your contract',
98
- url: 'https://pris.ly/db-verify',
99
- details,
100
- flags,
101
- });
102
- console.log(header);
103
- }
104
-
105
- // Load contract file (file I/O)
106
- let contractJsonContent: string;
107
- try {
108
- contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');
109
- } catch (error) {
110
- if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {
111
- throw errorFileNotFound(contractPathAbsolute, {
112
- why: `Contract file not found at ${contractPathAbsolute}`,
113
- });
114
- }
115
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
116
- why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,
117
- });
118
- }
119
- const contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;
120
-
121
- // Resolve database URL
122
- const dbUrl = options.db ?? config.db?.url;
123
- if (!dbUrl) {
124
- throw errorDatabaseUrlRequired();
125
- }
466
+ const modeResult = resolveDbVerifyMode(options);
467
+ if (!modeResult.ok) {
468
+ const exitCode = handleResult(modeResult as Result<never, CliStructuredError>, flags, ui);
469
+ process.exit(exitCode);
470
+ }
126
471
 
127
- // Check for driver
128
- if (!config.driver) {
129
- throw errorDriverRequired();
130
- }
131
-
132
- // Store driver descriptor after null check
133
- const driverDescriptor = config.driver;
134
-
135
- // Create driver
136
- const driver = await withSpinner(() => driverDescriptor.create(dbUrl), {
137
- message: 'Connecting to database...',
138
- flags,
139
- });
140
-
141
- try {
142
- // Create family instance
143
- const stack = createControlPlaneStack({
144
- target: config.target,
145
- adapter: config.adapter,
146
- driver: driverDescriptor,
147
- extensionPacks: config.extensionPacks,
148
- });
149
- const familyInstance = config.family.create(stack);
150
-
151
- // Validate contract using instance validator
152
- const contractIR = familyInstance.validateContractIR(contractJson) as ContractIR;
153
- assertContractRequirementsSatisfied({ contract: contractIR, stack });
154
-
155
- // Call family instance verify method
156
- let verifyResult: VerifyDatabaseResult;
157
- try {
158
- verifyResult = await withSpinner(
159
- () =>
160
- familyInstance.verify({
161
- driver,
162
- contractIR,
163
- expectedTargetId: config.target.targetId,
164
- contractPath: contractPathAbsolute,
165
- configPath,
166
- }),
167
- {
168
- message: 'Verifying database schema...',
169
- flags,
170
- },
171
- );
172
- } catch (error) {
173
- // Wrap errors from verify() in structured error
174
- throw errorUnexpected(error instanceof Error ? error.message : String(error), {
175
- why: `Failed to verify database: ${error instanceof Error ? error.message : String(error)}`,
176
- });
177
- }
472
+ const mode = modeResult.value;
178
473
 
179
- // If verification failed, throw structured error
180
- if (!verifyResult.ok && verifyResult.code) {
181
- if (verifyResult.code === 'PN-RTM-3001') {
182
- throw errorMarkerMissing();
474
+ if (mode === 'schema-only') {
475
+ const result = await executeDbSchemaOnlyVerifyCommand(options, flags, ui);
476
+ const exitCode = handleResult(result, flags, ui, (schemaVerifyResult) => {
477
+ if (flags.json) {
478
+ ui.output(formatSchemaVerifyJson(schemaVerifyResult));
479
+ } else {
480
+ const output = formatSchemaVerifyOutput(schemaVerifyResult, flags);
481
+ if (output) {
482
+ ui.log(output);
183
483
  }
184
- if (verifyResult.code === 'PN-RTM-3002') {
185
- throw errorHashMismatch({
186
- expected: verifyResult.contract.coreHash,
187
- ...(verifyResult.marker?.coreHash ? { actual: verifyResult.marker.coreHash } : {}),
188
- });
189
- }
190
- if (verifyResult.code === 'PN-RTM-3003') {
191
- throw errorTargetMismatch(
192
- verifyResult.target.expected,
193
- verifyResult.target.actual ?? 'unknown',
194
- );
195
- }
196
- throw errorRuntime(verifyResult.summary);
197
- }
198
-
199
- // Add blank line after all async operations if spinners were shown
200
- if (!flags.quiet && flags.json !== 'object' && process.stdout.isTTY) {
201
- console.log('');
202
484
  }
485
+ });
203
486
 
204
- return verifyResult;
205
- } finally {
206
- // Ensure driver connection is closed
207
- await driver.close();
487
+ if (result.ok && !result.value.ok) {
488
+ process.exit(1);
208
489
  }
209
- });
210
490
 
211
- // Handle result - formats output and returns exit code
212
- const exitCode = handleResult(result, flags, (verifyResult) => {
213
- // Output based on flags
214
- if (flags.json === 'object') {
215
- // JSON output to stdout
216
- console.log(formatVerifyJson(verifyResult));
491
+ process.exit(exitCode);
492
+ }
493
+
494
+ const result = await executeDbVerifyCommand(options, flags, ui, mode);
495
+
496
+ if (result.ok) {
497
+ if (flags.json) {
498
+ ui.output(formatVerifyJson(result.value));
217
499
  } else {
218
- // Human-readable output to stdout
219
- const output = formatVerifyOutput(verifyResult, flags);
500
+ const output = formatVerifyOutput(result.value, flags);
220
501
  if (output) {
221
- console.log(output);
502
+ ui.log(output);
222
503
  }
223
504
  }
224
- });
225
- process.exit(exitCode);
505
+ process.exit(0);
506
+ }
507
+
508
+ if (CliStructuredError.is(result.failure)) {
509
+ const exitCode = handleResult(result as Result<never, CliStructuredError>, flags, ui);
510
+ process.exit(exitCode);
511
+ }
512
+
513
+ if (flags.json) {
514
+ ui.output(formatSchemaVerifyJson(result.failure));
515
+ } else {
516
+ // Always show schema-drift failures, even in quiet mode — exiting 1 without
517
+ // diagnostics is unhelpful.
518
+ const output = formatSchemaVerifyOutput(result.failure, { ...flags, quiet: false });
519
+ if (output) {
520
+ ui.log(output);
521
+ }
522
+ }
523
+ process.exit(1);
226
524
  });
227
525
 
228
526
  return command;