@prisma-next/core-control-plane 0.1.0-dev.2 → 0.1.0-dev.21

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 CHANGED
@@ -14,9 +14,10 @@ This package provides the core domain logic for control plane operations (contra
14
14
  - **Domain Actions**:
15
15
  - `verifyDatabase()`: Verifies database contract markers (accepts config object and ContractIR)
16
16
 
17
- Note: Contract emission is implemented on family instances (e.g., `familyInstance.emitContract()`), not as a core domain action.
17
+ Note: Contract emission is implemented on the SQL family instance (e.g., `familyInstance.emitContract()`), not as a core domain action.
18
18
  - **Error Factories**: Domain error factories (`CliStructuredError`, config errors, runtime errors)
19
19
  - **Pack Manifest Types**: Type definitions for extension pack manifests
20
+ - **Migration SPI**: Generic migration planner/runner interfaces (`MigrationPlanner<TFamilyId, TTargetId>`, `MigrationRunner<TFamilyId, TTargetId>`, `TargetMigrationsCapability<TFamilyId, TTargetId, TFamilyInstance>`) that thread family/target IDs for compile-time component compatibility enforcement
20
21
 
21
22
  ## Dependencies
22
23
 
@@ -102,13 +103,37 @@ throw errorConfigFileNotFound('prisma-next.config.ts', {
102
103
  });
103
104
  ```
104
105
 
106
+ ## Migration SPI Design
107
+
108
+ The migration planner/runner interfaces are generic over `TFamilyId` and `TTargetId` to enable compile-time enforcement of component compatibility:
109
+
110
+ - **`MigrationPlanner<TFamilyId, TTargetId>`**: Generic planner interface that accepts `TargetBoundComponentDescriptor<TFamilyId, TTargetId>[]`
111
+ - **`MigrationRunner<TFamilyId, TTargetId>`**: Generic runner interface that accepts `TargetBoundComponentDescriptor<TFamilyId, TTargetId>[]`
112
+ - **`TargetMigrationsCapability<TFamilyId, TTargetId, TFamilyInstance>`**: Generic capability interface for targets that support migrations
113
+
114
+ The CLI performs runtime validation at the composition boundary using `assertFrameworkComponentsCompatible()` before calling typed planner/runner instances. This validates that all components have matching `familyId` and `targetId`, then returns a typed `TargetBoundComponentDescriptor` array that satisfies the planner/runner interface requirements.
115
+
116
+ ```typescript
117
+ // CLI composition boundary - runtime assertion + type narrowing
118
+ const rawComponents = [config.target, config.adapter, ...(config.extensions ?? [])];
119
+ const frameworkComponents = assertFrameworkComponentsCompatible(
120
+ config.family.familyId,
121
+ config.target.targetId,
122
+ rawComponents,
123
+ );
124
+
125
+ // Now frameworkComponents is typed as TargetBoundComponentDescriptor<TFamilyId, TTargetId>[]
126
+ const planner = target.migrations.createPlanner(sqlFamilyInstance);
127
+ planner.plan({ contract, schema, policy, frameworkComponents });
128
+ ```
129
+
105
130
  ## Package Location
106
131
 
107
132
  This package is part of the **framework domain**, **core layer**, **migration plane**:
108
133
  - **Domain**: framework (target-agnostic)
109
134
  - **Layer**: core
110
135
  - **Plane**: migration (control plane operations)
111
- - **Path**: `packages/framework/core-control-plane`
136
+ - **Path**: `packages/1-framework/1-core/migration/control-plane`
112
137
 
113
138
  ## Related Documentation
114
139
 
@@ -106,6 +106,27 @@ function errorDriverRequired(options) {
106
106
  docsUrl: "https://prisma-next.dev/docs/cli/db-verify"
107
107
  });
108
108
  }
109
+ function errorMigrationPlanningFailed(options) {
110
+ const conflictSummaries = options.conflicts.map((c) => c.summary);
111
+ const computedWhy = options.why ?? conflictSummaries.join("\n");
112
+ const conflictFixes = options.conflicts.map((c) => c.why).filter((why) => typeof why === "string");
113
+ const computedFix = conflictFixes.length > 0 ? conflictFixes.join("\n") : "Use `db schema-verify` to inspect conflicts, or ensure the database is empty";
114
+ return new CliStructuredError("4020", "Migration planning failed", {
115
+ domain: "CLI",
116
+ why: computedWhy,
117
+ fix: computedFix,
118
+ meta: { conflicts: options.conflicts },
119
+ docsUrl: "https://prisma-next.dev/docs/cli/db-init"
120
+ });
121
+ }
122
+ function errorTargetMigrationNotSupported(options) {
123
+ return new CliStructuredError("4021", "Target does not support migrations", {
124
+ domain: "CLI",
125
+ why: options?.why ?? "The configured target does not provide migration planner/runner",
126
+ fix: "Ensure you are using a target that supports migrations",
127
+ docsUrl: "https://prisma-next.dev/docs/cli/db-init"
128
+ });
129
+ }
109
130
  function errorConfigValidation(field, options) {
110
131
  return new CliStructuredError("4001", "Config file not found", {
111
132
  domain: "CLI",
@@ -168,6 +189,8 @@ export {
168
189
  errorQueryRunnerFactoryRequired,
169
190
  errorFamilyReadMarkerSqlRequired,
170
191
  errorDriverRequired,
192
+ errorMigrationPlanningFailed,
193
+ errorTargetMigrationNotSupported,
171
194
  errorConfigValidation,
172
195
  errorMarkerMissing,
173
196
  errorHashMismatch,
@@ -175,4 +198,4 @@ export {
175
198
  errorRuntime,
176
199
  errorUnexpected
177
200
  };
178
- //# sourceMappingURL=chunk-DZPZSLCM.js.map
201
+ //# sourceMappingURL=chunk-R7MOUJNP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/**\n * CLI error envelope for output formatting.\n * This is the serialized form of a CliStructuredError.\n */\nexport interface CliErrorEnvelope {\n readonly code: string;\n readonly domain: string;\n readonly severity: 'error' | 'warn' | 'info';\n readonly summary: string;\n readonly why: string | undefined;\n readonly fix: string | undefined;\n readonly where:\n | {\n readonly path: string | undefined;\n readonly line: number | undefined;\n }\n | undefined;\n readonly meta: Record<string, unknown> | undefined;\n readonly docsUrl: string | undefined;\n}\n\n/**\n * Structured CLI error that contains all information needed for error envelopes.\n * Call sites throw these errors with full context.\n */\nexport class CliStructuredError extends Error {\n readonly code: string;\n readonly domain: 'CLI' | 'RTM';\n readonly severity: 'error' | 'warn' | 'info';\n readonly why: string | undefined;\n readonly fix: string | undefined;\n readonly where:\n | {\n readonly path: string | undefined;\n readonly line: number | undefined;\n }\n | undefined;\n readonly meta: Record<string, unknown> | undefined;\n readonly docsUrl: string | undefined;\n\n constructor(\n code: string,\n summary: string,\n options?: {\n readonly domain?: 'CLI' | 'RTM';\n readonly severity?: 'error' | 'warn' | 'info';\n readonly why?: string;\n readonly fix?: string;\n readonly where?: { readonly path?: string; readonly line?: number };\n readonly meta?: Record<string, unknown>;\n readonly docsUrl?: string;\n },\n ) {\n super(summary);\n this.name = 'CliStructuredError';\n this.code = code;\n this.domain = options?.domain ?? 'CLI';\n this.severity = options?.severity ?? 'error';\n this.why = options?.why;\n this.fix = options?.fix;\n this.where = options?.where\n ? {\n path: options.where.path,\n line: options.where.line,\n }\n : undefined;\n this.meta = options?.meta;\n this.docsUrl = options?.docsUrl;\n }\n\n /**\n * Converts this error to a CLI error envelope for output formatting.\n */\n toEnvelope(): CliErrorEnvelope {\n const codePrefix = this.domain === 'CLI' ? 'PN-CLI-' : 'PN-RTM-';\n return {\n code: `${codePrefix}${this.code}`,\n domain: this.domain,\n severity: this.severity,\n summary: this.message,\n why: this.why,\n fix: this.fix,\n where: this.where,\n meta: this.meta,\n docsUrl: this.docsUrl,\n };\n }\n}\n\n// ============================================================================\n// Config Errors (PN-CLI-4001-4007)\n// ============================================================================\n\n/**\n * Config file not found or missing.\n */\nexport function errorConfigFileNotFound(\n configPath?: string,\n options?: {\n readonly why?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('4001', 'Config file not found', {\n domain: 'CLI',\n ...(options?.why ? { why: options.why } : { why: 'Config file not found' }),\n fix: \"Run 'prisma-next init' to create a config file\",\n docsUrl: 'https://prisma-next.dev/docs/cli/config',\n ...(configPath ? { where: { path: configPath } } : {}),\n });\n}\n\n/**\n * Contract configuration missing from config.\n */\nexport function errorContractConfigMissing(options?: {\n readonly why?: string;\n}): CliStructuredError {\n return new CliStructuredError('4002', 'Contract configuration missing', {\n domain: 'CLI',\n why: options?.why ?? 'The contract configuration is required for emit',\n fix: 'Add contract configuration to your prisma-next.config.ts',\n docsUrl: 'https://prisma-next.dev/docs/cli/contract-emit',\n });\n}\n\n/**\n * Contract validation failed.\n */\nexport function errorContractValidationFailed(\n reason: string,\n options?: {\n readonly where?: { readonly path?: string; readonly line?: number };\n },\n): CliStructuredError {\n return new CliStructuredError('4003', 'Contract validation failed', {\n domain: 'CLI',\n why: reason,\n fix: 'Check your contract file for errors',\n docsUrl: 'https://prisma-next.dev/docs/contracts',\n ...(options?.where ? { where: options.where } : {}),\n });\n}\n\n/**\n * File not found.\n */\nexport function errorFileNotFound(\n filePath: string,\n options?: {\n readonly why?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('4004', 'File not found', {\n domain: 'CLI',\n why: options?.why ?? `File not found: ${filePath}`,\n fix: 'Check that the file path is correct',\n where: { path: filePath },\n });\n}\n\n/**\n * Database URL is required but not provided.\n */\nexport function errorDatabaseUrlRequired(options?: { readonly why?: string }): CliStructuredError {\n return new CliStructuredError('4005', 'Database URL is required', {\n domain: 'CLI',\n why: options?.why ?? 'Database URL is required for db verify',\n fix: 'Provide --db flag or config.db.url in prisma-next.config.ts',\n });\n}\n\n/**\n * Query runner factory is required but not provided in config.\n */\nexport function errorQueryRunnerFactoryRequired(options?: {\n readonly why?: string;\n}): CliStructuredError {\n return new CliStructuredError('4006', 'Query runner factory is required', {\n domain: 'CLI',\n why: options?.why ?? 'Config.db.queryRunnerFactory is required for db verify',\n fix: 'Add db.queryRunnerFactory to prisma-next.config.ts',\n docsUrl: 'https://prisma-next.dev/docs/cli/db-verify',\n });\n}\n\n/**\n * Family verify.readMarker is required but not provided.\n */\nexport function errorFamilyReadMarkerSqlRequired(options?: {\n readonly why?: string;\n}): CliStructuredError {\n return new CliStructuredError('4007', 'Family readMarker() is required', {\n domain: 'CLI',\n why: options?.why ?? 'Family verify.readMarker is required for db verify',\n fix: 'Ensure family.verify.readMarker() is exported by your family package',\n docsUrl: 'https://prisma-next.dev/docs/cli/db-verify',\n });\n}\n\n/**\n * Driver is required for DB-connected commands but not provided.\n */\nexport function errorDriverRequired(options?: { readonly why?: string }): CliStructuredError {\n return new CliStructuredError('4010', 'Driver is required for DB-connected commands', {\n domain: 'CLI',\n why: options?.why ?? 'Config.driver is required for db verify',\n fix: 'Add driver to prisma-next.config.ts',\n docsUrl: 'https://prisma-next.dev/docs/cli/db-verify',\n });\n}\n\n/**\n * Migration planning failed due to conflicts.\n */\nexport function errorMigrationPlanningFailed(options: {\n readonly conflicts: readonly {\n readonly kind: string;\n readonly summary: string;\n readonly why?: string;\n }[];\n readonly why?: string;\n}): CliStructuredError {\n // Build \"why\" from conflict summaries - these contain the actual problem description\n const conflictSummaries = options.conflicts.map((c) => c.summary);\n const computedWhy = options.why ?? conflictSummaries.join('\\n');\n\n // Build \"fix\" from conflict \"why\" fields - these contain actionable advice\n const conflictFixes = options.conflicts\n .map((c) => c.why)\n .filter((why): why is string => typeof why === 'string');\n const computedFix =\n conflictFixes.length > 0\n ? conflictFixes.join('\\n')\n : 'Use `db schema-verify` to inspect conflicts, or ensure the database is empty';\n\n return new CliStructuredError('4020', 'Migration planning failed', {\n domain: 'CLI',\n why: computedWhy,\n fix: computedFix,\n meta: { conflicts: options.conflicts },\n docsUrl: 'https://prisma-next.dev/docs/cli/db-init',\n });\n}\n\n/**\n * Target does not support migrations (missing createPlanner/createRunner).\n */\nexport function errorTargetMigrationNotSupported(options?: {\n readonly why?: string;\n}): CliStructuredError {\n return new CliStructuredError('4021', 'Target does not support migrations', {\n domain: 'CLI',\n why: options?.why ?? 'The configured target does not provide migration planner/runner',\n fix: 'Ensure you are using a target that supports migrations',\n docsUrl: 'https://prisma-next.dev/docs/cli/db-init',\n });\n}\n\n/**\n * Config validation error (missing required fields).\n */\nexport function errorConfigValidation(\n field: string,\n options?: {\n readonly why?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('4001', 'Config file not found', {\n domain: 'CLI',\n why: options?.why ?? `Config must have a \"${field}\" field`,\n fix: \"Run 'prisma-next init' to create a config file\",\n docsUrl: 'https://prisma-next.dev/docs/cli/config',\n });\n}\n\n// ============================================================================\n// Runtime Errors (PN-RTM-3000-3003)\n// ============================================================================\n\n/**\n * Contract marker not found in database.\n */\nexport function errorMarkerMissing(options?: {\n readonly why?: string;\n readonly dbUrl?: string;\n}): CliStructuredError {\n return new CliStructuredError('3001', 'Marker missing', {\n domain: 'RTM',\n why: options?.why ?? 'Contract marker not found in database',\n fix: 'Run `prisma-next db sign --db <url>` to create marker',\n });\n}\n\n/**\n * Contract hash does not match database marker.\n */\nexport function errorHashMismatch(options?: {\n readonly why?: string;\n readonly expected?: string;\n readonly actual?: string;\n}): CliStructuredError {\n return new CliStructuredError('3002', 'Hash mismatch', {\n domain: 'RTM',\n why: options?.why ?? 'Contract hash does not match database marker',\n fix: 'Migrate database or re-sign if intentional',\n ...(options?.expected || options?.actual\n ? {\n meta: {\n ...(options.expected ? { expected: options.expected } : {}),\n ...(options.actual ? { actual: options.actual } : {}),\n },\n }\n : {}),\n });\n}\n\n/**\n * Contract target does not match config target.\n */\nexport function errorTargetMismatch(\n expected: string,\n actual: string,\n options?: {\n readonly why?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('3003', 'Target mismatch', {\n domain: 'RTM',\n why:\n options?.why ??\n `Contract target does not match config target (expected: ${expected}, actual: ${actual})`,\n fix: 'Align contract target and config target',\n meta: { expected, actual },\n });\n}\n\n/**\n * Generic runtime error.\n */\nexport function errorRuntime(\n summary: string,\n options?: {\n readonly why?: string;\n readonly fix?: string;\n readonly meta?: Record<string, unknown>;\n },\n): CliStructuredError {\n return new CliStructuredError('3000', summary, {\n domain: 'RTM',\n ...(options?.why ? { why: options.why } : { why: 'Verification failed' }),\n ...(options?.fix ? { fix: options.fix } : { fix: 'Check contract and database state' }),\n ...(options?.meta ? { meta: options.meta } : {}),\n });\n}\n\n// ============================================================================\n// Generic Error\n// ============================================================================\n\n/**\n * Generic unexpected error.\n */\nexport function errorUnexpected(\n message: string,\n options?: {\n readonly why?: string;\n readonly fix?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('4999', 'Unexpected error', {\n domain: 'CLI',\n why: options?.why ?? message,\n fix: options?.fix ?? 'Check the error message and try again',\n });\n}\n"],"mappings":";AAyBO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAMA;AAAA,EACA;AAAA,EAET,YACE,MACA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AC;AACH;AAKO,SAAS,oBACd,UACA,QACA,SAGoB;AACpB,SAAO,IAAI,mBAAmB,QAAQ,mBAAmB;AAAA,IACvD,QAAQ;AAAA,IACR,KACE,SAAS,OACT,2DAA2D,QAAQ,aAAa,MAAM;AAAA,IACxF,KAAK;AAAA,IACL,MAAM,EAAE,UAAU,OAAO;AAAA,EAC3B,CAAC;AACH;AAKO,SAAS,aACd,SACA,SAKoB;AACpB,SAAO,IAAI,mBAAmB,QAAQ,SAAS;AAAA,IAC7C,QAAQ;AAAA,IACR,GAAI,SAAS,MAAM,EAAE,KAAK,QAAQ,IAAI,IAAI,EAAE,KAAK,sBAAsB;AAAA,IACvE,GAAI,SAAS,MAAM,EAAE,KAAK,QAAQ,IAAI,IAAI,EAAE,KAAK,oCAAoC;AAAA,IACrF,GAAI,SAAS,OAAO,EAAE,MAAM,QAAQ,KAAK,IAAI,CAAC;AAAA,EAChD,CAAC;AACH;AASO,SAAS,gBACd,SACA,SAIoB;AACpB,SAAO,IAAI,mBAAmB,QAAQ,oBAAoB;AAAA,IACxD,QAAQ;AAAA,IACR,KAAK,SAAS,OAAO;AAAA,IACrB,KAAK,SAAS,OAAO;AAAA,EACvB,CAAC;AACH;","names":[]}
@@ -1,7 +1,8 @@
1
1
  import { ControlFamilyDescriptor, ControlTargetDescriptor, ControlAdapterDescriptor, ControlExtensionDescriptor, ControlDriverDescriptor } from './types.js';
2
+ import '@prisma-next/contract/framework-components';
2
3
  import '@prisma-next/contract/ir';
3
- import '@prisma-next/contract/pack-manifest-types';
4
4
  import '@prisma-next/contract/types';
5
+ import '@prisma-next/utils/result';
5
6
  import './schema-view.js';
6
7
 
7
8
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config-types.ts"],"sourcesContent":["import { dirname, join } from 'node:path';\nimport { type } from 'arktype';\nimport type {\n ControlAdapterDescriptor,\n ControlDriverDescriptor,\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyDescriptor,\n ControlTargetDescriptor,\n} from './types';\n\n/**\n * Type alias for CLI driver instances.\n */\nexport type CliDriver = ControlDriverInstance;\n\n/**\n * Contract configuration specifying source and artifact locations.\n */\nexport interface ContractConfig {\n /**\n * Contract source. Can be a value or a function that returns a value (sync or async).\n * If a function, it will be called to resolve the contract.\n */\n readonly source: unknown | (() => unknown | Promise<unknown>);\n /**\n * Path to contract.json artifact. Defaults to 'src/prisma/contract.json'.\n * This is the canonical location where other CLI commands can find the contract JSON.\n */\n readonly output?: string;\n /**\n * Path to contract.d.ts artifact. Defaults to output with .d.ts extension.\n * If output ends with .json, replaces .json with .d.ts.\n * Otherwise, appends .d.ts to the directory containing output.\n */\n readonly types?: string;\n}\n\n/**\n * Configuration for Prisma Next CLI.\n * Uses Control*Descriptor types for type-safe wiring with compile-time compatibility checks.\n *\n * @template TFamilyId - The family ID (e.g., 'sql', 'document')\n * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')\n */\nexport interface PrismaNextConfig<\n TFamilyId extends string = string,\n TTargetId extends string = string,\n> {\n readonly family: ControlFamilyDescriptor<TFamilyId>;\n readonly target: ControlTargetDescriptor<TFamilyId, TTargetId>;\n readonly adapter: ControlAdapterDescriptor<TFamilyId, TTargetId>;\n readonly extensions?: readonly ControlExtensionDescriptor<TFamilyId, TTargetId>[];\n /**\n * Driver descriptor for DB-connected CLI commands.\n * Required for DB-connected commands (e.g., db verify).\n * Optional for commands that don't need database access (e.g., emit).\n */\n readonly driver?: ControlDriverDescriptor<TFamilyId, TTargetId>;\n readonly db?: {\n readonly url?: string;\n };\n /**\n * Contract configuration. Specifies source and artifact locations.\n * Required for emit command; optional for other commands that only read artifacts.\n */\n readonly contract?: ContractConfig;\n}\n\n/**\n * Arktype schema for ContractConfig validation.\n * Validates that source is present and output/types are strings when provided.\n */\nconst ContractConfigSchema = type({\n source: 'unknown', // Can be value or function - runtime check needed\n 'output?': 'string',\n 'types?': 'string',\n});\n\n/**\n * Arktype schema for PrismaNextConfig validation.\n * Note: This validates structure only. Descriptor objects (family, target, adapter) are validated separately.\n */\nconst PrismaNextConfigSchema = type({\n family: 'unknown', // ControlFamilyDescriptor - validated separately\n target: 'unknown', // ControlTargetDescriptor - validated separately\n adapter: 'unknown', // ControlAdapterDescriptor - validated separately\n 'extensions?': 'unknown[]',\n 'driver?': 'unknown', // ControlDriverDescriptor - validated separately (optional)\n 'db?': 'unknown',\n 'contract?': ContractConfigSchema,\n});\n\n/**\n * Helper function to define a Prisma Next config.\n * Validates and normalizes the config using Arktype, then returns the normalized IR.\n *\n * Normalization:\n * - contract.output defaults to 'src/prisma/contract.json' if missing\n * - contract.types defaults to output with .d.ts extension if missing\n *\n * @param config - Raw config input from user\n * @returns Normalized config IR with defaults applied\n * @throws Error if config structure is invalid\n */\nexport function defineConfig<TFamilyId extends string = string, TTargetId extends string = string>(\n config: PrismaNextConfig<TFamilyId, TTargetId>,\n): PrismaNextConfig<TFamilyId, TTargetId> {\n // Validate structure using Arktype\n const validated = PrismaNextConfigSchema(config);\n if (validated instanceof type.errors) {\n const messages = validated.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Config validation failed: ${messages}`);\n }\n\n // Normalize contract config if present\n if (config.contract) {\n // Validate contract.source is a value or function (runtime check)\n const source = config.contract.source;\n if (\n source !== null &&\n typeof source !== 'object' &&\n typeof source !== 'function' &&\n typeof source !== 'string' &&\n typeof source !== 'number' &&\n typeof source !== 'boolean'\n ) {\n throw new Error(\n 'Config.contract.source must be a value (object, string, number, boolean, null) or a function',\n );\n }\n\n // Apply defaults\n const output = config.contract.output ?? 'src/prisma/contract.json';\n const types =\n config.contract.types ??\n (output.endsWith('.json')\n ? `${output.slice(0, -5)}.d.ts`\n : join(dirname(output), 'contract.d.ts'));\n\n const normalizedContract: ContractConfig = {\n source: config.contract.source,\n output,\n types,\n };\n\n // Return normalized config\n return {\n ...config,\n contract: normalizedContract,\n };\n }\n\n // Return config as-is if no contract (preserve literal types)\n return config;\n}\n"],"mappings":";AAAA,SAAS,SAAS,YAAY;AAC9B,SAAS,YAAY;AAwErB,IAAM,uBAAuB,KAAK;AAAA,EAChC,QAAQ;AAAA;AAAA,EACR,WAAW;AAAA,EACX,UAAU;AACZ,CAAC;AAMD,IAAM,yBAAyB,KAAK;AAAA,EAClC,QAAQ;AAAA;AAAA,EACR,QAAQ;AAAA;AAAA,EACR,SAAS;AAAA;AAAA,EACT,eAAe;AAAA,EACf,WAAW;AAAA;AAAA,EACX,OAAO;AAAA,EACP,aAAa;AACf,CAAC;AAcM,SAAS,aACd,QACwC;AAExC,QAAM,YAAY,uBAAuB,MAAM;AAC/C,MAAI,qBAAqB,KAAK,QAAQ;AACpC,UAAM,WAAW,UAAU,IAAI,CAAC,MAA2B,EAAE,OAAO,EAAE,KAAK,IAAI;AAC/E,UAAM,IAAI,MAAM,6BAA6B,QAAQ,EAAE;AAAA,EACzD;AAGA,MAAI,OAAO,UAAU;AAEnB,UAAM,SAAS,OAAO,SAAS;AAC/B,QACE,WAAW,QACX,OAAO,WAAW,YAClB,OAAO,WAAW,cAClB,OAAO,WAAW,YAClB,OAAO,WAAW,YAClB,OAAO,WAAW,WAClB;AACA,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAGA,UAAM,SAAS,OAAO,SAAS,UAAU;AACzC,UAAM,QACJ,OAAO,SAAS,UACf,OAAO,SAAS,OAAO,IACpB,GAAG,OAAO,MAAM,GAAG,EAAE,CAAC,UACtB,KAAK,QAAQ,MAAM,GAAG,eAAe;AAE3C,UAAM,qBAAqC;AAAA,MACzC,QAAQ,OAAO,SAAS;AAAA,MACxB;AAAA,MACA;AAAA,IACF;AAGA,WAAO;AAAA,MACL,GAAG;AAAA,MACH,UAAU;AAAA,IACZ;AAAA,EACF;AAGA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/config-types.ts"],"sourcesContent":["import { dirname, join } from 'node:path';\nimport { type } from 'arktype';\nimport type {\n ControlAdapterDescriptor,\n ControlDriverDescriptor,\n ControlDriverInstance,\n ControlExtensionDescriptor,\n ControlFamilyDescriptor,\n ControlTargetDescriptor,\n} from './types';\n\n/**\n * Type alias for CLI driver instances.\n * Uses string for both family and target IDs for maximum flexibility.\n */\nexport type CliDriver = ControlDriverInstance<string, string>;\n\n/**\n * Contract configuration specifying source and artifact locations.\n */\nexport interface ContractConfig {\n /**\n * Contract source. Can be a value or a function that returns a value (sync or async).\n * If a function, it will be called to resolve the contract.\n */\n readonly source: unknown | (() => unknown | Promise<unknown>);\n /**\n * Path to contract.json artifact. Defaults to 'src/prisma/contract.json'.\n * This is the canonical location where other CLI commands can find the contract JSON.\n */\n readonly output?: string;\n /**\n * Path to contract.d.ts artifact. Defaults to output with .d.ts extension.\n * If output ends with .json, replaces .json with .d.ts.\n * Otherwise, appends .d.ts to the directory containing output.\n */\n readonly types?: string;\n}\n\n/**\n * Configuration for Prisma Next CLI.\n * Uses Control*Descriptor types for type-safe wiring with compile-time compatibility checks.\n *\n * @template TFamilyId - The family ID (e.g., 'sql', 'document')\n * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')\n */\nexport interface PrismaNextConfig<\n TFamilyId extends string = string,\n TTargetId extends string = string,\n> {\n readonly family: ControlFamilyDescriptor<TFamilyId>;\n readonly target: ControlTargetDescriptor<TFamilyId, TTargetId>;\n readonly adapter: ControlAdapterDescriptor<TFamilyId, TTargetId>;\n readonly extensions?: readonly ControlExtensionDescriptor<TFamilyId, TTargetId>[];\n /**\n * Driver descriptor for DB-connected CLI commands.\n * Required for DB-connected commands (e.g., db verify).\n * Optional for commands that don't need database access (e.g., emit).\n */\n readonly driver?: ControlDriverDescriptor<TFamilyId, TTargetId>;\n readonly db?: {\n readonly url?: string;\n };\n /**\n * Contract configuration. Specifies source and artifact locations.\n * Required for emit command; optional for other commands that only read artifacts.\n */\n readonly contract?: ContractConfig;\n}\n\n/**\n * Arktype schema for ContractConfig validation.\n * Validates that source is present and output/types are strings when provided.\n */\nconst ContractConfigSchema = type({\n source: 'unknown', // Can be value or function - runtime check needed\n 'output?': 'string',\n 'types?': 'string',\n});\n\n/**\n * Arktype schema for PrismaNextConfig validation.\n * Note: This validates structure only. Descriptor objects (family, target, adapter) are validated separately.\n */\nconst PrismaNextConfigSchema = type({\n family: 'unknown', // ControlFamilyDescriptor - validated separately\n target: 'unknown', // ControlTargetDescriptor - validated separately\n adapter: 'unknown', // ControlAdapterDescriptor - validated separately\n 'extensions?': 'unknown[]',\n 'driver?': 'unknown', // ControlDriverDescriptor - validated separately (optional)\n 'db?': 'unknown',\n 'contract?': ContractConfigSchema,\n});\n\n/**\n * Helper function to define a Prisma Next config.\n * Validates and normalizes the config using Arktype, then returns the normalized IR.\n *\n * Normalization:\n * - contract.output defaults to 'src/prisma/contract.json' if missing\n * - contract.types defaults to output with .d.ts extension if missing\n *\n * @param config - Raw config input from user\n * @returns Normalized config IR with defaults applied\n * @throws Error if config structure is invalid\n */\nexport function defineConfig<TFamilyId extends string = string, TTargetId extends string = string>(\n config: PrismaNextConfig<TFamilyId, TTargetId>,\n): PrismaNextConfig<TFamilyId, TTargetId> {\n // Validate structure using Arktype\n const validated = PrismaNextConfigSchema(config);\n if (validated instanceof type.errors) {\n const messages = validated.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Config validation failed: ${messages}`);\n }\n\n // Normalize contract config if present\n if (config.contract) {\n // Validate contract.source is a value or function (runtime check)\n const source = config.contract.source;\n if (\n source !== null &&\n typeof source !== 'object' &&\n typeof source !== 'function' &&\n typeof source !== 'string' &&\n typeof source !== 'number' &&\n typeof source !== 'boolean'\n ) {\n throw new Error(\n 'Config.contract.source must be a value (object, string, number, boolean, null) or a function',\n );\n }\n\n // Apply defaults\n const output = config.contract.output ?? 'src/prisma/contract.json';\n const types =\n config.contract.types ??\n (output.endsWith('.json')\n ? `${output.slice(0, -5)}.d.ts`\n : join(dirname(output), 'contract.d.ts'));\n\n const normalizedContract: ContractConfig = {\n source: config.contract.source,\n output,\n types,\n };\n\n // Return normalized config\n return {\n ...config,\n contract: normalizedContract,\n };\n }\n\n // Return config as-is if no contract (preserve literal types)\n return config;\n}\n"],"mappings":";AAAA,SAAS,SAAS,YAAY;AAC9B,SAAS,YAAY;AAyErB,IAAM,uBAAuB,KAAK;AAAA,EAChC,QAAQ;AAAA;AAAA,EACR,WAAW;AAAA,EACX,UAAU;AACZ,CAAC;AAMD,IAAM,yBAAyB,KAAK;AAAA,EAClC,QAAQ;AAAA;AAAA,EACR,QAAQ;AAAA;AAAA,EACR,SAAS;AAAA;AAAA,EACT,eAAe;AAAA,EACf,WAAW;AAAA;AAAA,EACX,OAAO;AAAA,EACP,aAAa;AACf,CAAC;AAcM,SAAS,aACd,QACwC;AAExC,QAAM,YAAY,uBAAuB,MAAM;AAC/C,MAAI,qBAAqB,KAAK,QAAQ;AACpC,UAAM,WAAW,UAAU,IAAI,CAAC,MAA2B,EAAE,OAAO,EAAE,KAAK,IAAI;AAC/E,UAAM,IAAI,MAAM,6BAA6B,QAAQ,EAAE;AAAA,EACzD;AAGA,MAAI,OAAO,UAAU;AAEnB,UAAM,SAAS,OAAO,SAAS;AAC/B,QACE,WAAW,QACX,OAAO,WAAW,YAClB,OAAO,WAAW,cAClB,OAAO,WAAW,YAClB,OAAO,WAAW,YAClB,OAAO,WAAW,WAClB;AACA,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAGA,UAAM,SAAS,OAAO,SAAS,UAAU;AACzC,UAAM,QACJ,OAAO,SAAS,UACf,OAAO,SAAS,OAAO,IACpB,GAAG,OAAO,MAAM,GAAG,EAAE,CAAC,UACtB,KAAK,QAAQ,MAAM,GAAG,eAAe;AAE3C,UAAM,qBAAqC;AAAA,MACzC,QAAQ,OAAO,SAAS;AAAA,MACxB;AAAA,MACA;AAAA,IACF;AAGA,WAAO;AAAA,MACL,GAAG;AAAA,MACH,UAAU;AAAA,IACZ;AAAA,EACF;AAGA,SAAO;AACT;","names":[]}
@@ -1,8 +1,9 @@
1
1
  import { PrismaNextConfig } from './config-types.js';
2
2
  import './types.js';
3
+ import '@prisma-next/contract/framework-components';
3
4
  import '@prisma-next/contract/ir';
4
- import '@prisma-next/contract/pack-manifest-types';
5
5
  import '@prisma-next/contract/types';
6
+ import '@prisma-next/utils/result';
6
7
  import './schema-view.js';
7
8
 
8
9
  /**
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  errorConfigValidation
3
- } from "../chunk-DZPZSLCM.js";
3
+ } from "../chunk-R7MOUJNP.js";
4
4
 
5
5
  // src/config-validation.ts
6
6
  function validateConfig(config) {
@@ -232,16 +232,6 @@ function validateCoreStructure(ir) {
232
232
  throw new Error("ContractIR must have sources");
233
233
  }
234
234
  }
235
- function validateExtensions(ir, extensionIds) {
236
- const extensions = ir.extensions;
237
- for (const extensionId of extensionIds) {
238
- if (!extensions[extensionId]) {
239
- throw new Error(
240
- `Extension "${extensionId}" must appear in contract.extensions.${extensionId}`
241
- );
242
- }
243
- }
244
- }
245
235
  async function emit(ir, options, targetFamily) {
246
236
  const { operationRegistry, codecTypeImports, operationTypeImports, extensionIds } = options;
247
237
  validateCoreStructure(ir);
@@ -253,9 +243,6 @@ async function emit(ir, options, targetFamily) {
253
243
  };
254
244
  targetFamily.validateTypes(ir, ctx);
255
245
  targetFamily.validateStructure(ir);
256
- if (extensionIds) {
257
- validateExtensions(ir, extensionIds);
258
- }
259
246
  const contractJson = {
260
247
  schemaVersion: ir.schemaVersion,
261
248
  targetFamily: ir.targetFamily,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/emission/canonicalization.ts","../../src/emission/emit.ts","../../src/emission/hashing.ts"],"sourcesContent":["import type { ContractIR } from '@prisma-next/contract/ir';\n\ntype NormalizedContract = {\n schemaVersion: string;\n targetFamily: string;\n target: string;\n coreHash?: string;\n profileHash?: string;\n models: Record<string, unknown>;\n relations: Record<string, unknown>;\n storage: Record<string, unknown>;\n extensions: Record<string, unknown>;\n capabilities: Record<string, Record<string, boolean>>;\n meta: Record<string, unknown>;\n sources: Record<string, unknown>;\n};\n\nconst TOP_LEVEL_ORDER = [\n 'schemaVersion',\n 'canonicalVersion',\n 'targetFamily',\n 'target',\n 'coreHash',\n 'profileHash',\n 'models',\n 'storage',\n 'capabilities',\n 'extensions',\n 'meta',\n 'sources',\n] as const;\n\nfunction isDefaultValue(value: unknown): boolean {\n if (value === false) return true;\n if (value === null) return false;\n if (Array.isArray(value) && value.length === 0) return true;\n if (typeof value === 'object' && value !== null) {\n const keys = Object.keys(value);\n return keys.length === 0;\n }\n return false;\n}\n\nfunction omitDefaults(obj: unknown, path: readonly string[]): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => omitDefaults(item, path));\n }\n\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const currentPath = [...path, key];\n\n // Exclude metadata fields from canonicalization\n if (key === '_generated') {\n continue;\n }\n\n if (key === 'nullable' && value === false) {\n continue;\n }\n\n if (key === 'generated' && value === false) {\n continue;\n }\n\n if (isDefaultValue(value)) {\n const isRequiredModels = currentPath.length === 1 && currentPath[0] === 'models';\n const isRequiredTables =\n currentPath.length === 2 && currentPath[0] === 'storage' && currentPath[1] === 'tables';\n const isRequiredRelations = currentPath.length === 1 && currentPath[0] === 'relations';\n const isRequiredExtensions = currentPath.length === 1 && currentPath[0] === 'extensions';\n const isRequiredCapabilities = currentPath.length === 1 && currentPath[0] === 'capabilities';\n const isRequiredMeta = currentPath.length === 1 && currentPath[0] === 'meta';\n const isRequiredSources = currentPath.length === 1 && currentPath[0] === 'sources';\n const isExtensionNamespace = currentPath.length === 2 && currentPath[0] === 'extensions';\n const isModelRelations =\n currentPath.length === 3 && currentPath[0] === 'models' && currentPath[2] === 'relations';\n const isTableUniques =\n currentPath.length === 4 &&\n currentPath[0] === 'storage' &&\n currentPath[1] === 'tables' &&\n currentPath[3] === 'uniques';\n const isTableIndexes =\n currentPath.length === 4 &&\n currentPath[0] === 'storage' &&\n currentPath[1] === 'tables' &&\n currentPath[3] === 'indexes';\n const isTableForeignKeys =\n currentPath.length === 4 &&\n currentPath[0] === 'storage' &&\n currentPath[1] === 'tables' &&\n currentPath[3] === 'foreignKeys';\n\n if (\n !isRequiredModels &&\n !isRequiredTables &&\n !isRequiredRelations &&\n !isRequiredExtensions &&\n !isRequiredCapabilities &&\n !isRequiredMeta &&\n !isRequiredSources &&\n !isExtensionNamespace &&\n !isModelRelations &&\n !isTableUniques &&\n !isTableIndexes &&\n !isTableForeignKeys\n ) {\n continue;\n }\n }\n\n result[key] = omitDefaults(value, currentPath);\n }\n\n return result;\n}\n\nfunction sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => sortObjectKeys(item));\n }\n\n const sorted: Record<string, unknown> = {};\n const keys = Object.keys(obj).sort();\n for (const key of keys) {\n sorted[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n\n return sorted;\n}\n\ntype StorageObject = {\n tables?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\ntype TableObject = {\n indexes?: unknown[];\n uniques?: unknown[];\n [key: string]: unknown;\n};\n\nfunction sortIndexesAndUniques(storage: unknown): unknown {\n if (!storage || typeof storage !== 'object') {\n return storage;\n }\n\n const storageObj = storage as StorageObject;\n if (!storageObj.tables || typeof storageObj.tables !== 'object') {\n return storage;\n }\n\n const tables = storageObj.tables;\n const result: StorageObject = { ...storageObj };\n\n result.tables = {};\n // Sort table names to ensure deterministic ordering\n const sortedTableNames = Object.keys(tables).sort();\n for (const tableName of sortedTableNames) {\n const table = tables[tableName];\n if (!table || typeof table !== 'object') {\n result.tables[tableName] = table;\n continue;\n }\n\n const tableObj = table as TableObject;\n const sortedTable: TableObject = { ...tableObj };\n\n if (Array.isArray(tableObj.indexes)) {\n sortedTable.indexes = [...tableObj.indexes].sort((a, b) => {\n const nameA = (a as { name?: string })?.name || '';\n const nameB = (b as { name?: string })?.name || '';\n return nameA.localeCompare(nameB);\n });\n }\n\n if (Array.isArray(tableObj.uniques)) {\n sortedTable.uniques = [...tableObj.uniques].sort((a, b) => {\n const nameA = (a as { name?: string })?.name || '';\n const nameB = (b as { name?: string })?.name || '';\n return nameA.localeCompare(nameB);\n });\n }\n\n result.tables[tableName] = sortedTable;\n }\n\n return result;\n}\n\nfunction orderTopLevel(obj: Record<string, unknown>): Record<string, unknown> {\n const ordered: Record<string, unknown> = {};\n const remaining = new Set(Object.keys(obj));\n\n for (const key of TOP_LEVEL_ORDER) {\n if (remaining.has(key)) {\n ordered[key] = obj[key];\n remaining.delete(key);\n }\n }\n\n for (const key of Array.from(remaining).sort()) {\n ordered[key] = obj[key];\n }\n\n return ordered;\n}\n\nexport function canonicalizeContract(\n ir: ContractIR & { coreHash?: string; profileHash?: string },\n): string {\n const normalized: NormalizedContract = {\n schemaVersion: ir.schemaVersion,\n targetFamily: ir.targetFamily,\n target: ir.target,\n models: ir.models,\n relations: ir.relations,\n storage: ir.storage,\n extensions: ir.extensions,\n capabilities: ir.capabilities,\n meta: ir.meta,\n sources: ir.sources,\n };\n\n if (ir.coreHash !== undefined) {\n normalized.coreHash = ir.coreHash;\n }\n\n if (ir.profileHash !== undefined) {\n normalized.profileHash = ir.profileHash;\n }\n\n const withDefaultsOmitted = omitDefaults(normalized, []) as NormalizedContract;\n const withSortedIndexes = sortIndexesAndUniques(withDefaultsOmitted.storage);\n const withSortedStorage = { ...withDefaultsOmitted, storage: withSortedIndexes };\n const withSortedKeys = sortObjectKeys(withSortedStorage) as Record<string, unknown>;\n const withOrderedTopLevel = orderTopLevel(withSortedKeys);\n\n return JSON.stringify(withOrderedTopLevel, null, 2);\n}\n","import type { ContractIR } from '@prisma-next/contract/ir';\nimport type { TargetFamilyHook, ValidationContext } from '@prisma-next/contract/types';\nimport { format } from 'prettier';\nimport { canonicalizeContract } from './canonicalization';\nimport { computeCoreHash, computeProfileHash } from './hashing';\nimport type { EmitOptions, EmitResult } from './types';\n\nfunction validateCoreStructure(ir: ContractIR): void {\n if (!ir.targetFamily) {\n throw new Error('ContractIR must have targetFamily');\n }\n if (!ir.target) {\n throw new Error('ContractIR must have target');\n }\n if (!ir.schemaVersion) {\n throw new Error('ContractIR must have schemaVersion');\n }\n if (!ir.models || typeof ir.models !== 'object') {\n throw new Error('ContractIR must have models');\n }\n if (!ir.storage || typeof ir.storage !== 'object') {\n throw new Error('ContractIR must have storage');\n }\n if (!ir.relations || typeof ir.relations !== 'object') {\n throw new Error('ContractIR must have relations');\n }\n if (!ir.extensions || typeof ir.extensions !== 'object') {\n throw new Error('ContractIR must have extensions');\n }\n if (!ir.capabilities || typeof ir.capabilities !== 'object') {\n throw new Error('ContractIR must have capabilities');\n }\n if (!ir.meta || typeof ir.meta !== 'object') {\n throw new Error('ContractIR must have meta');\n }\n if (!ir.sources || typeof ir.sources !== 'object') {\n throw new Error('ContractIR must have sources');\n }\n}\n\nfunction validateExtensions(ir: ContractIR, extensionIds: ReadonlyArray<string>): void {\n const extensions = ir.extensions as Record<string, unknown>;\n for (const extensionId of extensionIds) {\n if (!extensions[extensionId]) {\n throw new Error(\n `Extension \"${extensionId}\" must appear in contract.extensions.${extensionId}`,\n );\n }\n }\n}\n\nexport async function emit(\n ir: ContractIR,\n options: EmitOptions,\n targetFamily: TargetFamilyHook,\n): Promise<EmitResult> {\n const { operationRegistry, codecTypeImports, operationTypeImports, extensionIds } = options;\n\n validateCoreStructure(ir);\n\n const ctx: ValidationContext = {\n ...(operationRegistry ? { operationRegistry } : {}),\n ...(codecTypeImports ? { codecTypeImports } : {}),\n ...(operationTypeImports ? { operationTypeImports } : {}),\n ...(extensionIds ? { extensionIds } : {}),\n };\n targetFamily.validateTypes(ir, ctx);\n\n targetFamily.validateStructure(ir);\n\n if (extensionIds) {\n validateExtensions(ir, extensionIds);\n }\n\n const contractJson = {\n schemaVersion: ir.schemaVersion,\n targetFamily: ir.targetFamily,\n target: ir.target,\n models: ir.models,\n relations: ir.relations,\n storage: ir.storage,\n extensions: ir.extensions,\n capabilities: ir.capabilities,\n meta: ir.meta,\n sources: ir.sources,\n } as const;\n\n const coreHash = computeCoreHash(contractJson);\n const profileHash = computeProfileHash(contractJson);\n\n const contractWithHashes: ContractIR & { coreHash?: string; profileHash?: string } = {\n ...ir,\n schemaVersion: contractJson.schemaVersion,\n coreHash,\n profileHash,\n };\n\n // Add _generated metadata to indicate this is a generated artifact\n // This ensures consistency between CLI emit and programmatic emit\n // Always add/update _generated with standard content for consistency\n const contractJsonObj = JSON.parse(canonicalizeContract(contractWithHashes)) as Record<\n string,\n unknown\n >;\n const contractJsonWithMeta = {\n ...contractJsonObj,\n _generated: {\n warning: '⚠️ GENERATED FILE - DO NOT EDIT',\n message: 'This file is automatically generated by \"prisma-next emit\".',\n regenerate: 'To regenerate, run: prisma-next emit',\n },\n };\n const contractJsonString = JSON.stringify(contractJsonWithMeta, null, 2);\n\n const contractDtsRaw = targetFamily.generateContractTypes(\n ir,\n codecTypeImports ?? [],\n operationTypeImports ?? [],\n );\n const contractDts = await format(contractDtsRaw, {\n parser: 'typescript',\n singleQuote: true,\n semi: true,\n printWidth: 100,\n });\n\n return {\n contractJson: contractJsonString,\n contractDts,\n coreHash,\n profileHash,\n };\n}\n","import { createHash } from 'node:crypto';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport { canonicalizeContract } from './canonicalization';\n\ntype ContractInput = {\n schemaVersion: string;\n targetFamily: string;\n target: string;\n models: Record<string, unknown>;\n relations: Record<string, unknown>;\n storage: Record<string, unknown>;\n extensions: Record<string, unknown>;\n sources: Record<string, unknown>;\n capabilities: Record<string, Record<string, boolean>>;\n meta: Record<string, unknown>;\n [key: string]: unknown;\n};\n\nfunction computeHash(content: string): string {\n const hash = createHash('sha256');\n hash.update(content);\n return `sha256:${hash.digest('hex')}`;\n}\n\nexport function computeCoreHash(contract: ContractInput): string {\n const coreContract: ContractIR = {\n schemaVersion: contract.schemaVersion,\n targetFamily: contract.targetFamily,\n target: contract.target,\n models: contract.models,\n relations: contract.relations,\n storage: contract.storage,\n extensions: contract.extensions,\n sources: contract.sources,\n capabilities: contract.capabilities,\n meta: contract.meta,\n };\n const canonical = canonicalizeContract(coreContract);\n return computeHash(canonical);\n}\n\nexport function computeProfileHash(contract: ContractInput): string {\n const profileContract: ContractIR = {\n schemaVersion: contract.schemaVersion,\n targetFamily: contract.targetFamily,\n target: contract.target,\n models: {},\n relations: {},\n storage: {},\n extensions: {},\n capabilities: contract.capabilities,\n meta: {},\n sources: {},\n };\n const canonical = canonicalizeContract(profileContract);\n return computeHash(canonical);\n}\n"],"mappings":";AAiBA,IAAM,kBAAkB;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,eAAe,OAAyB;AAC/C,MAAI,UAAU,MAAO,QAAO;AAC5B,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,EAAG,QAAO;AACvD,MAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C,UAAM,OAAO,OAAO,KAAK,KAAK;AAC9B,WAAO,KAAK,WAAW;AAAA,EACzB;AACA,SAAO;AACT;AAEA,SAAS,aAAa,KAAc,MAAkC;AACpE,MAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,WAAO;AAAA,EACT;AAEA,MAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,WAAO,IAAI,IAAI,CAAC,SAAS,aAAa,MAAM,IAAI,CAAC;AAAA,EACnD;AAEA,QAAM,SAAkC,CAAC;AAEzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC9C,UAAM,cAAc,CAAC,GAAG,MAAM,GAAG;AAGjC,QAAI,QAAQ,cAAc;AACxB;AAAA,IACF;AAEA,QAAI,QAAQ,cAAc,UAAU,OAAO;AACzC;AAAA,IACF;AAEA,QAAI,QAA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,IAAI,GAAG;AAElC,eAAa,kBAAkB,EAAE;AAEjC,MAAI,cAAc;AAChB,uBAAmB,IAAI,YAAY;AAAA,EACrC;AAEA,QAAM,eAAe;AAAA,IACnB,eAAe,GAAG;AAAA,IAClB,cAAc,GAAG;AAAA,IACjB,QAAQ,GAAG;AAAA,IACX,QAAQ,GAAG;AAAA,IACX,WAAW,GAAG;AAAA,IACd,SAAS,GAAG;AAAA,IACZ,YAAY,GAAG;AAAA,IACf,cAAc,GAAG;AAAA,IACjB,MAAM,GAAG;AAAA,IACT,SAAS,GAAG;AAAA,EACd;AAEA,QAAM,WAAW,gBAAgB,YAAY;AAC7C,QAAM,cAAc,mBAAmB,YAAY;AAEnD,QAAM,qBAA+E;AAAA,IACnF,GAAG;AAAA,IACH,eAAe,aAAa;AAAA,IAC5B;AAAA,IACA;AAAA,EACF;AAKA,QAAM,kBAAkB,KAAK,MAAM,qBAAqB,kBAAkB,CAAC;AAI3E,QAAM,uBAAuB;AAAA,IAC3B,GAAG;AAAA,IACH,YAAY;AAAA,MACV,SAAS;AAAA,MACT,SAAS;AAAA,MACT,YAAY;AAAA,IACd;AAAA,EACF;AACA,QAAM,qBAAqB,KAAK,UAAU,sBAAsB,MAAM,CAAC;AAEvE,QAAM,iBAAiB,aAAa;AAAA,IAClC;AAAA,IACA,oBAAoB,CAAC;AAAA,IACrB,wBAAwB,CAAC;AAAA,EAC3B;AACA,QAAM,cAAc,MAAM,OAAO,gBAAgB;AAAA,IAC/C,QAAQ;AAAA,IACR,aAAa;AAAA,IACb,MAAM;AAAA,IACN,YAAY;AAAA,EACd,CAAC;AAED,SAAO;AAAA,IACL,cAAc;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/emission/canonicalization.ts","../../src/emission/emit.ts","../../src/emission/hashing.ts"],"sourcesContent":["import type { ContractIR } from '@prisma-next/contract/ir';\n\ntype NormalizedContract = {\n schemaVersion: string;\n targetFamily: string;\n target: string;\n coreHash?: string;\n profileHash?: string;\n models: Record<string, unknown>;\n relations: Record<string, unknown>;\n storage: Record<string, unknown>;\n extensions: Record<string, unknown>;\n capabilities: Record<string, Record<string, boolean>>;\n meta: Record<string, unknown>;\n sources: Record<string, unknown>;\n};\n\nconst TOP_LEVEL_ORDER = [\n 'schemaVersion',\n 'canonicalVersion',\n 'targetFamily',\n 'target',\n 'coreHash',\n 'profileHash',\n 'models',\n 'storage',\n 'capabilities',\n 'extensions',\n 'meta',\n 'sources',\n] as const;\n\nfunction isDefaultValue(value: unknown): boolean {\n if (value === false) return true;\n if (value === null) return false;\n if (Array.isArray(value) && value.length === 0) return true;\n if (typeof value === 'object' && value !== null) {\n const keys = Object.keys(value);\n return keys.length === 0;\n }\n return false;\n}\n\nfunction omitDefaults(obj: unknown, path: readonly string[]): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => omitDefaults(item, path));\n }\n\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const currentPath = [...path, key];\n\n // Exclude metadata fields from canonicalization\n if (key === '_generated') {\n continue;\n }\n\n if (key === 'nullable' && value === false) {\n continue;\n }\n\n if (key === 'generated' && value === false) {\n continue;\n }\n\n if (isDefaultValue(value)) {\n const isRequiredModels = currentPath.length === 1 && currentPath[0] === 'models';\n const isRequiredTables =\n currentPath.length === 2 && currentPath[0] === 'storage' && currentPath[1] === 'tables';\n const isRequiredRelations = currentPath.length === 1 && currentPath[0] === 'relations';\n const isRequiredExtensions = currentPath.length === 1 && currentPath[0] === 'extensions';\n const isRequiredCapabilities = currentPath.length === 1 && currentPath[0] === 'capabilities';\n const isRequiredMeta = currentPath.length === 1 && currentPath[0] === 'meta';\n const isRequiredSources = currentPath.length === 1 && currentPath[0] === 'sources';\n const isExtensionNamespace = currentPath.length === 2 && currentPath[0] === 'extensions';\n const isModelRelations =\n currentPath.length === 3 && currentPath[0] === 'models' && currentPath[2] === 'relations';\n const isTableUniques =\n currentPath.length === 4 &&\n currentPath[0] === 'storage' &&\n currentPath[1] === 'tables' &&\n currentPath[3] === 'uniques';\n const isTableIndexes =\n currentPath.length === 4 &&\n currentPath[0] === 'storage' &&\n currentPath[1] === 'tables' &&\n currentPath[3] === 'indexes';\n const isTableForeignKeys =\n currentPath.length === 4 &&\n currentPath[0] === 'storage' &&\n currentPath[1] === 'tables' &&\n currentPath[3] === 'foreignKeys';\n\n if (\n !isRequiredModels &&\n !isRequiredTables &&\n !isRequiredRelations &&\n !isRequiredExtensions &&\n !isRequiredCapabilities &&\n !isRequiredMeta &&\n !isRequiredSources &&\n !isExtensionNamespace &&\n !isModelRelations &&\n !isTableUniques &&\n !isTableIndexes &&\n !isTableForeignKeys\n ) {\n continue;\n }\n }\n\n result[key] = omitDefaults(value, currentPath);\n }\n\n return result;\n}\n\nfunction sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => sortObjectKeys(item));\n }\n\n const sorted: Record<string, unknown> = {};\n const keys = Object.keys(obj).sort();\n for (const key of keys) {\n sorted[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n\n return sorted;\n}\n\ntype StorageObject = {\n tables?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\ntype TableObject = {\n indexes?: unknown[];\n uniques?: unknown[];\n [key: string]: unknown;\n};\n\nfunction sortIndexesAndUniques(storage: unknown): unknown {\n if (!storage || typeof storage !== 'object') {\n return storage;\n }\n\n const storageObj = storage as StorageObject;\n if (!storageObj.tables || typeof storageObj.tables !== 'object') {\n return storage;\n }\n\n const tables = storageObj.tables;\n const result: StorageObject = { ...storageObj };\n\n result.tables = {};\n // Sort table names to ensure deterministic ordering\n const sortedTableNames = Object.keys(tables).sort();\n for (const tableName of sortedTableNames) {\n const table = tables[tableName];\n if (!table || typeof table !== 'object') {\n result.tables[tableName] = table;\n continue;\n }\n\n const tableObj = table as TableObject;\n const sortedTable: TableObject = { ...tableObj };\n\n if (Array.isArray(tableObj.indexes)) {\n sortedTable.indexes = [...tableObj.indexes].sort((a, b) => {\n const nameA = (a as { name?: string })?.name || '';\n const nameB = (b as { name?: string })?.name || '';\n return nameA.localeCompare(nameB);\n });\n }\n\n if (Array.isArray(tableObj.uniques)) {\n sortedTable.uniques = [...tableObj.uniques].sort((a, b) => {\n const nameA = (a as { name?: string })?.name || '';\n const nameB = (b as { name?: string })?.name || '';\n return nameA.localeCompare(nameB);\n });\n }\n\n result.tables[tableName] = sortedTable;\n }\n\n return result;\n}\n\nfunction orderTopLevel(obj: Record<string, unknown>): Record<string, unknown> {\n const ordered: Record<string, unknown> = {};\n const remaining = new Set(Object.keys(obj));\n\n for (const key of TOP_LEVEL_ORDER) {\n if (remaining.has(key)) {\n ordered[key] = obj[key];\n remaining.delete(key);\n }\n }\n\n for (const key of Array.from(remaining).sort()) {\n ordered[key] = obj[key];\n }\n\n return ordered;\n}\n\nexport function canonicalizeContract(\n ir: ContractIR & { coreHash?: string; profileHash?: string },\n): string {\n const normalized: NormalizedContract = {\n schemaVersion: ir.schemaVersion,\n targetFamily: ir.targetFamily,\n target: ir.target,\n models: ir.models,\n relations: ir.relations,\n storage: ir.storage,\n extensions: ir.extensions,\n capabilities: ir.capabilities,\n meta: ir.meta,\n sources: ir.sources,\n };\n\n if (ir.coreHash !== undefined) {\n normalized.coreHash = ir.coreHash;\n }\n\n if (ir.profileHash !== undefined) {\n normalized.profileHash = ir.profileHash;\n }\n\n const withDefaultsOmitted = omitDefaults(normalized, []) as NormalizedContract;\n const withSortedIndexes = sortIndexesAndUniques(withDefaultsOmitted.storage);\n const withSortedStorage = { ...withDefaultsOmitted, storage: withSortedIndexes };\n const withSortedKeys = sortObjectKeys(withSortedStorage) as Record<string, unknown>;\n const withOrderedTopLevel = orderTopLevel(withSortedKeys);\n\n return JSON.stringify(withOrderedTopLevel, null, 2);\n}\n","import type { ContractIR } from '@prisma-next/contract/ir';\nimport type { TargetFamilyHook, ValidationContext } from '@prisma-next/contract/types';\nimport { format } from 'prettier';\nimport { canonicalizeContract } from './canonicalization';\nimport { computeCoreHash, computeProfileHash } from './hashing';\nimport type { EmitOptions, EmitResult } from './types';\n\nfunction validateCoreStructure(ir: ContractIR): void {\n if (!ir.targetFamily) {\n throw new Error('ContractIR must have targetFamily');\n }\n if (!ir.target) {\n throw new Error('ContractIR must have target');\n }\n if (!ir.schemaVersion) {\n throw new Error('ContractIR must have schemaVersion');\n }\n if (!ir.models || typeof ir.models !== 'object') {\n throw new Error('ContractIR must have models');\n }\n if (!ir.storage || typeof ir.storage !== 'object') {\n throw new Error('ContractIR must have storage');\n }\n if (!ir.relations || typeof ir.relations !== 'object') {\n throw new Error('ContractIR must have relations');\n }\n if (!ir.extensions || typeof ir.extensions !== 'object') {\n throw new Error('ContractIR must have extensions');\n }\n if (!ir.capabilities || typeof ir.capabilities !== 'object') {\n throw new Error('ContractIR must have capabilities');\n }\n if (!ir.meta || typeof ir.meta !== 'object') {\n throw new Error('ContractIR must have meta');\n }\n if (!ir.sources || typeof ir.sources !== 'object') {\n throw new Error('ContractIR must have sources');\n }\n}\n\nexport async function emit(\n ir: ContractIR,\n options: EmitOptions,\n targetFamily: TargetFamilyHook,\n): Promise<EmitResult> {\n const { operationRegistry, codecTypeImports, operationTypeImports, extensionIds } = options;\n\n validateCoreStructure(ir);\n\n const ctx: ValidationContext = {\n ...(operationRegistry ? { operationRegistry } : {}),\n ...(codecTypeImports ? { codecTypeImports } : {}),\n ...(operationTypeImports ? { operationTypeImports } : {}),\n ...(extensionIds ? { extensionIds } : {}),\n };\n targetFamily.validateTypes(ir, ctx);\n\n targetFamily.validateStructure(ir);\n\n const contractJson = {\n schemaVersion: ir.schemaVersion,\n targetFamily: ir.targetFamily,\n target: ir.target,\n models: ir.models,\n relations: ir.relations,\n storage: ir.storage,\n extensions: ir.extensions,\n capabilities: ir.capabilities,\n meta: ir.meta,\n sources: ir.sources,\n } as const;\n\n const coreHash = computeCoreHash(contractJson);\n const profileHash = computeProfileHash(contractJson);\n\n const contractWithHashes: ContractIR & { coreHash?: string; profileHash?: string } = {\n ...ir,\n schemaVersion: contractJson.schemaVersion,\n coreHash,\n profileHash,\n };\n\n // Add _generated metadata to indicate this is a generated artifact\n // This ensures consistency between CLI emit and programmatic emit\n // Always add/update _generated with standard content for consistency\n const contractJsonObj = JSON.parse(canonicalizeContract(contractWithHashes)) as Record<\n string,\n unknown\n >;\n const contractJsonWithMeta = {\n ...contractJsonObj,\n _generated: {\n warning: '⚠️ GENERATED FILE - DO NOT EDIT',\n message: 'This file is automatically generated by \"prisma-next emit\".',\n regenerate: 'To regenerate, run: prisma-next emit',\n },\n };\n const contractJsonString = JSON.stringify(contractJsonWithMeta, null, 2);\n\n const contractDtsRaw = targetFamily.generateContractTypes(\n ir,\n codecTypeImports ?? [],\n operationTypeImports ?? [],\n );\n const contractDts = await format(contractDtsRaw, {\n parser: 'typescript',\n singleQuote: true,\n semi: true,\n printWidth: 100,\n });\n\n return {\n contractJson: contractJsonString,\n contractDts,\n coreHash,\n profileHash,\n };\n}\n","import { createHash } from 'node:crypto';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport { canonicalizeContract } from './canonicalization';\n\ntype ContractInput = {\n schemaVersion: string;\n targetFamily: string;\n target: string;\n models: Record<string, unknown>;\n relations: Record<string, unknown>;\n storage: Record<string, unknown>;\n extensions: Record<string, unknown>;\n sources: Record<string, unknown>;\n capabilities: Record<string, Record<string, boolean>>;\n meta: Record<string, unknown>;\n [key: string]: unknown;\n};\n\nfunction computeHash(content: string): string {\n const hash = createHash('sha256');\n hash.update(content);\n return `sha256:${hash.digest('hex')}`;\n}\n\nexport function computeCoreHash(contract: ContractInput): string {\n const coreContract: ContractIR = {\n schemaVersion: contract.schemaVersion,\n targetFamily: contract.targetFamily,\n target: contract.target,\n models: contract.models,\n relations: contract.relations,\n storage: contract.storage,\n extensions: contract.extensions,\n sources: contract.sources,\n capabilities: contract.capabilities,\n meta: contract.meta,\n };\n const canonical = canonicalizeContract(coreContract);\n return computeHash(canonical);\n}\n\nexport function computeProfileHash(contract: ContractInput): string {\n const profileContract: ContractIR = {\n schemaVersion: contract.schemaVersion,\n targetFamily: contract.targetFamily,\n target: contract.target,\n models: {},\n relations: {},\n storage: {},\n extensions: {},\n capabilities: contract.capabilities,\n meta: {},\n sources: {},\n };\n const canonical = canonicalizeContract(profileContract);\n return computeHash(canonical);\n}\n"],"mappings":";AAiBA,IAAM,kBAAkB;AAAA,EACtB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,eAAe,OAAyB;AAC/C,MAAI,UAAU,MAAO,QAAO;AAC5B,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,EAAG,QAAO;AACvD,MAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C,UAAM,OAAO,OAAO,KAAK,KAAK;AAC9B,WAAO,KAAK,WAAW;AAAA,EACzB;AACA,SAAO;AACT;AAEA,SAAS,aAAa,KAAc,MAAkC;AACpE,MAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,WAAO;AAAA,EACT;AAEA,MAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,WAAO,IAAI,IAAI,CAAC,SAAS,aAAa,MAAM,IAAI,CAAC;AAAA,EACnD;AAEA,QAAM,SAAkC,CAAC;AAEzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC9C,UAAM,cAAc,CAAC,GAAG,MAAM,GAAG;AAGjC,QAAI,QAAQ,cAAc;AACxB;AAAA,IACF;AAEA,QAAI,QAAQ,cAAc,UAAU,OAAO;AACzC;AAAA,IACF;AAEA,QAAI,QAAQ,eAAe,UAAU,OAAO;AAC1C;AAAA,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AAA,IACjB,MAAM,GAAG;AAAA,IACT,SAAS,GAAG;AAAA,EACd;AAEA,QAAM,WAAW,gBAAgB,YAAY;AAC7C,QAAM,cAAc,mBAAmB,YAAY;AAEnD,QAAM,qBAA+E;AAAA,IACnF,GAAG;AAAA,IACH,eAAe,aAAa;AAAA,IAC5B;AAAA,IACA;AAAA,EACF;AAKA,QAAM,kBAAkB,KAAK,MAAM,qBAAqB,kBAAkB,CAAC;AAI3E,QAAM,uBAAuB;AAAA,IAC3B,GAAG;AAAA,IACH,YAAY;AAAA,MACV,SAAS;AAAA,MACT,SAAS;AAAA,MACT,YAAY;AAAA,IACd;AAAA,EACF;AACA,QAAM,qBAAqB,KAAK,UAAU,sBAAsB,MAAM,CAAC;AAEvE,QAAM,iBAAiB,aAAa;AAAA,IAClC;AAAA,IACA,oBAAoB,CAAC;AAAA,IACrB,wBAAwB,CAAC;AAAA,EAC3B;AACA,QAAM,cAAc,MAAM,OAAO,gBAAgB;AAAA,IAC/C,QAAQ;AAAA,IACR,aAAa;AAAA,IACb,MAAM;AAAA,IACN,YAAY;AAAA,EACd,CAAC;AAED,SAAO;AAAA,IACL,cAAc;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -100,6 +100,23 @@ declare function errorFamilyReadMarkerSqlRequired(options?: {
100
100
  declare function errorDriverRequired(options?: {
101
101
  readonly why?: string;
102
102
  }): CliStructuredError;
103
+ /**
104
+ * Migration planning failed due to conflicts.
105
+ */
106
+ declare function errorMigrationPlanningFailed(options: {
107
+ readonly conflicts: readonly {
108
+ readonly kind: string;
109
+ readonly summary: string;
110
+ readonly why?: string;
111
+ }[];
112
+ readonly why?: string;
113
+ }): CliStructuredError;
114
+ /**
115
+ * Target does not support migrations (missing createPlanner/createRunner).
116
+ */
117
+ declare function errorTargetMigrationNotSupported(options?: {
118
+ readonly why?: string;
119
+ }): CliStructuredError;
103
120
  /**
104
121
  * Config validation error (missing required fields).
105
122
  */
@@ -143,4 +160,4 @@ declare function errorUnexpected(message: string, options?: {
143
160
  readonly fix?: string;
144
161
  }): CliStructuredError;
145
162
 
146
- export { type CliErrorEnvelope, CliStructuredError, errorConfigFileNotFound, errorConfigValidation, errorContractConfigMissing, errorContractValidationFailed, errorDatabaseUrlRequired, errorDriverRequired, errorFamilyReadMarkerSqlRequired, errorFileNotFound, errorHashMismatch, errorMarkerMissing, errorQueryRunnerFactoryRequired, errorRuntime, errorTargetMismatch, errorUnexpected };
163
+ export { type CliErrorEnvelope, CliStructuredError, errorConfigFileNotFound, errorConfigValidation, errorContractConfigMissing, errorContractValidationFailed, errorDatabaseUrlRequired, errorDriverRequired, errorFamilyReadMarkerSqlRequired, errorFileNotFound, errorHashMismatch, errorMarkerMissing, errorMigrationPlanningFailed, errorQueryRunnerFactoryRequired, errorRuntime, errorTargetMigrationNotSupported, errorTargetMismatch, errorUnexpected };
@@ -10,11 +10,13 @@ import {
10
10
  errorFileNotFound,
11
11
  errorHashMismatch,
12
12
  errorMarkerMissing,
13
+ errorMigrationPlanningFailed,
13
14
  errorQueryRunnerFactoryRequired,
14
15
  errorRuntime,
16
+ errorTargetMigrationNotSupported,
15
17
  errorTargetMismatch,
16
18
  errorUnexpected
17
- } from "../chunk-DZPZSLCM.js";
19
+ } from "../chunk-R7MOUJNP.js";
18
20
  export {
19
21
  CliStructuredError,
20
22
  errorConfigFileNotFound,
@@ -27,8 +29,10 @@ export {
27
29
  errorFileNotFound,
28
30
  errorHashMismatch,
29
31
  errorMarkerMissing,
32
+ errorMigrationPlanningFailed,
30
33
  errorQueryRunnerFactoryRequired,
31
34
  errorRuntime,
35
+ errorTargetMigrationNotSupported,
32
36
  errorTargetMismatch,
33
37
  errorUnexpected
34
38
  };
@@ -1,185 +1,235 @@
1
+ import { TargetBoundComponentDescriptor, FamilyInstance, DriverInstance, FamilyDescriptor, TargetInstance, TargetDescriptor, AdapterInstance, AdapterDescriptor, DriverDescriptor, ExtensionInstance, ExtensionDescriptor } from '@prisma-next/contract/framework-components';
1
2
  import { ContractIR } from '@prisma-next/contract/ir';
2
- import { ExtensionPackManifest } from '@prisma-next/contract/pack-manifest-types';
3
- import { TargetFamilyHook } from '@prisma-next/contract/types';
3
+ import { ContractMarkerRecord, TargetFamilyHook } from '@prisma-next/contract/types';
4
+ import { Result } from '@prisma-next/utils/result';
4
5
  import { CoreSchemaView } from './schema-view.js';
5
6
 
6
7
  /**
7
- * Base interface for control-plane family instances.
8
- * Families extend this with domain-specific methods.
8
+ * Core migration types for the framework control plane.
9
9
  *
10
- * @template TFamilyId - The family ID (e.g., 'sql', 'document')
10
+ * These are family-agnostic, display-oriented types that provide a stable
11
+ * vocabulary for CLI commands to work with migration planners and runners
12
+ * without importing family-specific types.
13
+ *
14
+ * Family-specific types (e.g., SqlMigrationPlan) extend these base types
15
+ * with additional fields for execution (precheck SQL, execute SQL, etc.).
16
+ */
17
+
18
+ /**
19
+ * Migration operation classes define the safety level of an operation.
20
+ * - 'additive': Adds new structures without modifying existing ones (safe)
21
+ * - 'widening': Relaxes constraints or expands types (generally safe)
22
+ * - 'destructive': Removes or alters existing structures (potentially unsafe)
11
23
  */
12
- interface ControlFamilyInstance<TFamilyId extends string = string> {
13
- readonly familyId: TFamilyId;
24
+ type MigrationOperationClass = 'additive' | 'widening' | 'destructive';
25
+ /**
26
+ * Policy defining which operation classes are allowed during a migration.
27
+ */
28
+ interface MigrationOperationPolicy {
29
+ readonly allowedOperationClasses: readonly MigrationOperationClass[];
14
30
  }
15
31
  /**
16
- * Base interface for control-plane target instances.
17
- *
18
- * @template TFamilyId - The family ID (e.g., 'sql', 'document')
19
- * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
32
+ * A single migration operation for display purposes.
33
+ * Contains only the fields needed for CLI output (tree view, JSON envelope).
20
34
  */
21
- interface ControlTargetInstance<TFamilyId extends string = string, TTargetId extends string = string> {
22
- readonly familyId: TFamilyId;
23
- readonly targetId: TTargetId;
35
+ interface MigrationPlanOperation {
36
+ /** Unique identifier for this operation (e.g., "table.users.create"). */
37
+ readonly id: string;
38
+ /** Human-readable label for display in UI/CLI (e.g., "Create table users"). */
39
+ readonly label: string;
40
+ /** The class of operation (additive, widening, destructive). */
41
+ readonly operationClass: MigrationOperationClass;
24
42
  }
25
43
  /**
26
- * Base interface for control-plane adapter instances.
27
- * Families extend this with family-specific adapter interfaces.
28
- *
29
- * @template TFamilyId - The family ID (e.g., 'sql', 'document')
30
- * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
44
+ * A migration plan for display purposes.
45
+ * Contains only the fields needed for CLI output (summary, JSON envelope).
31
46
  */
32
- interface ControlAdapterInstance<TFamilyId extends string = string, TTargetId extends string = string> {
33
- readonly familyId: TFamilyId;
34
- readonly targetId: TTargetId;
47
+ interface MigrationPlan {
48
+ /** The target ID this plan is for (e.g., 'postgres'). */
49
+ readonly targetId: string;
50
+ /** Destination contract identity that the plan intends to reach. */
51
+ readonly destination: {
52
+ readonly coreHash: string;
53
+ readonly profileHash?: string;
54
+ };
55
+ /** Ordered list of operations to execute. */
56
+ readonly operations: readonly MigrationPlanOperation[];
35
57
  }
36
58
  /**
37
- * Base interface for control-plane driver instances.
38
- * Replaces ControlPlaneDriver with plane-first naming.
39
- *
40
- * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
59
+ * A conflict detected during migration planning.
41
60
  */
42
- interface ControlDriverInstance<TTargetId extends string = string> {
43
- readonly targetId?: TTargetId;
44
- query<Row = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<{
45
- readonly rows: Row[];
46
- }>;
47
- close(): Promise<void>;
61
+ interface MigrationPlannerConflict {
62
+ /** Kind of conflict (e.g., 'typeMismatch', 'nullabilityConflict'). */
63
+ readonly kind: string;
64
+ /** Human-readable summary of the conflict. */
65
+ readonly summary: string;
66
+ /** Optional explanation of why this conflict occurred. */
67
+ readonly why?: string;
48
68
  }
49
69
  /**
50
- * Base interface for control-plane extension instances.
51
- *
52
- * @template TFamilyId - The family ID (e.g., 'sql', 'document')
53
- * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
70
+ * Successful planner result with the migration plan.
54
71
  */
55
- interface ControlExtensionInstance<TFamilyId extends string = string, TTargetId extends string = string> {
56
- readonly familyId: TFamilyId;
57
- readonly targetId: TTargetId;
72
+ interface MigrationPlannerSuccessResult {
73
+ readonly kind: 'success';
74
+ readonly plan: MigrationPlan;
58
75
  }
59
76
  /**
60
- * Descriptor for a control-plane family (e.g., SQL).
61
- * Provides the family hook and factory method.
62
- *
63
- * @template TFamilyId - The family ID (e.g., 'sql', 'document')
64
- * @template TFamilyInstance - The family instance type
77
+ * Failed planner result with the list of conflicts.
65
78
  */
66
- interface ControlFamilyDescriptor<TFamilyId extends string, TFamilyInstance extends ControlFamilyInstance<TFamilyId> = ControlFamilyInstance<TFamilyId>> {
67
- readonly kind: 'family';
68
- readonly id: string;
69
- readonly familyId: TFamilyId;
70
- readonly manifest: ExtensionPackManifest;
71
- readonly hook: TargetFamilyHook;
72
- create<TTargetId extends string>(options: {
73
- readonly target: ControlTargetDescriptor<TFamilyId, TTargetId>;
74
- readonly adapter: ControlAdapterDescriptor<TFamilyId, TTargetId>;
75
- readonly driver: ControlDriverDescriptor<TFamilyId, TTargetId>;
76
- readonly extensions: readonly ControlExtensionDescriptor<TFamilyId, TTargetId>[];
77
- }): TFamilyInstance;
79
+ interface MigrationPlannerFailureResult {
80
+ readonly kind: 'failure';
81
+ readonly conflicts: readonly MigrationPlannerConflict[];
78
82
  }
79
83
  /**
80
- * Descriptor for a control-plane target pack (e.g., Postgres target).
81
- *
82
- * @template TFamilyId - The family ID (e.g., 'sql', 'document')
83
- * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
84
- * @template TTargetInstance - The target instance type
84
+ * Union type for planner results.
85
85
  */
86
- interface ControlTargetDescriptor<TFamilyId extends string, TTargetId extends string, TTargetInstance extends ControlTargetInstance<TFamilyId, TTargetId> = ControlTargetInstance<TFamilyId, TTargetId>> {
87
- readonly kind: 'target';
88
- readonly id: string;
89
- readonly familyId: TFamilyId;
90
- readonly targetId: TTargetId;
91
- readonly manifest: ExtensionPackManifest;
92
- create(): TTargetInstance;
86
+ type MigrationPlannerResult = MigrationPlannerSuccessResult | MigrationPlannerFailureResult;
87
+ /**
88
+ * Success value for migration runner execution.
89
+ */
90
+ interface MigrationRunnerSuccessValue {
91
+ readonly operationsPlanned: number;
92
+ readonly operationsExecuted: number;
93
93
  }
94
94
  /**
95
- * Descriptor for a control-plane adapter pack (e.g., Postgres adapter).
95
+ * Failure details for migration runner execution.
96
+ */
97
+ interface MigrationRunnerFailure {
98
+ /** Error code for the failure. */
99
+ readonly code: string;
100
+ /** Human-readable summary of the failure. */
101
+ readonly summary: string;
102
+ /** Optional explanation of why the failure occurred. */
103
+ readonly why?: string;
104
+ }
105
+ /**
106
+ * Result type for migration runner execution.
107
+ */
108
+ type MigrationRunnerResult = Result<MigrationRunnerSuccessValue, MigrationRunnerFailure>;
109
+ /**
110
+ * Migration planner interface for planning schema changes.
111
+ * This is the minimal interface that CLI commands use.
96
112
  *
97
113
  * @template TFamilyId - The family ID (e.g., 'sql', 'document')
98
114
  * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
99
- * @template TAdapterInstance - The adapter instance type
100
115
  */
101
- interface ControlAdapterDescriptor<TFamilyId extends string, TTargetId extends string, TAdapterInstance extends ControlAdapterInstance<TFamilyId, TTargetId> = ControlAdapterInstance<TFamilyId, TTargetId>> {
102
- readonly kind: 'adapter';
103
- readonly id: string;
104
- readonly familyId: TFamilyId;
105
- readonly targetId: TTargetId;
106
- readonly manifest: ExtensionPackManifest;
107
- create(): TAdapterInstance;
116
+ interface MigrationPlanner<TFamilyId extends string = string, TTargetId extends string = string> {
117
+ plan(options: {
118
+ readonly contract: unknown;
119
+ readonly schema: unknown;
120
+ readonly policy: MigrationOperationPolicy;
121
+ /**
122
+ * Active framework components participating in this composition.
123
+ * Families/targets can interpret this list to derive family-specific metadata.
124
+ * All components must have matching familyId and targetId.
125
+ */
126
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;
127
+ }): MigrationPlannerResult;
108
128
  }
109
129
  /**
110
- * Descriptor for a control-plane driver pack (e.g., Postgres driver).
130
+ * Migration runner interface for executing migration plans.
131
+ * This is the minimal interface that CLI commands use.
111
132
  *
112
133
  * @template TFamilyId - The family ID (e.g., 'sql', 'document')
113
134
  * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
114
- * @template TDriverInstance - The driver instance type
115
135
  */
116
- interface ControlDriverDescriptor<TFamilyId extends string, TTargetId extends string, TDriverInstance extends ControlDriverInstance<TTargetId> = ControlDriverInstance<TTargetId>> {
117
- readonly kind: 'driver';
118
- readonly id: string;
119
- readonly familyId: TFamilyId;
120
- readonly targetId: TTargetId;
121
- readonly manifest: ExtensionPackManifest;
122
- create(url: string): Promise<TDriverInstance>;
136
+ interface MigrationRunner<TFamilyId extends string = string, TTargetId extends string = string> {
137
+ execute(options: {
138
+ readonly plan: MigrationPlan;
139
+ readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;
140
+ readonly destinationContract: unknown;
141
+ readonly policy: MigrationOperationPolicy;
142
+ readonly callbacks?: {
143
+ onOperationStart?(op: MigrationPlanOperation): void;
144
+ onOperationComplete?(op: MigrationPlanOperation): void;
145
+ };
146
+ /**
147
+ * Active framework components participating in this composition.
148
+ * Families/targets can interpret this list to derive family-specific metadata.
149
+ * All components must have matching familyId and targetId.
150
+ */
151
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;
152
+ }): Promise<MigrationRunnerResult>;
123
153
  }
124
154
  /**
125
- * Descriptor for a control-plane extension pack (e.g., pgvector).
155
+ * Optional capability interface for targets that support migrations.
156
+ * Targets that implement migrations expose this via their descriptor.
126
157
  *
127
158
  * @template TFamilyId - The family ID (e.g., 'sql', 'document')
128
159
  * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
129
- * @template TExtensionInstance - The extension instance type
160
+ * @template TFamilyInstance - The family instance type (e.g., SqlControlFamilyInstance)
130
161
  */
131
- interface ControlExtensionDescriptor<TFamilyId extends string, TTargetId extends string, TExtensionInstance extends ControlExtensionInstance<TFamilyId, TTargetId> = ControlExtensionInstance<TFamilyId, TTargetId>> {
132
- readonly kind: 'extension';
133
- readonly id: string;
134
- readonly familyId: TFamilyId;
135
- readonly targetId: TTargetId;
136
- readonly manifest: ExtensionPackManifest;
137
- create(): TExtensionInstance;
162
+ interface TargetMigrationsCapability<TFamilyId extends string = string, TTargetId extends string = string, TFamilyInstance extends ControlFamilyInstance<TFamilyId> = ControlFamilyInstance<TFamilyId>> {
163
+ createPlanner(family: TFamilyInstance): MigrationPlanner<TFamilyId, TTargetId>;
164
+ createRunner(family: TFamilyInstance): MigrationRunner<TFamilyId, TTargetId>;
138
165
  }
166
+
139
167
  /**
140
- * Family instance interface for control-plane domain actions.
141
- * Each family implements this interface with family-specific types.
168
+ * Control-plane family instance interface.
169
+ * Extends the base FamilyInstance with control-plane domain actions.
170
+ *
171
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
172
+ * @template TSchemaIR - The schema IR type returned by introspect() (family-specific)
142
173
  */
143
- interface FamilyInstance<TFamilyId extends string, TSchemaIR = unknown, TVerifyResult = unknown, TSchemaVerifyResult = unknown, TSignResult = unknown> {
144
- readonly familyId: TFamilyId;
174
+ interface ControlFamilyInstance<TFamilyId extends string, TSchemaIR = unknown> extends FamilyInstance<TFamilyId> {
145
175
  /**
146
176
  * Validates a contract JSON and returns a validated ContractIR (without mappings).
147
177
  * Mappings are runtime-only and should not be part of ContractIR.
178
+ *
179
+ * Note: The returned ContractIR may include additional fields from the emitted contract
180
+ * (like coreHash, profileHash) that are not part of the ContractIR type but are preserved
181
+ * for use by verify/sign operations.
148
182
  */
149
- validateContractIR(contractJson: unknown): unknown;
183
+ validateContractIR(contractJson: unknown): ContractIR;
150
184
  /**
151
185
  * Verifies the database marker against the contract.
152
186
  * Compares target, coreHash, and profileHash.
187
+ *
188
+ * @param options.contractIR - The validated contract (from validateContractIR). Must have
189
+ * coreHash and target fields for verification. These fields are present in emitted
190
+ * contracts but not in the ContractIR type definition.
153
191
  */
154
192
  verify(options: {
155
- readonly driver: ControlDriverInstance;
193
+ readonly driver: ControlDriverInstance<TFamilyId, string>;
156
194
  readonly contractIR: unknown;
157
195
  readonly expectedTargetId: string;
158
196
  readonly contractPath: string;
159
197
  readonly configPath?: string;
160
- }): Promise<TVerifyResult>;
198
+ }): Promise<VerifyDatabaseResult>;
161
199
  /**
162
200
  * Verifies the database schema against the contract.
163
201
  * Compares contract requirements against live database schema.
164
202
  */
165
203
  schemaVerify(options: {
166
- readonly driver: ControlDriverInstance;
204
+ readonly driver: ControlDriverInstance<TFamilyId, string>;
167
205
  readonly contractIR: unknown;
168
206
  readonly strict: boolean;
169
207
  readonly contractPath: string;
170
208
  readonly configPath?: string;
171
- }): Promise<TSchemaVerifyResult>;
209
+ /**
210
+ * Active framework components participating in this composition.
211
+ * All components must have matching familyId and targetId.
212
+ */
213
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, string>>;
214
+ }): Promise<VerifyDatabaseSchemaResult>;
172
215
  /**
173
216
  * Signs the database with the contract marker.
174
217
  * Writes or updates the contract marker if schema verification passes.
175
218
  * This operation is idempotent - if the marker already matches, no changes are made.
176
219
  */
177
220
  sign(options: {
178
- readonly driver: ControlDriverInstance;
221
+ readonly driver: ControlDriverInstance<TFamilyId, string>;
179
222
  readonly contractIR: unknown;
180
223
  readonly contractPath: string;
181
224
  readonly configPath?: string;
182
- }): Promise<TSignResult>;
225
+ }): Promise<SignDatabaseResult>;
226
+ /**
227
+ * Reads the contract marker from the database.
228
+ * Returns null if no marker exists.
229
+ */
230
+ readMarker(options: {
231
+ readonly driver: ControlDriverInstance<TFamilyId, string>;
232
+ }): Promise<ContractMarkerRecord | null>;
183
233
  /**
184
234
  * Introspects the database schema and returns a family-specific schema IR.
185
235
  *
@@ -189,15 +239,15 @@ interface FamilyInstance<TFamilyId extends string, TSchemaIR = unknown, TVerifyR
189
239
  *
190
240
  * @param options - Introspection options
191
241
  * @param options.driver - Control plane driver for database connection
192
- * @param options.contractIR - Optional contract IR for contract-guided introspection.
242
+ * @param options.contractIR - Optional contract for contract-guided introspection.
193
243
  * When provided, families may use it for filtering, optimization, or validation
194
- * during introspection. The contract IR does not change the meaning of "what exists"
244
+ * during introspection. The contract does not change the meaning of "what exists"
195
245
  * in the database - it only guides how introspection is performed.
196
246
  * @returns Promise resolving to the family-specific Schema IR (e.g., `SqlSchemaIR` for SQL).
197
247
  * The IR represents the complete schema snapshot at the time of introspection.
198
248
  */
199
249
  introspect(options: {
200
- readonly driver: ControlDriverInstance;
250
+ readonly driver: ControlDriverInstance<TFamilyId, string>;
201
251
  readonly contractIR?: unknown;
202
252
  }): Promise<TSchemaIR>;
203
253
  /**
@@ -215,6 +265,146 @@ interface FamilyInstance<TFamilyId extends string, TSchemaIR = unknown, TVerifyR
215
265
  readonly contractIR: ContractIR | unknown;
216
266
  }): Promise<EmitContractResult>;
217
267
  }
268
+ /**
269
+ * Control-plane target instance interface.
270
+ * Extends the base TargetInstance with control-plane specific behavior.
271
+ *
272
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
273
+ * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
274
+ */
275
+ interface ControlTargetInstance<TFamilyId extends string, TTargetId extends string> extends TargetInstance<TFamilyId, TTargetId> {
276
+ }
277
+ /**
278
+ * Control-plane adapter instance interface.
279
+ * Extends the base AdapterInstance with control-plane specific behavior.
280
+ * Families extend this with family-specific adapter interfaces.
281
+ *
282
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
283
+ * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
284
+ */
285
+ interface ControlAdapterInstance<TFamilyId extends string, TTargetId extends string> extends AdapterInstance<TFamilyId, TTargetId> {
286
+ }
287
+ /**
288
+ * Control-plane driver instance interface.
289
+ * Extends the base DriverInstance with control-plane specific behavior.
290
+ *
291
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
292
+ * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
293
+ */
294
+ interface ControlDriverInstance<TFamilyId extends string, TTargetId extends string> extends DriverInstance<TFamilyId, TTargetId> {
295
+ query<Row = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<{
296
+ readonly rows: Row[];
297
+ }>;
298
+ close(): Promise<void>;
299
+ }
300
+ /**
301
+ * Control-plane extension instance interface.
302
+ * Extends the base ExtensionInstance with control-plane specific behavior.
303
+ *
304
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
305
+ * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
306
+ */
307
+ interface ControlExtensionInstance<TFamilyId extends string, TTargetId extends string> extends ExtensionInstance<TFamilyId, TTargetId> {
308
+ }
309
+ /**
310
+ * Operation context for propagating metadata through control-plane operation call chains.
311
+ * Inspired by OpenTelemetry's Context and Sentry's Scope patterns.
312
+ *
313
+ * This context carries informational metadata (like file paths) that can be used for
314
+ * error reporting, logging, and debugging, but is not required for structural correctness.
315
+ * It allows subsystems to propagate context without coupling to file I/O concerns.
316
+ *
317
+ * @example
318
+ * ```typescript
319
+ * const context: OperationContext = {
320
+ * contractPath: './contract.json',
321
+ * configPath: './prisma-next.config.ts',
322
+ * };
323
+ *
324
+ * await runner.execute({ plan, driver, destinationContract: contract, context });
325
+ * ```
326
+ */
327
+ interface OperationContext {
328
+ /**
329
+ * Path to the contract file (if applicable).
330
+ * Used for error reporting and metadata, not for file I/O.
331
+ */
332
+ readonly contractPath?: string;
333
+ /**
334
+ * Path to the configuration file (if applicable).
335
+ * Used for error reporting and metadata, not for file I/O.
336
+ */
337
+ readonly configPath?: string;
338
+ /**
339
+ * Additional metadata that can be propagated through the call chain.
340
+ * Extensible for future needs without breaking changes.
341
+ */
342
+ readonly meta?: Readonly<Record<string, unknown>>;
343
+ }
344
+ /**
345
+ * Descriptor for a control-plane family (e.g., SQL).
346
+ * Provides the family hook and factory method.
347
+ *
348
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
349
+ * @template TFamilyInstance - The family instance type
350
+ */
351
+ interface ControlFamilyDescriptor<TFamilyId extends string, TFamilyInstance extends ControlFamilyInstance<TFamilyId> = ControlFamilyInstance<TFamilyId>> extends FamilyDescriptor<TFamilyId> {
352
+ readonly hook: TargetFamilyHook;
353
+ create<TTargetId extends string>(options: {
354
+ readonly target: ControlTargetDescriptor<TFamilyId, TTargetId>;
355
+ readonly adapter: ControlAdapterDescriptor<TFamilyId, TTargetId>;
356
+ readonly driver: ControlDriverDescriptor<TFamilyId, TTargetId>;
357
+ readonly extensions: readonly ControlExtensionDescriptor<TFamilyId, TTargetId>[];
358
+ }): TFamilyInstance;
359
+ }
360
+ /**
361
+ * Descriptor for a control-plane target component (e.g., Postgres target).
362
+ *
363
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
364
+ * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
365
+ * @template TTargetInstance - The target instance type
366
+ * @template TFamilyInstance - The family instance type for migrations (optional)
367
+ */
368
+ interface ControlTargetDescriptor<TFamilyId extends string, TTargetId extends string, TTargetInstance extends ControlTargetInstance<TFamilyId, TTargetId> = ControlTargetInstance<TFamilyId, TTargetId>, TFamilyInstance extends ControlFamilyInstance<TFamilyId> = ControlFamilyInstance<TFamilyId>> extends TargetDescriptor<TFamilyId, TTargetId> {
369
+ /**
370
+ * Optional migrations capability.
371
+ * Targets that support migrations expose this property.
372
+ * The capability is parameterized by family and target IDs to ensure type-level
373
+ * compatibility of framework components.
374
+ */
375
+ readonly migrations?: TargetMigrationsCapability<TFamilyId, TTargetId, TFamilyInstance>;
376
+ create(): TTargetInstance;
377
+ }
378
+ /**
379
+ * Descriptor for a control-plane adapter component (e.g., Postgres adapter).
380
+ *
381
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
382
+ * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
383
+ * @template TAdapterInstance - The adapter instance type
384
+ */
385
+ interface ControlAdapterDescriptor<TFamilyId extends string, TTargetId extends string, TAdapterInstance extends ControlAdapterInstance<TFamilyId, TTargetId> = ControlAdapterInstance<TFamilyId, TTargetId>> extends AdapterDescriptor<TFamilyId, TTargetId> {
386
+ create(): TAdapterInstance;
387
+ }
388
+ /**
389
+ * Descriptor for a control-plane driver component (e.g., Postgres driver).
390
+ *
391
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
392
+ * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
393
+ * @template TDriverInstance - The driver instance type
394
+ */
395
+ interface ControlDriverDescriptor<TFamilyId extends string, TTargetId extends string, TDriverInstance extends ControlDriverInstance<TFamilyId, TTargetId> = ControlDriverInstance<TFamilyId, TTargetId>> extends DriverDescriptor<TFamilyId, TTargetId> {
396
+ create(url: string): Promise<TDriverInstance>;
397
+ }
398
+ /**
399
+ * Descriptor for a control-plane extension component (e.g., pgvector).
400
+ *
401
+ * @template TFamilyId - The family ID (e.g., 'sql', 'document')
402
+ * @template TTargetId - The target ID (e.g., 'postgres', 'mysql')
403
+ * @template TExtensionInstance - The extension instance type
404
+ */
405
+ interface ControlExtensionDescriptor<TFamilyId extends string, TTargetId extends string, TExtensionInstance extends ControlExtensionInstance<TFamilyId, TTargetId> = ControlExtensionInstance<TFamilyId, TTargetId>> extends ExtensionDescriptor<TFamilyId, TTargetId> {
406
+ create(): TExtensionInstance;
407
+ }
218
408
  /**
219
409
  * Result type for database marker verification operations.
220
410
  */
@@ -248,7 +438,7 @@ interface VerifyDatabaseResult {
248
438
  * Schema issue type for schema verification results.
249
439
  */
250
440
  interface SchemaIssue {
251
- readonly kind: 'missing_table' | 'missing_column' | 'type_mismatch' | 'nullability_mismatch' | 'primary_key_mismatch' | 'foreign_key_mismatch' | 'unique_constraint_mismatch' | 'index_mismatch' | 'extension_missing';
441
+ readonly kind: 'missing_table' | 'missing_column' | 'extra_table' | 'extra_column' | 'extra_primary_key' | 'extra_foreign_key' | 'extra_unique_constraint' | 'extra_index' | 'type_mismatch' | 'nullability_mismatch' | 'primary_key_mismatch' | 'foreign_key_mismatch' | 'unique_constraint_mismatch' | 'index_mismatch' | 'extension_missing';
252
442
  readonly table: string;
253
443
  readonly column?: string;
254
444
  readonly indexOrConstraint?: string;
@@ -298,7 +488,7 @@ interface VerifyDatabaseSchemaResult {
298
488
  };
299
489
  readonly meta?: {
300
490
  readonly configPath?: string;
301
- readonly contractPath: string;
491
+ readonly contractPath?: string;
302
492
  readonly strict: boolean;
303
493
  };
304
494
  readonly timings: {
@@ -320,7 +510,7 @@ interface EmitContractResult {
320
510
  *
321
511
  * @template TSchemaIR - The family-specific Schema IR type (e.g., `SqlSchemaIR` for SQL)
322
512
  */
323
- interface IntrospectSchemaResult<TSchemaIR = unknown> {
513
+ interface IntrospectSchemaResult<TSchemaIR> {
324
514
  readonly ok: true;
325
515
  readonly summary: string;
326
516
  readonly target: {
@@ -368,4 +558,4 @@ interface SignDatabaseResult {
368
558
  };
369
559
  }
370
560
 
371
- export type { ControlAdapterDescriptor, ControlAdapterInstance, ControlDriverDescriptor, ControlDriverInstance, ControlExtensionDescriptor, ControlExtensionInstance, ControlFamilyDescriptor, ControlFamilyInstance, ControlTargetDescriptor, ControlTargetInstance, EmitContractResult, FamilyInstance, IntrospectSchemaResult, SchemaIssue, SchemaVerificationNode, SignDatabaseResult, VerifyDatabaseResult, VerifyDatabaseSchemaResult };
561
+ export type { ControlAdapterDescriptor, ControlAdapterInstance, ControlDriverDescriptor, ControlDriverInstance, ControlExtensionDescriptor, ControlExtensionInstance, ControlFamilyDescriptor, ControlFamilyInstance, ControlTargetDescriptor, ControlTargetInstance, EmitContractResult, IntrospectSchemaResult, MigrationOperationClass, MigrationOperationPolicy, MigrationPlan, MigrationPlanOperation, MigrationPlanner, MigrationPlannerConflict, MigrationPlannerFailureResult, MigrationPlannerResult, MigrationPlannerSuccessResult, MigrationRunner, MigrationRunnerFailure, MigrationRunnerResult, MigrationRunnerSuccessValue, OperationContext, SchemaIssue, SchemaVerificationNode, SignDatabaseResult, TargetMigrationsCapability, VerifyDatabaseResult, VerifyDatabaseSchemaResult };
package/package.json CHANGED
@@ -1,19 +1,20 @@
1
1
  {
2
2
  "name": "@prisma-next/core-control-plane",
3
- "version": "0.1.0-dev.2",
3
+ "version": "0.1.0-dev.21",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "Control plane domain actions, config types, validation, and error factories for Prisma Next",
7
7
  "dependencies": {
8
8
  "arktype": "^2.1.26",
9
9
  "prettier": "^3.3.3",
10
- "@prisma-next/operations": "0.1.0-dev.2",
11
- "@prisma-next/contract": "0.1.0-dev.2"
10
+ "@prisma-next/contract": "0.1.0-dev.21",
11
+ "@prisma-next/operations": "0.1.0-dev.21",
12
+ "@prisma-next/utils": "0.1.0-dev.21"
12
13
  },
13
14
  "devDependencies": {
14
15
  "tsup": "^8.3.0",
15
16
  "typescript": "^5.9.3",
16
- "vitest": "^2.1.1",
17
+ "vitest": "^4.0.16",
17
18
  "@prisma-next/test-utils": "0.0.1"
18
19
  },
19
20
  "files": [
@@ -50,7 +51,9 @@
50
51
  "test": "vitest run --passWithNoTests",
51
52
  "test:coverage": "vitest run --coverage --passWithNoTests",
52
53
  "typecheck": "tsc --project tsconfig.json --noEmit",
53
- "lint": "biome check . --config-path ../../../biome.json --error-on-warnings",
54
- "clean": "node ../../../scripts/clean.mjs"
54
+ "lint": "biome check . --config-path ../../../../../biome.json --error-on-warnings",
55
+ "lint:fix": "biome check --write . --config-path ../../../biome.json",
56
+ "lint:fix:unsafe": "biome check --write --unsafe . --config-path ../../../biome.json",
57
+ "clean": "node ../../../../../scripts/clean.mjs"
55
58
  }
56
59
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/**\n * CLI error envelope for output formatting.\n * This is the serialized form of a CliStructuredError.\n */\nexport interface CliErrorEnvelope {\n readonly code: string;\n readonly domain: string;\n readonly severity: 'error' | 'warn' | 'info';\n readonly summary: string;\n readonly why: string | undefined;\n readonly fix: string | undefined;\n readonly where:\n | {\n readonly path: string | undefined;\n readonly line: number | undefined;\n }\n | undefined;\n readonly meta: Record<string, unknown> | undefined;\n readonly docsUrl: string | undefined;\n}\n\n/**\n * Structured CLI error that contains all information needed for error envelopes.\n * Call sites throw these errors with full context.\n */\nexport class CliStructuredError extends Error {\n readonly code: string;\n readonly domain: 'CLI' | 'RTM';\n readonly severity: 'error' | 'warn' | 'info';\n readonly why: string | undefined;\n readonly fix: string | undefined;\n readonly where:\n | {\n readonly path: string | undefined;\n readonly line: number | undefined;\n }\n | undefined;\n readonly meta: Record<string, unknown> | undefined;\n readonly docsUrl: string | undefined;\n\n constructor(\n code: string,\n summary: string,\n options?: {\n readonly domain?: 'CLI' | 'RTM';\n readonly severity?: 'error' | 'warn' | 'info';\n readonly why?: string;\n readonly fix?: string;\n readonly where?: { readonly path?: string; readonly line?: number };\n readonly meta?: Record<string, unknown>;\n readonly docsUrl?: string;\n },\n ) {\n super(summary);\n this.name = 'CliStructuredError';\n this.code = code;\n this.domain = options?.domain ?? 'CLI';\n this.severity = options?.severity ?? 'error';\n this.why = options?.why;\n this.fix = options?.fix;\n this.where = options?.where\n ? {\n path: options.where.path,\n line: options.where.line,\n }\n : undefined;\n this.meta = options?.meta;\n this.docsUrl = options?.docsUrl;\n }\n\n /**\n * Converts this error to a CLI error envelope for output formatting.\n */\n toEnvelope(): CliErrorEnvelope {\n const codePrefix = this.domain === 'CLI' ? 'PN-CLI-' : 'PN-RTM-';\n return {\n code: `${codePrefix}${this.code}`,\n domain: this.domain,\n severity: this.severity,\n summary: this.message,\n why: this.why,\n fix: this.fix,\n where: this.where,\n meta: this.meta,\n docsUrl: this.docsUrl,\n };\n }\n}\n\n// ============================================================================\n// Config Errors (PN-CLI-4001-4007)\n// ============================================================================\n\n/**\n * Config file not found or missing.\n */\nexport function errorConfigFileNotFound(\n configPath?: string,\n options?: {\n readonly why?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('4001', 'Config file not found', {\n domain: 'CLI',\n ...(options?.why ? { why: options.why } : { why: 'Config file not found' }),\n fix: \"Run 'prisma-next init' to create a config file\",\n docsUrl: 'https://prisma-next.dev/docs/cli/config',\n ...(configPath ? { where: { path: configPath } } : {}),\n });\n}\n\n/**\n * Contract configuration missing from config.\n */\nexport function errorContractConfigMissing(options?: {\n readonly why?: string;\n}): CliStructuredError {\n return new CliStructuredError('4002', 'Contract configuration missing', {\n domain: 'CLI',\n why: options?.why ?? 'The contract configuration is required for emit',\n fix: 'Add contract configuration to your prisma-next.config.ts',\n docsUrl: 'https://prisma-next.dev/docs/cli/contract-emit',\n });\n}\n\n/**\n * Contract validation failed.\n */\nexport function errorContractValidationFailed(\n reason: string,\n options?: {\n readonly where?: { readonly path?: string; readonly line?: number };\n },\n): CliStructuredError {\n return new CliStructuredError('4003', 'Contract validation failed', {\n domain: 'CLI',\n why: reason,\n fix: 'Check your contract file for errors',\n docsUrl: 'https://prisma-next.dev/docs/contracts',\n ...(options?.where ? { where: options.where } : {}),\n });\n}\n\n/**\n * File not found.\n */\nexport function errorFileNotFound(\n filePath: string,\n options?: {\n readonly why?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('4004', 'File not found', {\n domain: 'CLI',\n why: options?.why ?? `File not found: ${filePath}`,\n fix: 'Check that the file path is correct',\n where: { path: filePath },\n });\n}\n\n/**\n * Database URL is required but not provided.\n */\nexport function errorDatabaseUrlRequired(options?: { readonly why?: string }): CliStructuredError {\n return new CliStructuredError('4005', 'Database URL is required', {\n domain: 'CLI',\n why: options?.why ?? 'Database URL is required for db verify',\n fix: 'Provide --db flag or config.db.url in prisma-next.config.ts',\n });\n}\n\n/**\n * Query runner factory is required but not provided in config.\n */\nexport function errorQueryRunnerFactoryRequired(options?: {\n readonly why?: string;\n}): CliStructuredError {\n return new CliStructuredError('4006', 'Query runner factory is required', {\n domain: 'CLI',\n why: options?.why ?? 'Config.db.queryRunnerFactory is required for db verify',\n fix: 'Add db.queryRunnerFactory to prisma-next.config.ts',\n docsUrl: 'https://prisma-next.dev/docs/cli/db-verify',\n });\n}\n\n/**\n * Family verify.readMarker is required but not provided.\n */\nexport function errorFamilyReadMarkerSqlRequired(options?: {\n readonly why?: string;\n}): CliStructuredError {\n return new CliStructuredError('4007', 'Family readMarker() is required', {\n domain: 'CLI',\n why: options?.why ?? 'Family verify.readMarker is required for db verify',\n fix: 'Ensure family.verify.readMarker() is exported by your family package',\n docsUrl: 'https://prisma-next.dev/docs/cli/db-verify',\n });\n}\n\n/**\n * Driver is required for DB-connected commands but not provided.\n */\nexport function errorDriverRequired(options?: { readonly why?: string }): CliStructuredError {\n return new CliStructuredError('4010', 'Driver is required for DB-connected commands', {\n domain: 'CLI',\n why: options?.why ?? 'Config.driver is required for db verify',\n fix: 'Add driver to prisma-next.config.ts',\n docsUrl: 'https://prisma-next.dev/docs/cli/db-verify',\n });\n}\n\n/**\n * Config validation error (missing required fields).\n */\nexport function errorConfigValidation(\n field: string,\n options?: {\n readonly why?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('4001', 'Config file not found', {\n domain: 'CLI',\n why: options?.why ?? `Config must have a \"${field}\" field`,\n fix: \"Run 'prisma-next init' to create a config file\",\n docsUrl: 'https://prisma-next.dev/docs/cli/config',\n });\n}\n\n// ============================================================================\n// Runtime Errors (PN-RTM-3000-3003)\n// ============================================================================\n\n/**\n * Contract marker not found in database.\n */\nexport function errorMarkerMissing(options?: {\n readonly why?: string;\n readonly dbUrl?: string;\n}): CliStructuredError {\n return new CliStructuredError('3001', 'Marker missing', {\n domain: 'RTM',\n why: options?.why ?? 'Contract marker not found in database',\n fix: 'Run `prisma-next db sign --db <url>` to create marker',\n });\n}\n\n/**\n * Contract hash does not match database marker.\n */\nexport function errorHashMismatch(options?: {\n readonly why?: string;\n readonly expected?: string;\n readonly actual?: string;\n}): CliStructuredError {\n return new CliStructuredError('3002', 'Hash mismatch', {\n domain: 'RTM',\n why: options?.why ?? 'Contract hash does not match database marker',\n fix: 'Migrate database or re-sign if intentional',\n ...(options?.expected || options?.actual\n ? {\n meta: {\n ...(options.expected ? { expected: options.expected } : {}),\n ...(options.actual ? { actual: options.actual } : {}),\n },\n }\n : {}),\n });\n}\n\n/**\n * Contract target does not match config target.\n */\nexport function errorTargetMismatch(\n expected: string,\n actual: string,\n options?: {\n readonly why?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('3003', 'Target mismatch', {\n domain: 'RTM',\n why:\n options?.why ??\n `Contract target does not match config target (expected: ${expected}, actual: ${actual})`,\n fix: 'Align contract target and config target',\n meta: { expected, actual },\n });\n}\n\n/**\n * Generic runtime error.\n */\nexport function errorRuntime(\n summary: string,\n options?: {\n readonly why?: string;\n readonly fix?: string;\n readonly meta?: Record<string, unknown>;\n },\n): CliStructuredError {\n return new CliStructuredError('3000', summary, {\n domain: 'RTM',\n ...(options?.why ? { why: options.why } : { why: 'Verification failed' }),\n ...(options?.fix ? { fix: options.fix } : { fix: 'Check contract and database state' }),\n ...(options?.meta ? { meta: options.meta } : {}),\n });\n}\n\n// ============================================================================\n// Generic Error\n// ============================================================================\n\n/**\n * Generic unexpected error.\n */\nexport function errorUnexpected(\n message: string,\n options?: {\n readonly why?: string;\n readonly fix?: string;\n },\n): CliStructuredError {\n return new CliStructuredError('4999', 'Unexpected error', {\n domain: 'CLI',\n why: options?.why ?? message,\n fix: options?.fix ?? 'Check the error message and try again',\n });\n}\n"],"mappings":";AAyBO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAMA;AAAA,EACA;AAAA,EAET,YACE,MACA,SACA,SASA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS,SAAS,UAAU;AACjC,SAAK,WAAW,SAAS,YAAY;AACrC,SAAK,MAAM,SAAS;AACpB,SAAK,MAAM,SAAS;AACpB,SAAK,QAA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