@prisma-next/sql-runtime 0.5.0-dev.60 → 0.5.0-dev.61

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.
@@ -17,7 +17,6 @@ import type { SqlStorage } from '@prisma-next/sql-contract/types';
17
17
  import type {
18
18
  Adapter,
19
19
  AnyQueryAst,
20
- CodecRegistry,
21
20
  ContractCodecRegistry,
22
21
  LoweredStatement,
23
22
  SqlCodecCallContext,
@@ -25,11 +24,9 @@ import type {
25
24
  SqlQueryable,
26
25
  SqlTransaction,
27
26
  } from '@prisma-next/sql-relational-core/ast';
27
+ import { validateParamRefRefs } from '@prisma-next/sql-relational-core/ast';
28
28
  import type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';
29
- import type {
30
- CodecDescriptorRegistry,
31
- JsonSchemaValidatorRegistry,
32
- } from '@prisma-next/sql-relational-core/query-lane-context';
29
+ import type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';
33
30
  import type { RuntimeScope } from '@prisma-next/sql-relational-core/types';
34
31
  import { ifDefined } from '@prisma-next/utils/defined';
35
32
  import { decodeRow } from './codecs/decoding';
@@ -93,25 +90,15 @@ export interface Runtime extends RuntimeQueryable {
93
90
  export interface RuntimeConnection extends RuntimeQueryable {
94
91
  transaction(): Promise<RuntimeTransaction>;
95
92
  /**
96
- * Returns the connection to the pool for reuse. Only call this when the
97
- * connection is known to be in a clean state. If a transaction
98
- * commit/rollback failed or the connection is otherwise suspect, call
99
- * `destroy(reason)` instead.
93
+ * Returns the connection to the pool for reuse. Only call this when the connection is known to be in a clean state. If a transaction commit/rollback failed or the connection is otherwise suspect, call `destroy(reason)` instead.
100
94
  */
101
95
  release(): Promise<void>;
102
96
  /**
103
- * Evicts the connection so it is never reused. Call this when the
104
- * connection may be in an indeterminate state (e.g. a failed rollback
105
- * leaving an open transaction, or a broken socket).
97
+ * Evicts the connection so it is never reused. Call this when the connection may be in an indeterminate state (e.g. a failed rollback leaving an open transaction, or a broken socket).
106
98
  *
107
- * If teardown fails the error is propagated and the connection remains
108
- * retryable, so the caller can decide whether to swallow the failure or
109
- * retry cleanup. Calling destroy() or release() more than once after a
110
- * successful teardown is caller error.
99
+ * If teardown fails the error is propagated and the connection remains retryable, so the caller can decide whether to swallow the failure or retry cleanup. Calling destroy() or release() more than once after a successful teardown is caller error.
111
100
  *
112
- * `reason` is advisory context only. It may be surfaced to driver-level
113
- * observability hooks (e.g. pg-pool's `'release'` event) but does not
114
- * influence eviction behavior and is not rethrown.
101
+ * `reason` is advisory context only. It may be surfaced to driver-level observability hooks (e.g. pg-pool's `'release'` event) but does not influence eviction behavior and is not rethrown.
115
102
  */
116
103
  destroy(reason?: unknown): Promise<void>;
117
104
  }
@@ -133,6 +120,10 @@ function isExecutionPlan(plan: SqlExecutionPlan | SqlQueryPlan): plan is SqlExec
133
120
  return 'sql' in plan;
134
121
  }
135
122
 
123
+ // v8 ignore next 2
124
+ const noopLogSink = (): void => {};
125
+ const noopLog: Log = { info: noopLogSink, warn: noopLogSink, error: noopLogSink };
126
+
136
127
  class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorage>>
137
128
  extends RuntimeCore<SqlQueryPlan, SqlExecutionPlan, SqlMiddleware>
138
129
  implements Runtime
@@ -141,10 +132,8 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
141
132
  private readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;
142
133
  private readonly driver: SqlDriver<unknown>;
143
134
  private readonly familyAdapter: RuntimeFamilyAdapter<Contract<SqlStorage>>;
144
- private readonly codecRegistry: CodecRegistry;
145
135
  private readonly contractCodecs: ContractCodecRegistry;
146
136
  private readonly codecDescriptors: CodecDescriptorRegistry;
147
- private readonly jsonSchemaValidators: JsonSchemaValidatorRegistry | undefined;
148
137
  private readonly sqlCtx: SqlMiddlewareContext;
149
138
  private readonly verify: RuntimeVerifyOptions;
150
139
  private codecRegistryValidated: boolean;
@@ -165,13 +154,8 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
165
154
  contract: context.contract,
166
155
  mode: mode ?? 'strict',
167
156
  now: () => Date.now(),
168
- log: log ?? {
169
- info: () => {},
170
- warn: () => {},
171
- error: () => {},
172
- },
173
- // ctx is only invoked by runWithMiddleware with execs this runtime lowered;
174
- // the framework parameter type is the cross-family base.
157
+ log: log ?? noopLog,
158
+ // ctx is only invoked by runWithMiddleware with execs this runtime lowered; the framework parameter type is the cross-family base.
175
159
  contentHash: (exec) => computeSqlContentHash(exec as SqlExecutionPlan),
176
160
  };
177
161
 
@@ -181,10 +165,8 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
181
165
  this.adapter = adapter;
182
166
  this.driver = driver;
183
167
  this.familyAdapter = new SqlFamilyAdapter(context.contract, adapter.profile);
184
- this.codecRegistry = context.codecs;
185
168
  this.contractCodecs = context.contractCodecs;
186
169
  this.codecDescriptors = context.codecDescriptors;
187
- this.jsonSchemaValidators = context.jsonSchemaValidators;
188
170
  this.sqlCtx = sqlCtx;
189
171
  this.verify = verify;
190
172
  this.codecRegistryValidated = false;
@@ -199,33 +181,26 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
199
181
  }
200
182
 
201
183
  /**
202
- * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan` with
203
- * encoded parameters ready for the driver. This is the single point at
204
- * which params transition from app-layer values to driver wire-format.
184
+ * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan` with encoded parameters ready for the driver. This is the single point at which params transition from app-layer values to driver wire-format.
205
185
  *
206
- * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so per-query
207
- * cancellation reaches every codec body during parameter encoding. The
208
- * framework abstract typed this as `CodecCallContext`; the SQL family
209
- * narrows it to the SQL-specific extension. SQL params do not populate
210
- * `ctx.column` — encode-side column metadata is the middleware's domain.
186
+ * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so per-query cancellation reaches every codec body during parameter encoding. The framework abstract typed this as `CodecCallContext`; the SQL family narrows it to the SQL-specific extension. SQL params do not populate `ctx.column` — encode-side column metadata is the middleware's domain.
211
187
  */
212
188
  protected override async lower(
213
189
  plan: SqlQueryPlan,
214
190
  ctx: SqlCodecCallContext,
215
191
  ): Promise<SqlExecutionPlan> {
192
+ validateParamRefRefs(plan.ast, this.codecDescriptors);
216
193
  const lowered = lowerSqlPlan(this.adapter, this.contract, plan);
217
194
  return Object.freeze({
218
195
  ...lowered,
219
- params: await encodeParams(lowered, this.codecRegistry, ctx, this.contractCodecs),
196
+ params: await encodeParams(lowered, ctx, this.contractCodecs),
220
197
  });
221
198
  }
222
199
 
223
200
  /**
224
- * Default driver invocation. Production execution paths override the
225
- * queryable target (e.g. transaction or connection) by going through
226
- * `executeAgainstQueryable`; this implementation supports any caller of
227
- * `super.execute(plan)` and the abstract-base contract.
201
+ * Default driver invocation required by the abstract `RuntimeCore` contract. Every production path overrides `execute()` and routes through `executeAgainstQueryable`, so this hook is defensive only — subclasses that delegate back to `super.execute()` would land here.
228
202
  */
203
+ // v8 ignore next 6
229
204
  protected override runDriver(exec: SqlExecutionPlan): AsyncIterable<Record<string, unknown>> {
230
205
  return this.driver.execute<Record<string, unknown>>({
231
206
  sql: exec.sql,
@@ -234,13 +209,8 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
234
209
  }
235
210
 
236
211
  /**
237
- * SQL pre-compile hook. Runs the registered middleware `beforeCompile`
238
- * chain over the plan's draft (AST + meta). Returns the original plan
239
- * unchanged when no middleware rewrote the AST; otherwise returns a new
240
- * plan carrying the rewritten AST and meta. The AST is the authoritative
241
- * source of execution metadata, so a rewrite needs no sidecar
242
- * reconciliation here — the lowering adapter and the encoder both walk
243
- * the rewritten AST directly.
212
+ * SQL pre-compile hook. Runs the registered middleware `beforeCompile` chain over the plan's draft (AST + meta). Returns the original plan unchanged when no middleware rewrote the AST; otherwise returns a new plan carrying the rewritten AST and meta. The AST is the authoritative source of execution metadata, so a rewrite needs no sidecar reconciliation here — the lowering adapter and the encoder both walk the rewritten
213
+ * AST directly.
244
214
  */
245
215
  protected override async runBeforeCompile(plan: SqlQueryPlan): Promise<SqlQueryPlan> {
246
216
  const rewrittenDraft = await runBeforeCompileChain(
@@ -269,23 +239,24 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
269
239
 
270
240
  const self = this;
271
241
  const signal = options?.signal;
272
- // One ctx per execute() call — the same reference is shared by
273
- // encodeParams (lower), decodeRow (per-row), and the stream loop's
274
- // between-row checks. Per-cell ctx allocations inside decodeField add
275
- // `column` for resolvable cells without re-wrapping the signal. The
276
- // ctx object is always allocated; the `signal` field is only included
277
- // when a signal was supplied (exactOptionalPropertyTypes).
242
+ // One ctx per execute() call — the same reference is shared by encodeParams (lower), decodeRow (per-row), and the stream loop's between-row checks. Per-cell ctx allocations inside decodeField add `column` for resolvable cells without re-wrapping the signal. The ctx object is always allocated; the `signal` field is only included when a signal was supplied (exactOptionalPropertyTypes).
278
243
  const codecCtx: SqlCodecCallContext = signal === undefined ? {} : { signal };
279
244
 
280
245
  const generator = async function* (): AsyncGenerator<Row, void, unknown> {
281
246
  checkAborted(codecCtx, 'stream');
282
247
 
283
- const exec: SqlExecutionPlan = isExecutionPlan(plan)
284
- ? Object.freeze({
285
- ...plan,
286
- params: await encodeParams(plan, self.codecRegistry, codecCtx, self.contractCodecs),
287
- })
288
- : await self.lower(await self.runBeforeCompile(plan), codecCtx);
248
+ let exec: SqlExecutionPlan;
249
+ if (isExecutionPlan(plan)) {
250
+ if (plan.ast) {
251
+ validateParamRefRefs(plan.ast, self.codecDescriptors);
252
+ }
253
+ exec = Object.freeze({
254
+ ...plan,
255
+ params: await encodeParams(plan, codecCtx, self.contractCodecs),
256
+ });
257
+ } else {
258
+ exec = await self.lower(await self.runBeforeCompile(plan), codecCtx);
259
+ }
289
260
 
290
261
  self.familyAdapter.validatePlan(exec, self.contract);
291
262
  self._telemetry = null;
@@ -317,11 +288,7 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
317
288
  }),
318
289
  );
319
290
 
320
- // Manually drive the driver's async iterator so the between-row
321
- // abort check fires *before* requesting the next row. With a
322
- // `for await...of` loop the runtime would await `iterator.next()`
323
- // first, leaving a window where one extra row is pulled through
324
- // the driver after the signal aborted.
291
+ // Manually drive the driver's async iterator so the between-row abort check fires *before* requesting the next row. With a `for await...of` loop the runtime would await `iterator.next()` first, leaving a window where one extra row is pulled through the driver after the signal aborted.
325
292
  const iterator = stream[Symbol.asyncIterator]();
326
293
  try {
327
294
  while (true) {
@@ -330,20 +297,11 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
330
297
  if (next.done) {
331
298
  break;
332
299
  }
333
- const decodedRow = await decodeRow(
334
- next.value,
335
- exec,
336
- self.codecRegistry,
337
- self.jsonSchemaValidators,
338
- codecCtx,
339
- self.contractCodecs,
340
- );
300
+ const decodedRow = await decodeRow(next.value, exec, codecCtx, self.contractCodecs);
341
301
  yield decodedRow as Row;
342
302
  }
343
303
  } finally {
344
- // Best-effort iterator cleanup so the driver can release its
345
- // resources whether the stream finished normally, threw, or was
346
- // abandoned by the consumer.
304
+ // Best-effort iterator cleanup so the driver can release its resources whether the stream finished normally, threw, or was abandoned by the consumer.
347
305
  await iterator.return?.();
348
306
  }
349
307
 
@@ -421,14 +379,6 @@ class SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorag
421
379
  }
422
380
 
423
381
  private async verifyMarker(): Promise<void> {
424
- if (this.verify.mode === 'always') {
425
- this.verified = false;
426
- }
427
-
428
- if (this.verified) {
429
- return;
430
- }
431
-
432
382
  const readStatement = this.familyAdapter.markerReader.readMarkerStatement();
433
383
  const result = await this.driver.query(readStatement.sql, readStatement.params);
434
384
 
@@ -536,11 +486,7 @@ export async function withTransaction<R>(
536
486
  const destroyConnection = async (reason: unknown): Promise<void> => {
537
487
  if (connectionDisposed) return;
538
488
  connectionDisposed = true;
539
- // SqlConnection.destroy() propagates teardown errors so callers can
540
- // decide what to do with them. Here, we're already about to throw a
541
- // more informative error describing why we're evicting the connection
542
- // (rollback/commit failure), so swallowing the teardown error is the
543
- // right call — surfacing it would mask the original cause.
489
+ // SqlConnection.destroy() propagates teardown errors so callers can decide what to do with them. Here, we're already about to throw a more informative error describing why we're evicting the connection (rollback/commit failure), so swallowing the teardown error is the right call — surfacing it would mask the original cause.
544
490
  await connection.destroy(reason).catch(() => undefined);
545
491
  };
546
492
 
@@ -569,17 +515,9 @@ export async function withTransaction<R>(
569
515
  try {
570
516
  await transaction.commit();
571
517
  } catch (commitError) {
572
- // After a failed COMMIT the server-side transaction may be: (a) already
573
- // committed (error on response path), (b) already rolled back (deferred
574
- // constraint / serialization failure), or (c) still open (COMMIT never
575
- // reached the server). Attempt a best-effort rollback to cover (c) and
576
- // confirm the protocol is healthy.
518
+ // After a failed COMMIT the server-side transaction may be: (a) already committed (error on response path), (b) already rolled back (deferred constraint / serialization failure), or (c) still open (COMMIT never reached the server). Attempt a best-effort rollback to cover (c) and confirm the protocol is healthy.
577
519
  //
578
- // If rollback succeeds, the server is definitely no longer in a
579
- // transaction (no-op in (a)/(b), real cleanup in (c)) and we've just
580
- // proved the connection round-trips correctly — it's safe to return
581
- // to the pool. If rollback fails, the connection state is ambiguous
582
- // (broken socket, protocol desync, etc.) and we must destroy it.
520
+ // If rollback succeeds, the server is definitely no longer in a transaction (no-op in (a)/(b), real cleanup in (c)) and we've just proved the connection round-trips correctly — it's safe to return to the pool. If rollback fails, the connection state is ambiguous (broken socket, protocol desync, etc.) and we must destroy it.
583
521
  try {
584
522
  await transaction.rollback();
585
523
  } catch {
@@ -1 +0,0 @@
1
- {"version":3,"file":"exports-BcX9wp4z.mjs","names":["lookup: CodecLookupForValidation","invalidCodecs: Array<{ table: string; column: string; codecId: string }>","details: Record<string, unknown>","parsed: unknown","lints: LintFinding[]","budgets: BudgetFinding[]","findings: LintFinding[]","codec","helpers: TypeHelperRegistry","ctx: SqlCodecInstanceContext","resolvedCodec: Codec | undefined","applied: AppliedMutationDefault[]","contributors: Array<SqlStaticContributions & ComponentDescriptor<string>>","options","ensureSchemaStatement: SqlStatement","ensureTableStatement: SqlStatement","params: readonly unknown[]","EMPTY_INCLUDE_ALIASES: ReadonlySet<string>","aliases: string[]","codec","parsed: unknown","cellCtx: SqlCodecCallContext","decoded: unknown","tasks: Promise<unknown>[]","includeIndices: { index: number; alias: string; value: unknown }[]","decoded: Record<string, unknown>","NO_METADATA: ParamMetadata","codec","metadata: ParamMetadata[]","tasks: Promise<unknown>[]","sqlCtx: SqlMiddlewareContext","codecCtx: SqlCodecCallContext","exec: SqlExecutionPlan","outcome: TelemetryOutcome | null","txContext: TransactionContext","result: R"],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/marker.ts","../src/middleware/budgets.ts","../src/guardrails/raw.ts","../src/middleware/lints.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/codecs/json-schema-validation.ts","../src/codecs/decoding.ts","../src/codecs/encoding.ts","../src/content-hash.ts","../src/fingerprint.ts","../src/middleware/before-compile-chain.ts","../src/sql-family-adapter.ts","../src/sql-runtime.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { CodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\n\nexport function extractCodecIds(contract: Contract<SqlStorage>): Set<string> {\n const codecIds = new Set<string>();\n\n for (const table of Object.values(contract.storage.tables)) {\n for (const column of Object.values(table.columns)) {\n const codecId = column.codecId;\n codecIds.add(codecId);\n }\n }\n\n return codecIds;\n}\n\nfunction extractCodecIdsFromColumns(contract: Contract<SqlStorage>): Map<string, string> {\n const codecIds = new Map<string, string>();\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n const codecId = column.codecId;\n const key = `${tableName}.${columnName}`;\n codecIds.set(key, codecId);\n }\n }\n\n return codecIds;\n}\n\ninterface CodecLookupForValidation {\n has(id: string): boolean;\n}\n\nfunction adaptDescriptorRegistry(registry: CodecDescriptorRegistry): CodecLookupForValidation {\n return { has: (id: string) => registry.descriptorFor(id) !== undefined };\n}\n\nfunction isDescriptorRegistry(\n registry: CodecRegistry | CodecDescriptorRegistry,\n): registry is CodecDescriptorRegistry {\n return 'descriptorFor' in registry;\n}\n\nexport function validateContractCodecMappings(\n registry: CodecRegistry | CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\n const lookup: CodecLookupForValidation = isDescriptorRegistry(registry)\n ? adaptDescriptorRegistry(registry)\n : registry;\n\n const codecIds = extractCodecIdsFromColumns(contract);\n const invalidCodecs: Array<{ table: string; column: string; codecId: string }> = [];\n\n for (const [key, codecId] of codecIds.entries()) {\n if (!lookup.has(codecId)) {\n const parts = key.split('.');\n const table = parts[0] ?? '';\n const column = parts[1] ?? '';\n invalidCodecs.push({ table, column, codecId });\n }\n }\n\n if (invalidCodecs.length > 0) {\n const details: Record<string, unknown> = {\n contractTarget: contract.target,\n invalidCodecs,\n };\n\n throw runtimeError(\n 'RUNTIME.CODEC_MISSING',\n `Missing codec implementations for column codecIds: ${invalidCodecs.map((c) => `${c.table}.${c.column} (${c.codecId})`).join(', ')}`,\n details,\n );\n }\n}\n\nexport function validateCodecRegistryCompleteness(\n registry: CodecRegistry | CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\n validateContractCodecMappings(registry, contract);\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Adapter, AnyQueryAst, LoweredStatement } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\n\n/**\n * Lowers a SQL query plan to an executable Plan by calling the adapter's lower method.\n *\n * @param adapter - Adapter to lower AST to SQL\n * @param contract - Contract for lowering context\n * @param queryPlan - SQL query plan from a lane (contains AST, params, meta, but no SQL)\n * @returns Fully executable Plan with SQL string\n */\nexport function lowerSqlPlan<Row>(\n adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>,\n contract: Contract<SqlStorage>,\n queryPlan: SqlQueryPlan<Row>,\n): SqlExecutionPlan<Row> {\n const lowered = adapter.lower(queryPlan.ast, {\n contract,\n params: queryPlan.params,\n });\n\n return Object.freeze({\n sql: lowered.sql,\n params: lowered.params ?? queryPlan.params,\n ast: queryPlan.ast,\n meta: queryPlan.meta,\n });\n}\n","import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport { type } from 'arktype';\n\nexport interface ContractMarkerRow {\n core_hash: string;\n profile_hash: string;\n contract_json: unknown | null;\n canonical_version: number | null;\n updated_at: Date;\n app_tag: string | null;\n meta: unknown | null;\n invariants: readonly string[];\n}\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\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\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: result.contract_json ?? null,\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","import {\n type AfterExecuteResult,\n type RuntimeErrorEnvelope,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport { isQueryAst, type SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport interface BudgetsOptions {\n readonly maxRows?: number;\n readonly defaultTableRows?: number;\n readonly tableRows?: Record<string, number>;\n readonly maxLatencyMs?: number;\n readonly severities?: {\n readonly rowCount?: 'warn' | 'error';\n readonly latency?: 'warn' | 'error';\n };\n}\n\nfunction hasAggregateWithoutGroupBy(ast: SelectAst): boolean {\n if (ast.groupBy !== undefined) {\n return false;\n }\n return ast.projection.some((item) => item.expr.kind === 'aggregate');\n}\n\nfunction primaryTableFromAst(ast: SelectAst): string | undefined {\n switch (ast.from.kind) {\n case 'table-source':\n return ast.from.name;\n case 'derived-table-source':\n return ast.from.alias;\n default:\n return undefined;\n }\n}\n\nfunction estimateRowsFromAst(\n ast: SelectAst,\n tableRows: Record<string, number>,\n defaultTableRows: number,\n hasAggregateWithoutGroup: boolean,\n): number | null {\n if (hasAggregateWithoutGroup) {\n return 1;\n }\n\n const table = primaryTableFromAst(ast);\n if (!table) {\n return null;\n }\n\n const tableEstimate = tableRows[table] ?? defaultTableRows;\n\n if (ast.limit !== undefined) {\n return Math.min(ast.limit, tableEstimate);\n }\n\n return tableEstimate;\n}\n\nfunction emitBudgetViolation(\n error: RuntimeErrorEnvelope,\n shouldBlock: boolean,\n ctx: SqlMiddlewareContext,\n): void {\n if (shouldBlock) {\n throw error;\n }\n ctx.log.warn({\n code: error.code,\n message: error.message,\n details: error.details,\n });\n}\n\nexport function budgets(options?: BudgetsOptions): SqlMiddleware {\n const maxRows = options?.maxRows ?? 10_000;\n const defaultTableRows = options?.defaultTableRows ?? 10_000;\n const tableRows = options?.tableRows ?? {};\n const maxLatencyMs = options?.maxLatencyMs ?? 1_000;\n const rowSeverity = options?.severities?.rowCount ?? 'error';\n\n const observedRowsByPlan = new WeakMap<SqlExecutionPlan, { count: number }>();\n\n return Object.freeze({\n name: 'budgets',\n familyId: 'sql' as const,\n\n async beforeExecute(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext) {\n observedRowsByPlan.set(plan, { count: 0 });\n\n if (isQueryAst(plan.ast) && plan.ast.kind === 'select') {\n return evaluateSelectAst(plan.ast, ctx);\n }\n },\n\n async onRow(_row: Record<string, unknown>, plan: SqlExecutionPlan, _ctx: SqlMiddlewareContext) {\n const state = observedRowsByPlan.get(plan);\n if (!state) return;\n state.count += 1;\n if (state.count > maxRows) {\n throw runtimeError('BUDGET.ROWS_EXCEEDED', 'Observed row count exceeds budget', {\n source: 'observed',\n observedRows: state.count,\n maxRows,\n });\n }\n },\n\n async afterExecute(\n _plan: SqlExecutionPlan,\n result: AfterExecuteResult,\n ctx: SqlMiddlewareContext,\n ) {\n const latencyMs = result.latencyMs;\n if (latencyMs > maxLatencyMs) {\n const shouldBlock = ctx.mode === 'strict';\n emitBudgetViolation(\n runtimeError('BUDGET.TIME_EXCEEDED', 'Query latency exceeds budget', {\n latencyMs,\n maxLatencyMs,\n }),\n shouldBlock,\n ctx,\n );\n }\n },\n });\n\n function evaluateSelectAst(ast: SelectAst, ctx: SqlMiddlewareContext) {\n const hasAggNoGroup = hasAggregateWithoutGroupBy(ast);\n const estimated = estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggNoGroup);\n const isUnbounded = ast.limit === undefined && !hasAggNoGroup;\n const shouldBlock = rowSeverity === 'error' || ctx.mode === 'strict';\n\n if (isUnbounded) {\n if (estimated !== null && estimated >= maxRows) {\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', {\n source: 'ast',\n estimatedRows: estimated,\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', {\n source: 'ast',\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n if (estimated !== null && estimated > maxRows) {\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Estimated row count exceeds budget', {\n source: 'ast',\n estimatedRows: estimated,\n maxRows,\n }),\n shouldBlock,\n ctx,\n );\n }\n }\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\n\nexport type LintSeverity = 'error' | 'warn';\nexport type BudgetSeverity = 'error' | 'warn';\n\nexport interface LintFinding {\n readonly code: `LINT.${string}`;\n readonly severity: LintSeverity;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nexport interface BudgetFinding {\n readonly code: `BUDGET.${string}`;\n readonly severity: BudgetSeverity;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nexport interface RawGuardrailConfig {\n readonly budgets?: {\n readonly unboundedSelectSeverity?: BudgetSeverity;\n readonly estimatedRows?: number;\n };\n}\n\nexport interface RawGuardrailResult {\n readonly lints: LintFinding[];\n readonly budgets: BudgetFinding[];\n readonly statement: 'select' | 'mutation' | 'other';\n}\n\n/**\n * Minimal plan view consumed by raw-SQL guardrails. Structurally satisfied\n * by `SqlExecutionPlan`; declared inline so this module stays decoupled\n * from a specific plan type at the call site.\n */\ninterface RawGuardrailPlan {\n readonly sql: string;\n readonly meta: PlanMeta;\n}\n\nconst SELECT_STAR_REGEX = /select\\s+\\*/i;\nconst LIMIT_REGEX = /\\blimit\\b/i;\nconst MUTATION_PREFIX_REGEX = /^(insert|update|delete|create|alter|drop|truncate)\\b/i;\n\nconst READ_ONLY_INTENTS = new Set(['read', 'report', 'readonly']);\n\nexport function evaluateRawGuardrails(\n plan: RawGuardrailPlan,\n config?: RawGuardrailConfig,\n): RawGuardrailResult {\n const lints: LintFinding[] = [];\n const budgets: BudgetFinding[] = [];\n\n const normalized = normalizeWhitespace(plan.sql);\n const statementType = classifyStatement(normalized);\n\n if (statementType === 'select') {\n if (SELECT_STAR_REGEX.test(normalized)) {\n lints.push(\n createLint('LINT.SELECT_STAR', 'error', 'Raw SQL plan selects all columns via *', {\n sql: snippet(plan.sql),\n }),\n );\n }\n\n if (!LIMIT_REGEX.test(normalized)) {\n const severity = config?.budgets?.unboundedSelectSeverity ?? 'error';\n lints.push(\n createLint('LINT.NO_LIMIT', 'warn', 'Raw SQL plan omits LIMIT clause', {\n sql: snippet(plan.sql),\n }),\n );\n\n budgets.push(\n createBudget(\n 'BUDGET.ROWS_EXCEEDED',\n severity,\n 'Raw SQL plan is unbounded and may exceed row budget',\n {\n sql: snippet(plan.sql),\n ...(config?.budgets?.estimatedRows !== undefined\n ? { estimatedRows: config.budgets.estimatedRows }\n : {}),\n },\n ),\n );\n }\n }\n\n if (isMutationStatement(statementType) && isReadOnlyIntent(plan.meta)) {\n lints.push(\n createLint(\n 'LINT.READ_ONLY_MUTATION',\n 'error',\n 'Raw SQL plan mutates data despite read-only intent',\n {\n sql: snippet(plan.sql),\n intent: plan.meta.annotations?.['intent'],\n },\n ),\n );\n }\n\n return { lints, budgets, statement: statementType };\n}\n\nfunction classifyStatement(sql: string): 'select' | 'mutation' | 'other' {\n const trimmed = sql.trim();\n const lower = trimmed.toLowerCase();\n\n if (lower.startsWith('with')) {\n if (lower.includes('select')) {\n return 'select';\n }\n }\n\n if (lower.startsWith('select')) {\n return 'select';\n }\n\n if (MUTATION_PREFIX_REGEX.test(trimmed)) {\n return 'mutation';\n }\n\n return 'other';\n}\n\nfunction isMutationStatement(statement: 'select' | 'mutation' | 'other'): boolean {\n return statement === 'mutation';\n}\n\nfunction isReadOnlyIntent(meta: PlanMeta): boolean {\n const annotations = meta.annotations as { intent?: string } | undefined;\n const intent =\n typeof annotations?.intent === 'string' ? annotations.intent.toLowerCase() : undefined;\n return intent !== undefined && READ_ONLY_INTENTS.has(intent);\n}\n\nfunction normalizeWhitespace(value: string): string {\n return value.replace(/\\s+/g, ' ').trim();\n}\n\nfunction snippet(sql: string): string {\n return normalizeWhitespace(sql).slice(0, 200);\n}\n\nfunction createLint(\n code: LintFinding['code'],\n severity: LintFinding['severity'],\n message: string,\n details?: Record<string, unknown>,\n): LintFinding {\n return { code, severity, message, ...(details ? { details } : {}) };\n}\n\nfunction createBudget(\n code: BudgetFinding['code'],\n severity: BudgetFinding['severity'],\n message: string,\n details?: Record<string, unknown>,\n): BudgetFinding {\n return { code, severity, message, ...(details ? { details } : {}) };\n}\n","import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport {\n type AnyFromSource,\n type AnyQueryAst,\n isQueryAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { evaluateRawGuardrails } from '../guardrails/raw';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport interface LintsOptions {\n readonly severities?: {\n readonly selectStar?: 'warn' | 'error';\n readonly noLimit?: 'warn' | 'error';\n readonly deleteWithoutWhere?: 'warn' | 'error';\n readonly updateWithoutWhere?: 'warn' | 'error';\n readonly readOnlyMutation?: 'warn' | 'error';\n readonly unindexedPredicate?: 'warn' | 'error';\n };\n readonly fallbackWhenAstMissing?: 'raw' | 'skip';\n}\n\nexport interface LintFinding {\n readonly code: `LINT.${string}`;\n readonly severity: 'error' | 'warn';\n readonly message: string;\n readonly details?: Record<string, unknown>;\n}\n\nfunction getFromSourceTableDetail(source: AnyFromSource): string | undefined {\n switch (source.kind) {\n case 'table-source':\n return source.name;\n case 'derived-table-source':\n return source.alias;\n // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source kind: ${(source satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction evaluateAstLints(ast: AnyQueryAst): LintFinding[] {\n const findings: LintFinding[] = [];\n\n switch (ast.kind) {\n case 'delete':\n if (ast.where === undefined) {\n findings.push({\n code: 'LINT.DELETE_WITHOUT_WHERE',\n severity: 'error',\n message:\n 'DELETE without WHERE clause blocks execution to prevent accidental full-table deletion',\n details: { table: ast.table.name },\n });\n }\n break;\n\n case 'update':\n if (ast.where === undefined) {\n findings.push({\n code: 'LINT.UPDATE_WITHOUT_WHERE',\n severity: 'error',\n message:\n 'UPDATE without WHERE clause blocks execution to prevent accidental full-table update',\n details: { table: ast.table.name },\n });\n }\n break;\n\n case 'select':\n if (ast.limit === undefined) {\n const table = getFromSourceTableDetail(ast.from);\n findings.push({\n code: 'LINT.NO_LIMIT',\n severity: 'warn',\n message: 'Unbounded SELECT may return large result sets',\n ...ifDefined('details', table !== undefined ? { table } : undefined),\n });\n }\n if (ast.selectAllIntent !== undefined) {\n const table = ast.selectAllIntent.table;\n findings.push({\n code: 'LINT.SELECT_STAR',\n severity: 'warn',\n message: 'Query selects all columns via selectAll intent',\n ...ifDefined('details', table !== undefined ? { table } : undefined),\n });\n }\n break;\n\n case 'insert':\n break;\n\n // v8 ignore next 2\n default:\n throw new Error(`Unsupported AST kind: ${(ast satisfies never as { kind: string }).kind}`);\n }\n\n return findings;\n}\n\nfunction getConfiguredSeverity(code: string, options?: LintsOptions): 'warn' | 'error' | undefined {\n const severities = options?.severities;\n if (!severities) return undefined;\n\n switch (code) {\n case 'LINT.SELECT_STAR':\n return severities.selectStar;\n case 'LINT.NO_LIMIT':\n return severities.noLimit;\n case 'LINT.DELETE_WITHOUT_WHERE':\n return severities.deleteWithoutWhere;\n case 'LINT.UPDATE_WITHOUT_WHERE':\n return severities.updateWithoutWhere;\n case 'LINT.READ_ONLY_MUTATION':\n return severities.readOnlyMutation;\n case 'LINT.UNINDEXED_PREDICATE':\n return severities.unindexedPredicate;\n default:\n return undefined;\n }\n}\n\n/**\n * AST-first lint middleware for SQL plans. When `plan.ast` is a SQL QueryAst, inspects\n * the AST structurally. When `plan.ast` is missing, falls back to raw heuristic\n * guardrails or skips linting depending on `fallbackWhenAstMissing`.\n *\n * Rules (AST-based):\n * - DELETE without WHERE: blocks execution (configurable severity, default error)\n * - UPDATE without WHERE: blocks execution (configurable severity, default error)\n * - Unbounded SELECT: warn/error (severity from noLimit)\n * - SELECT * intent: warn/error (severity from selectStar)\n *\n * Fallback: When ast is missing, `fallbackWhenAstMissing: 'raw'` uses heuristic\n * SQL parsing; `'skip'` skips all lints. Default is `'raw'`.\n */\nexport function lints(options?: LintsOptions): SqlMiddleware {\n const fallback = options?.fallbackWhenAstMissing ?? 'raw';\n\n return Object.freeze({\n name: 'lints',\n familyId: 'sql' as const,\n\n async beforeExecute(plan: SqlExecutionPlan, ctx: SqlMiddlewareContext) {\n if (isQueryAst(plan.ast)) {\n const findings = evaluateAstLints(plan.ast);\n\n for (const lint of findings) {\n const configuredSeverity = getConfiguredSeverity(lint.code, options);\n const effectiveSeverity = configuredSeverity ?? lint.severity;\n\n if (effectiveSeverity === 'error') {\n throw runtimeError(lint.code, lint.message, lint.details);\n }\n if (effectiveSeverity === 'warn') {\n ctx.log.warn({\n code: lint.code,\n message: lint.message,\n details: lint.details,\n });\n }\n }\n return;\n }\n\n if (fallback === 'skip') {\n return;\n }\n\n const evaluation = evaluateRawGuardrails(plan);\n for (const lint of evaluation.lints) {\n const configuredSeverity = getConfiguredSeverity(lint.code, options);\n const effectiveSeverity = configuredSeverity ?? lint.severity;\n\n if (effectiveSeverity === 'error') {\n throw runtimeError(lint.code, lint.message, lint.details);\n }\n if (effectiveSeverity === 'warn') {\n ctx.log.warn({\n code: lint.code,\n message: lint.message,\n details: lint.details,\n });\n }\n }\n },\n });\n}\n","import type { Contract, ExecutionMutationDefaultValue } from '@prisma-next/contract/types';\nimport type { CodecDescriptor } from '@prisma-next/framework-components/codec';\nimport { synthesizeNonParameterizedDescriptor } from '@prisma-next/framework-components/codec';\nimport type { ComponentDescriptor } from '@prisma-next/framework-components/components';\nimport { checkContractComponentRequirements } from '@prisma-next/framework-components/components';\nimport {\n createExecutionStack,\n type ExecutionStack,\n type RuntimeAdapterDescriptor,\n type RuntimeAdapterInstance,\n type RuntimeDriverDescriptor,\n type RuntimeDriverInstance,\n type RuntimeExtensionDescriptor,\n type RuntimeExtensionInstance,\n type RuntimeTargetDescriptor,\n type RuntimeTargetInstance,\n} from '@prisma-next/framework-components/execution';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport {\n createSqlOperationRegistry,\n type SqlOperationDescriptor,\n} from '@prisma-next/sql-operations';\nimport type {\n Adapter,\n AnyQueryAst,\n Codec,\n CodecRegistry,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecInstanceContext,\n SqlDriver,\n} from '@prisma-next/sql-relational-core/ast';\nimport { createCodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type {\n AppliedMutationDefault,\n CodecDescriptorRegistry,\n ExecutionContext,\n JsonSchemaValidateFn,\n JsonSchemaValidatorRegistry,\n MutationDefaultsOptions,\n TypeHelperRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\n\n/**\n * Runtime parameterized codec descriptor.\n *\n * The unified `CodecDescriptor<P>` shape applied to parameterized codecs\n * — `paramsSchema: StandardSchemaV1<P>` for JSON-boundary validation,\n * `factory: (P) => (CodecInstanceContext) => Codec` for the curried higher-order codec.\n * The factory is called once per `storage.types` instance (or once per\n * inline-`typeParams` column); per-instance state lives in the closure.\n *\n * Codec-registry-unification spec § Decision.\n */\nexport type RuntimeParameterizedCodecDescriptor<P = Record<string, unknown>> = CodecDescriptor<P>;\n\nexport interface SqlStaticContributions {\n readonly codecs: () => CodecRegistry;\n // biome-ignore lint/suspicious/noExplicitAny: needed for covariance with concrete descriptor types\n readonly parameterizedCodecs: () => ReadonlyArray<RuntimeParameterizedCodecDescriptor<any>>;\n readonly queryOperations?: () => ReadonlyArray<SqlOperationDescriptor>;\n readonly mutationDefaultGenerators?: () => ReadonlyArray<RuntimeMutationDefaultGenerator>;\n}\n\n/**\n * Scope across which a generator's value is constant.\n *\n * - `'field'` — one value per defaulting site (one column, one row).\n * Cache strategy: no cache; call per defaulting site. Right for\n * per-row identifiers (UUIDs, CUIDs, ULIDs, nanoid, ksuid).\n * - `'row'` — one value across all defaulting sites of one row of one\n * operation. Cache strategy: per-call cache keyed by `generatorId`.\n * Right for correlation ids stamped into multiple columns of one row.\n * - `'query'` — one value across all rows and columns of one ORM\n * operation. Cache strategy: caller-provided cache keyed by\n * `generatorId`. Right for `timestampNow` (a single timestamp per\n * bulk insert/update).\n */\nexport type GeneratorStability = 'field' | 'row' | 'query';\n\nexport interface RuntimeMutationDefaultGenerator {\n readonly id: string;\n readonly generate: (params?: Record<string, unknown>) => unknown;\n /**\n * Scope across which the generator's value is constant. The framework\n * derives the cache strategy from this declaration; generator authors\n * never need to know about cache keys. See `GeneratorStability` for\n * the per-value semantics.\n */\n readonly stability: GeneratorStability;\n}\n\nexport interface SqlRuntimeTargetDescriptor<\n TTargetId extends string = string,\n TTargetInstance extends RuntimeTargetInstance<'sql', TTargetId> = RuntimeTargetInstance<\n 'sql',\n TTargetId\n >,\n> extends RuntimeTargetDescriptor<'sql', TTargetId, TTargetInstance>,\n SqlStaticContributions {}\n\nexport interface SqlRuntimeAdapterDescriptor<\n TTargetId extends string = string,\n TAdapterInstance extends RuntimeAdapterInstance<\n 'sql',\n TTargetId\n > = SqlRuntimeAdapterInstance<TTargetId>,\n> extends RuntimeAdapterDescriptor<'sql', TTargetId, TAdapterInstance>,\n SqlStaticContributions {}\n\nexport interface SqlRuntimeExtensionDescriptor<TTargetId extends string = string>\n extends RuntimeExtensionDescriptor<'sql', TTargetId, SqlRuntimeExtensionInstance<TTargetId>>,\n SqlStaticContributions {\n create(): SqlRuntimeExtensionInstance<TTargetId>;\n}\n\nexport interface SqlExecutionStack<TTargetId extends string = string> {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId>;\n readonly extensionPacks: readonly SqlRuntimeExtensionDescriptor<TTargetId>[];\n}\n\nexport type SqlExecutionStackWithDriver<TTargetId extends string = string> = Omit<\n ExecutionStack<\n 'sql',\n TTargetId,\n SqlRuntimeAdapterInstance<TTargetId>,\n SqlRuntimeDriverInstance<TTargetId>,\n SqlRuntimeExtensionInstance<TTargetId>\n >,\n 'target' | 'adapter' | 'driver' | 'extensionPacks'\n> & {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId, SqlRuntimeAdapterInstance<TTargetId>>;\n readonly driver:\n | RuntimeDriverDescriptor<'sql', TTargetId, unknown, SqlRuntimeDriverInstance<TTargetId>>\n | undefined;\n readonly extensionPacks: readonly SqlRuntimeExtensionDescriptor<TTargetId>[];\n};\n\nexport interface SqlRuntimeExtensionInstance<TTargetId extends string>\n extends RuntimeExtensionInstance<'sql', TTargetId> {}\n\nexport type SqlRuntimeAdapterInstance<TTargetId extends string = string> = RuntimeAdapterInstance<\n 'sql',\n TTargetId\n> &\n Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n\n/**\n * NOTE: Binding type is intentionally erased to unknown at this shared runtime layer.\n * Target clients (for example `postgres()`) validate and construct the concrete binding\n * before calling `driver.connect(binding)`, which keeps runtime behavior safe today.\n * A future follow-up can preserve TBinding through stack/context generics end-to-end.\n */\nexport type SqlRuntimeDriverInstance<TTargetId extends string = string> = RuntimeDriverInstance<\n 'sql',\n TTargetId\n> &\n SqlDriver<unknown>;\n\nexport function createSqlExecutionStack<TTargetId extends string>(options: {\n readonly target: SqlRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: SqlRuntimeAdapterDescriptor<TTargetId>;\n readonly driver?:\n | RuntimeDriverDescriptor<'sql', TTargetId, unknown, SqlRuntimeDriverInstance<TTargetId>>\n | undefined;\n readonly extensionPacks?: readonly SqlRuntimeExtensionDescriptor<TTargetId>[] | undefined;\n}): SqlExecutionStackWithDriver<TTargetId> {\n return createExecutionStack({\n target: options.target,\n adapter: options.adapter,\n driver: options.driver,\n extensionPacks: options.extensionPacks,\n });\n}\n\nexport type { ExecutionContext, JsonSchemaValidatorRegistry, TypeHelperRegistry };\n\nexport function assertExecutionStackContractRequirements(\n contract: Contract<SqlStorage>,\n stack: SqlExecutionStack,\n): void {\n const providedComponentIds = new Set<string>([\n stack.target.id,\n stack.adapter.id,\n ...stack.extensionPacks.map((pack) => pack.id),\n ]);\n\n const result = checkContractComponentRequirements({\n contract,\n expectedTargetFamily: 'sql',\n expectedTargetId: stack.target.targetId,\n providedComponentIds,\n });\n\n if (result.familyMismatch) {\n throw runtimeError(\n 'RUNTIME.CONTRACT_FAMILY_MISMATCH',\n `Contract target family '${result.familyMismatch.actual}' does not match runtime family '${result.familyMismatch.expected}'.`,\n {\n actual: result.familyMismatch.actual,\n expected: result.familyMismatch.expected,\n },\n );\n }\n\n if (result.targetMismatch) {\n throw runtimeError(\n 'RUNTIME.CONTRACT_TARGET_MISMATCH',\n `Contract target '${result.targetMismatch.actual}' does not match runtime target descriptor '${result.targetMismatch.expected}'.`,\n {\n actual: result.targetMismatch.actual,\n expected: result.targetMismatch.expected,\n },\n );\n }\n\n if (result.missingExtensionPackIds.length > 0) {\n const packIds = result.missingExtensionPackIds;\n const packList = packIds.map((id) => `'${id}'`).join(', ');\n throw runtimeError(\n 'RUNTIME.MISSING_EXTENSION_PACK',\n `Contract requires extension pack(s) ${packList}, but runtime descriptors do not provide matching component(s).`,\n { packIds },\n );\n }\n}\n\nfunction validateTypeParams(\n typeParams: Record<string, unknown>,\n codecDescriptor: RuntimeParameterizedCodecDescriptor,\n context: { typeName?: string; tableName?: string; columnName?: string },\n): Record<string, unknown> {\n const result = codecDescriptor.paramsSchema['~standard'].validate(typeParams);\n if (result instanceof Promise) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `paramsSchema for codec '${codecDescriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`,\n { ...context, codecId: codecDescriptor.codecId, typeParams },\n );\n }\n if (result.issues) {\n const messages = result.issues.map((issue) => issue.message).join('; ');\n const locationInfo = context.typeName\n ? `type '${context.typeName}'`\n : `column '${context.tableName}.${context.columnName}'`;\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Invalid typeParams for ${locationInfo} (codecId: ${codecDescriptor.codecId}): ${messages}`,\n { ...context, codecId: codecDescriptor.codecId, typeParams },\n );\n }\n return result.value as Record<string, unknown>;\n}\n\nfunction collectParameterizedCodecDescriptors(\n contributors: ReadonlyArray<SqlStaticContributions>,\n): Map<string, RuntimeParameterizedCodecDescriptor> {\n const descriptors = new Map<string, RuntimeParameterizedCodecDescriptor>();\n\n for (const contributor of contributors) {\n for (const descriptor of contributor.parameterizedCodecs()) {\n if (descriptors.has(descriptor.codecId)) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_PARAMETERIZED_CODEC',\n `Duplicate parameterized codec descriptor for codecId '${descriptor.codecId}'.`,\n { codecId: descriptor.codecId },\n );\n }\n descriptors.set(descriptor.codecId, descriptor);\n }\n }\n\n return descriptors;\n}\n\n/**\n * Build the unified descriptor map. Combines parameterized descriptors\n * (which already ship as `CodecDescriptor`s) with synthesized descriptors\n * for non-parameterized codecs registered through the legacy `codecs:`\n * slot. Codec ids that ship a parameterized descriptor take precedence —\n * even when the legacy registry registers a representative codec under\n * the same id, the parameterized descriptor is the authoritative source.\n *\n * Codec-registry-unification spec § Decision: every codec resolves\n * through one descriptor map; reads are non-branching.\n */\nfunction buildCodecDescriptorRegistry(\n codecRegistry: CodecRegistry,\n parameterizedDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): CodecDescriptorRegistry {\n type AnyDescriptor = CodecDescriptor<unknown>;\n const byId = new Map<string, AnyDescriptor>();\n const byTargetType = new Map<string, Array<AnyDescriptor>>();\n\n function registerInIndices(descriptor: AnyDescriptor): void {\n byId.set(descriptor.codecId, descriptor);\n for (const targetType of descriptor.targetTypes) {\n const list = byTargetType.get(targetType);\n if (list) {\n list.push(descriptor);\n } else {\n byTargetType.set(targetType, [descriptor]);\n }\n }\n }\n\n // The descriptor map is heterogeneous in `P` — each codec id has its own\n // params shape. The public `CodecDescriptorRegistry` interface widens to\n // `CodecDescriptor<unknown>` and consumers narrow per codec id at the\n // call site (the descriptor's `paramsSchema` validates JSON-sourced\n // params before the factory ever sees them, so the runtime narrow is\n // safe). The cast at registration goes through `unknown` because\n // `CodecDescriptor<P>` is invariant in `P` (the `factory` and\n // `renderOutputType` slots use `P` contravariantly).\n for (const descriptor of parameterizedDescriptors.values()) {\n registerInIndices(descriptor as unknown as AnyDescriptor);\n }\n\n for (const codec of codecRegistry.values()) {\n if (byId.has(codec.id)) continue;\n registerInIndices(synthesizeNonParameterizedDescriptor(codec) as unknown as AnyDescriptor);\n }\n\n return {\n descriptorFor(codecId: string): AnyDescriptor | undefined {\n return byId.get(codecId);\n },\n *values(): IterableIterator<AnyDescriptor> {\n yield* byId.values();\n },\n byTargetType(targetType: string): readonly AnyDescriptor[] {\n return byTargetType.get(targetType) ?? Object.freeze([]);\n },\n };\n}\n\nfunction collectTypeRefSites(\n storage: SqlStorage,\n): Map<string, Array<{ readonly table: string; readonly column: string }>> {\n const sites = new Map<string, Array<{ readonly table: string; readonly column: string }>>();\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (typeof column.typeRef !== 'string') continue;\n const list = sites.get(column.typeRef);\n const entry = { table: tableName, column: columnName };\n if (list) {\n list.push(entry);\n } else {\n sites.set(column.typeRef, [entry]);\n }\n }\n }\n return sites;\n}\n\nfunction initializeTypeHelpers(\n storage: SqlStorage,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): TypeHelperRegistry {\n const helpers: TypeHelperRegistry = {};\n const storageTypes = storage.types;\n\n if (!storageTypes) {\n return helpers;\n }\n\n const typeRefSites = collectTypeRefSites(storage);\n\n for (const [typeName, typeInstance] of Object.entries(storageTypes)) {\n const descriptor = codecDescriptors.get(typeInstance.codecId);\n\n if (!descriptor) {\n // No parameterized descriptor for this codec id — store the raw\n // type instance for callers that need typeParams metadata.\n helpers[typeName] = typeInstance;\n continue;\n }\n\n const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, {\n typeName,\n });\n\n const usedAt = typeRefSites.get(typeName) ?? [];\n const ctx: SqlCodecInstanceContext = { name: typeName, usedAt };\n helpers[typeName] = descriptor.factory(validatedParams)(ctx);\n }\n\n return helpers;\n}\n\nfunction validateColumnTypeParams(\n storage: SqlStorage,\n codecDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): void {\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeParams) {\n const descriptor = codecDescriptors.get(column.codecId);\n if (descriptor) {\n validateTypeParams(column.typeParams, descriptor, { tableName, columnName });\n }\n }\n }\n }\n}\n\n/**\n * View of a codec that exposes a per-instance JSON-schema `validate`\n * function. Codecs declare this contract by including the\n * `'json-validator'` `CodecTrait` in their `traits` array; the trait is\n * the gate that lets `extractValidator` resolve from structurally-typed\n * `unknown` to this typed view.\n */\ntype JsonValidatorCodec = {\n readonly traits?: ReadonlyArray<unknown>;\n readonly validate: JsonSchemaValidateFn;\n};\n\nfunction hasJsonValidatorTrait(candidate: unknown): candidate is JsonValidatorCodec {\n if (candidate === null || typeof candidate !== 'object') return false;\n const traits = (candidate as { readonly traits?: unknown }).traits;\n if (!Array.isArray(traits)) return false;\n if (!traits.includes('json-validator')) return false;\n const validate = (candidate as { readonly validate?: unknown }).validate;\n return typeof validate === 'function';\n}\n\nfunction extractValidator(candidate: unknown): JsonSchemaValidateFn | undefined {\n return hasJsonValidatorTrait(candidate) ? candidate.validate : undefined;\n}\n\nfunction isResolvedCodec(candidate: unknown): candidate is Codec {\n return (\n candidate !== null &&\n typeof candidate === 'object' &&\n 'id' in candidate &&\n 'decode' in candidate\n );\n}\n\n/**\n * Walk the contract's `storage.tables[].columns[]` and resolve each\n * column to a `Codec` through the unified descriptor map. Per-instance\n * behavior:\n *\n * - **typeRef columns**: reuse the resolved codec materialized once by\n * `initializeTypeHelpers` for the `storage.types` entry. Multiple\n * columns sharing one typeRef share one codec instance.\n * - **inline-typeParams columns**: call `descriptor.factory(typeParams)\n * (ctx)` once per column (per-column anonymous instance).\n * - **non-parameterized columns**: call `descriptor.factory()(ctx)`\n * once. The synthesized descriptor's factory is constant — every call\n * returns the same shared codec instance — so columns sharing a non-\n * parameterized codec id share one resolved codec without explicit\n * caching.\n *\n * Combines what `initializeTypeHelpers` (named-instance walk) and the\n * old `buildJsonSchemaValidatorRegistry` (per-column walk) used to do\n * separately: one walk over all columns, one resolved codec per column,\n * one trait-gated validator extraction per column. The result drives\n * both the dispatch registry (`ContractCodecRegistry.forColumn`) and the\n * validator registry.\n *\n * Codec-registry-unification spec § AC-4: every column resolves through\n * one descriptor map without branching on parameterization.\n */\nfunction buildContractCodecRegistry(\n contract: Contract<SqlStorage>,\n codecDescriptors: CodecDescriptorRegistry,\n legacyCodecRegistry: CodecRegistry,\n types: TypeHelperRegistry,\n parameterizedDescriptors: Map<string, RuntimeParameterizedCodecDescriptor>,\n): {\n readonly registry: ContractCodecRegistry;\n readonly jsonValidators: JsonSchemaValidatorRegistry | undefined;\n} {\n const byColumn = new Map<string, Codec>();\n const byCodecId = new Map<string, Codec>();\n // Codec ids whose `byCodecId` entry is ambiguous — multiple distinct\n // resolved instances landed under the same parameterized codec id (e.g.\n // `Vector<1024>` and `Vector<1536>` both registering under\n // `pg/vector@1`). The encode-side `forCodecId` fallback rejects these\n // ids so a DSL-param without a column ref cannot silently bind to the\n // wrong instance. Retires when AC-5's `ParamRef.refs` plumbing lands\n // (TML-2357).\n const ambiguousCodecIds = new Set<string>();\n const validators = new Map<string, JsonSchemaValidateFn>();\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n const columnKey = `${tableName}.${columnName}`;\n const descriptor = codecDescriptors.descriptorFor(column.codecId);\n\n let resolvedCodec: Codec | undefined;\n\n if (descriptor) {\n const isParameterized = parameterizedDescriptors.has(column.codecId);\n\n if (column.typeRef) {\n // The named instance was already materialized once by\n // `initializeTypeHelpers`; reuse it so multiple columns sharing\n // the same typeRef share one codec instance (and any per-\n // instance helper state on it).\n const helper = types[column.typeRef];\n if (isResolvedCodec(helper)) {\n resolvedCodec = helper;\n }\n } else if (column.typeParams && isParameterized) {\n const parameterizedDescriptor = parameterizedDescriptors.get(column.codecId);\n if (parameterizedDescriptor) {\n const validatedParams = validateTypeParams(column.typeParams, parameterizedDescriptor, {\n tableName,\n columnName,\n });\n const ctx: SqlCodecInstanceContext = {\n name: `<anon:${tableName}.${columnName}>`,\n usedAt: [{ table: tableName, column: columnName }],\n };\n resolvedCodec = parameterizedDescriptor.factory(validatedParams)(ctx);\n }\n } else if (!isParameterized) {\n // Non-parameterized column. Cache the resolved codec by codec\n // id — the synthesized descriptor's factory is constant for\n // non-parameterized codecs, so columns sharing this codec id\n // share one resolved instance.\n let cached = byCodecId.get(column.codecId);\n if (!cached) {\n const ctx: SqlCodecInstanceContext = {\n name: `<shared:${column.codecId}>`,\n usedAt: [{ table: tableName, column: columnName }],\n };\n // `synthesizeNonParameterizedDescriptor` produces a\n // `CodecDescriptor<void>` whose factory ignores its params\n // and ctx; the runtime's `void` value is `undefined`. The\n // structural cast goes through `unknown` to satisfy the\n // heterogeneous-`P` registry boundary (the factory's\n // declared `P` is `any` here; the consumer narrows per\n // codec id). The cast narrows the descriptor's\n // family-agnostic `CodecInstanceContext` slot to the SQL\n // `SqlCodecInstanceContext` we pass at this call site —\n // function-argument contravariance makes the narrow safe\n // (a callee that accepts the base will also accept the\n // SQL extension). Per spec § Non-functional constraints.\n const voidFactory = descriptor.factory as unknown as (\n params: undefined,\n ) => (ctx: SqlCodecInstanceContext) => Codec;\n cached = voidFactory(undefined)(ctx);\n byCodecId.set(column.codecId, cached);\n }\n resolvedCodec = cached;\n }\n // else: parameterized codec id with no typeRef and no typeParams\n // — this is the legitimate \"undimensioned\" form for codecs that\n // ship a no-params column variant alongside a parameterized one\n // (e.g. pgvector's `vectorColumn` vs. `vector(N)`). Leave\n // `resolvedCodec` undefined; encode/decode for this column flows\n // through `forCodecId` (the AC-5-deferred carve-out documented\n // in `relational-core/src/ast/codec-types.ts`). The fallback\n // works for these cases because their wire format is\n // params-independent (vector formats `[v1,v2,...]` regardless\n // of declared length).\n }\n\n if (resolvedCodec) {\n byColumn.set(columnKey, resolvedCodec);\n const validate = extractValidator(resolvedCodec);\n if (validate) {\n validators.set(columnKey, validate);\n }\n const existing = byCodecId.get(column.codecId);\n if (existing === undefined) {\n byCodecId.set(column.codecId, resolvedCodec);\n } else if (existing !== resolvedCodec && parameterizedDescriptors.has(column.codecId)) {\n ambiguousCodecIds.add(column.codecId);\n }\n }\n }\n }\n\n const registry: ContractCodecRegistry = {\n forColumn(table, column) {\n return byColumn.get(`${table}.${column}`);\n },\n forCodecId(codecId) {\n // Codec-id-only fallback for sites without a column ref (encode-\n // side DSL params whose `ParamRef.refs` isn't populated). Prefer\n // the contract-walk-derived shared codec; fall back to the legacy\n // `codecRegistry.get` for parameterized codec ids whose contracts\n // don't have a typeRef/typeParams column the walk could resolve\n // through. The legacy fallback retires once `ParamRef.refs` is\n // threaded everywhere (TML-2357).\n //\n // Reject ambiguous parameterized fallbacks: if the contract walk\n // resolved more than one distinct codec instance under this id\n // (e.g. multiple vector dimensions, multiple arktype-json\n // schemas), the codec-id-keyed lookup cannot honor the call site\n // — fail fast rather than bind to whichever instance happened to\n // land first.\n if (ambiguousCodecIds.has(codecId)) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Codec '${codecId}' resolves to multiple parameterized instances; column-aware dispatch is required.`,\n { codecId },\n );\n }\n return byCodecId.get(codecId) ?? legacyCodecRegistry.get(codecId);\n },\n };\n\n const jsonValidators: JsonSchemaValidatorRegistry | undefined =\n validators.size > 0\n ? {\n get: (key: string) => validators.get(key),\n size: validators.size,\n }\n : undefined;\n\n return { registry, jsonValidators };\n}\n\nfunction assertMutationDefaultGeneratorsAvailable(\n contract: Contract<SqlStorage>,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n): void {\n const defaults = contract.execution?.mutations.defaults ?? [];\n if (defaults.length === 0) return;\n\n const missing = new Set<string>();\n for (const mutationDefault of defaults) {\n for (const phase of [mutationDefault.onCreate, mutationDefault.onUpdate]) {\n if (!phase) continue;\n if (phase.kind === 'generator' && !generatorRegistry.has(phase.id)) {\n missing.add(phase.id);\n }\n }\n }\n\n if (missing.size === 0) return;\n\n const ids = Array.from(missing);\n const idList = ids.map((id) => `'${id}'`).join(', ');\n throw runtimeError(\n 'RUNTIME.MISSING_MUTATION_DEFAULT_GENERATOR',\n `Contract requires mutation default generator(s) ${idList}, but no runtime component provides them.`,\n { ids },\n );\n}\n\nfunction collectMutationDefaultGenerators(\n contributors: ReadonlyArray<SqlStaticContributions & { readonly id: string }>,\n): ReadonlyMap<string, RuntimeMutationDefaultGenerator> {\n const generators = new Map<string, RuntimeMutationDefaultGenerator>();\n const owners = new Map<string, string>();\n\n for (const contributor of contributors) {\n const nextGenerators = contributor.mutationDefaultGenerators?.() ?? [];\n for (const generator of nextGenerators) {\n const existingOwner = owners.get(generator.id);\n if (existingOwner !== undefined) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_MUTATION_DEFAULT_GENERATOR',\n `Duplicate mutation default generator '${generator.id}'.`,\n {\n id: generator.id,\n existingOwner,\n incomingOwner: contributor.id,\n },\n );\n }\n generators.set(generator.id, generator);\n owners.set(generator.id, contributor.id);\n }\n }\n\n return generators;\n}\n\nfunction computeExecutionDefaultValue(\n spec: ExecutionMutationDefaultValue,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n): unknown {\n switch (spec.kind) {\n case 'generator': {\n const generator = generatorRegistry.get(spec.id);\n if (!generator) {\n throw runtimeError(\n 'RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING',\n `Contract references mutation default generator '${spec.id}' but no runtime component provides it.`,\n {\n id: spec.id,\n },\n );\n }\n // nosemgrep: javascript.express.security.express-wkhtml-injection.express-wkhtmltoimage-injection\n return generator.generate(spec.params);\n }\n }\n}\n\nfunction applyMutationDefaults(\n contract: Contract<SqlStorage>,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n options: MutationDefaultsOptions,\n): ReadonlyArray<AppliedMutationDefault> {\n const defaults = contract.execution?.mutations.defaults ?? [];\n if (defaults.length === 0) {\n return [];\n }\n\n const isEmptyUpdate = options.op === 'update' && Object.keys(options.values).length === 0;\n\n const applied: AppliedMutationDefault[] = [];\n const appliedColumns = new Set<string>();\n // Fresh per-call cache for `stability: 'row'` generators — they share\n // across columns of a single row but regenerate on the next call.\n const rowCache = new Map<string, unknown>();\n\n for (const mutationDefault of defaults) {\n if (mutationDefault.ref.table !== options.table) {\n continue;\n }\n\n const defaultSpec =\n options.op === 'create' ? mutationDefault.onCreate : mutationDefault.onUpdate;\n if (!defaultSpec) {\n continue;\n }\n\n // RD2: empty update payloads skip onUpdate defaults — no write means\n // no `@updatedAt` advance.\n if (isEmptyUpdate) {\n continue;\n }\n\n const columnName = mutationDefault.ref.column;\n if (Object.hasOwn(options.values, columnName) || appliedColumns.has(columnName)) {\n continue;\n }\n\n applied.push({\n column: columnName,\n value: resolveScopedValue(\n defaultSpec,\n generatorRegistry,\n rowCache,\n options.defaultValueCache,\n ),\n });\n appliedColumns.add(columnName);\n }\n\n return applied;\n}\n\nfunction resolveScopedValue(\n spec: ExecutionMutationDefaultValue,\n generatorRegistry: ReadonlyMap<string, RuntimeMutationDefaultGenerator>,\n rowCache: Map<string, unknown>,\n queryCache: Map<string, unknown> | undefined,\n): unknown {\n if (spec.kind !== 'generator') {\n return computeExecutionDefaultValue(spec, generatorRegistry);\n }\n const generator = generatorRegistry.get(spec.id);\n const cache = scopedCache(generator?.stability, rowCache, queryCache);\n if (!cache) {\n return computeExecutionDefaultValue(spec, generatorRegistry);\n }\n if (cache.has(spec.id)) {\n return cache.get(spec.id);\n }\n const value = computeExecutionDefaultValue(spec, generatorRegistry);\n cache.set(spec.id, value);\n return value;\n}\n\nfunction scopedCache(\n stability: GeneratorStability | undefined,\n rowCache: Map<string, unknown>,\n queryCache: Map<string, unknown> | undefined,\n): Map<string, unknown> | undefined {\n switch (stability) {\n case 'row':\n return rowCache;\n case 'query':\n return queryCache;\n default:\n return undefined;\n }\n}\n\nexport function createExecutionContext<\n TContract extends Contract<SqlStorage> = Contract<SqlStorage>,\n TTargetId extends string = string,\n>(options: {\n readonly contract: TContract;\n readonly stack: SqlExecutionStack<TTargetId>;\n}): ExecutionContext<TContract> {\n const { contract, stack } = options;\n\n assertExecutionStackContractRequirements(contract, stack);\n\n const codecRegistry = createCodecRegistry();\n\n const contributors: Array<SqlStaticContributions & ComponentDescriptor<string>> = [\n stack.target,\n stack.adapter,\n ...stack.extensionPacks,\n ];\n\n for (const contributor of contributors) {\n for (const c of contributor.codecs().values()) {\n codecRegistry.register(c);\n }\n }\n\n const queryOperationRegistry = createSqlOperationRegistry();\n for (const contributor of contributors) {\n for (const op of contributor.queryOperations?.() ?? []) {\n queryOperationRegistry.register(op);\n }\n }\n\n const parameterizedCodecDescriptors = collectParameterizedCodecDescriptors(contributors);\n const codecDescriptors = buildCodecDescriptorRegistry(\n codecRegistry,\n parameterizedCodecDescriptors,\n );\n const mutationDefaultGeneratorRegistry = collectMutationDefaultGenerators(contributors);\n assertMutationDefaultGeneratorsAvailable(contract, mutationDefaultGeneratorRegistry);\n\n if (parameterizedCodecDescriptors.size > 0) {\n validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);\n }\n\n const types = initializeTypeHelpers(contract.storage, parameterizedCodecDescriptors);\n\n const { registry: contractCodecs, jsonValidators: jsonSchemaValidators } =\n buildContractCodecRegistry(\n contract,\n codecDescriptors,\n codecRegistry,\n types,\n parameterizedCodecDescriptors,\n );\n\n return {\n contract,\n codecs: codecRegistry,\n contractCodecs,\n codecDescriptors,\n queryOperations: queryOperationRegistry,\n types,\n ...(jsonSchemaValidators ? { jsonSchemaValidators } : {}),\n applyMutationDefaults: (options) =>\n applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options),\n };\n}\n","import type { MarkerStatement } from '@prisma-next/sql-relational-core/ast';\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport interface WriteMarkerInput {\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number;\n readonly appTag?: string;\n readonly meta?: Record<string, unknown>;\n /**\n * Applied-invariants set on the marker.\n *\n * - `undefined` → existing column left untouched. Sign and\n * verify-database paths use this; they don't accumulate invariants.\n * - explicit value (including `[]`) → column overwritten with\n * exactly that value.\n */\n readonly invariants?: readonly string[];\n}\n\nexport const ensureSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\nexport const ensureTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n id smallint primary key default 1,\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}',\n invariants text[] not null default '{}'\n )`,\n params: [],\n};\n\nexport function readContractMarker(): MarkerStatement {\n return {\n sql: `select\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta,\n invariants\n from prisma_contract.marker\n where id = $1`,\n params: [1],\n };\n}\n\nexport interface WriteContractMarkerStatements {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n}\n\n/**\n * Variable columns that participate in INSERT/UPDATE alongside the\n * always-on `id = $1` and `updated_at = now()`. Each column declares\n * its name, optional cast type, and parameter value; the placeholder\n * (`$N`) is computed positionally below — adding or reordering a\n * column doesn't desync indices. `invariants` only appears when the\n * caller supplies it — see `WriteMarkerInput.invariants`.\n */\nfunction markerColumns(\n input: WriteMarkerInput,\n): ReadonlyArray<{ readonly name: string; readonly type?: string; readonly param: unknown }> {\n return [\n { name: 'core_hash', param: input.storageHash },\n { name: 'profile_hash', param: input.profileHash },\n { name: 'contract_json', type: 'jsonb', param: input.contractJson ?? null },\n { name: 'canonical_version', param: input.canonicalVersion ?? null },\n { name: 'app_tag', param: input.appTag ?? null },\n { name: 'meta', type: 'jsonb', param: JSON.stringify(input.meta ?? {}) },\n ...(input.invariants !== undefined\n ? [{ name: 'invariants' as const, type: 'text[]' as const, param: input.invariants }]\n : []),\n ];\n}\n\nexport function writeContractMarker(input: WriteMarkerInput): WriteContractMarkerStatements {\n const cols = markerColumns(input);\n // $1 is reserved for `id`; subsequent positions follow the order of cols.\n const placed = cols.map((c, i) => ({\n name: c.name,\n expr: c.type ? `$${i + 2}::${c.type}` : `$${i + 2}`,\n param: c.param,\n }));\n const params: readonly unknown[] = [1, ...placed.map((c) => c.param)];\n\n // `updated_at = now()` is a SQL literal with no parameter slot, so it\n // sits outside `placed` and is appended directly to each statement.\n const insertColumns = ['id', ...placed.map((c) => c.name), 'updated_at'].join(', ');\n const insertValues = ['$1', ...placed.map((c) => c.expr), 'now()'].join(', ');\n const setClauses = [...placed.map((c) => `${c.name} = ${c.expr}`), 'updated_at = now()'].join(\n ', ',\n );\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (${insertColumns}) values (${insertValues})`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set ${setClauses} where id = $1`,\n params,\n },\n };\n}\n","import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type {\n JsonSchemaValidationError,\n JsonSchemaValidatorRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\n\n/**\n * Validates a JSON value against its column's JSON Schema, if a validator exists.\n *\n * Throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` on validation failure.\n * No-ops if no validator is registered for the column.\n */\nexport function validateJsonValue(\n registry: JsonSchemaValidatorRegistry,\n table: string,\n column: string,\n value: unknown,\n direction: 'encode' | 'decode',\n codecId?: string,\n): void {\n const key = `${table}.${column}`;\n const validate = registry.get(key);\n if (!validate) return;\n\n const result = validate(value);\n if (result.valid) return;\n\n throw createJsonSchemaValidationError(table, column, direction, result.errors, codecId);\n}\n\nfunction createJsonSchemaValidationError(\n table: string,\n column: string,\n direction: 'encode' | 'decode',\n errors: ReadonlyArray<JsonSchemaValidationError>,\n codecId?: string,\n): Error {\n const summary = formatErrorSummary(errors);\n return runtimeError(\n 'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED',\n `JSON schema validation failed for column '${table}.${column}' (${direction}): ${summary}`,\n {\n table,\n column,\n codecId,\n direction,\n errors: [...errors],\n },\n );\n}\n\nfunction formatErrorSummary(errors: ReadonlyArray<JsonSchemaValidationError>): string {\n if (errors.length === 0) return 'unknown validation error';\n if (errors.length === 1) {\n const err = errors[0] as JsonSchemaValidationError;\n return err.path === '/' ? err.message : `${err.path}: ${err.message}`;\n }\n return errors\n .map((err) => (err.path === '/' ? err.message : `${err.path}: ${err.message}`))\n .join('; ');\n}\n","import {\n checkAborted,\n isRuntimeError,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport type {\n AnyQueryAst,\n Codec,\n CodecRegistry,\n ContractCodecRegistry,\n ProjectionItem,\n SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { JsonSchemaValidatorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\nimport { validateJsonValue } from './json-schema-validation';\n\ntype ColumnRef = { table: string; column: string };\n\ninterface DecodeContext {\n readonly aliases: ReadonlyArray<string> | undefined;\n readonly codecs: ReadonlyMap<string, Codec>;\n readonly columnRefs: ReadonlyMap<string, ColumnRef>;\n readonly includeAliases: ReadonlySet<string>;\n}\n\nconst WIRE_PREVIEW_LIMIT = 100;\nconst EMPTY_INCLUDE_ALIASES: ReadonlySet<string> = new Set<string>();\n\nfunction isAstBackedPlan(\n plan: SqlExecutionPlan,\n): plan is SqlExecutionPlan & { readonly ast: AnyQueryAst } {\n return plan.ast !== undefined;\n}\n\nfunction projectionListFromAst(ast: AnyQueryAst): ReadonlyArray<ProjectionItem> | undefined {\n if (ast.kind === 'select') {\n return ast.projection;\n }\n return ast.returning;\n}\n\n/**\n * Resolve the per-cell codec for a projection item.\n *\n * Phase B: when a `(table, column)` ref is available for the projection,\n * prefer `contractCodecs.forColumn(table, column)` — that's the per-\n * instance resolved codec materialized from the codec descriptor's\n * factory at context-construction time (carries any per-instance state\n * such as the compiled JSON-Schema validator). When the projection\n * resolves to a non-`column-ref` expression (computed projections, raw\n * SQL aliases) but still carries a codec id (ADR 205 stamps every\n * `ProjectionItem` with the producer's codec id), fall back to the\n * codec-id-keyed `forCodecId(codecId)` lookup, which itself falls back\n * to the legacy `CodecRegistry` for codec ids the contract walk\n * couldn't resolve.\n *\n * Codec-registry-unification spec § AC-4.\n */\nfunction resolveProjectionCodec(\n item: ProjectionItem,\n registry: CodecRegistry,\n contractCodecs: ContractCodecRegistry | undefined,\n): Codec | undefined {\n if (item.expr.kind === 'column-ref' && contractCodecs) {\n const byColumn = contractCodecs.forColumn(item.expr.table, item.expr.column);\n if (byColumn) return byColumn;\n }\n if (item.codecId) {\n const fromContract = contractCodecs?.forCodecId(item.codecId);\n if (fromContract) return fromContract;\n return registry.get(item.codecId);\n }\n return undefined;\n}\n\nfunction buildDecodeContext(\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n contractCodecs: ContractCodecRegistry | undefined,\n): DecodeContext {\n if (!isAstBackedPlan(plan)) {\n return {\n aliases: undefined,\n codecs: new Map(),\n columnRefs: new Map(),\n includeAliases: EMPTY_INCLUDE_ALIASES,\n };\n }\n\n const projection = projectionListFromAst(plan.ast);\n if (!projection) {\n return {\n aliases: undefined,\n codecs: new Map(),\n columnRefs: new Map(),\n includeAliases: EMPTY_INCLUDE_ALIASES,\n };\n }\n\n const aliases: string[] = [];\n const codecs = new Map<string, Codec>();\n const columnRefs = new Map<string, ColumnRef>();\n const includeAliases = new Set<string>();\n\n for (const item of projection) {\n aliases.push(item.alias);\n\n const codec = resolveProjectionCodec(item, registry, contractCodecs);\n if (codec) {\n codecs.set(item.alias, codec);\n }\n\n if (item.expr.kind === 'column-ref') {\n columnRefs.set(item.alias, { table: item.expr.table, column: item.expr.column });\n } else if (item.expr.kind === 'subquery' || item.expr.kind === 'json-array-agg') {\n includeAliases.add(item.alias);\n }\n }\n\n return { aliases, codecs, columnRefs, includeAliases };\n}\n\nfunction previewWireValue(wireValue: unknown): string {\n if (typeof wireValue === 'string') {\n return wireValue.length > WIRE_PREVIEW_LIMIT\n ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...`\n : wireValue;\n }\n return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);\n}\n\nfunction isJsonSchemaValidationError(error: unknown): boolean {\n return isRuntimeError(error) && error.code === 'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED';\n}\n\nfunction wrapDecodeFailure(\n error: unknown,\n alias: string,\n ref: ColumnRef | undefined,\n codec: Codec,\n wireValue: unknown,\n): never {\n const message = error instanceof Error ? error.message : String(error);\n const target = ref ? `${ref.table}.${ref.column}` : alias;\n const wrapped = runtimeError(\n 'RUNTIME.DECODE_FAILED',\n `Failed to decode column ${target} with codec '${codec.id}': ${message}`,\n {\n ...(ref ? { table: ref.table, column: ref.column } : { alias }),\n codec: codec.id,\n wirePreview: previewWireValue(wireValue),\n },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\nfunction wrapIncludeAggregateFailure(error: unknown, alias: string, wireValue: unknown): never {\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.DECODE_FAILED',\n `Failed to parse JSON array for include alias '${alias}': ${message}`,\n {\n alias,\n wirePreview: previewWireValue(wireValue),\n },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\nfunction decodeIncludeAggregate(alias: string, wireValue: unknown): unknown {\n if (wireValue === null || wireValue === undefined) {\n return [];\n }\n\n try {\n let parsed: unknown;\n if (typeof wireValue === 'string') {\n parsed = JSON.parse(wireValue);\n } else if (Array.isArray(wireValue)) {\n parsed = wireValue;\n } else {\n parsed = JSON.parse(String(wireValue));\n }\n\n if (!Array.isArray(parsed)) {\n throw new Error(`Expected array for include alias '${alias}', got ${typeof parsed}`);\n }\n\n return parsed;\n } catch (error) {\n wrapIncludeAggregateFailure(error, alias, wireValue);\n }\n}\n\n/**\n * Decodes a single field. Single-armed: every cell takes the same path —\n * `codec.decode → await → JSON-Schema validate → return plain value` — so\n * sync- and async-authored codecs are indistinguishable to callers.\n *\n * The row-level `rowCtx` is repackaged into a per-cell\n * `SqlCodecCallContext` whose `column = { table, name }` is a structural\n * projection of the per-cell `ColumnRef = { table, column }` resolved from\n * the AST-backed `DecodeContext` (the same resolution `wrapDecodeFailure`\n * uses for envelope construction — one resolution per cell, two consumers).\n * Cells the runtime cannot resolve to a single underlying column (aggregate\n * aliases, computed projections without a simple ref) get\n * `column: undefined`, matching the spec contract that the runtime never\n * silently defaults this field.\n */\nasync function decodeField(\n alias: string,\n wireValue: unknown,\n decodeCtx: DecodeContext,\n jsonValidators: JsonSchemaValidatorRegistry | undefined,\n rowCtx: SqlCodecCallContext,\n): Promise<unknown> {\n if (wireValue === null) {\n return null;\n }\n\n const codec = decodeCtx.codecs.get(alias);\n if (!codec) {\n return wireValue;\n }\n\n const ref = decodeCtx.columnRefs.get(alias);\n\n // Per-cell ctx: the cell-level `column` is a `SqlColumnRef = { table, name }`\n // projection of the resolved `ColumnRef = { table, column }` (same\n // resolution `wrapDecodeFailure` uses below — no double work). Cells the\n // runtime cannot resolve (aggregate aliases, computed projections without\n // a simple ref) drop the `column` field entirely — explicitly cleared so\n // a previously-populated `rowCtx.column` cannot leak through to unrelated\n // cells. Destructuring (rather than `column: undefined`) is required\n // because `SqlCodecCallContext.column` is declared `column?: SqlColumnRef`\n // under `exactOptionalPropertyTypes`.\n let cellCtx: SqlCodecCallContext;\n if (ref) {\n cellCtx = { ...rowCtx, column: { table: ref.table, name: ref.column } };\n } else {\n const { column: _drop, ...rowCtxWithoutColumn } = rowCtx;\n cellCtx = rowCtxWithoutColumn;\n }\n\n let decoded: unknown;\n try {\n decoded = await codec.decode(wireValue, cellCtx);\n } catch (error) {\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n\n if (jsonValidators && ref) {\n try {\n validateJsonValue(jsonValidators, ref.table, ref.column, decoded, 'decode', codec.id);\n } catch (error) {\n if (isJsonSchemaValidationError(error)) throw error;\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n }\n\n return decoded;\n}\n\n/**\n * Decodes a row by dispatching all per-cell codec calls concurrently via\n * `Promise.all`. Each cell follows the single-armed `decodeField` path.\n * Failures are wrapped in `RUNTIME.DECODE_FAILED` with `{ table, column,\n * codec }` (or `{ alias, codec }` when no column ref is resolvable) and the\n * original error attached on `cause`.\n *\n * When `rowCtx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED`\n * (`{ phase: 'decode' }`) before any `codec.decode` call is made.\n * - **Mid-flight aborts** race the per-cell `Promise.all` against the\n * signal so the runtime returns promptly even when codec bodies ignore\n * it. In-flight bodies that ignore the signal complete in the\n * background (cooperative cancellation).\n * - Existing `RUNTIME.DECODE_FAILED` envelopes from codec bodies pass\n * through unchanged (no double wrap).\n */\nexport async function decodeRow(\n row: Record<string, unknown>,\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n jsonValidators: JsonSchemaValidatorRegistry | undefined,\n rowCtx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<Record<string, unknown>> {\n checkAborted(rowCtx, 'decode');\n const signal = rowCtx.signal;\n\n const decodeCtx = buildDecodeContext(plan, registry, contractCodecs);\n\n const aliases = decodeCtx.aliases ?? Object.keys(row);\n\n if (decodeCtx.aliases !== undefined) {\n for (const alias of decodeCtx.aliases) {\n if (!Object.hasOwn(row, alias)) {\n throw runtimeError('RUNTIME.DECODE_FAILED', `Row missing projection alias \"${alias}\"`, {\n alias,\n expectedAliases: decodeCtx.aliases,\n presentKeys: Object.keys(row),\n });\n }\n }\n }\n\n const tasks: Promise<unknown>[] = [];\n const includeIndices: { index: number; alias: string; value: unknown }[] = [];\n\n for (let i = 0; i < aliases.length; i++) {\n const alias = aliases[i] as string;\n const wireValue = row[alias];\n\n if (decodeCtx.includeAliases.has(alias)) {\n includeIndices.push({ index: i, alias, value: wireValue });\n tasks.push(Promise.resolve(undefined));\n continue;\n }\n\n tasks.push(decodeField(alias, wireValue, decodeCtx, jsonValidators, rowCtx));\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'decode');\n\n // Include aggregates are decoded synchronously after concurrent codec\n // dispatch settles, so any decode failures upstream propagate first.\n for (const entry of includeIndices) {\n settled[entry.index] = decodeIncludeAggregate(entry.alias, entry.value);\n }\n\n const decoded: Record<string, unknown> = {};\n for (let i = 0; i < aliases.length; i++) {\n decoded[aliases[i] as string] = settled[i];\n }\n return decoded;\n}\n","import {\n checkAborted,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport {\n type Codec,\n type CodecRegistry,\n type ContractCodecRegistry,\n collectOrderedParamRefs,\n type SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\n\ninterface ParamMetadata {\n readonly codecId: string | undefined;\n readonly name: string | undefined;\n}\n\nconst NO_METADATA: ParamMetadata = Object.freeze({ codecId: undefined, name: undefined });\n\n/**\n * Resolve the codec for an outgoing param.\n *\n * Phase B (and AC-5-deferred carve-out): `ParamRef` does not carry a\n * `(table, column)` ref today — every `ParamRef` carries `codecId` but\n * not the column it relates to. Encode-side dispatch therefore consults\n * `contractCodecs.forCodecId(codecId)` (which itself prefers the\n * contract-walk-derived shared codec, falling back to the legacy\n * `CodecRegistry.get` for parameterized codec ids whose contracts don't\n * have a column the walk could resolve through).\n *\n * For the parameterized codecs shipped at Phase B (pgvector, postgres\n * json/jsonb), encode is per-instance-stateless w.r.t. params:\n * - pgvector formats `[v1,v2,...]` regardless of declared length;\n * - postgres json/jsonb encode is `JSON.stringify` regardless of schema.\n *\n * So the codec-id-keyed lookup yields a structurally equivalent encoder\n * even when the resolved per-instance codec carries extra state (e.g. a\n * compiled JSON-Schema validator used only by `decode`). TML-2357 retires\n * the fallback by threading `ParamRef.refs` through column-bound\n * construction sites.\n */\nfunction resolveParamCodec(\n metadata: ParamMetadata,\n registry: CodecRegistry,\n contractCodecs: ContractCodecRegistry | undefined,\n): Codec | undefined {\n if (!metadata.codecId) return undefined;\n const fromContract = contractCodecs?.forCodecId(metadata.codecId);\n if (fromContract) return fromContract;\n return registry.get(metadata.codecId);\n}\n\nfunction paramLabel(metadata: ParamMetadata, paramIndex: number): string {\n return metadata.name ?? `param[${paramIndex}]`;\n}\n\nfunction wrapEncodeFailure(\n error: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\n codecId: string,\n): never {\n const label = paramLabel(metadata, paramIndex);\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.ENCODE_FAILED',\n `Failed to encode parameter ${label} with codec '${codecId}': ${message}`,\n { label, codec: codecId, paramIndex },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\n/**\n * Encodes a single parameter through its codec. Always awaits codec.encode so\n * a Promise can never leak into the driver, even if a sync-authored codec is\n * lifted to async by the codec() factory. Failures are wrapped in\n * `RUNTIME.ENCODE_FAILED` with `{ label, codec, paramIndex }` and the original\n * error attached on `cause`.\n *\n * `ctx` is forwarded verbatim to `codec.encode` so codec authors who opt\n * into the `(value, ctx)` arity see the same `SqlCodecCallContext` the\n * runtime built for the surrounding `runtime.execute()` call. The ctx is\n * always present; its `signal` field may be `undefined`. Encode call\n * sites do not populate `ctx.column` — encode-time column context is the\n * middleware's domain.\n */\nexport async function encodeParam(\n value: unknown,\n paramRef: { readonly codecId?: string; readonly name?: string },\n paramIndex: number,\n registry: CodecRegistry,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<unknown> {\n return encodeParamValue(\n value,\n { codecId: paramRef.codecId, name: paramRef.name },\n paramIndex,\n registry,\n ctx,\n contractCodecs,\n );\n}\n\nasync function encodeParamValue(\n value: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\n registry: CodecRegistry,\n ctx: SqlCodecCallContext,\n contractCodecs: ContractCodecRegistry | undefined,\n): Promise<unknown> {\n if (value === null || value === undefined) {\n return null;\n }\n\n const codec = resolveParamCodec(metadata, registry, contractCodecs);\n if (!codec) {\n return value;\n }\n\n try {\n return await codec.encode(value, ctx);\n } catch (error) {\n wrapEncodeFailure(error, metadata, paramIndex, codec.id);\n }\n}\n\n/**\n * Encodes all parameters concurrently via `Promise.all`. Per parameter, sync-\n * and async-authored codecs share the same path: `codec.encode → await →\n * return`. Param-level failures are wrapped in `RUNTIME.ENCODE_FAILED`.\n *\n * When `ctx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED`\n * (`{ phase: 'encode' }`) before any `codec.encode` call is made — codecs\n * can pin this with a per-call counter that stays at zero.\n * - **Mid-flight abort** races the per-param `Promise.all` against\n * `abortable(ctx.signal)`. The runtime returns `RUNTIME.ABORTED` promptly\n * even if codec bodies ignore the signal; the in-flight bodies are\n * abandoned and run to completion in the background (cooperative\n * cancellation, see ADR 204).\n * - Existing `RUNTIME.ENCODE_FAILED` envelopes that surface from a codec\n * body before the runtime observes the abort pass through unchanged\n * (no double wrap).\n */\nexport async function encodeParams(\n plan: SqlExecutionPlan,\n registry: CodecRegistry,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<readonly unknown[]> {\n checkAborted(ctx, 'encode');\n const signal = ctx.signal;\n\n if (plan.params.length === 0) {\n return plan.params;\n }\n\n const paramCount = plan.params.length;\n const metadata: ParamMetadata[] = new Array(paramCount).fill(NO_METADATA);\n\n if (plan.ast) {\n const refs = collectOrderedParamRefs(plan.ast);\n for (let i = 0; i < paramCount && i < refs.length; i++) {\n const ref = refs[i];\n if (ref) {\n metadata[i] = { codecId: ref.codecId, name: ref.name };\n }\n }\n }\n\n const tasks: Promise<unknown>[] = new Array(paramCount);\n for (let i = 0; i < paramCount; i++) {\n tasks[i] = encodeParamValue(\n plan.params[i],\n metadata[i] ?? NO_METADATA,\n i,\n registry,\n ctx,\n contractCodecs,\n );\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'encode');\n return Object.freeze(settled);\n}\n","import type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\nimport { canonicalStringify } from '@prisma-next/utils/canonical-stringify';\nimport { hashContent } from '@prisma-next/utils/hash-content';\n\n/**\n * Computes a stable content hash for a lowered SQL execution plan.\n *\n * Internally builds an unambiguous canonical-stringified preimage from\n * three components:\n *\n * 1. `meta.storageHash` — discriminates by schema. A migration changes the\n * storage hash, which invalidates cached entries automatically.\n * 2. `exec.sql` — the raw lowered SQL text. Two queries with different\n * structure produce different keys. Note that we deliberately do **not**\n * use `computeSqlFingerprint` here: that helper strips literals to group\n * executions by statement shape (used by telemetry), which is the\n * opposite of what a content hash needs — we want per-execution\n * discrimination, not per-statement-shape grouping.\n * 3. `exec.params` — the bound parameters. `canonicalStringify` produces a\n * deterministic serialization that is stable across object key\n * insertion order and that distinguishes types JSON would otherwise\n * conflate (e.g. `BigInt(1)` vs `1`).\n *\n * The components are wrapped in an object and canonicalized as a single\n * unit (rather than concatenated with a delimiter) so component\n * boundaries are unambiguous: any character appearing inside `sql` or\n * `storageHash` cannot bleed across components and produce a collision\n * with a different split of the same characters.\n *\n * The canonical string is then piped through `hashContent` to produce a\n * bounded, opaque digest. See `@prisma-next/utils/hash-content` for the\n * rationale.\n *\n * @internal\n */\nexport function computeSqlContentHash(exec: SqlExecutionPlan): Promise<string> {\n return hashContent(\n canonicalStringify({\n storageHash: exec.meta.storageHash,\n sql: exec.sql,\n params: exec.params,\n }),\n );\n}\n","import { createHash } from 'node:crypto';\n\nconst STRING_LITERAL_REGEX = /'(?:''|[^'])*'/g;\nconst NUMERIC_LITERAL_REGEX = /\\b\\d+(?:\\.\\d+)?\\b/g;\nconst WHITESPACE_REGEX = /\\s+/g;\n\n/**\n * Computes a literal-stripped, normalized fingerprint of a SQL statement.\n *\n * The function strips string and numeric literals, collapses whitespace, and\n * lowercases the result before hashing — so two structurally equivalent\n * statements (with different parameter values) produce the same fingerprint.\n * Used by SQL telemetry to group queries.\n */\nexport function computeSqlFingerprint(sql: string): string {\n const withoutStrings = sql.replace(STRING_LITERAL_REGEX, '?');\n const withoutNumbers = withoutStrings.replace(NUMERIC_LITERAL_REGEX, '?');\n const normalized = withoutNumbers.replace(WHITESPACE_REGEX, ' ').trim().toLowerCase();\n\n const hash = createHash('sha256').update(normalized).digest('hex');\n return `sha256:${hash}`;\n}\n","import type { DraftPlan, SqlMiddleware, SqlMiddlewareContext } from './sql-middleware';\n\nexport async function runBeforeCompileChain(\n middleware: readonly SqlMiddleware[],\n initial: DraftPlan,\n ctx: SqlMiddlewareContext,\n): Promise<DraftPlan> {\n let current = initial;\n for (const mw of middleware) {\n if (!mw.beforeCompile) {\n continue;\n }\n const result = await mw.beforeCompile(current, ctx);\n if (result === undefined) {\n continue;\n }\n if (result.ast === current.ast) {\n continue;\n }\n ctx.log.debug?.({\n event: 'middleware.rewrite',\n middleware: mw.name,\n lane: current.meta.lane,\n });\n current = result;\n }\n\n return current;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { ExecutionPlan } from '@prisma-next/framework-components/runtime';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { AdapterProfile } from '@prisma-next/sql-relational-core/ast';\nimport type { MarkerReader, RuntimeFamilyAdapter } from './runtime-spi';\n\nexport class SqlFamilyAdapter<TContract extends Contract<SqlStorage>>\n implements RuntimeFamilyAdapter<TContract>\n{\n readonly contract: TContract;\n readonly markerReader: MarkerReader;\n\n constructor(contract: TContract, adapterProfile: AdapterProfile) {\n this.contract = contract;\n this.markerReader = adapterProfile;\n }\n\n validatePlan(plan: ExecutionPlan, contract: TContract): void {\n if (plan.meta.target !== contract.target) {\n throw runtimeError('PLAN.TARGET_MISMATCH', 'Plan target does not match runtime target', {\n planTarget: plan.meta.target,\n runtimeTarget: contract.target,\n });\n }\n\n if (plan.meta.storageHash !== contract.storage.storageHash) {\n throw runtimeError(\n 'PLAN.HASH_MISMATCH',\n 'Plan storage hash does not match runtime contract',\n {\n planStorageHash: plan.meta.storageHash,\n runtimeStorageHash: contract.storage.storageHash,\n },\n );\n }\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n ExecutionStackInstance,\n RuntimeDriverInstance,\n} from '@prisma-next/framework-components/execution';\nimport {\n AsyncIterableResult,\n checkAborted,\n checkMiddlewareCompatibility,\n RuntimeCore,\n type RuntimeExecuteOptions,\n type RuntimeLog,\n runtimeError,\n runWithMiddleware,\n} from '@prisma-next/framework-components/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n AnyQueryAst,\n CodecRegistry,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecCallContext,\n SqlDriver,\n SqlQueryable,\n SqlTransaction,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type {\n CodecDescriptorRegistry,\n JsonSchemaValidatorRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport type { RuntimeScope } from '@prisma-next/sql-relational-core/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { decodeRow } from './codecs/decoding';\nimport { encodeParams } from './codecs/encoding';\nimport { validateCodecRegistryCompleteness } from './codecs/validation';\nimport { computeSqlContentHash } from './content-hash';\nimport { computeSqlFingerprint } from './fingerprint';\nimport { lowerSqlPlan } from './lower-sql-plan';\nimport { runBeforeCompileChain } from './middleware/before-compile-chain';\nimport type { SqlMiddleware, SqlMiddlewareContext } from './middleware/sql-middleware';\nimport type {\n RuntimeFamilyAdapter,\n RuntimeTelemetryEvent,\n RuntimeVerifyOptions,\n TelemetryOutcome,\n} from './runtime-spi';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterInstance,\n SqlRuntimeExtensionInstance,\n} from './sql-context';\nimport { SqlFamilyAdapter } from './sql-family-adapter';\n\nexport type Log = RuntimeLog;\n\nexport interface RuntimeOptions<TContract extends Contract<SqlStorage> = Contract<SqlStorage>> {\n readonly context: ExecutionContext<TContract>;\n readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n readonly driver: SqlDriver<unknown>;\n readonly verify: RuntimeVerifyOptions;\n readonly middleware?: readonly SqlMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n readonly log?: Log;\n}\n\nexport interface CreateRuntimeOptions<\n TContract extends Contract<SqlStorage> = Contract<SqlStorage>,\n TTargetId extends string = string,\n> {\n readonly stackInstance: ExecutionStackInstance<\n 'sql',\n TTargetId,\n SqlRuntimeAdapterInstance<TTargetId>,\n RuntimeDriverInstance<'sql', TTargetId>,\n SqlRuntimeExtensionInstance<TTargetId>\n >;\n readonly context: ExecutionContext<TContract>;\n readonly driver: SqlDriver<unknown>;\n readonly verify: RuntimeVerifyOptions;\n readonly middleware?: readonly SqlMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n readonly log?: Log;\n}\n\nexport interface Runtime extends RuntimeQueryable {\n connection(): Promise<RuntimeConnection>;\n telemetry(): RuntimeTelemetryEvent | null;\n close(): Promise<void>;\n}\n\nexport interface RuntimeConnection extends RuntimeQueryable {\n transaction(): Promise<RuntimeTransaction>;\n /**\n * Returns the connection to the pool for reuse. Only call this when the\n * connection is known to be in a clean state. If a transaction\n * commit/rollback failed or the connection is otherwise suspect, call\n * `destroy(reason)` instead.\n */\n release(): Promise<void>;\n /**\n * Evicts the connection so it is never reused. Call this when the\n * connection may be in an indeterminate state (e.g. a failed rollback\n * leaving an open transaction, or a broken socket).\n *\n * If teardown fails the error is propagated and the connection remains\n * retryable, so the caller can decide whether to swallow the failure or\n * retry cleanup. Calling destroy() or release() more than once after a\n * successful teardown is caller error.\n *\n * `reason` is advisory context only. It may be surfaced to driver-level\n * observability hooks (e.g. pg-pool's `'release'` event) but does not\n * influence eviction behavior and is not rethrown.\n */\n destroy(reason?: unknown): Promise<void>;\n}\n\nexport interface RuntimeTransaction extends RuntimeQueryable {\n commit(): Promise<void>;\n rollback(): Promise<void>;\n}\n\nexport interface RuntimeQueryable extends RuntimeScope {}\n\nexport interface TransactionContext extends RuntimeQueryable {\n readonly invalidated: boolean;\n}\n\nexport type { RuntimeTelemetryEvent, RuntimeVerifyOptions, TelemetryOutcome };\n\nfunction isExecutionPlan(plan: SqlExecutionPlan | SqlQueryPlan): plan is SqlExecutionPlan {\n return 'sql' in plan;\n}\n\nclass SqlRuntimeImpl<TContract extends Contract<SqlStorage> = Contract<SqlStorage>>\n extends RuntimeCore<SqlQueryPlan, SqlExecutionPlan, SqlMiddleware>\n implements Runtime\n{\n private readonly contract: TContract;\n private readonly adapter: Adapter<AnyQueryAst, Contract<SqlStorage>, LoweredStatement>;\n private readonly driver: SqlDriver<unknown>;\n private readonly familyAdapter: RuntimeFamilyAdapter<Contract<SqlStorage>>;\n private readonly codecRegistry: CodecRegistry;\n private readonly contractCodecs: ContractCodecRegistry;\n private readonly codecDescriptors: CodecDescriptorRegistry;\n private readonly jsonSchemaValidators: JsonSchemaValidatorRegistry | undefined;\n private readonly sqlCtx: SqlMiddlewareContext;\n private readonly verify: RuntimeVerifyOptions;\n private codecRegistryValidated: boolean;\n private verified: boolean;\n private startupVerified: boolean;\n private _telemetry: RuntimeTelemetryEvent | null;\n\n constructor(options: RuntimeOptions<TContract>) {\n const { context, adapter, driver, verify, middleware, mode, log } = options;\n\n if (middleware) {\n for (const mw of middleware) {\n checkMiddlewareCompatibility(mw, 'sql', context.contract.target);\n }\n }\n\n const sqlCtx: SqlMiddlewareContext = {\n contract: context.contract,\n mode: mode ?? 'strict',\n now: () => Date.now(),\n log: log ?? {\n info: () => {},\n warn: () => {},\n error: () => {},\n },\n // ctx is only invoked by runWithMiddleware with execs this runtime lowered;\n // the framework parameter type is the cross-family base.\n contentHash: (exec) => computeSqlContentHash(exec as SqlExecutionPlan),\n };\n\n super({ middleware: middleware ?? [], ctx: sqlCtx });\n\n this.contract = context.contract;\n this.adapter = adapter;\n this.driver = driver;\n this.familyAdapter = new SqlFamilyAdapter(context.contract, adapter.profile);\n this.codecRegistry = context.codecs;\n this.contractCodecs = context.contractCodecs;\n this.codecDescriptors = context.codecDescriptors;\n this.jsonSchemaValidators = context.jsonSchemaValidators;\n this.sqlCtx = sqlCtx;\n this.verify = verify;\n this.codecRegistryValidated = false;\n this.verified = verify.mode === 'startup' ? false : verify.mode === 'always';\n this.startupVerified = false;\n this._telemetry = null;\n\n if (verify.mode === 'startup') {\n validateCodecRegistryCompleteness(this.codecDescriptors, context.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n /**\n * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan` with\n * encoded parameters ready for the driver. This is the single point at\n * which params transition from app-layer values to driver wire-format.\n *\n * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so per-query\n * cancellation reaches every codec body during parameter encoding. The\n * framework abstract typed this as `CodecCallContext`; the SQL family\n * narrows it to the SQL-specific extension. SQL params do not populate\n * `ctx.column` — encode-side column metadata is the middleware's domain.\n */\n protected override async lower(\n plan: SqlQueryPlan,\n ctx: SqlCodecCallContext,\n ): Promise<SqlExecutionPlan> {\n const lowered = lowerSqlPlan(this.adapter, this.contract, plan);\n return Object.freeze({\n ...lowered,\n params: await encodeParams(lowered, this.codecRegistry, ctx, this.contractCodecs),\n });\n }\n\n /**\n * Default driver invocation. Production execution paths override the\n * queryable target (e.g. transaction or connection) by going through\n * `executeAgainstQueryable`; this implementation supports any caller of\n * `super.execute(plan)` and the abstract-base contract.\n */\n protected override runDriver(exec: SqlExecutionPlan): AsyncIterable<Record<string, unknown>> {\n return this.driver.execute<Record<string, unknown>>({\n sql: exec.sql,\n params: exec.params,\n });\n }\n\n /**\n * SQL pre-compile hook. Runs the registered middleware `beforeCompile`\n * chain over the plan's draft (AST + meta). Returns the original plan\n * unchanged when no middleware rewrote the AST; otherwise returns a new\n * plan carrying the rewritten AST and meta. The AST is the authoritative\n * source of execution metadata, so a rewrite needs no sidecar\n * reconciliation here — the lowering adapter and the encoder both walk\n * the rewritten AST directly.\n */\n protected override async runBeforeCompile(plan: SqlQueryPlan): Promise<SqlQueryPlan> {\n const rewrittenDraft = await runBeforeCompileChain(\n this.middleware,\n { ast: plan.ast, meta: plan.meta },\n this.sqlCtx,\n );\n return rewrittenDraft.ast === plan.ast\n ? plan\n : { ...plan, ast: rewrittenDraft.ast, meta: rewrittenDraft.meta };\n }\n\n override execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return this.executeAgainstQueryable<Row>(plan, this.driver, options);\n }\n\n private executeAgainstQueryable<Row>(\n plan: SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>,\n queryable: SqlQueryable,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n this.ensureCodecRegistryValidated();\n\n const self = this;\n const signal = options?.signal;\n // One ctx per execute() call — the same reference is shared by\n // encodeParams (lower), decodeRow (per-row), and the stream loop's\n // between-row checks. Per-cell ctx allocations inside decodeField add\n // `column` for resolvable cells without re-wrapping the signal. The\n // ctx object is always allocated; the `signal` field is only included\n // when a signal was supplied (exactOptionalPropertyTypes).\n const codecCtx: SqlCodecCallContext = signal === undefined ? {} : { signal };\n\n const generator = async function* (): AsyncGenerator<Row, void, unknown> {\n checkAborted(codecCtx, 'stream');\n\n const exec: SqlExecutionPlan = isExecutionPlan(plan)\n ? Object.freeze({\n ...plan,\n params: await encodeParams(plan, self.codecRegistry, codecCtx, self.contractCodecs),\n })\n : await self.lower(await self.runBeforeCompile(plan), codecCtx);\n\n self.familyAdapter.validatePlan(exec, self.contract);\n self._telemetry = null;\n\n if (!self.startupVerified && self.verify.mode === 'startup') {\n await self.verifyMarker();\n }\n\n if (!self.verified && self.verify.mode === 'onFirstUse') {\n await self.verifyMarker();\n }\n\n const startedAt = Date.now();\n let outcome: TelemetryOutcome | null = null;\n\n try {\n if (self.verify.mode === 'always') {\n await self.verifyMarker();\n }\n\n const stream = runWithMiddleware<SqlExecutionPlan, Record<string, unknown>>(\n exec,\n self.middleware,\n self.ctx,\n () =>\n queryable.execute<Record<string, unknown>>({\n sql: exec.sql,\n params: exec.params,\n }),\n );\n\n // Manually drive the driver's async iterator so the between-row\n // abort check fires *before* requesting the next row. With a\n // `for await...of` loop the runtime would await `iterator.next()`\n // first, leaving a window where one extra row is pulled through\n // the driver after the signal aborted.\n const iterator = stream[Symbol.asyncIterator]();\n try {\n while (true) {\n checkAborted(codecCtx, 'stream');\n const next = await iterator.next();\n if (next.done) {\n break;\n }\n const decodedRow = await decodeRow(\n next.value,\n exec,\n self.codecRegistry,\n self.jsonSchemaValidators,\n codecCtx,\n self.contractCodecs,\n );\n yield decodedRow as Row;\n }\n } finally {\n // Best-effort iterator cleanup so the driver can release its\n // resources whether the stream finished normally, threw, or was\n // abandoned by the consumer.\n await iterator.return?.();\n }\n\n outcome = 'success';\n } catch (error) {\n outcome = 'runtime-error';\n throw error;\n } finally {\n if (outcome !== null) {\n self.recordTelemetry(exec, outcome, Date.now() - startedAt);\n }\n }\n };\n\n return new AsyncIterableResult(generator());\n }\n\n async connection(): Promise<RuntimeConnection> {\n const driverConn = await this.driver.acquireConnection();\n const self = this;\n\n const wrappedConnection: RuntimeConnection = {\n async transaction(): Promise<RuntimeTransaction> {\n const driverTx = await driverConn.beginTransaction();\n return self.wrapTransaction(driverTx);\n },\n async release(): Promise<void> {\n await driverConn.release();\n },\n async destroy(reason?: unknown): Promise<void> {\n await driverConn.destroy(reason);\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverConn, options);\n },\n };\n\n return wrappedConnection;\n }\n\n private wrapTransaction(driverTx: SqlTransaction): RuntimeTransaction {\n const self = this;\n return {\n async commit(): Promise<void> {\n await driverTx.commit();\n },\n async rollback(): Promise<void> {\n await driverTx.rollback();\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executeAgainstQueryable<Row>(plan, driverTx, options);\n },\n };\n }\n\n telemetry(): RuntimeTelemetryEvent | null {\n return this._telemetry;\n }\n\n async close(): Promise<void> {\n await this.driver.close();\n }\n\n private ensureCodecRegistryValidated(): void {\n if (!this.codecRegistryValidated) {\n validateCodecRegistryCompleteness(this.codecDescriptors, this.contract);\n this.codecRegistryValidated = true;\n }\n }\n\n private async verifyMarker(): Promise<void> {\n if (this.verify.mode === 'always') {\n this.verified = false;\n }\n\n if (this.verified) {\n return;\n }\n\n const readStatement = this.familyAdapter.markerReader.readMarkerStatement();\n const result = await this.driver.query(readStatement.sql, readStatement.params);\n\n if (result.rows.length === 0) {\n if (this.verify.requireMarker) {\n throw runtimeError('CONTRACT.MARKER_MISSING', 'Contract marker not found in database');\n }\n\n this.verified = true;\n return;\n }\n\n const marker = this.familyAdapter.markerReader.parseMarkerRow(result.rows[0]);\n\n const contract = this.contract as {\n storage: { storageHash: string };\n execution?: { executionHash?: string | null };\n profileHash?: string | null;\n };\n\n if (marker.storageHash !== contract.storage.storageHash) {\n throw runtimeError(\n 'CONTRACT.MARKER_MISMATCH',\n 'Database storage hash does not match contract',\n {\n expected: contract.storage.storageHash,\n actual: marker.storageHash,\n },\n );\n }\n\n const expectedProfile = contract.profileHash ?? null;\n if (expectedProfile !== null && marker.profileHash !== expectedProfile) {\n throw runtimeError(\n 'CONTRACT.MARKER_MISMATCH',\n 'Database profile hash does not match contract',\n {\n expectedProfile,\n actualProfile: marker.profileHash,\n },\n );\n }\n\n this.verified = true;\n this.startupVerified = true;\n }\n\n private recordTelemetry(\n plan: SqlExecutionPlan,\n outcome: TelemetryOutcome,\n durationMs?: number,\n ): void {\n const contract = this.contract as { target: string };\n this._telemetry = Object.freeze({\n lane: plan.meta.lane,\n target: contract.target,\n fingerprint: computeSqlFingerprint(plan.sql),\n outcome,\n ...(durationMs !== undefined ? { durationMs } : {}),\n });\n }\n}\n\nfunction transactionClosedError(): Error {\n return runtimeError(\n 'RUNTIME.TRANSACTION_CLOSED',\n 'Cannot read from a query result after the transaction has ended. Await the result or call .toArray() inside the transaction callback.',\n {},\n );\n}\n\nexport async function withTransaction<R>(\n runtime: Runtime,\n fn: (tx: TransactionContext) => PromiseLike<R>,\n): Promise<R> {\n const connection = await runtime.connection();\n const transaction = await connection.transaction();\n\n let invalidated = false;\n const txContext: TransactionContext = {\n get invalidated() {\n return invalidated;\n },\n execute<Row>(\n plan: (SqlExecutionPlan<unknown> | SqlQueryPlan<unknown>) & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n if (invalidated) {\n throw transactionClosedError();\n }\n const inner = transaction.execute(plan, options);\n const guarded = async function* (): AsyncGenerator<Row, void, unknown> {\n for await (const row of inner) {\n if (invalidated) {\n throw transactionClosedError();\n }\n yield row;\n }\n };\n return new AsyncIterableResult(guarded());\n },\n };\n\n let connectionDisposed = false;\n const destroyConnection = async (reason: unknown): Promise<void> => {\n if (connectionDisposed) return;\n connectionDisposed = true;\n // SqlConnection.destroy() propagates teardown errors so callers can\n // decide what to do with them. Here, we're already about to throw a\n // more informative error describing why we're evicting the connection\n // (rollback/commit failure), so swallowing the teardown error is the\n // right call — surfacing it would mask the original cause.\n await connection.destroy(reason).catch(() => undefined);\n };\n\n try {\n let result: R;\n try {\n result = await fn(txContext);\n } catch (error) {\n try {\n await transaction.rollback();\n } catch (rollbackError) {\n await destroyConnection(rollbackError);\n const wrapped = runtimeError(\n 'RUNTIME.TRANSACTION_ROLLBACK_FAILED',\n 'Transaction rollback failed after callback error',\n { rollbackError },\n );\n wrapped.cause = error;\n throw wrapped;\n }\n throw error;\n } finally {\n invalidated = true;\n }\n\n try {\n await transaction.commit();\n } catch (commitError) {\n // After a failed COMMIT the server-side transaction may be: (a) already\n // committed (error on response path), (b) already rolled back (deferred\n // constraint / serialization failure), or (c) still open (COMMIT never\n // reached the server). Attempt a best-effort rollback to cover (c) and\n // confirm the protocol is healthy.\n //\n // If rollback succeeds, the server is definitely no longer in a\n // transaction (no-op in (a)/(b), real cleanup in (c)) and we've just\n // proved the connection round-trips correctly — it's safe to return\n // to the pool. If rollback fails, the connection state is ambiguous\n // (broken socket, protocol desync, etc.) and we must destroy it.\n try {\n await transaction.rollback();\n } catch {\n await destroyConnection(commitError);\n }\n const wrapped = runtimeError(\n 'RUNTIME.TRANSACTION_COMMIT_FAILED',\n 'Transaction commit failed',\n { commitError },\n );\n wrapped.cause = commitError;\n throw wrapped;\n }\n return result;\n } finally {\n if (!connectionDisposed) {\n await connection.release();\n }\n }\n}\n\nexport function createRuntime<TContract extends Contract<SqlStorage>, TTargetId extends string>(\n options: CreateRuntimeOptions<TContract, TTargetId>,\n): Runtime {\n const { stackInstance, context, driver, verify, middleware, mode, log } = options;\n\n return new SqlRuntimeImpl({\n context,\n adapter: stackInstance.adapter,\n driver,\n verify,\n ...ifDefined('middleware', middleware),\n ...ifDefined('mode',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