@prisma-next/family-sql 0.5.0-dev.9 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +2 -3
  2. package/dist/{authoring-type-constructors-BAR65pSK.mjs → authoring-type-constructors-F4JpCJl7.mjs} +14 -15
  3. package/dist/authoring-type-constructors-F4JpCJl7.mjs.map +1 -0
  4. package/dist/control-adapter.d.mts +26 -2
  5. package/dist/control-adapter.d.mts.map +1 -1
  6. package/dist/control-adapter.mjs +1 -1
  7. package/dist/control.d.mts +125 -45
  8. package/dist/control.d.mts.map +1 -1
  9. package/dist/control.mjs +1174 -54
  10. package/dist/control.mjs.map +1 -1
  11. package/dist/migration.d.mts +22 -24
  12. package/dist/migration.d.mts.map +1 -1
  13. package/dist/migration.mjs +25 -24
  14. package/dist/migration.mjs.map +1 -1
  15. package/dist/pack.d.mts +35 -23
  16. package/dist/pack.d.mts.map +1 -1
  17. package/dist/pack.mjs +3 -5
  18. package/dist/pack.mjs.map +1 -1
  19. package/dist/runtime.d.mts +19 -2
  20. package/dist/runtime.d.mts.map +1 -1
  21. package/dist/runtime.mjs +26 -4
  22. package/dist/runtime.mjs.map +1 -1
  23. package/dist/schema-verify.d.mts +4 -15
  24. package/dist/schema-verify.d.mts.map +1 -1
  25. package/dist/schema-verify.mjs +2 -3
  26. package/dist/test-utils.d.mts +2 -2
  27. package/dist/test-utils.mjs +2 -3
  28. package/dist/timestamp-now-generator-BWp8S2sa.mjs +86 -0
  29. package/dist/timestamp-now-generator-BWp8S2sa.mjs.map +1 -0
  30. package/dist/types-mhjAPuMn.d.mts +470 -0
  31. package/dist/types-mhjAPuMn.d.mts.map +1 -0
  32. package/dist/verify-pRYxnpiG.mjs +81 -0
  33. package/dist/verify-pRYxnpiG.mjs.map +1 -0
  34. package/dist/{verify-sql-schema-Ovz7RXR5.mjs → verify-sql-schema-1tDh3x5x.mjs} +18 -72
  35. package/dist/verify-sql-schema-1tDh3x5x.mjs.map +1 -0
  36. package/dist/{verify-sql-schema-BBhkqEDo.d.mts → verify-sql-schema-CPHiuYHR.d.mts} +2 -3
  37. package/dist/verify-sql-schema-CPHiuYHR.d.mts.map +1 -0
  38. package/dist/verify.d.mts +16 -21
  39. package/dist/verify.d.mts.map +1 -1
  40. package/dist/verify.mjs +2 -3
  41. package/package.json +23 -21
  42. package/src/core/authoring-field-presets.ts +35 -23
  43. package/src/core/control-adapter.ts +32 -0
  44. package/src/core/control-descriptor.ts +2 -1
  45. package/src/core/control-instance.ts +117 -30
  46. package/src/core/migrations/contract-to-schema-ir.ts +4 -29
  47. package/src/core/migrations/field-event-planner.ts +194 -0
  48. package/src/core/migrations/plan-helpers.ts +4 -0
  49. package/src/core/migrations/types.ts +207 -59
  50. package/src/core/operation-preview.ts +62 -0
  51. package/src/core/psl-contract-infer/default-mapping.ts +56 -0
  52. package/src/core/psl-contract-infer/name-transforms.ts +178 -0
  53. package/src/core/psl-contract-infer/postgres-default-mapping.ts +16 -0
  54. package/src/core/psl-contract-infer/postgres-type-map.ts +165 -0
  55. package/src/core/psl-contract-infer/printer-config.ts +55 -0
  56. package/src/core/psl-contract-infer/raw-default-parser.ts +91 -0
  57. package/src/core/psl-contract-infer/relation-inference.ts +196 -0
  58. package/src/core/psl-contract-infer/sql-schema-ir-to-psl-ast.ts +832 -0
  59. package/src/core/schema-verify/verify-helpers.ts +47 -70
  60. package/src/core/schema-verify/verify-sql-schema.ts +1 -6
  61. package/src/core/sql-migration.ts +25 -23
  62. package/src/core/timestamp-now-generator.ts +74 -0
  63. package/src/core/timestamp-now-runtime-generator.ts +24 -0
  64. package/src/core/verify.ts +46 -108
  65. package/src/exports/control.ts +11 -4
  66. package/src/exports/runtime.ts +2 -0
  67. package/src/exports/schema-verify.ts +0 -1
  68. package/src/exports/test-utils.ts +0 -1
  69. package/src/exports/verify.ts +1 -1
  70. package/dist/authoring-type-constructors-BAR65pSK.mjs.map +0 -1
  71. package/dist/types-C6K4mxDM.d.mts +0 -301
  72. package/dist/types-C6K4mxDM.d.mts.map +0 -1
  73. package/dist/verify-4GshvY4p.mjs +0 -122
  74. package/dist/verify-4GshvY4p.mjs.map +0 -1
  75. package/dist/verify-sql-schema-BBhkqEDo.d.mts.map +0 -1
  76. package/dist/verify-sql-schema-Ovz7RXR5.mjs.map +0 -1
@@ -0,0 +1,470 @@
1
+ import { ContractSpace, ControlAdapterDescriptor, ControlDriverInstance, ControlExtensionDescriptor, ControlFamilyInstance, ControlStack, MigratableTargetDescriptor, MigrationOperationPolicy, MigrationPlan, MigrationPlanOperation, MigrationPlannerConflict, MigrationPlannerFailureResult, MigrationPlannerSuccessResult, MigrationRunnerExecutionChecks, MigrationRunnerFailure, MigrationRunnerSuccessValue, OpFactoryCall, OperationContext, OperationPreview, OperationPreviewCapable, PslContractInferCapable, SchemaIssue, SchemaViewCapable, SignDatabaseResult, VerifyDatabaseResult, VerifyDatabaseSchemaResult } from "@prisma-next/framework-components/control";
2
+ import { Result } from "@prisma-next/utils/result";
3
+ import { Contract } from "@prisma-next/contract/types";
4
+ import { SqlSchemaIR } from "@prisma-next/sql-schema-ir/types";
5
+ import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";
6
+ import { SqlStorage, StorageColumn, StorageTable, StorageTypeInstance } from "@prisma-next/sql-contract/types";
7
+ import { TypesImportSpec } from "@prisma-next/framework-components/emission";
8
+ import { PslDocumentAst } from "@prisma-next/framework-components/psl-ast";
9
+ import { SqlOperationDescriptors } from "@prisma-next/sql-operations";
10
+
11
+ //#region src/core/control-instance.d.ts
12
+ interface SqlTypeMetadata {
13
+ readonly typeId: string;
14
+ readonly familyId: 'sql';
15
+ readonly targetId: string;
16
+ readonly nativeType?: string;
17
+ }
18
+ type SqlTypeMetadataRegistry = Map<string, SqlTypeMetadata>;
19
+ interface SqlFamilyInstanceState {
20
+ readonly codecTypeImports: ReadonlyArray<TypesImportSpec>;
21
+ readonly extensionIds: ReadonlyArray<string>;
22
+ readonly typeMetadataRegistry: SqlTypeMetadataRegistry;
23
+ }
24
+ interface SchemaVerifyOptions {
25
+ readonly driver: ControlDriverInstance<'sql', string>;
26
+ readonly contract: unknown;
27
+ readonly strict: boolean;
28
+ readonly context?: OperationContext;
29
+ /**
30
+ * Active framework components participating in this composition.
31
+ * All components must have matching familyId ('sql') and targetId.
32
+ */
33
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
34
+ }
35
+ interface SqlControlFamilyInstance extends ControlFamilyInstance<'sql', SqlSchemaIR>, SchemaViewCapable<SqlSchemaIR>, PslContractInferCapable<SqlSchemaIR>, OperationPreviewCapable, SqlFamilyInstanceState {
36
+ validateContract(contractJson: unknown): Contract;
37
+ verify(options: {
38
+ readonly driver: ControlDriverInstance<'sql', string>;
39
+ readonly contract: unknown;
40
+ readonly expectedTargetId: string;
41
+ readonly contractPath: string;
42
+ readonly configPath?: string;
43
+ }): Promise<VerifyDatabaseResult>;
44
+ schemaVerify(options: SchemaVerifyOptions): Promise<VerifyDatabaseSchemaResult>;
45
+ /**
46
+ * Verify a contract against an already-introspected schema slice.
47
+ *
48
+ * Used by the aggregate verifier to invoke per-member verification
49
+ * with the live schema pre-projected to the member's claimed slice
50
+ * via `projectSchemaToSpace`. Closes F23 — without per-member
51
+ * pre-projection, single-contract verifiers see other-space tables
52
+ * as `extras`.
53
+ */
54
+ schemaVerifyAgainstSchema(options: {
55
+ readonly contract: unknown;
56
+ readonly schema: SqlSchemaIR;
57
+ readonly strict: boolean;
58
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
59
+ }): VerifyDatabaseSchemaResult;
60
+ sign(options: {
61
+ readonly driver: ControlDriverInstance<'sql', string>;
62
+ readonly contract: unknown;
63
+ readonly contractPath: string;
64
+ readonly configPath?: string;
65
+ }): Promise<SignDatabaseResult>;
66
+ introspect(options: {
67
+ readonly driver: ControlDriverInstance<'sql', string>;
68
+ readonly contract?: unknown;
69
+ }): Promise<SqlSchemaIR>;
70
+ inferPslContract(schemaIR: SqlSchemaIR): PslDocumentAst;
71
+ toOperationPreview(operations: readonly MigrationPlanOperation[]): OperationPreview;
72
+ }
73
+ //#endregion
74
+ //#region src/core/migrations/types.d.ts
75
+ type AnyRecord = Readonly<Record<string, unknown>>;
76
+ interface StorageTypePlanResult<TTargetDetails> {
77
+ readonly operations: readonly SqlMigrationPlanOperation<TTargetDetails>[];
78
+ }
79
+ /**
80
+ * Input for expanding parameterized native types.
81
+ */
82
+ interface ExpandNativeTypeInput {
83
+ readonly nativeType: string;
84
+ readonly codecId?: string;
85
+ readonly typeParams?: Record<string, unknown>;
86
+ }
87
+ /**
88
+ * Input for resolving an identity-value SQL literal used to backfill existing rows when
89
+ * adding a NOT NULL column without an explicit default.
90
+ *
91
+ * "Identity value" in the algebraic (monoid) sense: the neutral element for the type
92
+ * (0 for numbers, '' for strings, false for booleans, etc.).
93
+ */
94
+ interface ResolveIdentityValueInput {
95
+ readonly nativeType: string;
96
+ readonly codecId?: string;
97
+ readonly typeParams?: Record<string, unknown>;
98
+ }
99
+ /**
100
+ * Per-field lifecycle event a codec hook can react to.
101
+ *
102
+ * Fired during app-space migration emission as the SQL family diffs the
103
+ * prior contract against the new contract. See
104
+ * `docs/architecture docs/adrs/ADR 213 - Codec lifecycle hooks.md`
105
+ * for the wiring contract.
106
+ *
107
+ * - `'added'` — the field is present in the new contract but not the prior.
108
+ * - `'dropped'` — the field is present in the prior contract but not the new.
109
+ * - `'altered'` — the field is present in both and any property other than
110
+ * `codecId` differs. Codec-id changes are a v1 non-goal:
111
+ * when only `codecId` differs, no `'altered'` event fires.
112
+ */
113
+ type FieldEvent = 'added' | 'dropped' | 'altered';
114
+ /**
115
+ * Context passed to {@link CodecControlHooks.onFieldEvent}.
116
+ *
117
+ * `tableName` and `fieldName` are always populated; `priorTable` /
118
+ * `priorField` carry the prior contract's view of the table and column
119
+ * (present for `'dropped'` and `'altered'`); `newTable` / `newField`
120
+ * carry the new contract's view (present for `'added'` and `'altered'`).
121
+ *
122
+ * The hook only ever receives app-space contract IR — extension-space
123
+ * fields are scoped out by the API: the hook is wired at the
124
+ * application emitter only.
125
+ */
126
+ interface FieldEventContext {
127
+ readonly tableName: string;
128
+ readonly fieldName: string;
129
+ readonly priorTable?: StorageTable;
130
+ readonly newTable?: StorageTable;
131
+ readonly priorField?: StorageColumn;
132
+ readonly newField?: StorageColumn;
133
+ }
134
+ interface CodecControlHooks<TTargetDetails = unknown> {
135
+ planTypeOperations?: (options: {
136
+ readonly typeName: string;
137
+ readonly typeInstance: StorageTypeInstance;
138
+ readonly contract: Contract<SqlStorage>;
139
+ readonly schema: SqlSchemaIR;
140
+ readonly schemaName?: string;
141
+ readonly policy: MigrationOperationPolicy;
142
+ }) => StorageTypePlanResult<TTargetDetails>;
143
+ verifyType?: (options: {
144
+ readonly typeName: string;
145
+ readonly typeInstance: StorageTypeInstance;
146
+ readonly schema: SqlSchemaIR;
147
+ readonly schemaName?: string;
148
+ }) => readonly SchemaIssue[];
149
+ introspectTypes?: (options: {
150
+ readonly driver: ControlDriverInstance<'sql', string>;
151
+ readonly schemaName?: string;
152
+ }) => Promise<Record<string, StorageTypeInstance>>;
153
+ /**
154
+ * Expands a parameterized native type to its full SQL representation.
155
+ * Used by schema verification to compare contract types against database types.
156
+ *
157
+ * For example, expands:
158
+ * - { nativeType: 'character varying', typeParams: { length: 255 } } -> 'character varying(255)'
159
+ * - { nativeType: 'numeric', typeParams: { precision: 10, scale: 2 } } -> 'numeric(10,2)'
160
+ *
161
+ * Returns the expanded type string, or the original nativeType if no expansion is needed.
162
+ */
163
+ expandNativeType?: (input: ExpandNativeTypeInput) => string;
164
+ /**
165
+ * Resolves the identity value (monoid neutral element) as a SQL literal for safely adding
166
+ * a NOT NULL column without an explicit default to a non-empty table.
167
+ *
168
+ * Return semantics:
169
+ * - string: use this literal
170
+ * - null: explicitly no safe identity value is known; fall back to another strategy
171
+ * - undefined: no opinion; planner may use built-in fallbacks
172
+ */
173
+ resolveIdentityValue?: (input: ResolveIdentityValueInput) => string | null | undefined;
174
+ /**
175
+ * Reacts to per-field added / dropped / altered events as the app-space
176
+ * emitter diffs the prior contract against the new contract. Returned
177
+ * ops are inlined into the app-space migration's `ops.json` alongside
178
+ * the user's structural ops.
179
+ *
180
+ * Synchronous. Each returned op must carry its own `invariantId`. Hooks
181
+ * are dispatched per `(table, field)` based on the field's `codecId`
182
+ * (the new field's codec for `'added'` / `'altered'`; the prior field's
183
+ * codec for `'dropped'`).
184
+ *
185
+ * See `docs/architecture docs/adrs/ADR 213 - Codec lifecycle hooks.md`
186
+ * for the wiring contract and the deterministic ordering rule.
187
+ */
188
+ onFieldEvent?: (event: FieldEvent, ctx: FieldEventContext) => readonly OpFactoryCall[];
189
+ }
190
+ interface SqlControlExtensionDescriptor<TTargetId extends string> extends ControlExtensionDescriptor<'sql', TTargetId> {
191
+ readonly queryOperations?: () => SqlOperationDescriptors;
192
+ /**
193
+ * Schema-contributing extensions opt into the per-space planner / runner /
194
+ * verifier by setting this field. Extensions without it are codec-only or
195
+ * query-ops-only — today's behaviour preserved.
196
+ *
197
+ * The shape comes from `@prisma-next/framework-components/control`
198
+ * (`ContractSpace`) — contract-space identity is a framework concept,
199
+ * not a SQL-specific one. The SQL family specialises the generic to
200
+ * `Contract<SqlStorage>` so descriptor authors continue to see a
201
+ * typed contract value.
202
+ */
203
+ readonly contractSpace?: ContractSpace<Contract<SqlStorage>>;
204
+ }
205
+ interface SqlControlAdapterDescriptor<TTargetId extends string> extends ControlAdapterDescriptor<'sql', TTargetId> {
206
+ readonly queryOperations?: () => SqlOperationDescriptors;
207
+ }
208
+ interface SqlMigrationPlanOperationStep {
209
+ readonly description: string;
210
+ readonly sql: string;
211
+ /**
212
+ * Optional parameter values bound at execution time. The runner forwards
213
+ * these to `driver.query(sql, params ?? [])`, so step authors can use
214
+ * placeholder syntax (`$1`, `$2`, …) instead of inlining literals into
215
+ * the SQL string. Reuses the driver's parameter binder rather than
216
+ * rolling per-target literal serialization for every type the planner
217
+ * may emit.
218
+ */
219
+ readonly params?: readonly unknown[];
220
+ readonly meta?: AnyRecord;
221
+ }
222
+ /**
223
+ * Minimal shape every SQL-family target must conform to for its per-operation
224
+ * `target.details` payload. Each SQL operation addresses a named database
225
+ * object in some schema; targets (Postgres, MySQL, SQLite, …) extend this
226
+ * shape with their own fields (e.g. Postgres adds `objectType` and optional
227
+ * `table`).
228
+ */
229
+ interface SqlPlanTargetDetails {
230
+ readonly schema: string;
231
+ readonly name: string;
232
+ }
233
+ interface SqlMigrationPlanOperationTarget<TTargetDetails> {
234
+ readonly id: string;
235
+ readonly details?: TTargetDetails;
236
+ }
237
+ interface SqlMigrationPlanOperation<TTargetDetails> extends MigrationPlanOperation {
238
+ readonly summary?: string;
239
+ readonly target: SqlMigrationPlanOperationTarget<TTargetDetails>;
240
+ readonly precheck: readonly SqlMigrationPlanOperationStep[];
241
+ readonly execute: readonly SqlMigrationPlanOperationStep[];
242
+ readonly postcheck: readonly SqlMigrationPlanOperationStep[];
243
+ readonly meta?: AnyRecord;
244
+ }
245
+ interface SqlMigrationPlanContractInfo {
246
+ readonly storageHash: string;
247
+ readonly profileHash?: string;
248
+ }
249
+ interface SqlMigrationPlan<TTargetDetails> extends MigrationPlan {
250
+ /**
251
+ * Contract space this plan applies to. The runner uses this to key the
252
+ * `prisma_contract.marker` row it writes/reads (`space = <spaceId>`),
253
+ * so per-extension plans hit per-extension marker rows instead of all
254
+ * collapsing onto the app's row.
255
+ *
256
+ * App-plan callers pass `APP_SPACE_ID` (`'app'`); per-extension plans
257
+ * pass the extension's space id. Required at every call site so the
258
+ * type system surfaces every place that needs to thread the value
259
+ * (rather than letting an `?? APP_SPACE_ID` fall-through silently
260
+ * collapse multi-space markers onto the `'app'` row).
261
+ *
262
+ * @see specs/framework-mechanism.spec.md § 2.
263
+ */
264
+ readonly spaceId: string;
265
+ /**
266
+ * Origin contract identity that the plan expects the database to currently be at.
267
+ * If omitted or null, the runner skips origin validation entirely.
268
+ */
269
+ readonly origin?: SqlMigrationPlanContractInfo | null;
270
+ /**
271
+ * Destination contract identity that the plan intends to reach.
272
+ */
273
+ readonly destination: SqlMigrationPlanContractInfo;
274
+ readonly operations: readonly SqlMigrationPlanOperation<TTargetDetails>[];
275
+ /**
276
+ * Sorted, deduplicated invariant ids declared by this plan's data-transform
277
+ * ops. Required at the SQL-family layer (the SQL runners consume this as
278
+ * the source of truth for marker writes and self-edge no-op checks); the
279
+ * framework-level {@link MigrationPlan.providedInvariants} stays optional
280
+ * because `db init` / `db update` plans don't have a corresponding
281
+ * migration manifest.
282
+ */
283
+ readonly providedInvariants: readonly string[];
284
+ readonly meta?: AnyRecord;
285
+ }
286
+ type SqlPlannerConflictKind = 'typeMismatch' | 'nullabilityConflict' | 'indexIncompatible' | 'foreignKeyConflict' | 'missingButNonAdditive' | 'unsupportedOperation';
287
+ interface SqlPlannerConflictLocation {
288
+ readonly table?: string;
289
+ readonly column?: string;
290
+ readonly index?: string;
291
+ readonly constraint?: string;
292
+ readonly type?: string;
293
+ }
294
+ interface SqlPlannerConflict extends MigrationPlannerConflict {
295
+ readonly kind: SqlPlannerConflictKind;
296
+ readonly location?: SqlPlannerConflictLocation;
297
+ readonly meta?: AnyRecord;
298
+ }
299
+ interface SqlPlannerSuccessResult<TTargetDetails> extends Omit<MigrationPlannerSuccessResult, 'plan'> {
300
+ readonly kind: 'success';
301
+ readonly plan: SqlMigrationPlan<TTargetDetails>;
302
+ }
303
+ interface SqlPlannerFailureResult extends Omit<MigrationPlannerFailureResult, 'conflicts'> {
304
+ readonly kind: 'failure';
305
+ readonly conflicts: readonly SqlPlannerConflict[];
306
+ }
307
+ type SqlPlannerResult<TTargetDetails> = SqlPlannerSuccessResult<TTargetDetails> | SqlPlannerFailureResult;
308
+ interface SqlMigrationPlannerPlanOptions {
309
+ readonly contract: Contract<SqlStorage>;
310
+ readonly schema: SqlSchemaIR;
311
+ readonly policy: MigrationOperationPolicy;
312
+ readonly schemaName?: string;
313
+ /**
314
+ * Contract space the plan applies to. The planner stamps this onto
315
+ * the produced {@link SqlMigrationPlan.spaceId} so the runner keys
316
+ * the marker row by the right space. App-plan callers pass
317
+ * `APP_SPACE_ID`; per-extension callers pass the extension's space
318
+ * id.
319
+ */
320
+ readonly spaceId: string;
321
+ /**
322
+ * The "from" contract (state the planner assumes the database starts at),
323
+ * or `null` for reconciliation flows that have no prior contract.
324
+ *
325
+ * Required at every call site so the structural fact "I have a prior
326
+ * contract / I don't" is visible in the type. `migration plan` supplies
327
+ * the previous bundle's `metadata.toContract`; `db update` / `db init`
328
+ * reconcile against the live schema and pass `null`. Strategies that
329
+ * need from/to column-shape comparisons (unsafe type change, nullability
330
+ * tightening) use this to decide whether to emit `dataTransform`
331
+ * placeholders; they short-circuit when it is `null`.
332
+ *
333
+ * Planners also derive the "from" identity they stamp onto the produced
334
+ * plan's `describe()` as `fromContract?.storage.storageHash ?? null`.
335
+ */
336
+ readonly fromContract: Contract<SqlStorage> | null;
337
+ /**
338
+ * Active framework components participating in this composition.
339
+ * Each component is target-bound so SQL targets can dispatch
340
+ * component-owned planning behaviour from the same descriptor list.
341
+ * All components must have matching familyId ('sql') and targetId.
342
+ */
343
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
344
+ }
345
+ interface SqlMigrationPlanner<TTargetDetails> {
346
+ plan(options: SqlMigrationPlannerPlanOptions): SqlPlannerResult<TTargetDetails>;
347
+ }
348
+ interface SqlMigrationRunnerExecuteCallbacks<TTargetDetails> {
349
+ onOperationStart?(operation: SqlMigrationPlanOperation<TTargetDetails>): void;
350
+ onOperationComplete?(operation: SqlMigrationPlanOperation<TTargetDetails>): void;
351
+ }
352
+ interface SqlMigrationRunnerExecuteOptions<TTargetDetails> {
353
+ readonly plan: SqlMigrationPlan<TTargetDetails>;
354
+ readonly driver: ControlDriverInstance<'sql', string>;
355
+ /**
356
+ * Logical contract space this plan applies to. When omitted the
357
+ * runner derives the space from {@link SqlMigrationPlan.spaceId};
358
+ * when supplied, the runner asserts it matches `plan.spaceId` so a
359
+ * caller cannot accidentally write the marker row for a different
360
+ * space than the plan was produced for.
361
+ */
362
+ readonly space?: string;
363
+ /**
364
+ * Destination contract IR.
365
+ * Must correspond to `plan.destination` and is used for schema verification and marker/ledger writes.
366
+ */
367
+ readonly destinationContract: Contract<SqlStorage>;
368
+ /**
369
+ * Execution-time policy that defines which operation classes are allowed.
370
+ * The runner validates each operation against this policy before execution.
371
+ */
372
+ readonly policy: MigrationOperationPolicy;
373
+ readonly schemaName?: string;
374
+ readonly strictVerification?: boolean;
375
+ readonly callbacks?: SqlMigrationRunnerExecuteCallbacks<TTargetDetails>;
376
+ readonly context?: OperationContext;
377
+ /**
378
+ * Execution-time checks configuration.
379
+ * All checks default to `true` (enabled) when omitted.
380
+ */
381
+ readonly executionChecks?: MigrationRunnerExecutionChecks;
382
+ /**
383
+ * Active framework components participating in this composition.
384
+ * Each component is target-bound so SQL targets can dispatch
385
+ * component-owned execution behaviour from the same descriptor list.
386
+ * All components must have matching familyId ('sql') and targetId.
387
+ */
388
+ readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
389
+ }
390
+ type SqlMigrationRunnerErrorCode = 'DESTINATION_CONTRACT_MISMATCH' | 'LEGACY_MARKER_SHAPE' | 'MARKER_ORIGIN_MISMATCH' | 'POLICY_VIOLATION' | 'PRECHECK_FAILED' | 'POSTCHECK_FAILED' | 'SCHEMA_VERIFY_FAILED' | 'FOREIGN_KEY_VIOLATION' | 'EXECUTION_FAILED';
391
+ interface SqlMigrationRunnerFailure extends MigrationRunnerFailure {
392
+ readonly code: SqlMigrationRunnerErrorCode;
393
+ readonly meta?: AnyRecord;
394
+ }
395
+ interface SqlMigrationRunnerSuccessValue extends MigrationRunnerSuccessValue {}
396
+ type SqlMigrationRunnerResult = Result<SqlMigrationRunnerSuccessValue, SqlMigrationRunnerFailure>;
397
+ interface SqlMigrationRunner<TTargetDetails> {
398
+ /**
399
+ * Apply a single migration plan, opening and managing its own
400
+ * transaction (and any target-specific connection-level setup, e.g.
401
+ * SQLite's `PRAGMA foreign_keys` toggle). Existing single-space
402
+ * callers route through here.
403
+ */
404
+ execute(options: SqlMigrationRunnerExecuteOptions<TTargetDetails>): Promise<SqlMigrationRunnerResult>;
405
+ /**
406
+ * Apply a single migration plan against an already-open connection
407
+ * **without** opening a transaction. The caller is responsible for
408
+ * wrapping the call (and any siblings) in `BEGIN` / `COMMIT` /
409
+ * `ROLLBACK`. Used by the per-space runner wiring to fan out across
410
+ * contract spaces inside one outer transaction so a mid-apply
411
+ * failure rolls back every space's writes.
412
+ *
413
+ * Idempotent control-table setup (`prisma_contract.*`) and marker
414
+ * writes use `options.space` to address the per-space marker row.
415
+ */
416
+ executeOnConnection(options: SqlMigrationRunnerExecuteOptions<TTargetDetails>): Promise<SqlMigrationRunnerResult>;
417
+ /**
418
+ * Apply per-space plans across multiple contract spaces inside a
419
+ * single outer transaction. The caller orders the input list
420
+ * (typically via the aggregate planner's `applyOrder`: extensions
421
+ * alphabetical, then app); the runner is responsible for opening
422
+ * / committing the outer
423
+ * transaction (and any target-specific connection-level setup such
424
+ * as the SQLite FK pragma toggle). A failure on any space rolls
425
+ * back every space's writes.
426
+ *
427
+ * Each space's `SqlMigrationRunnerExecuteOptions` must reference the
428
+ * same `driver` (the connection the outer transaction is open on).
429
+ * Per-space marker writes use `options.space` to address the row.
430
+ */
431
+ executeAcrossSpaces(options: {
432
+ readonly driver: ControlDriverInstance<'sql', string>;
433
+ readonly perSpaceOptions: ReadonlyArray<SqlMigrationRunnerExecuteOptions<TTargetDetails>>;
434
+ }): Promise<MultiSpaceRunnerResult>;
435
+ }
436
+ interface MultiSpaceRunnerSuccessValue {
437
+ readonly perSpaceResults: ReadonlyArray<{
438
+ readonly space: string;
439
+ readonly value: SqlMigrationRunnerSuccessValue;
440
+ }>;
441
+ }
442
+ interface MultiSpaceRunnerFailure extends SqlMigrationRunnerFailure {
443
+ readonly failingSpace: string;
444
+ }
445
+ type MultiSpaceRunnerResult = Result<MultiSpaceRunnerSuccessValue, MultiSpaceRunnerFailure>;
446
+ interface SqlControlTargetDescriptor<TTargetId extends string, TTargetDetails> extends MigratableTargetDescriptor<'sql', TTargetId, SqlControlFamilyInstance> {
447
+ readonly queryOperations?: () => SqlOperationDescriptors;
448
+ createPlanner(family: SqlControlFamilyInstance): SqlMigrationPlanner<TTargetDetails>;
449
+ createRunner(family: SqlControlFamilyInstance): SqlMigrationRunner<TTargetDetails>;
450
+ }
451
+ interface CreateSqlMigrationPlanOptions<TTargetDetails> {
452
+ readonly targetId: string;
453
+ /**
454
+ * Contract space this plan applies to. Mirrors {@link SqlMigrationPlan.spaceId}.
455
+ */
456
+ readonly spaceId: string;
457
+ readonly origin?: SqlMigrationPlanContractInfo | null;
458
+ readonly destination: SqlMigrationPlanContractInfo;
459
+ readonly operations: readonly SqlMigrationPlanOperation<TTargetDetails>[];
460
+ /**
461
+ * Sorted, deduplicated invariant ids for this plan; mirrors the required
462
+ * field on {@link SqlMigrationPlan}. Callers without a migration manifest
463
+ * (`db init`, `db update`, planner-built plans) pass `[]`.
464
+ */
465
+ readonly providedInvariants: readonly string[];
466
+ readonly meta?: AnyRecord;
467
+ }
468
+ //#endregion
469
+ export { SqlPlannerConflictKind as A, SqlMigrationRunnerExecuteCallbacks as C, SqlMigrationRunnerSuccessValue as D, SqlMigrationRunnerResult as E, StorageTypePlanResult as F, SchemaVerifyOptions as I, SqlControlFamilyInstance as L, SqlPlannerFailureResult as M, SqlPlannerResult as N, SqlPlanTargetDetails as O, SqlPlannerSuccessResult as P, SqlMigrationRunnerErrorCode as S, SqlMigrationRunnerFailure as T, SqlMigrationPlanOperationStep as _, FieldEvent as a, SqlMigrationPlannerPlanOptions as b, MultiSpaceRunnerResult as c, SqlControlAdapterDescriptor as d, SqlControlExtensionDescriptor as f, SqlMigrationPlanOperation as g, SqlMigrationPlanContractInfo as h, ExpandNativeTypeInput as i, SqlPlannerConflictLocation as j, SqlPlannerConflict as k, MultiSpaceRunnerSuccessValue as l, SqlMigrationPlan as m, CodecControlHooks as n, FieldEventContext as o, SqlControlTargetDescriptor as p, CreateSqlMigrationPlanOptions as r, MultiSpaceRunnerFailure as s, AnyRecord as t, ResolveIdentityValueInput as u, SqlMigrationPlanOperationTarget as v, SqlMigrationRunnerExecuteOptions as w, SqlMigrationRunner as x, SqlMigrationPlanner as y };
470
+ //# sourceMappingURL=types-mhjAPuMn.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-mhjAPuMn.d.mts","names":[],"sources":["../src/core/control-instance.ts","../src/core/migrations/types.ts"],"mappings":";;;;;;;;;;;UAkKU,eAAA;EAAA,SACC,MAAA;EAAA,SACA,QAAA;EAAA,SACA,QAAA;EAAA,SACA,UAAA;AAAA;AAAA,KAGN,uBAAA,GAA0B,GAAA,SAAY,eAAA;AAAA,UAEjC,sBAAA;EAAA,SACC,gBAAA,EAAkB,aAAA,CAAc,eAAA;EAAA,SAChC,YAAA,EAAc,aAAA;EAAA,SACd,oBAAA,EAAsB,uBAAA;AAAA;AAAA,UAGhB,mBAAA;EAAA,SACN,MAAA,EAAQ,qBAAA;EAAA,SACR,QAAA;EAAA,SACA,MAAA;EAAA,SACA,OAAA,GAAU,gBAAA;;;;AAZqC;WAiB/C,mBAAA,EAAqB,aAAA,CAAc,8BAAA;AAAA;AAAA,UAG7B,wBAAA,SACP,qBAAA,QAA6B,WAAA,GACnC,iBAAA,CAAkB,WAAA,GAClB,uBAAA,CAAwB,WAAA,GACxB,uBAAA,EACA,sBAAA;EACF,gBAAA,CAAiB,YAAA,YAAwB,QAAA;EAEzC,MAAA,CAAO,OAAA;IAAA,SACI,MAAA,EAAQ,qBAAA;IAAA,SACR,QAAA;IAAA,SACA,gBAAA;IAAA,SACA,YAAA;IAAA,SACA,UAAA;EAAA,IACP,OAAA,CAAQ,oBAAA;EAEZ,YAAA,CAAa,OAAA,EAAS,mBAAA,GAAsB,OAAA,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A;IAAA,SACR,eAAA,EAAiB,aAAA,CAAc,gCAAA,CAAiC,cAAA;EAAA,IACvE,OAAA,CAAQ,sBAAA;AAAA;AAAA,UAGG,4BAAA;EAAA,SACN,eAAA,EAAiB,aAAA;IAAA,SACf,KAAA;IAAA,SACA,KAAA,EAAO,8BAAA;EAAA;AAAA;AAAA,UAIH,uBAAA,SAAgC,yBAAA;EAAA,SACtC,YAAA;AAAA;AAAA,KAGC,sBAAA,GAAyB,MAAA,CAAO,4BAAA,EAA8B,uBAAA;AAAA,UAEzD,0BAAA,mDACP,0BAAA,QAAkC,SAAA,EAAW,wBAAA;EAAA,SAC5C,eAAA,SAAwB,uBAAA;EACjC,aAAA,CAAc,MAAA,EAAQ,wBAAA,GAA2B,mBAAA,CAAoB,cAAA;EACrE,YAAA,CAAa,MAAA,EAAQ,wBAAA,GAA2B,kBAAA,CAAmB,cAAA;AAAA;AAAA,UAGpD,6BAAA;EAAA,SACN,QAAA;EAhQkC;;;EAAA,SAoQlC,OAAA;EAAA,SACA,MAAA,GAAS,4BAAA;EAAA,SACT,WAAA,EAAa,4BAAA;EAAA,SACb,UAAA,WAAqB,yBAAA,CAA0B,cAAA;EA9OtC;;;;;EAAA,SAoPT,kBAAA;EAAA,SACA,IAAA,GAAO,SAAA;AAAA"}
@@ -0,0 +1,81 @@
1
+ import { type } from "arktype";
2
+ //#region src/core/verify.ts
3
+ const MetaSchema = type({ "[string]": "unknown" });
4
+ function parseMeta(meta) {
5
+ if (meta === null || meta === void 0) return {};
6
+ let parsed;
7
+ if (typeof meta === "string") try {
8
+ parsed = JSON.parse(meta);
9
+ } catch {
10
+ return {};
11
+ }
12
+ else parsed = meta;
13
+ const result = MetaSchema(parsed);
14
+ if (result instanceof type.errors) return {};
15
+ return result;
16
+ }
17
+ /**
18
+ * SQLite stores `contract_json` as TEXT, so the wire shape is a JSON string;
19
+ * Postgres uses `jsonb` and returns an already-parsed value. Normalize both
20
+ * here so `ContractMarkerRecord.contractJson` is always the structured form.
21
+ */
22
+ function parseContractJson(value) {
23
+ if (value === null || value === void 0) return null;
24
+ if (typeof value !== "string") return value;
25
+ try {
26
+ return JSON.parse(value);
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+ const ContractMarkerRowSchema = type({
32
+ core_hash: "string",
33
+ profile_hash: "string",
34
+ "contract_json?": "unknown | null",
35
+ "canonical_version?": "number | null",
36
+ "updated_at?": "Date | string",
37
+ "app_tag?": "string | null",
38
+ "meta?": "unknown | null",
39
+ invariants: type("string").array()
40
+ });
41
+ /**
42
+ * Parses a contract marker row from database query result.
43
+ * This is SQL-specific parsing logic (handles SQL row structure with snake_case columns).
44
+ */
45
+ function parseContractMarkerRow(row) {
46
+ const result = ContractMarkerRowSchema(row);
47
+ if (result instanceof type.errors) {
48
+ const messages = result.map((p) => p.message).join("; ");
49
+ throw new Error(`Invalid contract marker row: ${messages}`);
50
+ }
51
+ const updatedAt = result.updated_at ? result.updated_at instanceof Date ? result.updated_at : new Date(result.updated_at) : /* @__PURE__ */ new Date();
52
+ return {
53
+ storageHash: result.core_hash,
54
+ profileHash: result.profile_hash,
55
+ contractJson: parseContractJson(result.contract_json),
56
+ canonicalVersion: result.canonical_version ?? null,
57
+ updatedAt,
58
+ appTag: result.app_tag ?? null,
59
+ meta: parseMeta(result.meta),
60
+ invariants: result.invariants
61
+ };
62
+ }
63
+ /**
64
+ * Collects supported codec type IDs from adapter and extension manifests.
65
+ * Returns a sorted, unique array of type IDs that are declared in the manifests.
66
+ * This enables coverage checks by comparing contract column types against supported types.
67
+ *
68
+ * Note: This extracts type IDs from manifest type imports, not from runtime codec registries.
69
+ * The manifests declare which codec types are available, but the actual type IDs
70
+ * are defined in the codec-types TypeScript modules that are imported.
71
+ *
72
+ * For MVP, we return an empty array since extracting type IDs from TypeScript modules
73
+ * would require runtime evaluation or static analysis. This can be enhanced later.
74
+ */
75
+ function collectSupportedCodecTypeIds(descriptors) {
76
+ return [];
77
+ }
78
+ //#endregion
79
+ export { parseContractMarkerRow as n, collectSupportedCodecTypeIds as t };
80
+
81
+ //# sourceMappingURL=verify-pRYxnpiG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verify-pRYxnpiG.mjs","names":[],"sources":["../src/core/verify.ts"],"sourcesContent":["import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { type } from 'arktype';\n\nconst MetaSchema = type({ '[string]': 'unknown' });\n\nfunction parseMeta(meta: unknown): Record<string, unknown> {\n if (meta === null || meta === undefined) {\n return {};\n }\n\n let parsed: unknown;\n if (typeof meta === 'string') {\n try {\n parsed = JSON.parse(meta);\n } catch {\n return {};\n }\n } else {\n parsed = meta;\n }\n\n const result = MetaSchema(parsed);\n if (result instanceof type.errors) {\n return {};\n }\n\n return result as Record<string, unknown>;\n}\n\n/**\n * SQLite stores `contract_json` as TEXT, so the wire shape is a JSON string;\n * Postgres uses `jsonb` and returns an already-parsed value. Normalize both\n * here so `ContractMarkerRecord.contractJson` is always the structured form.\n */\nfunction parseContractJson(value: unknown): unknown {\n if (value === null || value === undefined) return null;\n if (typeof value !== 'string') return value;\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n}\n\n/**\n * Wire shape of a `prisma_contract.marker` row as it comes out of a SQL\n * driver. Snake-cased to match the on-disk column names. Shared by every\n * SQL target's `readMarker` so each runner doesn't redeclare it inline.\n */\nexport type ContractMarkerRow = {\n core_hash: string;\n profile_hash: string;\n contract_json: unknown | null;\n canonical_version: number | null;\n updated_at: Date | string;\n app_tag: string | null;\n meta: unknown | null;\n // SQLite stores arrays as JSON-TEXT, so this is `string` on the wire from\n // a SQLite driver and `string[]` from a Postgres driver. Targets normalize\n // before passing to `parseContractMarkerRow`.\n invariants: unknown;\n};\n\nconst ContractMarkerRowSchema = type({\n core_hash: 'string',\n profile_hash: 'string',\n 'contract_json?': 'unknown | null',\n 'canonical_version?': 'number | null',\n 'updated_at?': 'Date | string',\n 'app_tag?': 'string | null',\n 'meta?': 'unknown | null',\n invariants: type('string').array(),\n});\n\n/**\n * Parses a contract marker row from database query result.\n * This is SQL-specific parsing logic (handles SQL row structure with snake_case columns).\n */\nexport function parseContractMarkerRow(row: unknown): ContractMarkerRecord {\n const result = ContractMarkerRowSchema(row);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Invalid contract marker row: ${messages}`);\n }\n\n const updatedAt = result.updated_at\n ? result.updated_at instanceof Date\n ? result.updated_at\n : new Date(result.updated_at)\n : new Date();\n\n return {\n storageHash: result.core_hash,\n profileHash: result.profile_hash,\n contractJson: parseContractJson(result.contract_json),\n canonicalVersion: result.canonical_version ?? null,\n updatedAt,\n appTag: result.app_tag ?? null,\n meta: parseMeta(result.meta),\n invariants: result.invariants,\n };\n}\n\n/**\n * Collects supported codec type IDs from adapter and extension manifests.\n * Returns a sorted, unique array of type IDs that are declared in the manifests.\n * This enables coverage checks by comparing contract column types against supported types.\n *\n * Note: This extracts type IDs from manifest type imports, not from runtime codec registries.\n * The manifests declare which codec types are available, but the actual type IDs\n * are defined in the codec-types TypeScript modules that are imported.\n *\n * For MVP, we return an empty array since extracting type IDs from TypeScript modules\n * would require runtime evaluation or static analysis. This can be enhanced later.\n */\nexport function collectSupportedCodecTypeIds(\n descriptors: ReadonlyArray<{ readonly id: string }>,\n): readonly string[] {\n // For MVP, return empty array\n // Future enhancement: Extract type IDs from codec-types modules via static analysis\n // or require manifests to explicitly list supported type IDs\n void descriptors;\n return [];\n}\n"],"mappings":";;AAGA,MAAM,aAAa,KAAK,EAAE,YAAY,WAAW,CAAC;AAElD,SAAS,UAAU,MAAwC;CACzD,IAAI,SAAS,QAAQ,SAAS,KAAA,GAC5B,OAAO,EAAE;CAGX,IAAI;CACJ,IAAI,OAAO,SAAS,UAClB,IAAI;EACF,SAAS,KAAK,MAAM,KAAK;SACnB;EACN,OAAO,EAAE;;MAGX,SAAS;CAGX,MAAM,SAAS,WAAW,OAAO;CACjC,IAAI,kBAAkB,KAAK,QACzB,OAAO,EAAE;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