@prisma-next/cli 0.3.0-dev.12 → 0.3.0-dev.14

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 (52) hide show
  1. package/README.md +109 -25
  2. package/dist/{chunk-CVNWLFXO.js → chunk-6EPKRATC.js} +2 -2
  3. package/dist/{chunk-BZMBKEEQ.js → chunk-DIJPT5TZ.js} +3 -33
  4. package/dist/chunk-DIJPT5TZ.js.map +1 -0
  5. package/dist/{chunk-QUPBU4KV.js → chunk-MG7PBERL.js} +2 -2
  6. package/dist/chunk-VI2YETW7.js +38 -0
  7. package/dist/chunk-VI2YETW7.js.map +1 -0
  8. package/dist/cli.js +34 -38
  9. package/dist/cli.js.map +1 -1
  10. package/dist/commands/contract-emit.js +3 -2
  11. package/dist/commands/db-init.d.ts.map +1 -1
  12. package/dist/commands/db-init.js +21 -19
  13. package/dist/commands/db-init.js.map +1 -1
  14. package/dist/commands/db-introspect.d.ts.map +1 -1
  15. package/dist/commands/db-introspect.js +13 -16
  16. package/dist/commands/db-introspect.js.map +1 -1
  17. package/dist/commands/db-schema-verify.d.ts.map +1 -1
  18. package/dist/commands/db-schema-verify.js +8 -7
  19. package/dist/commands/db-schema-verify.js.map +1 -1
  20. package/dist/commands/db-sign.js +8 -7
  21. package/dist/commands/db-sign.js.map +1 -1
  22. package/dist/commands/db-verify.d.ts.map +1 -1
  23. package/dist/commands/db-verify.js +8 -7
  24. package/dist/commands/db-verify.js.map +1 -1
  25. package/dist/control-api/client.d.ts +13 -0
  26. package/dist/control-api/client.d.ts.map +1 -0
  27. package/dist/control-api/operations/db-init.d.ts +27 -0
  28. package/dist/control-api/operations/db-init.d.ts.map +1 -0
  29. package/dist/control-api/types.d.ts +203 -0
  30. package/dist/control-api/types.d.ts.map +1 -0
  31. package/dist/exports/control-api.d.ts +13 -0
  32. package/dist/exports/control-api.d.ts.map +1 -0
  33. package/dist/exports/control-api.js +240 -0
  34. package/dist/exports/control-api.js.map +1 -0
  35. package/dist/exports/index.js +3 -2
  36. package/dist/exports/index.js.map +1 -1
  37. package/dist/utils/cli-errors.d.ts +1 -1
  38. package/dist/utils/cli-errors.d.ts.map +1 -1
  39. package/package.json +14 -10
  40. package/src/commands/db-init.ts +12 -11
  41. package/src/commands/db-introspect.ts +16 -18
  42. package/src/commands/db-schema-verify.ts +6 -7
  43. package/src/commands/db-sign.ts +6 -6
  44. package/src/commands/db-verify.ts +6 -7
  45. package/src/control-api/client.ts +229 -0
  46. package/src/control-api/operations/db-init.ts +167 -0
  47. package/src/control-api/types.ts +251 -0
  48. package/src/exports/control-api.ts +34 -0
  49. package/src/utils/cli-errors.ts +1 -1
  50. package/dist/chunk-BZMBKEEQ.js.map +0 -1
  51. /package/dist/{chunk-CVNWLFXO.js.map → chunk-6EPKRATC.js.map} +0 -0
  52. /package/dist/{chunk-QUPBU4KV.js.map → chunk-MG7PBERL.js.map} +0 -0
@@ -0,0 +1,229 @@
1
+ import type { TargetBoundComponentDescriptor } from '@prisma-next/contract/framework-components';
2
+ import { createControlPlaneStack } from '@prisma-next/core-control-plane/stack';
3
+ import type {
4
+ ControlDriverInstance,
5
+ ControlFamilyInstance,
6
+ ControlPlaneStack,
7
+ SignDatabaseResult,
8
+ VerifyDatabaseResult,
9
+ VerifyDatabaseSchemaResult,
10
+ } from '@prisma-next/core-control-plane/types';
11
+ import { assertFrameworkComponentsCompatible } from '../utils/framework-components';
12
+ import { executeDbInit } from './operations/db-init';
13
+ import type {
14
+ ControlClient,
15
+ ControlClientOptions,
16
+ DbInitOptions,
17
+ DbInitResult,
18
+ IntrospectOptions,
19
+ SchemaVerifyOptions,
20
+ SignOptions,
21
+ VerifyOptions,
22
+ } from './types';
23
+
24
+ /**
25
+ * Creates a programmatic control client for Prisma Next operations.
26
+ *
27
+ * The client accepts framework component descriptors at creation time,
28
+ * manages driver lifecycle via connect()/close(), and exposes domain
29
+ * operations that delegate to the existing family instance methods.
30
+ *
31
+ * @see {@link ControlClient} for the client interface
32
+ * @see README.md "Programmatic Control API" section for usage examples
33
+ */
34
+ export function createControlClient(options: ControlClientOptions): ControlClient {
35
+ return new ControlClientImpl(options);
36
+ }
37
+
38
+ /**
39
+ * Implementation of ControlClient.
40
+ * Manages initialization and connection state, delegates operations to family instance.
41
+ */
42
+ class ControlClientImpl implements ControlClient {
43
+ private readonly options: ControlClientOptions;
44
+ private stack: ControlPlaneStack<string, string> | null = null;
45
+ private driver: ControlDriverInstance<string, string> | null = null;
46
+ private familyInstance: ControlFamilyInstance<string> | null = null;
47
+ private frameworkComponents: ReadonlyArray<
48
+ TargetBoundComponentDescriptor<string, string>
49
+ > | null = null;
50
+ private initialized = false;
51
+ private readonly defaultConnection: unknown;
52
+
53
+ constructor(options: ControlClientOptions) {
54
+ this.options = options;
55
+ this.defaultConnection = options.connection;
56
+ }
57
+
58
+ init(): void {
59
+ if (this.initialized) {
60
+ return; // Idempotent
61
+ }
62
+
63
+ // Create the control plane stack
64
+ this.stack = createControlPlaneStack({
65
+ target: this.options.target,
66
+ adapter: this.options.adapter,
67
+ driver: this.options.driver,
68
+ extensionPacks: this.options.extensionPacks,
69
+ });
70
+
71
+ // Create family instance using the stack
72
+ this.familyInstance = this.options.family.create(this.stack);
73
+
74
+ // Validate and type-narrow framework components
75
+ const rawComponents = [
76
+ this.options.target,
77
+ this.options.adapter,
78
+ ...(this.options.extensionPacks ?? []),
79
+ ];
80
+ this.frameworkComponents = assertFrameworkComponentsCompatible(
81
+ this.options.family.familyId,
82
+ this.options.target.targetId,
83
+ rawComponents,
84
+ );
85
+
86
+ this.initialized = true;
87
+ }
88
+
89
+ async connect(connection?: unknown): Promise<void> {
90
+ // Auto-init if needed
91
+ this.init();
92
+
93
+ if (this.driver) {
94
+ throw new Error('Already connected. Call close() before reconnecting.');
95
+ }
96
+
97
+ // Resolve connection: argument > default from options
98
+ const resolvedConnection = connection ?? this.defaultConnection;
99
+ if (resolvedConnection === undefined) {
100
+ throw new Error(
101
+ 'No connection provided. Pass a connection to connect() or provide a default connection when creating the client.',
102
+ );
103
+ }
104
+
105
+ // Check for driver descriptor
106
+ if (!this.stack?.driver) {
107
+ throw new Error(
108
+ 'Driver is not configured. Pass a driver descriptor when creating the control client to enable database operations.',
109
+ );
110
+ }
111
+
112
+ // Create driver instance
113
+ // Cast through any since connection type is driver-specific at runtime.
114
+ // The driver descriptor is typed with any for TConnection in ControlClientOptions,
115
+ // but createControlPlaneStack defaults it to string. We bridge this at runtime.
116
+ // biome-ignore lint/suspicious/noExplicitAny: required for runtime connection type flexibility
117
+ this.driver = await this.stack?.driver.create(resolvedConnection as any);
118
+ }
119
+
120
+ async close(): Promise<void> {
121
+ if (this.driver) {
122
+ await this.driver.close();
123
+ this.driver = null;
124
+ }
125
+ }
126
+
127
+ private async ensureConnected(): Promise<{
128
+ driver: ControlDriverInstance<string, string>;
129
+ familyInstance: ControlFamilyInstance<string>;
130
+ frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<string, string>>;
131
+ }> {
132
+ // Auto-init if needed
133
+ this.init();
134
+
135
+ // Auto-connect if not connected and default connection is available
136
+ if (!this.driver && this.defaultConnection !== undefined) {
137
+ await this.connect(this.defaultConnection);
138
+ }
139
+
140
+ if (!this.driver || !this.familyInstance || !this.frameworkComponents) {
141
+ throw new Error('Not connected. Call connect(connection) first.');
142
+ }
143
+ return {
144
+ driver: this.driver,
145
+ familyInstance: this.familyInstance,
146
+ frameworkComponents: this.frameworkComponents,
147
+ };
148
+ }
149
+
150
+ async verify(options: VerifyOptions): Promise<VerifyDatabaseResult> {
151
+ const { driver, familyInstance } = await this.ensureConnected();
152
+
153
+ // Validate contract using family instance
154
+ const contractIR = familyInstance.validateContractIR(options.contractIR);
155
+
156
+ // Delegate to family instance verify method
157
+ // Note: We pass empty strings for contractPath/configPath since the programmatic
158
+ // API doesn't deal with file paths. The family instance accepts these as optional
159
+ // metadata for error reporting.
160
+ return familyInstance.verify({
161
+ driver,
162
+ contractIR,
163
+ expectedTargetId: this.options.target.targetId,
164
+ contractPath: '',
165
+ });
166
+ }
167
+
168
+ async schemaVerify(options: SchemaVerifyOptions): Promise<VerifyDatabaseSchemaResult> {
169
+ const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
170
+
171
+ // Validate contract using family instance
172
+ const contractIR = familyInstance.validateContractIR(options.contractIR);
173
+
174
+ // Delegate to family instance schemaVerify method
175
+ return familyInstance.schemaVerify({
176
+ driver,
177
+ contractIR,
178
+ strict: options.strict ?? false,
179
+ contractPath: '',
180
+ frameworkComponents,
181
+ });
182
+ }
183
+
184
+ async sign(options: SignOptions): Promise<SignDatabaseResult> {
185
+ const { driver, familyInstance } = await this.ensureConnected();
186
+
187
+ // Validate contract using family instance
188
+ const contractIR = familyInstance.validateContractIR(options.contractIR);
189
+
190
+ // Delegate to family instance sign method
191
+ return familyInstance.sign({
192
+ driver,
193
+ contractIR,
194
+ contractPath: '',
195
+ });
196
+ }
197
+
198
+ async dbInit(options: DbInitOptions): Promise<DbInitResult> {
199
+ const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
200
+
201
+ // Check target supports migrations
202
+ if (!this.options.target.migrations) {
203
+ throw new Error(`Target "${this.options.target.targetId}" does not support migrations`);
204
+ }
205
+
206
+ // Validate contract using family instance
207
+ const contractIR = familyInstance.validateContractIR(options.contractIR);
208
+
209
+ // Delegate to extracted dbInit operation
210
+ return executeDbInit({
211
+ driver,
212
+ familyInstance,
213
+ contractIR,
214
+ mode: options.mode,
215
+ migrations: this.options.target.migrations,
216
+ frameworkComponents,
217
+ });
218
+ }
219
+
220
+ async introspect(options?: IntrospectOptions): Promise<unknown> {
221
+ const { driver, familyInstance } = await this.ensureConnected();
222
+
223
+ // TODO: Pass schema option to familyInstance.introspect when schema filtering is implemented
224
+ const _schema = options?.schema;
225
+ void _schema;
226
+
227
+ return familyInstance.introspect({ driver });
228
+ }
229
+ }
@@ -0,0 +1,167 @@
1
+ import type { TargetBoundComponentDescriptor } from '@prisma-next/contract/framework-components';
2
+ import type { ContractIR } from '@prisma-next/contract/ir';
3
+ import type {
4
+ ControlDriverInstance,
5
+ ControlFamilyInstance,
6
+ MigrationPlan,
7
+ MigrationPlannerResult,
8
+ MigrationRunnerResult,
9
+ TargetMigrationsCapability,
10
+ } from '@prisma-next/core-control-plane/types';
11
+ import { notOk, ok } from '@prisma-next/utils/result';
12
+ import type { DbInitResult, DbInitSuccess } from '../types';
13
+
14
+ /**
15
+ * Options for executing dbInit operation.
16
+ */
17
+ export interface ExecuteDbInitOptions<TFamilyId extends string, TTargetId extends string> {
18
+ readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;
19
+ readonly familyInstance: ControlFamilyInstance<TFamilyId>;
20
+ readonly contractIR: ContractIR;
21
+ readonly mode: 'plan' | 'apply';
22
+ readonly migrations: TargetMigrationsCapability<
23
+ TFamilyId,
24
+ TTargetId,
25
+ ControlFamilyInstance<TFamilyId>
26
+ >;
27
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;
28
+ }
29
+
30
+ /**
31
+ * Executes the dbInit operation.
32
+ *
33
+ * This is the core logic extracted from the CLI command, without any file I/O,
34
+ * process.exit(), or console output. It uses the Result pattern to return
35
+ * success or failure details.
36
+ *
37
+ * @param options - The options for executing dbInit
38
+ * @returns Result with DbInitSuccess on success, DbInitFailure on failure
39
+ */
40
+ export async function executeDbInit<TFamilyId extends string, TTargetId extends string>(
41
+ options: ExecuteDbInitOptions<TFamilyId, TTargetId>,
42
+ ): Promise<DbInitResult> {
43
+ const { driver, familyInstance, contractIR, mode, migrations, frameworkComponents } = options;
44
+
45
+ // Create planner and runner from target migrations capability
46
+ const planner = migrations.createPlanner(familyInstance);
47
+ const runner = migrations.createRunner(familyInstance);
48
+
49
+ // Introspect live schema
50
+ const schemaIR = await familyInstance.introspect({ driver });
51
+
52
+ // Policy for init mode (additive only)
53
+ const policy = { allowedOperationClasses: ['additive'] as const };
54
+
55
+ // Plan migration
56
+ const plannerResult: MigrationPlannerResult = await planner.plan({
57
+ contract: contractIR,
58
+ schema: schemaIR,
59
+ policy,
60
+ frameworkComponents,
61
+ });
62
+
63
+ if (plannerResult.kind === 'failure') {
64
+ return notOk({
65
+ code: 'PLANNING_FAILED' as const,
66
+ summary: 'Migration planning failed due to conflicts',
67
+ conflicts: plannerResult.conflicts,
68
+ });
69
+ }
70
+
71
+ const migrationPlan: MigrationPlan = plannerResult.plan;
72
+
73
+ // Check for existing marker - handle idempotency and mismatch errors
74
+ const existingMarker = await familyInstance.readMarker({ driver });
75
+ if (existingMarker) {
76
+ const markerMatchesDestination =
77
+ existingMarker.coreHash === migrationPlan.destination.coreHash &&
78
+ (!migrationPlan.destination.profileHash ||
79
+ existingMarker.profileHash === migrationPlan.destination.profileHash);
80
+
81
+ if (markerMatchesDestination) {
82
+ // Already at destination - return success with no operations
83
+ const result: DbInitSuccess = {
84
+ mode,
85
+ plan: { operations: [] },
86
+ ...(mode === 'apply'
87
+ ? {
88
+ execution: { operationsPlanned: 0, operationsExecuted: 0 },
89
+ marker: {
90
+ coreHash: existingMarker.coreHash,
91
+ profileHash: existingMarker.profileHash,
92
+ },
93
+ }
94
+ : {}),
95
+ summary: 'Database already at target contract state',
96
+ };
97
+ return ok(result);
98
+ }
99
+
100
+ // Marker exists but doesn't match destination - fail
101
+ return notOk({
102
+ code: 'MARKER_ORIGIN_MISMATCH' as const,
103
+ summary: 'Existing contract marker does not match plan destination',
104
+ marker: {
105
+ coreHash: existingMarker.coreHash,
106
+ profileHash: existingMarker.profileHash,
107
+ },
108
+ destination: {
109
+ coreHash: migrationPlan.destination.coreHash,
110
+ profileHash: migrationPlan.destination.profileHash,
111
+ },
112
+ });
113
+ }
114
+
115
+ // Plan mode - don't execute
116
+ if (mode === 'plan') {
117
+ const result: DbInitSuccess = {
118
+ mode: 'plan',
119
+ plan: { operations: migrationPlan.operations },
120
+ summary: `Planned ${migrationPlan.operations.length} operation(s)`,
121
+ };
122
+ return ok(result);
123
+ }
124
+
125
+ // Apply mode - execute runner
126
+ const runnerResult: MigrationRunnerResult = await runner.execute({
127
+ plan: migrationPlan,
128
+ driver,
129
+ destinationContract: contractIR,
130
+ policy,
131
+ // db init plans and applies back-to-back from a fresh introspection, so per-operation
132
+ // pre/postchecks and the idempotency probe are usually redundant overhead. We still
133
+ // enforce marker/origin compatibility and a full schema verification after apply.
134
+ executionChecks: {
135
+ prechecks: false,
136
+ postchecks: false,
137
+ idempotencyChecks: false,
138
+ },
139
+ frameworkComponents,
140
+ });
141
+
142
+ if (!runnerResult.ok) {
143
+ return notOk({
144
+ code: 'RUNNER_FAILED' as const,
145
+ summary: runnerResult.failure.summary,
146
+ });
147
+ }
148
+
149
+ const execution = runnerResult.value;
150
+
151
+ const result: DbInitSuccess = {
152
+ mode: 'apply',
153
+ plan: { operations: migrationPlan.operations },
154
+ execution: {
155
+ operationsPlanned: execution.operationsPlanned,
156
+ operationsExecuted: execution.operationsExecuted,
157
+ },
158
+ marker: migrationPlan.destination.profileHash
159
+ ? {
160
+ coreHash: migrationPlan.destination.coreHash,
161
+ profileHash: migrationPlan.destination.profileHash,
162
+ }
163
+ : { coreHash: migrationPlan.destination.coreHash },
164
+ summary: `Applied ${execution.operationsExecuted} operation(s), marker written`,
165
+ };
166
+ return ok(result);
167
+ }
@@ -0,0 +1,251 @@
1
+ import type {
2
+ ControlAdapterDescriptor,
3
+ ControlDriverDescriptor,
4
+ ControlExtensionDescriptor,
5
+ ControlFamilyDescriptor,
6
+ ControlTargetDescriptor,
7
+ MigrationPlannerConflict,
8
+ SignDatabaseResult,
9
+ VerifyDatabaseResult,
10
+ VerifyDatabaseSchemaResult,
11
+ } from '@prisma-next/core-control-plane/types';
12
+ import type { Result } from '@prisma-next/utils/result';
13
+
14
+ // ============================================================================
15
+ // Client Options
16
+ // ============================================================================
17
+
18
+ /**
19
+ * Options for creating a control client.
20
+ *
21
+ * Note: This is NOT the same as CLI config. There's no `contract` field,
22
+ * no file paths. The client is config-agnostic.
23
+ *
24
+ * The descriptor types use permissive `any` because family-specific descriptors
25
+ * (e.g., SqlFamilyDescriptor) have more specific `create` method signatures that
26
+ * are not compatible with the base ControlFamilyDescriptor type due to TypeScript
27
+ * variance rules. The client implementation casts these internally.
28
+ */
29
+ export interface ControlClientOptions {
30
+ // biome-ignore lint/suspicious/noExplicitAny: required for contravariance - SqlFamilyDescriptor.create has specific parameter types
31
+ readonly family: ControlFamilyDescriptor<any, any>;
32
+ // biome-ignore lint/suspicious/noExplicitAny: required for contravariance - SqlControlTargetDescriptor extends with additional methods
33
+ readonly target: ControlTargetDescriptor<any, any, any, any>;
34
+ // biome-ignore lint/suspicious/noExplicitAny: required for contravariance in adapter.create()
35
+ readonly adapter: ControlAdapterDescriptor<any, any, any>;
36
+ /** Optional - control client can be created without driver for offline operations */
37
+ // biome-ignore lint/suspicious/noExplicitAny: required for contravariance in driver.create()
38
+ readonly driver?: ControlDriverDescriptor<any, any, any, any>;
39
+ // biome-ignore lint/suspicious/noExplicitAny: required for contravariance in extension.create()
40
+ readonly extensionPacks?: ReadonlyArray<ControlExtensionDescriptor<any, any, any>>;
41
+ /**
42
+ * Optional default connection for auto-connect.
43
+ * When provided, operations will auto-connect if not already connected.
44
+ * The type is driver-specific (e.g., string URL for Postgres).
45
+ */
46
+ readonly connection?: unknown;
47
+ }
48
+
49
+ // ============================================================================
50
+ // Operation Options
51
+ // ============================================================================
52
+
53
+ /**
54
+ * Options for the verify operation.
55
+ */
56
+ export interface VerifyOptions {
57
+ /** Contract IR or unvalidated JSON - validated at runtime via familyInstance.validateContractIR() */
58
+ readonly contractIR: unknown;
59
+ }
60
+
61
+ /**
62
+ * Options for the schemaVerify operation.
63
+ */
64
+ export interface SchemaVerifyOptions {
65
+ /** Contract IR or unvalidated JSON - validated at runtime via familyInstance.validateContractIR() */
66
+ readonly contractIR: unknown;
67
+ /**
68
+ * Whether to use strict mode for schema verification.
69
+ * In strict mode, extra tables/columns are reported as issues.
70
+ * Default: false (tolerant mode - allows superset)
71
+ */
72
+ readonly strict?: boolean;
73
+ }
74
+
75
+ /**
76
+ * Options for the sign operation.
77
+ */
78
+ export interface SignOptions {
79
+ /** Contract IR or unvalidated JSON - validated at runtime via familyInstance.validateContractIR() */
80
+ readonly contractIR: unknown;
81
+ }
82
+
83
+ /**
84
+ * Options for the dbInit operation.
85
+ */
86
+ export interface DbInitOptions {
87
+ /** Contract IR or unvalidated JSON - validated at runtime via familyInstance.validateContractIR() */
88
+ readonly contractIR: unknown;
89
+ /**
90
+ * Mode for the dbInit operation.
91
+ * - 'plan': Returns planned operations without applying
92
+ * - 'apply': Applies operations and writes marker
93
+ */
94
+ readonly mode: 'plan' | 'apply';
95
+ }
96
+
97
+ /**
98
+ * Options for the introspect operation.
99
+ */
100
+ export interface IntrospectOptions {
101
+ /**
102
+ * Optional schema name to introspect.
103
+ */
104
+ readonly schema?: string;
105
+ }
106
+
107
+ // ============================================================================
108
+ // Result Types
109
+ // ============================================================================
110
+
111
+ /**
112
+ * Successful dbInit result.
113
+ */
114
+ export interface DbInitSuccess {
115
+ readonly mode: 'plan' | 'apply';
116
+ readonly plan: {
117
+ readonly operations: ReadonlyArray<{
118
+ readonly id: string;
119
+ readonly label: string;
120
+ readonly operationClass: string;
121
+ }>;
122
+ };
123
+ readonly execution?: {
124
+ readonly operationsPlanned: number;
125
+ readonly operationsExecuted: number;
126
+ };
127
+ readonly marker?: {
128
+ readonly coreHash: string;
129
+ readonly profileHash?: string;
130
+ };
131
+ readonly summary: string;
132
+ }
133
+
134
+ /**
135
+ * Failure codes for dbInit operation.
136
+ */
137
+ export type DbInitFailureCode = 'PLANNING_FAILED' | 'MARKER_ORIGIN_MISMATCH' | 'RUNNER_FAILED';
138
+
139
+ /**
140
+ * Failure details for dbInit operation.
141
+ */
142
+ export interface DbInitFailure {
143
+ readonly code: DbInitFailureCode;
144
+ readonly summary: string;
145
+ readonly conflicts?: ReadonlyArray<MigrationPlannerConflict>;
146
+ readonly marker?: {
147
+ readonly coreHash?: string;
148
+ readonly profileHash?: string;
149
+ };
150
+ readonly destination?: {
151
+ readonly coreHash: string;
152
+ readonly profileHash?: string | undefined;
153
+ };
154
+ }
155
+
156
+ /**
157
+ * Result type for dbInit operation.
158
+ * Uses Result pattern: success returns DbInitSuccess, failure returns DbInitFailure.
159
+ */
160
+ export type DbInitResult = Result<DbInitSuccess, DbInitFailure>;
161
+
162
+ // ============================================================================
163
+ // Client Interface
164
+ // ============================================================================
165
+
166
+ /**
167
+ * Programmatic control client for Prisma Next operations.
168
+ *
169
+ * Lifecycle: `connect(connection)` before operations, `close()` when done.
170
+ * Both `init()` and `connect()` are auto-called by operations if needed,
171
+ * but `connect()` requires a connection so must be called explicitly first
172
+ * unless a default connection was provided in options.
173
+ *
174
+ * @see README.md "Programmatic Control API" section for usage examples
175
+ */
176
+ export interface ControlClient {
177
+ /**
178
+ * Initializes the client by creating the control plane stack,
179
+ * family instance, and validating framework components.
180
+ *
181
+ * Idempotent (safe to call multiple times).
182
+ * Called automatically by `connect()` if not already initialized.
183
+ */
184
+ init(): void;
185
+
186
+ /**
187
+ * Establishes a database connection.
188
+ * Auto-calls `init()` if not already initialized.
189
+ * Must be called before any database operations unless a default connection
190
+ * was provided in options.
191
+ *
192
+ * @param connection - Driver-specific connection input (e.g., URL string for Postgres).
193
+ * If omitted, uses the default connection from options (if provided).
194
+ * @throws If connection fails, already connected, driver is not configured,
195
+ * or no connection provided and no default connection in options.
196
+ */
197
+ connect(connection?: unknown): Promise<void>;
198
+
199
+ /**
200
+ * Closes the database connection.
201
+ * Idempotent (safe to call multiple times).
202
+ * After close(), can call `connect()` again with same or different URL.
203
+ */
204
+ close(): Promise<void>;
205
+
206
+ /**
207
+ * Verifies database marker matches the contract.
208
+ * Compares coreHash and profileHash.
209
+ *
210
+ * @returns Structured result (ok: false for mismatch, not throwing)
211
+ * @throws If not connected or infrastructure failure
212
+ */
213
+ verify(options: VerifyOptions): Promise<VerifyDatabaseResult>;
214
+
215
+ /**
216
+ * Verifies database schema satisfies the contract requirements.
217
+ *
218
+ * @param options.strict - If true, extra tables/columns are issues. Default: false
219
+ * @returns Structured result with schema issues
220
+ * @throws If not connected or infrastructure failure
221
+ */
222
+ schemaVerify(options: SchemaVerifyOptions): Promise<VerifyDatabaseSchemaResult>;
223
+
224
+ /**
225
+ * Signs the database with a contract marker.
226
+ * Writes or updates the contract marker if schema verification passes.
227
+ * Idempotent (no-op if marker already matches).
228
+ *
229
+ * @returns Structured result
230
+ * @throws If not connected or infrastructure failure
231
+ */
232
+ sign(options: SignOptions): Promise<SignDatabaseResult>;
233
+
234
+ /**
235
+ * Initializes database schema from contract.
236
+ * Uses additive-only policy (no destructive changes).
237
+ *
238
+ * @param options.mode - 'plan' to preview, 'apply' to execute
239
+ * @returns Result pattern: Ok with planned/executed operations, NotOk with failure details
240
+ * @throws If not connected, target doesn't support migrations, or infrastructure failure
241
+ */
242
+ dbInit(options: DbInitOptions): Promise<DbInitResult>;
243
+
244
+ /**
245
+ * Introspects the database schema.
246
+ *
247
+ * @returns Raw schema IR
248
+ * @throws If not connected or infrastructure failure
249
+ */
250
+ introspect(options?: IntrospectOptions): Promise<unknown>;
251
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Programmatic Control API for Prisma Next.
3
+ *
4
+ * This module exports the control client factory and types for programmatic
5
+ * access to control-plane operations without using the CLI.
6
+ *
7
+ * @see README.md "Programmatic Control API" section for usage examples
8
+ * @module
9
+ */
10
+
11
+ // Re-export core control plane types for consumer convenience
12
+ export type {
13
+ ControlPlaneStack,
14
+ SignDatabaseResult,
15
+ VerifyDatabaseResult,
16
+ VerifyDatabaseSchemaResult,
17
+ } from '@prisma-next/core-control-plane/types';
18
+ // Client factory
19
+ export { createControlClient } from '../control-api/client';
20
+
21
+ // CLI-specific types
22
+ export type {
23
+ ControlClient,
24
+ ControlClientOptions,
25
+ DbInitFailure,
26
+ DbInitFailureCode,
27
+ DbInitOptions,
28
+ DbInitResult,
29
+ DbInitSuccess,
30
+ IntrospectOptions,
31
+ SchemaVerifyOptions,
32
+ SignOptions,
33
+ VerifyOptions,
34
+ } from '../control-api/types';
@@ -10,7 +10,7 @@ export {
10
10
  errorContractConfigMissing,
11
11
  errorContractMissingExtensionPacks,
12
12
  errorContractValidationFailed,
13
- errorDatabaseUrlRequired,
13
+ errorDatabaseConnectionRequired,
14
14
  errorDriverRequired,
15
15
  errorFamilyReadMarkerSqlRequired,
16
16
  errorFileNotFound,