@prisma-next/sql-runtime 0.8.0 → 0.9.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -54,7 +54,7 @@ import {
54
54
  createSqlExecutionStack,
55
55
  } from '@prisma-next/sql-runtime';
56
56
 
57
- const contract = validateContract<Contract>(contractJson);
57
+ const contract = postgresTarget.contractSerializer.deserializeContract(contractJson);
58
58
  const stack = createSqlExecutionStack({
59
59
  target: postgresTarget,
60
60
  adapter: postgresAdapter,
@@ -5,6 +5,7 @@ import { ifDefined } from "@prisma-next/utils/defined";
5
5
  import { checkContractComponentRequirements } from "@prisma-next/framework-components/components";
6
6
  import { createExecutionStack } from "@prisma-next/framework-components/execution";
7
7
  import { canonicalizeJson } from "@prisma-next/framework-components/utils";
8
+ import { isPostgresEnumStorageEntry } from "@prisma-next/sql-contract/types";
8
9
  import { createSqlOperationRegistry } from "@prisma-next/sql-operations";
9
10
  import { buildCodecDescriptorRegistry } from "@prisma-next/sql-relational-core/codec-descriptor-registry";
10
11
  import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
@@ -463,6 +464,25 @@ function assertExecutionStackContractRequirements(contract, stack) {
463
464
  throw runtimeError("RUNTIME.MISSING_EXTENSION_PACK", `Contract requires extension pack(s) ${packIds.map((id) => `'${id}'`).join(", ")}, but runtime descriptors do not provide matching component(s).`, { packIds });
464
465
  }
465
466
  }
467
+ /**
468
+ * Resolves codec id + typeParams for a `SqlStorage.types` entry that
469
+ * represents an enum. The canonical contract path always pipes raw JSON
470
+ * through the `SqlStorage` constructor, which rejects raw
471
+ * `kind: 'postgres-enum'` envelopes that bypass the per-target
472
+ * `ContractSerializer.deserializeContract` hydration. By the time this
473
+ * function runs, the entry is a live IR-class instance that
474
+ * structurally satisfies `PostgresEnumStorageEntry` — `codecId` and
475
+ * `values` are enumerable own properties on the instance. Returns
476
+ * `undefined` when the entry is not enum-shaped, so callers fall
477
+ * through to the codec-typed path.
478
+ */
479
+ function readEnumViewIfApplicable(typeInstance) {
480
+ if (!isPostgresEnumStorageEntry(typeInstance)) return;
481
+ return {
482
+ codecId: typeInstance.codecId,
483
+ typeParams: { values: typeInstance.values }
484
+ };
485
+ }
466
486
  function validateTypeParams(typeParams, descriptor, context) {
467
487
  const result = descriptor.paramsSchema["~standard"].validate(typeParams);
468
488
  if (result instanceof Promise) throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `paramsSchema for codec '${descriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`, {
@@ -520,12 +540,15 @@ function initializeTypeHelpers(storage, codecDescriptors) {
520
540
  if (!storageTypes) return helpers;
521
541
  const typeRefSites = collectTypeRefSites(storage);
522
542
  for (const [typeName, typeInstance] of Object.entries(storageTypes)) {
523
- const descriptor = codecDescriptors.get(typeInstance.codecId);
543
+ const enumView = readEnumViewIfApplicable(typeInstance);
544
+ const codecId = enumView ? enumView.codecId : typeInstance.codecId;
545
+ const typeParams = enumView ? enumView.typeParams : typeInstance.typeParams;
546
+ const descriptor = codecDescriptors.get(codecId);
524
547
  if (!descriptor) {
525
548
  helpers[typeName] = typeInstance;
526
549
  continue;
527
550
  }
528
- const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, { typeName });
551
+ const validatedParams = validateTypeParams(typeParams, descriptor, { typeName });
529
552
  const ctx = {
530
553
  name: typeName,
531
554
  usedAt: typeRefSites.get(typeName) ?? []
@@ -613,7 +636,11 @@ function buildContractCodecRegistry(contract, codecDescriptors) {
613
636
  const nameByKey = /* @__PURE__ */ new Map();
614
637
  const typeRefSites = collectTypeRefSites(contract.storage);
615
638
  for (const [typeName, typeInstance] of Object.entries(contract.storage.types ?? {})) {
616
- const key = refKeyOf({
639
+ const enumView = readEnumViewIfApplicable(typeInstance);
640
+ const key = refKeyOf(enumView ? {
641
+ codecId: enumView.codecId,
642
+ typeParams: enumView.typeParams
643
+ } : {
617
644
  codecId: typeInstance.codecId,
618
645
  typeParams: typeInstance.typeParams
619
646
  });
@@ -1568,4 +1595,4 @@ function createRuntime(options) {
1568
1595
  //#endregion
1569
1596
  export { ensureTableStatement as a, createExecutionContext as c, budgets as d, parseContractMarkerRow as f, validateContractCodecMappings as g, validateCodecRegistryCompleteness as h, ensureSchemaStatement as i, createSqlExecutionStack as l, extractCodecIds as m, withTransaction as n, readContractMarker as o, lowerSqlPlan as p, APP_SPACE_ID as r, writeContractMarker as s, createRuntime as t, lints as u };
1570
1597
 
1571
- //# sourceMappingURL=exports-5hiLH7NR.mjs.map
1598
+ //# sourceMappingURL=exports-C2zFVOFS.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exports-C2zFVOFS.mjs","names":["validateTypeParams"],"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/codecs/ast-codec-resolver.ts","../src/sql-context.ts","../src/sql-marker.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 { 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\nexport function validateContractCodecMappings(\n registry: CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\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 (registry.descriptorFor(codecId) === undefined) {\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: 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 {\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 // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source kind: ${(ast.from satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction estimateRowsFromAst(\n ast: SelectAst,\n tableRows: Record<string, number>,\n defaultTableRows: number,\n hasAggregateWithoutGroup: boolean,\n): number {\n if (hasAggregateWithoutGroup) {\n return 1;\n }\n\n const tableEstimate = tableRows[primaryTableFromAst(ast)] ?? 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 const details =\n estimated >= maxRows\n ? { source: 'ast', estimatedRows: estimated, maxRows }\n : { source: 'ast', maxRows };\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', details),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n if (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 case 'raw-sql':\n // Raw-SQL ASTs opt out of structural lints (LIMIT / WHERE etc.) —\n // the embedded SQL fragments are caller-authored and the lint's\n // shape-based heuristics don't apply.\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 const findings: LintFinding[] = [];\n if (isQueryAst(plan.ast)) {\n findings.push(...evaluateAstLints(plan.ast));\n // Raw-SQL ASTs opt out of structural AST lints (no LIMIT /\n // WHERE shape to inspect) but the embedded SQL text still\n // wants the raw-heuristic guardrails. Without this the lint\n // middleware would silently disable both for raw plans.\n if (plan.ast.kind === 'raw-sql') {\n findings.push(...evaluateRawGuardrails(plan).lints);\n }\n } else if (fallback !== 'skip') {\n findings.push(...evaluateRawGuardrails(plan).lints);\n }\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 },\n });\n}\n","import type { CodecRef } from '@prisma-next/framework-components/codec';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport type { Codec, SqlCodecInstanceContext } from '@prisma-next/sql-relational-core/ast';\nimport type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\n\n/**\n * Per-`ExecutionContext` resolver that materialises the {@link Codec} for a {@link CodecRef} carried on an AST node.\n *\n * Wraps `descriptorFor(codecId).factory(typeParams)(ctx)` with a content-keyed cache: lookups are keyed by `${codecId}:${canonicalizeJson(typeParams)}`, so two refs with the same `codecId` and structurally equal `typeParams` (regardless of object key order) resolve to the same memoised codec instance. Non-parameterized codecs key as `${codecId}:undefined` and share one instance per resolver.\n *\n * AST-bound codec resolution dissolves the legacy column-aware dispatch path: every codec-bearing AST node carries the canonical `CodecRef` directly, so the resolver is the single dispatch shape encode and decode share. Refs the contract walk pre-populates hit on first call; refs the AST supplies (e.g. deserialised migration ops) populate the cache lazily.\n */\nexport interface AstCodecResolver {\n /**\n * Resolve the {@link Codec} for the supplied {@link CodecRef}.\n *\n * Throws `RUNTIME.CODEC_DESCRIPTOR_MISSING` when no descriptor is registered for `ref.codecId`. Throws `RUNTIME.TYPE_PARAMS_INVALID` when the descriptor's `paramsSchema` rejects `ref.typeParams` (validated only on cache miss; subsequent lookups for the same canonical key skip validation).\n */\n forCodecRef(ref: CodecRef): Codec;\n}\n\n/**\n * Build an {@link AstCodecResolver} bound to a descriptor registry and a per-call instance-context factory.\n *\n * The instance-context factory lets callers control `name` / `usedAt` for refs the AST supplies (e.g. AST-embedded migration ops where the materialisation site is the AST node, not a contract column). The contract-walk pre-population path constructs its own contexts and invokes the resolver with those refs to seed the cache.\n */\nexport function createAstCodecResolver(\n descriptors: CodecDescriptorRegistry,\n instanceContextFor: (ref: CodecRef) => SqlCodecInstanceContext,\n): AstCodecResolver {\n const cache = new Map<string, Codec>();\n\n return {\n forCodecRef(ref: CodecRef): Codec {\n const key = `${ref.codecId}:${canonicalizeJson(ref.typeParams)}`;\n const cached = cache.get(key);\n if (cached) return cached;\n\n const descriptor = descriptors.descriptorFor(ref.codecId);\n if (!descriptor) {\n throw runtimeError(\n 'RUNTIME.CODEC_DESCRIPTOR_MISSING',\n `No codec descriptor registered for codecId '${ref.codecId}'.`,\n { codecId: ref.codecId },\n );\n }\n\n // Parameterized codecs whose paramsSchema accepts `{}` (every field\n // optional, e.g. `pg/timestamptz@1` precision) tolerate refs that omit\n // `typeParams` entirely. Normalize `undefined` to `{}` at the validation\n // boundary; the integrity check upstream already rejected refs whose\n // schemas reject the empty object.\n const validated = validateTypeParams(\n descriptor.paramsSchema,\n descriptor.isParameterized && ref.typeParams === undefined\n ? { ...ref, typeParams: {} }\n : ref,\n );\n const ctx = instanceContextFor(ref);\n // The descriptor's `factory` is typed against its own `P`; the registry erases `P` to `unknown`, so callers narrow per codec id at the dispatch boundary. The descriptor's `paramsSchema` validates the input above before we forward it, so this narrow is safe by construction.\n const codec = (\n descriptor.factory as (params: unknown) => (ctx: SqlCodecInstanceContext) => Codec\n )(validated)(ctx);\n\n cache.set(key, codec);\n return codec;\n },\n };\n}\n\nfunction validateTypeParams(\n paramsSchema: { '~standard': { validate: (input: unknown) => unknown } },\n ref: CodecRef,\n): unknown {\n const result = paramsSchema['~standard'].validate(ref.typeParams) as\n | { value: unknown }\n | { issues: ReadonlyArray<{ message: string }> }\n | Promise<unknown>;\n\n if (result instanceof Promise) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `paramsSchema for codec '${ref.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`,\n { codecId: ref.codecId, typeParams: ref.typeParams },\n );\n }\n\n if ('issues' in result && result.issues) {\n const messages = result.issues.map((issue) => issue.message).join('; ');\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Invalid typeParams for codec '${ref.codecId}': ${messages}`,\n { codecId: ref.codecId, typeParams: ref.typeParams },\n );\n }\n\n return (result as { value: unknown }).value;\n}\n","import type {\n Contract,\n ExecutionMutationDefaultValue,\n JsonValue,\n} from '@prisma-next/contract/types';\nimport type {\n AnyCodecDescriptor,\n CodecDescriptor,\n CodecRef,\n} 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 { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport {\n isPostgresEnumStorageEntry,\n type SqlStorage,\n type StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport {\n createSqlOperationRegistry,\n type SqlOperationDescriptors,\n} from '@prisma-next/sql-operations';\nimport type {\n Adapter,\n AnyQueryAst,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecInstanceContext,\n SqlDriver,\n} from '@prisma-next/sql-relational-core/ast';\nimport { buildCodecDescriptorRegistry } from '@prisma-next/sql-relational-core/codec-descriptor-registry';\nimport type {\n AppliedMutationDefault,\n CodecDescriptorRegistry,\n ExecutionContext,\n MutationDefaultsOptions,\n TypeHelperRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport { createAstCodecResolver } from './codecs/ast-codec-resolver';\n\n/**\n * Runtime parameterized codec descriptor.\n *\n * The unified `CodecDescriptor<P>` shape applied to parameterized codecs — `paramsSchema: StandardSchemaV1<P>` for JSON-boundary validation, `factory: (P) => (CodecInstanceContext) => Codec` for the curried higher-order codec. The factory is called once per `storage.types` instance (or once per 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\n/**\n * Contributor protocol for SQL components (target, adapter, extension pack). The unified `codecs:` slot returns the full {@link CodecDescriptor} list — non-parameterized and parameterized descriptors live side-by-side in the same array. The framework dispatches every codec id through the unified descriptor map without branching on parameterization.\n */\nexport interface SqlStaticContributions {\n readonly codecs: () => ReadonlyArray<AnyCodecDescriptor>;\n readonly queryOperations?: () => SqlOperationDescriptors;\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). Cache strategy: no cache; call per defaulting site. Right for per-row identifiers (UUIDs, CUIDs, ULIDs, nanoid, ksuid).\n * - `'row'` — one value across all defaulting sites of one row of one operation. Cache strategy: per-call cache keyed by `generatorId`. Right for correlation ids stamped into multiple columns of one row.\n * - `'query'` — one value across all rows and columns of one ORM operation. Cache strategy: caller-provided cache keyed by `generatorId`. Right for `timestampNow` (a single timestamp per 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 derives the cache strategy from this declaration; generator authors never need to know about cache keys. See `GeneratorStability` for 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. Target clients (for example `postgres()`) validate and construct the concrete binding before calling `driver.connect(binding)`, which keeps runtime behavior safe today. 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, 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\n/**\n * Resolves codec id + typeParams for a `SqlStorage.types` entry that\n * represents an enum. The canonical contract path always pipes raw JSON\n * through the `SqlStorage` constructor, which rejects raw\n * `kind: 'postgres-enum'` envelopes that bypass the per-target\n * `ContractSerializer.deserializeContract` hydration. By the time this\n * function runs, the entry is a live IR-class instance that\n * structurally satisfies `PostgresEnumStorageEntry` — `codecId` and\n * `values` are enumerable own properties on the instance. Returns\n * `undefined` when the entry is not enum-shaped, so callers fall\n * through to the codec-typed path.\n */\nfunction readEnumViewIfApplicable(\n typeInstance: unknown,\n): { readonly codecId: string; readonly typeParams: Record<string, unknown> } | undefined {\n if (!isPostgresEnumStorageEntry(typeInstance)) {\n return undefined;\n }\n return {\n codecId: typeInstance.codecId,\n typeParams: { values: typeInstance.values },\n };\n}\n\nfunction validateTypeParams(\n typeParams: Record<string, unknown>,\n descriptor: RuntimeParameterizedCodecDescriptor,\n context: { typeName?: string; tableName?: string; columnName?: string },\n): Record<string, unknown> {\n const result = descriptor.paramsSchema['~standard'].validate(typeParams);\n if (result instanceof Promise) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `paramsSchema for codec '${descriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`,\n { ...context, codecId: descriptor.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: ${descriptor.codecId}): ${messages}`,\n { ...context, codecId: descriptor.codecId, typeParams },\n );\n }\n return result.value as Record<string, unknown>;\n}\n\n/**\n * Collect every {@link CodecDescriptor} contributed by the SQL stack and partition into \"parameterized\" vs \"non-parameterized\" via the descriptor's own {@link CodecDescriptorImpl.isParameterized} getter. The getter is the canonical discriminator — a `paramsSchema` identity check would misroute any descriptor that doesn't reuse the exact `voidParamsSchema` singleton (e.g. a non-parameterized codec authoring its own no-op schema).\n *\n * The unified descriptor list collapses the legacy split (a separate slot used to register parameterized codecs) — every codec id resolves through the same map (codec-registry-unification spec § Decision).\n */\nfunction collectCodecDescriptors(contributors: ReadonlyArray<SqlStaticContributions>): {\n readonly all: ReadonlyArray<AnyCodecDescriptor>;\n readonly parameterized: Map<string, RuntimeParameterizedCodecDescriptor>;\n} {\n const all: AnyCodecDescriptor[] = [];\n const parameterized = new Map<string, RuntimeParameterizedCodecDescriptor>();\n const seen = new Set<string>();\n\n for (const contributor of contributors) {\n for (const descriptor of contributor.codecs()) {\n if (seen.has(descriptor.codecId)) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_CODEC',\n `Duplicate codec descriptor for codecId '${descriptor.codecId}'.`,\n { codecId: descriptor.codecId },\n );\n }\n seen.add(descriptor.codecId);\n all.push(descriptor);\n\n if (descriptor.isParameterized) {\n // Cast widens the descriptor's heterogeneous `P` to the runtime alias surface; consumers narrow per codec id at the dispatch site, where the descriptor's own `paramsSchema` validates JSON-sourced params before the factory ever sees them.\n parameterized.set(\n descriptor.codecId,\n descriptor as unknown as RuntimeParameterizedCodecDescriptor,\n );\n }\n }\n }\n\n return { all, parameterized };\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 enumView = readEnumViewIfApplicable(typeInstance);\n const codecId = enumView ? enumView.codecId : (typeInstance as StorageTypeInstance).codecId;\n const typeParams = enumView\n ? enumView.typeParams\n : (typeInstance as StorageTypeInstance).typeParams;\n const descriptor = codecDescriptors.get(codecId);\n\n if (!descriptor) {\n // No parameterized descriptor for this codec id — store the raw type instance for callers that need typeParams metadata.\n helpers[typeName] = typeInstance;\n continue;\n }\n\n const validatedParams = validateTypeParams(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 * Build-time contract-integrity check: every `(table, column)` resolves to a {@link CodecRef} whose `codecId` is registered and whose `typeParams` presence matches the descriptor's `isParameterized` flag.\n *\n * Surfaces three classes of malformed contract that AST-bound codec resolution would otherwise mask silently:\n *\n * - column references a codecId no contributor registered → `RUNTIME.CODEC_DESCRIPTOR_MISSING`.\n * - parameterized codec, no `typeParams` (legacy \"tolerate refs without params\" shape) → `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH`.\n * - non-parameterized codec, `typeParams` supplied → `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH`.\n *\n * Runs unconditionally from `createExecutionContext` so contract bugs fail fast at construction time instead of silently skipping affected columns in the codec registry's pre-population walk.\n */\nfunction assertColumnCodecIntegrity(\n storage: SqlStorage,\n codecDescriptors: CodecDescriptorRegistry,\n): void {\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const columnName of Object.keys(table.columns)) {\n const ref = codecDescriptors.codecRefForColumn(tableName, columnName);\n if (!ref) continue;\n\n const descriptor = codecDescriptors.descriptorFor(ref.codecId);\n if (!descriptor) {\n throw runtimeError(\n 'RUNTIME.CODEC_DESCRIPTOR_MISSING',\n `Column '${tableName}.${columnName}' references codec '${ref.codecId}' but no contributor registered a codec descriptor for that codecId. Add the extension pack that owns the codec to the runtime stack.`,\n { table: tableName, column: columnName, codecId: ref.codecId },\n );\n }\n\n if (descriptor.isParameterized && ref.typeParams === undefined) {\n // Some parameterized codecs declare every paramsSchema field as optional\n // (e.g. `pg/timestamptz@1` precision). Defer to the descriptor's own\n // schema rather than rejecting purely on structural absence: probe the\n // schema with an empty params object and only fail when the schema\n // rejects it (i.e. at least one field is required).\n const probe = descriptor.paramsSchema['~standard'].validate({});\n if (probe instanceof Promise) {\n // Swallow the probe Promise's rejection so Node doesn't warn about an\n // unhandled rejection once we throw synchronously below.\n probe.catch(() => {});\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Column '${tableName}.${columnName}' uses parameterized codec '${ref.codecId}' whose paramsSchema returned a Promise; paramsSchema must be a synchronous Standard Schema validator. Return a value/issues result directly instead of a Promise.`,\n { table: tableName, column: columnName, codecId: ref.codecId },\n );\n }\n const rejects = 'issues' in probe && !!probe.issues;\n if (rejects) {\n throw runtimeError(\n 'RUNTIME.CODEC_PARAMETERIZATION_MISMATCH',\n `Column '${tableName}.${columnName}' uses parameterized codec '${ref.codecId}' but no typeParams are supplied. Provide typeParams on the column, or use a typeRef pointing at a storage.types entry that carries them.`,\n {\n table: tableName,\n column: columnName,\n codecId: ref.codecId,\n expected: 'parameterized',\n actual: 'no typeParams',\n },\n );\n }\n }\n\n if (!descriptor.isParameterized && ref.typeParams !== undefined) {\n throw runtimeError(\n 'RUNTIME.CODEC_PARAMETERIZATION_MISMATCH',\n `Column '${tableName}.${columnName}' supplies typeParams to non-parameterized codec '${ref.codecId}'. Remove the typeParams or switch to a parameterized codec id.`,\n {\n table: tableName,\n column: columnName,\n codecId: ref.codecId,\n expected: 'non-parameterized',\n actual: 'has typeParams',\n },\n );\n }\n }\n }\n}\n\n/**\n * Build a {@link ContractCodecRegistry} that resolves codecs exclusively through the `forCodecRef` content-keyed cache.\n *\n * One pre-population pass walks `storage.types` and `storage.tables[].columns[]` to seed the resolver's per-ref instance context with the *aggregated* `usedAt` set for each canonical `(codecId, typeParams)` key. The same codec materialised through `forColumn` or `forCodecRef` is therefore one instance with one `SqlCodecInstanceContext` — stateful codecs reading `usedAt` see the full column set regardless of which surface the caller used.\n *\n * Per-key instance-name policy:\n *\n * - typeRef-shared columns use the `storage.types[name]` name.\n * - inline-`typeParams` columns use `<col:Table.column>` (the first column observed at that key; additional columns sharing the key extend `usedAt`).\n * - non-parameterized codec ids use `<codec:codecId>`, aggregating every column on that codec id into one `usedAt` set.\n * - ad-hoc refs the contract walk did not pre-populate (e.g. AST-supplied refs from deserialised migration ops) fall back to the canonical cache key `${codecId}:${canonicalizeJson(typeParams)}` — the only structurally honest identity for an ad-hoc ref, distinct per `(codecId, typeParams)`.\n *\n * Contract integrity is enforced upstream by {@link assertColumnCodecIntegrity}: every column must reference a registered `codecId` whose `descriptor.isParameterized` flag matches the presence of `typeParams` (via `codecRefForColumn`). The pre-population walk and `forColumn` therefore make no defensive checks — malformed columns fail fast at `createExecutionContext` construction with `RUNTIME.CODEC_DESCRIPTOR_MISSING` or `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH` rather than being silently skipped here.\n *\n * `forColumn(t, c)` is a thin delegate over `forCodecRef(codecRefForColumn(t, c))`; encode/decode hot paths read the resolver directly via `forCodecRef`. The only `undefined` `forColumn` returns is the legitimate \"no such column in the contract\" case.\n */\nfunction buildContractCodecRegistry(\n contract: Contract<SqlStorage>,\n codecDescriptors: CodecDescriptorRegistry,\n): ContractCodecRegistry {\n const refKeyOf = (ref: CodecRef): string => `${ref.codecId}:${canonicalizeJson(ref.typeParams)}`;\n\n const usedAtByKey = new Map<string, Array<{ readonly table: string; readonly column: string }>>();\n const nameByKey = new Map<string, string>();\n\n const typeRefSites = collectTypeRefSites(contract.storage);\n for (const [typeName, typeInstance] of Object.entries(contract.storage.types ?? {})) {\n const enumView = readEnumViewIfApplicable(typeInstance);\n const ref: CodecRef = enumView\n ? {\n codecId: enumView.codecId,\n typeParams: enumView.typeParams as unknown as JsonValue,\n }\n : {\n codecId: (typeInstance as StorageTypeInstance).codecId,\n typeParams: (typeInstance as StorageTypeInstance).typeParams as JsonValue,\n };\n const key = refKeyOf(ref);\n const sites = typeRefSites.get(typeName) ?? [];\n const existing = usedAtByKey.get(key);\n // Two `storage.types` aliases that canonicalize to the same (codecId, typeParams) share a single codec instance via the resolver. Append sites instead of replacing so a stateful codec reading the aggregated site list sees every column behind every alias rather than just the last one.\n if (existing) {\n existing.push(...sites);\n } else {\n usedAtByKey.set(key, [...sites]);\n nameByKey.set(key, typeName);\n }\n }\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeRef !== undefined) continue;\n const ref = codecDescriptors.codecRefForColumn(tableName, columnName);\n if (!ref) continue;\n const key = refKeyOf(ref);\n const site = { table: tableName, column: columnName };\n const existing = usedAtByKey.get(key);\n if (existing) {\n existing.push(site);\n } else {\n usedAtByKey.set(key, [site]);\n const name =\n ref.typeParams !== undefined\n ? `<col:${tableName}.${columnName}>`\n : `<codec:${ref.codecId}>`;\n nameByKey.set(key, name);\n }\n }\n }\n\n const resolver = createAstCodecResolver(codecDescriptors, (ref) => {\n const key = refKeyOf(ref);\n // Fallback uses the canonical cache key as the instance name. Two ad-hoc refs with the same `codecId` but different `typeParams` resolve to distinct codecs (different cache keys) and must therefore expose distinct `name`s; a `codecId`-only fallback would collide and break stateful codecs that key per-instance state on `name`.\n return {\n name: nameByKey.get(key) ?? key,\n usedAt: usedAtByKey.get(key) ?? [],\n };\n });\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const columnName of Object.keys(table.columns)) {\n const ref = codecDescriptors.codecRefForColumn(tableName, columnName);\n if (!ref) continue;\n resolver.forCodecRef(ref);\n }\n }\n\n const registry: ContractCodecRegistry = {\n forColumn(table, column) {\n const ref = codecDescriptors.codecRefForColumn(table, column);\n return ref ? resolver.forCodecRef(ref) : undefined;\n },\n forCodecRef(ref) {\n return resolver.forCodecRef(ref);\n },\n };\n\n return registry;\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 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 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 contributors: Array<SqlStaticContributions & ComponentDescriptor<string>> = [\n stack.target,\n stack.adapter,\n ...stack.extensionPacks,\n ];\n\n const { all: allCodecDescriptors, parameterized: parameterizedCodecDescriptors } =\n collectCodecDescriptors(contributors);\n\n const queryOperationRegistry = createSqlOperationRegistry();\n for (const contributor of contributors) {\n const ops = contributor.queryOperations?.() ?? {};\n for (const [name, op] of Object.entries(ops)) {\n queryOperationRegistry.register(name, op);\n }\n }\n\n const codecDescriptors = buildCodecDescriptorRegistry(allCodecDescriptors, contract.storage);\n assertColumnCodecIntegrity(contract.storage, codecDescriptors);\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 contractCodecs = buildContractCodecRegistry(contract, codecDescriptors);\n\n return {\n contract,\n contractCodecs,\n codecDescriptors,\n queryOperations: queryOperationRegistry,\n types,\n applyMutationDefaults: (options) =>\n applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options),\n };\n}\n","import { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport type { MarkerStatement } from '@prisma-next/sql-relational-core/ast';\n\nexport { APP_SPACE_ID };\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport interface WriteMarkerInput {\n /**\n * Logical space identifier for this marker row. Required at every\n * call site so the type system surfaces every place that needs to\n * thread the value (rather than letting an `?? APP_SPACE_ID`\n * fall-through silently collapse multi-space markers onto the\n * `'app'` row). App-plan callers pass {@link APP_SPACE_ID}\n * (`'app'`); per-extension callers pass the extension's space id.\n */\n readonly space: string;\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\n/**\n * Schema for `prisma_contract.marker`. The `space text` primary key\n * supports one row per loaded contract space (`'app'`,\n * `'<extension-id>'`, …); brand-new databases create this shape\n * directly. Pre-1.0 single-row markers (no `space` column) are not\n * auto-migrated — the target-specific migration runner detects the\n * legacy shape at boot and surfaces a structured `LEGACY_MARKER_SHAPE`\n * failure pointing the operator at re-running `dbInit`.\n *\n * @see specs/framework-mechanism.spec.md § 2.\n */\nexport const ensureTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n space text not null primary key default '${APP_SPACE_ID}',\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(space: string): 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 space = $1`,\n params: [space],\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 `space = $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 `space`; 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[] = [input.space, ...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 = ['space', ...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 space = $1`,\n params,\n },\n };\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 ContractCodecRegistry,\n ProjectionItem,\n SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\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 if (ast.kind === 'raw-sql') {\n return undefined;\n }\n return ast.returning;\n}\n\nfunction resolveProjectionCodec(\n item: ProjectionItem,\n contractCodecs: ContractCodecRegistry | undefined,\n): Codec | undefined {\n if (item.codec && contractCodecs) {\n return contractCodecs.forCodecRef(item.codec);\n }\n return undefined;\n}\n\nfunction buildDecodeContext(\n plan: SqlExecutionPlan,\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, contractCodecs);\n if (codec) {\n codecs.set(item.alias, codec);\n }\n\n if (item.expr.kind === 'column-ref') {\n columnRefs.set(item.alias, {\n table: item.expr.table,\n column: item.expr.column,\n });\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 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 — `codec.decode → await → return plain value` — so sync- and async-authored codecs are indistinguishable to callers. JSON-Schema validation, when required, lives inside the resolved codec's `decode` body (e.g. `arktype-json` validates against its rehydrated schema and throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` from `decode` directly); there is\n * no separate validator-registry pass.\n *\n * The row-level `rowCtx` is repackaged into a per-cell `SqlCodecCallContext` whose `column = { table, name }` is a structural projection of the per-cell `ColumnRef = { table, column }` resolved from the AST-backed `DecodeContext` (the same resolution `wrapDecodeFailure` uses for envelope construction — one resolution per cell, two consumers). Cells the runtime cannot resolve to a single underlying column (aggregate\n * aliases, computed projections without a simple ref) get `column: undefined`, matching the spec contract that the runtime never silently defaults this field.\n */\nasync function decodeField(\n alias: string,\n wireValue: unknown,\n decodeCtx: DecodeContext,\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 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 try {\n return await codec.decode(wireValue, cellCtx);\n } catch (error) {\n if (isRuntimeError(error)) {\n throw error;\n }\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n}\n\n/**\n * Decodes a row by dispatching all per-cell codec calls concurrently via `Promise.all`. Each cell follows the single-armed `decodeField` path. Failures are wrapped in `RUNTIME.DECODE_FAILED` with `{ table, column, codec }` (or `{ alias, codec }` when no column ref is resolvable) and the original error attached on `cause`.\n *\n * When `rowCtx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED` (`{ phase: 'decode' }`) before any `codec.decode` call is made.\n * - **Mid-flight aborts** race the per-cell `Promise.all` against the signal so the runtime returns promptly even when codec bodies ignore it. In-flight bodies that ignore the signal complete in the background (cooperative cancellation).\n * - Existing `RUNTIME.DECODE_FAILED` envelopes from codec bodies pass through unchanged (no double wrap).\n */\nexport async function decodeRow(\n row: Record<string, unknown>,\n plan: SqlExecutionPlan,\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, 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, rowCtx));\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'decode');\n\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 isRuntimeError,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport {\n type Codec,\n type CodecRef,\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 codec: CodecRef | undefined;\n readonly name: string | undefined;\n}\n\nconst NO_METADATA: ParamMetadata = Object.freeze({\n codec: undefined,\n name: undefined,\n});\n\nfunction resolveParamCodec(\n metadata: ParamMetadata,\n contractCodecs: ContractCodecRegistry | undefined,\n): Codec | undefined {\n if (metadata.codec && contractCodecs) {\n return contractCodecs.forCodecRef(metadata.codec);\n }\n return undefined;\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 a Promise can never leak into the driver, even if a sync-authored codec is lifted to async by the codec factory. Failures are wrapped in `RUNTIME.ENCODE_FAILED` with `{ label, codec, paramIndex }` and the original error attached on `cause`.\n *\n * `ctx` is forwarded verbatim to `codec.encode` so codec authors who opt into the `(value, ctx)` arity see the same `SqlCodecCallContext` the runtime built for the surrounding `runtime.execute()` call. The ctx is always present; its `signal` field may be `undefined`. Encode call sites do not populate `ctx.column` — encode-time column context is the middleware's domain.\n */\nexport async function encodeParam(\n value: unknown,\n paramRef: {\n readonly codec?: CodecRef;\n readonly name?: string;\n },\n paramIndex: number,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<unknown> {\n return encodeParamValue(\n value,\n { codec: paramRef.codec, name: paramRef.name },\n paramIndex,\n ctx,\n contractCodecs,\n );\n}\n\nasync function encodeParamValue(\n value: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\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, contractCodecs);\n if (!codec) {\n return value;\n }\n\n try {\n return await codec.encode(value, ctx);\n } catch (error) {\n // Any `runtimeError`-built envelope is stable by construction — let\n // it pass through unchanged. This covers codec-authored\n // `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` (per-library JSON-with-\n // schema codecs validate inside `encode` per ADR 208 § Case J),\n // codec-authored `RUNTIME.ENCODE_FAILED` (no double wrap), and any\n // future stable code thrown from a codec body. Symmetric with the\n // decode-side guard.\n if (isRuntimeError(error)) throw error;\n wrapEncodeFailure(error, metadata, paramIndex, codec.id);\n }\n}\n\n/**\n * Encodes all parameters concurrently via `Promise.all`. Per parameter, sync-and async-authored codecs share the same path: `codec.encode → await → 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` (`{ phase: 'encode' }`) before any `codec.encode` call is made — codecs can pin this with a per-call counter that stays at zero.\n * - **Mid-flight abort** races the per-param `Promise.all` against `abortable(ctx.signal)`. The runtime returns `RUNTIME.ABORTED` promptly even if codec bodies ignore the signal; the in-flight bodies are abandoned and run to completion in the background (cooperative cancellation, see ADR 204).\n * - Existing `RUNTIME.ENCODE_FAILED` envelopes that surface from a codec body before the runtime observes the abort pass through unchanged (no double wrap).\n */\nexport async function encodeParams(\n plan: SqlExecutionPlan,\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] = { codec: ref.codec, 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(plan.params[i], metadata[i] ?? NO_METADATA, i, ctx, contractCodecs);\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 type RuntimeMiddlewareContext,\n runBeforeExecuteChain,\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 ContractCodecRegistry,\n LoweredStatement,\n SqlCodecCallContext,\n SqlDriver,\n SqlQueryable,\n SqlTransaction,\n} from '@prisma-next/sql-relational-core/ast';\nimport {\n createSqlParamRefMutator,\n type SqlParamRefMutator,\n type SqlParamRefMutatorInternal,\n} from '@prisma-next/sql-relational-core/middleware';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { CodecDescriptorRegistry } 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 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.\n */\n release(): Promise<void>;\n /**\n * 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).\n *\n * 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.\n *\n * `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.\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\n// v8 ignore next 2\nconst noopLogSink = (): void => {};\nconst noopLog: Log = { info: noopLogSink, warn: noopLogSink, error: noopLogSink };\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 contractCodecs: ContractCodecRegistry;\n private readonly codecDescriptors: CodecDescriptorRegistry;\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 ?? noopLog,\n // ctx is only invoked by runWithMiddleware with execs this runtime lowered; the framework parameter type is the cross-family base.\n contentHash: (exec) => computeSqlContentHash(exec as SqlExecutionPlan),\n scope: 'runtime',\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.contractCodecs = context.contractCodecs;\n this.codecDescriptors = context.codecDescriptors;\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`\n * with encoded parameters ready for the driver.\n *\n * Implementation note: SQL splits lower-then-encode across\n * {@link lowerToDraft} + {@link encodeDraftParams} so the runtime\n * can fire the `beforeExecute` middleware chain between them\n * (cipherstash bulk-encrypt, for example, mutates pre-encode\n * `ParamRef.value` slots). This protected hook composes the two\n * back into the cross-family `lower()` shape `RuntimeCore.execute`\n * expects, and is called from the no-middleware fast paths /\n * fixtures that hit `RuntimeCore`'s default template directly.\n * `execute()` overrides the template and uses the split form so\n * `beforeExecute` lands between the two halves.\n *\n * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so\n * per-query cancellation reaches every codec body during parameter\n * encoding. SQL params do not populate `ctx.column` — encode-side\n * column metadata is the middleware's domain.\n */\n protected override async lower(\n plan: SqlQueryPlan,\n ctx: SqlCodecCallContext,\n ): Promise<SqlExecutionPlan> {\n const draft = this.lowerToDraft(plan);\n return await this.encodeDraftParams(draft, ctx);\n }\n\n /**\n * AST → pre-encode draft. The returned plan has `sql` rendered and\n * `params` populated with the user-domain values the lowering site\n * collected from `ParamRef` nodes. No codec encode has happened\n * yet; consumers can mutate `params` via the `SqlParamRefMutator`\n * before {@link encodeDraftParams} runs.\n */\n private lowerToDraft(plan: SqlQueryPlan): SqlExecutionPlan {\n return lowerSqlPlan(this.adapter, this.contract, plan);\n }\n\n /**\n * Encode a draft plan's params through the per-column codecs and\n * freeze the result into the final `SqlExecutionPlan` the driver\n * sees. Errors surface as `RUNTIME.ENCODE_FAILED` envelopes from\n * {@link encodeParams}.\n */\n private async encodeDraftParams(\n draft: SqlExecutionPlan,\n ctx: SqlCodecCallContext,\n ): Promise<SqlExecutionPlan> {\n return Object.freeze({\n ...draft,\n params: await encodeParams(draft, ctx, this.contractCodecs),\n });\n }\n\n /**\n * 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.\n */\n // v8 ignore next 6\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` 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\n * 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 const scope = options?.scope ?? 'runtime';\n // 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).\n const codecCtx: SqlCodecCallContext = signal === undefined ? {} : { signal };\n\n // Per-execute view of the middleware ctx that carries the per-query\n // signal. `self.ctx` is allocated once at construction (no signal); we\n // shallow-clone it here so middleware sees the same `AbortSignal`\n // reference threaded into `codecCtx.signal` (ADR 207 identity).\n //\n // The middleware context for this execution is also scope-narrowed: the\n // top-level runtime path uses the constructor-time `'runtime'` ctx as-is;\n // `connection.execute` and `transaction.execute` produce a derived ctx\n // with the appropriate scope. Middleware that observe `ctx.scope`\n // (e.g. the cache middleware, which only intercepts at `'runtime'`)\n // see the right value without any out-of-band signaling.\n const execMiddlewareCtx: RuntimeMiddlewareContext = {\n ...self.ctx,\n ...ifDefined('signal', signal),\n ...(scope !== 'runtime' ? { scope } : {}),\n };\n\n const generator = async function* (): AsyncGenerator<Row, void, unknown> {\n checkAborted(codecCtx, 'stream');\n\n let exec: SqlExecutionPlan;\n if (isExecutionPlan(plan)) {\n // Pre-lowered fixture path. The plan's params are typically\n // already encoded; we still fire `beforeExecute` so middleware\n // that mutates ParamRef values (e.g. cipherstash bulk-encrypt)\n // gets a chance to run, then re-encode so any mutations land.\n const preEncodeMutator: SqlParamRefMutatorInternal = createSqlParamRefMutator(plan);\n await runBeforeExecuteChain<SqlExecutionPlan, SqlParamRefMutator>(\n plan,\n self.middleware,\n execMiddlewareCtx,\n preEncodeMutator,\n );\n exec = Object.freeze({\n ...plan,\n params: await encodeParams(\n { ...plan, params: preEncodeMutator.currentParams() },\n codecCtx,\n self.contractCodecs,\n ),\n });\n } else {\n // Standard AST → exec path. Split lower from encode so the\n // `beforeExecute` chain fires between them with a mutator built\n // over the pre-encode draft params; encode then renders the\n // (possibly mutated) values through the column codecs.\n const compiled = await self.runBeforeCompile(plan);\n const draft = self.lowerToDraft(compiled);\n const preEncodeMutator: SqlParamRefMutatorInternal = createSqlParamRefMutator(draft);\n await runBeforeExecuteChain<SqlExecutionPlan, SqlParamRefMutator>(\n draft,\n self.middleware,\n execMiddlewareCtx,\n preEncodeMutator,\n );\n const draftWithMutations: SqlExecutionPlan = Object.freeze({\n ...draft,\n params: preEncodeMutator.currentParams(),\n });\n exec = await self.encodeDraftParams(draftWithMutations, codecCtx);\n }\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 execMiddlewareCtx,\n () =>\n queryable.execute<Record<string, unknown>>({\n sql: exec.sql,\n // `beforeExecute` ran on the pre-encode draft (see\n // generator setup above); `exec.params` already carries\n // any mutator-driven replacements through `encodeParams`.\n params: exec.params,\n }),\n );\n\n // 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.\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(next.value, exec, codecCtx, self.contractCodecs);\n yield decodedRow as Row;\n }\n } finally {\n // Best-effort iterator cleanup so the driver can release its resources whether the stream finished normally, threw, or was 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, {\n ...options,\n scope: 'connection',\n });\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, {\n ...options,\n scope: 'transaction',\n });\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 const readResult = await this.familyAdapter.markerReader.readMarker(this.driver);\n\n if (readResult.kind !== 'present') {\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 = readResult.record;\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 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.\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 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.\n //\n // 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.\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', mode),\n ...ifDefined('log', log),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAKA,SAAgB,gBAAgB,UAA6C;CAC3E,MAAM,2BAAW,IAAI,KAAa;CAElC,KAAK,MAAM,SAAS,OAAO,OAAO,SAAS,QAAQ,OAAO,EACxD,KAAK,MAAM,UAAU,OAAO,OAAO,MAAM,QAAQ,EAAE;EACjD,MAAM,UAAU,OAAO;EACvB,SAAS,IAAI,QAAQ;;CAIzB,OAAO;;AAGT,SAAS,2BAA2B,UAAqD;CACvF,MAAM,2BAAW,IAAI,KAAqB;CAE1C,KAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,SAAS,QAAQ,OAAO,EACtE,KAAK,MAAM,CAAC,YAAY,WAAW,OAAO,QAAQ,MAAM,QAAQ,EAAE;EAChE,MAAM,UAAU,OAAO;EACvB,MAAM,MAAM,GAAG,UAAU,GAAG;EAC5B,SAAS,IAAI,KAAK,QAAQ;;CAI9B,OAAO;;AAGT,SAAgB,8BACd,UACA,UACM;CACN,MAAM,WAAW,2BAA2B,SAAS;CACrD,MAAM,gBAA2E,EAAE;CAEnF,KAAK,MAAM,CAAC,KAAK,YAAY,SAAS,SAAS,EAC7C,IAAI,SAAS,cAAc,QAAQ,KAAK,KAAA,GAAW;EACjD,MAAM,QAAQ,IAAI,MAAM,IAAI;EAC5B,MAAM,QAAQ,MAAM,MAAM;EAC1B,MAAM,SAAS,MAAM,MAAM;EAC3B,cAAc,KAAK;GAAE;GAAO;GAAQ;GAAS,CAAC;;CAIlD,IAAI,cAAc,SAAS,GAAG;EAC5B,MAAM,UAAmC;GACvC,gBAAgB,SAAS;GACzB;GACD;EAED,MAAM,aACJ,yBACA,sDAAsD,cAAc,KAAK,MAAM,GAAG,EAAE,MAAM,GAAG,EAAE,OAAO,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B,MAAM,oBAAoB,OAAO,WAAmC;EAClE,IAAI,oBAAoB;EACxB,qBAAqB;EAErB,MAAM,WAAW,QAAQ,OAAO,CAAC,YAAY,KAAA,EAAU;;CAGzD,IAAI;EACF,IAAI;EACJ,IAAI;GACF,SAAS,MAAM,GAAG,UAAU;WACrB,OAAO;GACd,IAAI;IACF,MAAM,YAAY,UAAU;YACrB,eAAe;IACtB,MAAM,kBAAkB,cAAc;IACtC,MAAM,UAAU,aACd,uCACA,oDACA,EAAE,eAAe,CAClB;IACD,QAAQ,QAAQ;IAChB,MAAM;;GAER,MAAM;YACE;GACR,cAAc;;EAGhB,IAAI;GACF,MAAM,YAAY,QAAQ;WACnB,aAAa;GAIpB,IAAI;IACF,MAAM,YAAY,UAAU;WACtB;IACN,MAAM,kBAAkB,YAAY;;GAEtC,MAAM,UAAU,aACd,qCACA,6BACA,EAAE,aAAa,CAChB;GACD,QAAQ,QAAQ;GAChB,MAAM;;EAER,OAAO;WACC;EACR,IAAI,CAAC,oBACH,MAAM,WAAW,SAAS;;;AAKhC,SAAgB,cACd,SACS;CACT,MAAM,EAAE,eAAe,SAAS,QAAQ,QAAQ,YAAY,MAAM,QAAQ;CAE1E,OAAO,IAAI,eAAe;EACxB;EACA,SAAS,cAAc;EACvB;EACA;EACA,GAAG,UAAU,cAAc,WAAW;EACtC,GAAG,UAAU,QAAQ,KAAK;EAC1B,GAAG,UAAU,OAAO,IAAI;EACzB,CAAC"}
@@ -1,11 +1,11 @@
1
1
  import { AfterExecuteResult, AfterExecuteResult as AfterExecuteResult$1, ExecutionPlan, RuntimeLog, RuntimeLog as Log, RuntimeMiddleware, RuntimeMiddlewareContext } from "@prisma-next/framework-components/runtime";
2
2
  import { Adapter, AnyQueryAst, LoweredStatement, MarkerReadResult, MarkerReadResult as MarkerReadResult$1, MarkerStatement, MarkerStatement as MarkerStatement$1, SqlDriver, SqlQueryable } from "@prisma-next/sql-relational-core/ast";
3
3
  import { ExecutionStack, ExecutionStackInstance, RuntimeAdapterDescriptor, RuntimeAdapterInstance, RuntimeDriverDescriptor, RuntimeDriverInstance, RuntimeExtensionDescriptor, RuntimeExtensionInstance, RuntimeTargetDescriptor, RuntimeTargetInstance } from "@prisma-next/framework-components/execution";
4
+ import { SqlStorage } from "@prisma-next/sql-contract/types";
4
5
  import { SqlOperationDescriptors } from "@prisma-next/sql-operations";
5
6
  import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
6
7
  import { SqlParamRefMutator } from "@prisma-next/sql-relational-core/middleware";
7
8
  import { Contract, ContractMarkerRecord, PlanMeta } from "@prisma-next/contract/types";
8
- import { SqlStorage } from "@prisma-next/sql-contract/types";
9
9
  import { CodecDescriptorRegistry, ExecutionContext, TypeHelperRegistry } from "@prisma-next/sql-relational-core/query-lane-context";
10
10
  import { SqlExecutionPlan, SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
11
11
  import { AnyCodecDescriptor, CodecDescriptor } from "@prisma-next/framework-components/codec";
@@ -327,4 +327,4 @@ declare function withTransaction<R>(runtime: Runtime, fn: (tx: TransactionContex
327
327
  declare function createRuntime<TContract extends Contract<SqlStorage>, TTargetId extends string>(options: CreateRuntimeOptions<TContract, TTargetId>): Runtime;
328
328
  //#endregion
329
329
  export { SqlRuntimeTargetDescriptor as A, LintsOptions as B, SqlExecutionStack as C, SqlRuntimeDriverInstance as D, SqlRuntimeAdapterInstance as E, MarkerReader as F, SqlMiddlewareContext as G, BudgetsOptions as H, RuntimeFamilyAdapter as I, extractCodecIds as J, parseContractMarkerRow as K, RuntimeTelemetryEvent as L, TypeHelperRegistry as M, createExecutionContext as N, SqlRuntimeExtensionDescriptor as O, createSqlExecutionStack as P, RuntimeVerifyOptions as R, RuntimeParameterizedCodecDescriptor as S, SqlRuntimeAdapterDescriptor as T, budgets as U, lints as V, SqlMiddleware as W, validateContractCodecMappings as X, validateCodecRegistryCompleteness as Y, readContractMarker as _, CreateRuntimeOptions as a, GeneratorStability as b, RuntimeQueryable as c, createRuntime as d, withTransaction as f, ensureTableStatement as g, ensureSchemaStatement as h, MarkerStatement$1 as i, SqlStaticContributions as j, SqlRuntimeExtensionInstance as k, RuntimeTransaction as l, SqlStatement as m, Log as n, Runtime as o, APP_SPACE_ID as p, lowerSqlPlan as q, MarkerReadResult$1 as r, RuntimeConnection as s, AfterExecuteResult$1 as t, TransactionContext as u, writeContractMarker as v, SqlExecutionStackWithDriver as w, RuntimeMutationDefaultGenerator as x, ExecutionContext as y, TelemetryOutcome as z };
330
- //# sourceMappingURL=index-CNy2q72g.d.mts.map
330
+ //# sourceMappingURL=index-BhG8bX80.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index-CNy2q72g.d.mts","names":[],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/marker.ts","../src/middleware/sql-middleware.ts","../src/middleware/budgets.ts","../src/middleware/lints.ts","../src/runtime-spi.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/sql-runtime.ts"],"mappings":";;;;;;;;;;;;;;iBAKgB,eAAA,CAAgB,QAAA,EAAU,QAAA,CAAS,UAAA,IAAc,GAAA;AAAA,iBA2BjD,6BAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;AAAA,iBA4BL,iCAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;;;;;;;;;;;iBCnDL,YAAA,KAAA,CACd,OAAA,EAAS,OAAA,CAAQ,WAAA,EAAa,QAAA,CAAS,UAAA,GAAa,gBAAA,GACpD,QAAA,EAAU,QAAA,CAAS,UAAA,GACnB,SAAA,EAAW,YAAA,CAAa,GAAA,IACvB,gBAAA,CAAiB,GAAA;;;iBCkCJ,sBAAA,CAAuB,GAAA,YAAe,oBAAA;;;UCxCrC,oBAAA,SAA6B,wBAAA;EAAA,SACnC,QAAA,EAAU,QAAA,CAAS,UAAA;AAAA;;;;;UAOb,SAAA;EAAA,SACN,GAAA,EAAK,WAAA;EAAA,SACL,IAAA,E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B,gBAAA;EAAA,SACjC,WAAA;AAAA;AAAA,iBAibW,eAAA,GAAA,CACpB,OAAA,EAAS,OAAA,EACT,EAAA,GAAK,EAAA,EAAI,kBAAA,KAAuB,WAAA,CAAY,CAAA,IAC3C,OAAA,CAAQ,CAAA;AAAA,iBAsFK,aAAA,mBAAgC,QAAA,CAAS,UAAA,4BAAA,CACvD,OAAA,EAAS,oBAAA,CAAqB,SAAA,EAAW,SAAA,IACxC,OAAA"}
1
+ {"version":3,"file":"index-BhG8bX80.d.mts","names":[],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/marker.ts","../src/middleware/sql-middleware.ts","../src/middleware/budgets.ts","../src/middleware/lints.ts","../src/runtime-spi.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/sql-runtime.ts"],"mappings":";;;;;;;;;;;;;;iBAKgB,eAAA,CAAgB,QAAA,EAAU,QAAA,CAAS,UAAA,IAAc,GAAA;AAAA,iBA2BjD,6BAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;AAAA,iBA4BL,iCAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;;;;;;;;;;;iBCnDL,YAAA,KAAA,CACd,OAAA,EAAS,OAAA,CAAQ,WAAA,EAAa,QAAA,CAAS,UAAA,GAAa,gBAAA,GACpD,QAAA,EAAU,QAAA,CAAS,UAAA,GACnB,SAAA,EAAW,YAAA,CAAa,GAAA,IACvB,gBAAA,CAAiB,GAAA;;;iBCkCJ,sBAAA,CAAuB,GAAA,YAAe,oBAAA;;;UCxCrC,oBAAA,SAA6B,wBAAA;EAAA,SACnC,QAAA,EAAU,QAAA,CAAS,UAAA;AAAA;;;;;UAOb,SAAA;EAAA,SACN,GAAA,EAAK,WAAA;EAAA,SACL,IAAA,EAAM,QAAA;AAAA;AAAA,UAGA,aAAA,mBAAgC,MAAA,oBAA0B,MAAA,2BACjE,iBAAA,CAAkB,gBAAA,EA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AAK,EAAA,EAAI,kBAAA,KAAuB,WAAA,CAAY,CAAA,IAC3C,OAAA,CAAQ,CAAA;AAAA,iBAsFK,aAAA,mBAAgC,QAAA,CAAS,UAAA,4BAAA,CACvD,OAAA,EAAS,oBAAA,CAAqB,SAAA,EAAW,SAAA,IACxC,OAAA"}
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as SqlRuntimeTargetDescriptor, B as LintsOptions, C as SqlExecutionStack, D as SqlRuntimeDriverInstance, E as SqlRuntimeAdapterInstance, F as MarkerReader, G as SqlMiddlewareContext, H as BudgetsOptions, I as RuntimeFamilyAdapter, J as extractCodecIds, K as parseContractMarkerRow, L as RuntimeTelemetryEvent, M as TypeHelperRegistry, N as createExecutionContext, O as SqlRuntimeExtensionDescriptor, P as createSqlExecutionStack, R as RuntimeVerifyOptions, S as RuntimeParameterizedCodecDescriptor, T as SqlRuntimeAdapterDescriptor, U as budgets, V as lints, W as SqlMiddleware, X as validateContractCodecMappings, Y as validateCodecRegistryCompleteness, _ as readContractMarker, a as CreateRuntimeOptions, b as GeneratorStability, c as RuntimeQueryable, d as createRuntime, f as withTransaction, g as ensureTableStatement, h as ensureSchemaStatement, i as MarkerStatement, j as SqlStaticContributions, k as SqlRuntimeExtensionInstance, l as RuntimeTransaction, m as SqlStatement, n as Log, o as Runtime, p as APP_SPACE_ID, q as lowerSqlPlan, r as MarkerReadResult, s as RuntimeConnection, t as AfterExecuteResult, u as TransactionContext, v as writeContractMarker, w as SqlExecutionStackWithDriver, x as RuntimeMutationDefaultGenerator, y as ExecutionContext, z as TelemetryOutcome } from "./index-CNy2q72g.mjs";
1
+ import { A as SqlRuntimeTargetDescriptor, B as LintsOptions, C as SqlExecutionStack, D as SqlRuntimeDriverInstance, E as SqlRuntimeAdapterInstance, F as MarkerReader, G as SqlMiddlewareContext, H as BudgetsOptions, I as RuntimeFamilyAdapter, J as extractCodecIds, K as parseContractMarkerRow, L as RuntimeTelemetryEvent, M as TypeHelperRegistry, N as createExecutionContext, O as SqlRuntimeExtensionDescriptor, P as createSqlExecutionStack, R as RuntimeVerifyOptions, S as RuntimeParameterizedCodecDescriptor, T as SqlRuntimeAdapterDescriptor, U as budgets, V as lints, W as SqlMiddleware, X as validateContractCodecMappings, Y as validateCodecRegistryCompleteness, _ as readContractMarker, a as CreateRuntimeOptions, b as GeneratorStability, c as RuntimeQueryable, d as createRuntime, f as withTransaction, g as ensureTableStatement, h as ensureSchemaStatement, i as MarkerStatement, j as SqlStaticContributions, k as SqlRuntimeExtensionInstance, l as RuntimeTransaction, m as SqlStatement, n as Log, o as Runtime, p as APP_SPACE_ID, q as lowerSqlPlan, r as MarkerReadResult, s as RuntimeConnection, t as AfterExecuteResult, u as TransactionContext, v as writeContractMarker, w as SqlExecutionStackWithDriver, x as RuntimeMutationDefaultGenerator, y as ExecutionContext, z as TelemetryOutcome } from "./index-BhG8bX80.mjs";
2
2
  export { APP_SPACE_ID, AfterExecuteResult, BudgetsOptions, CreateRuntimeOptions, ExecutionContext, GeneratorStability, LintsOptions, Log, MarkerReadResult, MarkerReader, MarkerStatement, Runtime, RuntimeConnection, RuntimeFamilyAdapter, RuntimeMutationDefaultGenerator, RuntimeParameterizedCodecDescriptor, RuntimeQueryable, RuntimeTelemetryEvent, RuntimeTransaction, RuntimeVerifyOptions, SqlExecutionStack, SqlExecutionStackWithDriver, SqlMiddleware, SqlMiddlewareContext, SqlRuntimeAdapterDescriptor, SqlRuntimeAdapterInstance, SqlRuntimeDriverInstance, SqlRuntimeExtensionDescriptor, SqlRuntimeExtensionInstance, SqlRuntimeTargetDescriptor, SqlStatement, SqlStaticContributions, TelemetryOutcome, TransactionContext, TypeHelperRegistry, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as ensureTableStatement, c as createExecutionContext, d as budgets, f as parseContractMarkerRow, g as validateContractCodecMappings, h as validateCodecRegistryCompleteness, i as ensureSchemaStatement, l as createSqlExecutionStack, m as extractCodecIds, n as withTransaction, o as readContractMarker, p as lowerSqlPlan, r as APP_SPACE_ID, s as writeContractMarker, t as createRuntime, u as lints } from "./exports-5hiLH7NR.mjs";
1
+ import { a as ensureTableStatement, c as createExecutionContext, d as budgets, f as parseContractMarkerRow, g as validateContractCodecMappings, h as validateCodecRegistryCompleteness, i as ensureSchemaStatement, l as createSqlExecutionStack, m as extractCodecIds, n as withTransaction, o as readContractMarker, p as lowerSqlPlan, r as APP_SPACE_ID, s as writeContractMarker, t as createRuntime, u as lints } from "./exports-C2zFVOFS.mjs";
2
2
  export { APP_SPACE_ID, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
@@ -1,11 +1,11 @@
1
- import { A as SqlRuntimeTargetDescriptor, D as SqlRuntimeDriverInstance, E as SqlRuntimeAdapterInstance, O as SqlRuntimeExtensionDescriptor, T as SqlRuntimeAdapterDescriptor, d as createRuntime, k as SqlRuntimeExtensionInstance, m as SqlStatement, y as ExecutionContext } from "../index-CNy2q72g.mjs";
1
+ import { A as SqlRuntimeTargetDescriptor, D as SqlRuntimeDriverInstance, E as SqlRuntimeAdapterInstance, O as SqlRuntimeExtensionDescriptor, T as SqlRuntimeAdapterDescriptor, d as createRuntime, k as SqlRuntimeExtensionInstance, m as SqlStatement, y as ExecutionContext } from "../index-BhG8bX80.mjs";
2
2
  import { ResultType } from "@prisma-next/framework-components/runtime";
3
3
  import { Adapter, Codec, ContractCodecRegistry, LoweredStatement, SelectAst } from "@prisma-next/sql-relational-core/ast";
4
4
  import * as _$_prisma_next_framework_components_execution0 from "@prisma-next/framework-components/execution";
5
5
  import { RuntimeDriverDescriptor } from "@prisma-next/framework-components/execution";
6
+ import { SqlStorage, SqlStorageInput } from "@prisma-next/sql-contract/types";
6
7
  import { Contract } from "@prisma-next/contract/types";
7
8
  import { DevDatabase, collectAsync, createDevDatabase, teardownTestDatabase, withClient } from "@prisma-next/test-utils";
8
- import { SqlStorage } from "@prisma-next/sql-contract/types";
9
9
  import { SqlExecutionPlan, SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
10
10
  import { CodecDescriptor } from "@prisma-next/framework-components/codec";
11
11
  import { Client } from "pg";
@@ -75,7 +75,7 @@ declare function createStubAdapter(): StubAdapter;
75
75
  declare function createTestContract(contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {
76
76
  storageHash?: string;
77
77
  profileHash?: string;
78
- storage?: Omit<SqlStorage, 'storageHash'>;
78
+ storage?: Omit<SqlStorageInput, 'storageHash'>;
79
79
  }): Contract<SqlStorage>;
80
80
  //#endregion
81
81
  export { type DevDatabase, StubAdapter, buildTestContractCodecs, collectAsync, createDevDatabase, createStubAdapter, createTestAdapterDescriptor, createTestContext, createTestContract, createTestStackInstance, createTestTargetDescriptor, descriptorsFromCodecs, drainPlanExecution, executePlanAndCollect, executeStatement, setupTestDatabase, teardownTestDatabase, withClient, writeTestContractMarker };
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../../test/utils.ts"],"mappings":";;;;;;;;;;;;;;;AA0DA;iBAAsB,qBAAA,WACV,gBAAA,CAAiB,UAAA,CAAW,CAAA,KAAM,YAAA,CAAa,UAAA,CAAW,CAAA,GAAA,CACpE,OAAA,EAAS,UAAA,QAAkB,aAAA,GAAgB,IAAA,EAAM,CAAA,GAAI,OAAA,CAAQ,UAAA,CAAW,CAAA;;;;iBAQpD,kBAAA,CACpB,OAAA,EAAS,UAAA,QAAkB,aAAA,GAC3B,IAAA,EAAM,gBAAA,GAAmB,YAAA,YACxB,OAAA;;;;iBAOmB,gBAAA,CAAiB,M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A,CAAc,6BAAA;EAC/B,MAAA,GAAS,uBAAA,6BAIP,wBAAA;AAAA,IAEH,8CAAA,CAAA,sBAAA,oBAAA,yBAAA,cAAA,wBAAA,cAAA,2BAAA;;;;KAcW,WAAA,GAAc,OAAA,CAAQ,SAAA,EAAW,QAAA,CAAS,UAAA,GAAa,gBAAA;EAAA,SACxD,QAAA,EAAU,aAAA,CAAc,KAAA;AAAA;AAzNnC;;;;;AAAA,iBAiOgB,iBAAA,CAAA,GAAqB,WAAA;AAAA,iBAoFrB,kBAAA,CACd,QAAA,EAAU,OAAA,CAAQ,IAAA,CAAK,QAAA,CAAS,UAAA;EAC9B,WAAA;EACA,WAAA;EACA,OAAA,GAAU,IAAA,CAAK,eAAA;AAAA,IAEhB,QAAA,CAAS,UAAA"}
@@ -1,7 +1,8 @@
1
- import { a as ensureTableStatement, c as createExecutionContext, i as ensureSchemaStatement, l as createSqlExecutionStack, r as APP_SPACE_ID, s as writeContractMarker } from "../exports-5hiLH7NR.mjs";
1
+ import { a as ensureTableStatement, c as createExecutionContext, i as ensureSchemaStatement, l as createSqlExecutionStack, r as APP_SPACE_ID, s as writeContractMarker } from "../exports-C2zFVOFS.mjs";
2
2
  import { runtimeError } from "@prisma-next/framework-components/runtime";
3
3
  import { instantiateExecutionStack } from "@prisma-next/framework-components/execution";
4
4
  import { canonicalizeJson } from "@prisma-next/framework-components/utils";
5
+ import { SqlStorage } from "@prisma-next/sql-contract/types";
5
6
  import { coreHash, profileHash } from "@prisma-next/contract/types";
6
7
  import { builtinGeneratorIds } from "@prisma-next/ids";
7
8
  import { generateId } from "@prisma-next/ids/runtime";
@@ -296,13 +297,13 @@ function createTestContract(contract) {
296
297
  return {
297
298
  target: rest["target"] ?? "postgres",
298
299
  targetFamily: rest["targetFamily"] ?? "sql",
299
- storage: rest["storage"] ? {
300
+ storage: rest["storage"] ? new SqlStorage({
300
301
  ...rest["storage"],
301
302
  storageHash: storageHashValue
302
- } : {
303
+ }) : new SqlStorage({
303
304
  storageHash: storageHashValue,
304
305
  tables: {}
305
- },
306
+ }),
306
307
  models: rest["models"] ?? {},
307
308
  roots: rest["roots"] ?? {},
308
309
  capabilities: rest["capabilities"] ?? {},
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":["collectAsync"],"sources":["../../test/test-codec.ts","../../test/utils.ts"],"sourcesContent":["/**\n * Test-only helper that constructs a SQL-family `Codec` instance from author-side encode/decode functions. Replaces the legacy public `mkCodec()` factory (deleted under TML-2357); tests that need a stub codec for behavioural assertions instantiate one through this helper rather than going through `descriptor.factory(...)`.\n *\n * The body is identical in spirit to the retired `mkCodec`: promise-lift sync author functions onto the framework-required `Promise<…>` boundary, default `encodeJson`/`decodeJson` to identity when `TInput` is JSON-safe, fail loudly otherwise.\n */\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { Codec, SqlCodecCallContext } from '@prisma-next/sql-relational-core/ast';\n\ntype JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]\n ? {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n }\n : {\n encodeJson: (value: TInput) => JsonValue;\n decodeJson: (json: JsonValue) => TInput;\n };\n\nexport function defineTestCodec<\n Id extends string,\n const TTraits extends readonly CodecTrait[] = readonly [],\n TWire = unknown,\n TInput = unknown,\n>(\n config: {\n typeId: Id;\n targetTypes?: readonly string[];\n encode: (value: TInput, ctx: SqlCodecCallContext) => TWire | Promise<TWire>;\n decode: (wire: TWire, ctx: SqlCodecCallContext) => TInput | Promise<TInput>;\n traits?: TTraits;\n } & JsonRoundTripConfig<TInput>,\n): Codec<Id, TTraits, TWire, TInput> {\n const identity = (v: unknown) => v;\n const userEncode = config.encode;\n const userDecode = config.decode;\n const widenedConfig = config as {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n };\n return {\n id: config.typeId,\n encode: (value, ctx) => {\n try {\n return Promise.resolve(userEncode(value, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n decode: (wire, ctx) => {\n try {\n return Promise.resolve(userDecode(wire, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,\n decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,\n } as Codec<Id, TTraits, TWire, TInput>;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport type {\n CodecDescriptor,\n CodecMeta,\n CodecTrait,\n} from '@prisma-next/framework-components/codec';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport type { ResultType } from '@prisma-next/framework-components/runtime';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n Codec,\n ContractCodecRegistry,\n LoweredStatement,\n SelectAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n APP_SPACE_ID,\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\nimport { defineTestCodec } from './test-codec';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n stability: 'field' as const,\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: SqlExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.\n */\n/**\n * Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.\n */\nexport function buildTestContractCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ContractCodecRegistry {\n const byId = new Map<string, Codec<string>>();\n for (const codec of codecs) {\n byId.set(codec.id, codec);\n }\n // Canonical-key cache: production `forCodecRef` memoizes per `(codecId, canonicalize(typeParams))`. Tests resolve by codecId, but key the cache on the canonical pair so callers passing distinct typeParams get distinct (still codec-id-templated) entries — and so this helper cannot silently coalesce them.\n const byCanonicalKey = new Map<string, Codec<string>>();\n return {\n forColumn: () => undefined,\n forCodecRef: (ref) => {\n const canonicalKey = canonicalizeJson({\n codecId: ref.codecId,\n ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n });\n const cached = byCanonicalKey.get(canonicalKey);\n if (cached) return cached;\n const template = byId.get(ref.codecId);\n if (!template) {\n throw runtimeError(\n 'RUNTIME.CODEC_DESCRIPTOR_MISSING',\n `Test ContractCodecRegistry has no codec for codecId '${ref.codecId}'.`,\n {\n codecId: ref.codecId,\n ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n },\n );\n }\n byCanonicalKey.set(canonicalKey, template);\n return template;\n },\n };\n}\n\n/**\n * Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry\n * `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.\n */\nexport function descriptorsFromCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ReadonlyArray<CodecDescriptor> {\n // Permissive paramsSchema for synthesized test descriptors: accepts any\n // shape (incl. undefined) and passes it through. Stubs do not encode\n // parameterization, so marking them `isParameterized: true` with this\n // schema lets the runtime integrity check tolerate columns that legitimately\n // carry typeParams (e.g. `sql/char@1` length=36) without re-introducing\n // the legacy \"non-parameterized + typeParams\" silent skip.\n // Permissive schema for synthesized test descriptors. `validate()` always\n // succeeds and discards input, narrowed to `void` to match the\n // `paramsSchema: StandardSchemaV1<void, void>` slot on the descriptor.\n // The factory ignores typeParams, so typing the validated output as `void`\n // is honest about what the stub does with the value.\n const acceptAnyParamsSchema = {\n '~standard': {\n version: 1 as const,\n vendor: 'sql-runtime/test-utils',\n validate: (_value: unknown) => ({ value: undefined }),\n },\n };\n const descriptors: CodecDescriptor[] = [];\n for (const instance of codecs) {\n const legacy = instance as {\n readonly traits?: readonly CodecTrait[];\n readonly targetTypes?: readonly string[];\n readonly meta?: CodecMeta;\n };\n descriptors.push({\n codecId: instance.id,\n traits: legacy.traits ?? [],\n targetTypes: legacy.targetTypes ?? [],\n paramsSchema: acceptAnyParamsSchema,\n isParameterized: true,\n factory: () => () => instance,\n ...(legacy.meta !== undefined ? { meta: legacy.meta } : {}),\n });\n }\n return descriptors;\n}\n\nexport function createTestAdapterDescriptor(\n adapter: StubAdapter,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const descriptors = descriptorsFromCodecs(adapter.__codecs);\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => descriptors,\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: StubAdapter,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Stub-adapter type augments the public {@link Adapter} surface with a `__codecs` slot that exposes the test stub's runtime codec set to descriptor-shaping helpers (`createTestAdapterDescriptor`). Production adapters do not declare this slot — runtime codecs flow through the descriptor list from `SqlRuntimeAdapterDescriptor.codecs()` — so the augmentation is intentionally test-only.\n */\nexport type StubAdapter = Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> & {\n readonly __codecs: ReadonlyArray<Codec<string>>;\n};\n\n/**\n * Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): StubAdapter {\n // Stub codecs for codec IDs that test contracts may reference. The set must\n // be complete enough to satisfy `assertColumnCodecIntegrity` against any\n // emitted test contract; the encode/decode bodies are passthrough since\n // the stub adapter never executes against a real driver.\n // The encode/decode bodies pass through; widen TInput to a JSON-safe type\n // so `defineTestCodec` does not require explicit JSON round-trip helpers.\n const passthroughCodec = (typeId: string, targetType: string): Codec<string> =>\n defineTestCodec({\n typeId,\n targetTypes: [targetType],\n encode: (value: string | number | boolean | null) => value,\n decode: (wire: string | number | boolean | null) => wire,\n });\n const codecs: ReadonlyArray<Codec<string>> = [\n passthroughCodec('pg/bit@1', 'bit'),\n passthroughCodec('pg/bool@1', 'bool'),\n passthroughCodec('pg/bytea@1', 'bytea'),\n passthroughCodec('pg/float4@1', 'float4'),\n passthroughCodec('pg/float8@1', 'float8'),\n passthroughCodec('pg/int2@1', 'int2'),\n defineTestCodec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n passthroughCodec('pg/int8@1', 'int8'),\n passthroughCodec('pg/interval@1', 'interval'),\n passthroughCodec('pg/json@1', 'json'),\n passthroughCodec('pg/jsonb@1', 'jsonb'),\n passthroughCodec('pg/numeric@1', 'numeric'),\n defineTestCodec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n passthroughCodec('pg/time@1', 'time'),\n defineTestCodec({\n typeId: 'pg/timestamp@1',\n targetTypes: ['timestamp'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n defineTestCodec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n // Date is not assignable to JsonValue, so the JSON round-trip pair must be supplied explicitly.\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n passthroughCodec('pg/timetz@1', 'timetz'),\n passthroughCodec('pg/varbit@1', 'varbit'),\n passthroughCodec('pg/uuid@1', 'uuid'),\n passthroughCodec('sql/char@1', 'char'),\n passthroughCodec('sql/varchar@1', 'varchar'),\n ];\n\n return {\n __codecs: codecs,\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n readMarker: async () => ({ kind: 'absent' as const }),\n },\n lower(ast: SelectAst, ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n return Object.freeze({ sql: sqlText, params: ctx.params ? [...ctx.params] : [] });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorage, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? { ...rest['storage'], storageHash: storageHashValue }\n : { storageHash: storageHashValue, tables: {} },\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;;AAmBA,SAAgB,gBA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AAK;IAAS,QAAQ,IAAI,SAAS,CAAC,GAAG,IAAI,OAAO,GAAG,EAAE;IAAE,CAAC;;EAEpF;;AAGH,SAAgB,mBACd,UAKsB;CACtB,MAAM,EAAE,WAAW,GAAG,SAAS;CAC/B,MAAM,mBAAmB,SAAS,KAAK,kBAAkB,kBAAkB;CAE3E,OAAO;EACL,QAAQ,KAAK,aAAa;EAC1B,cAAc,KAAK,mBAAmB;EACtC,SAAS,KAAK,aACV;GAAE,GAAG,KAAK;GAAY,aAAa;GAAkB,GACrD;GAAE,aAAa;GAAkB,QAAQ,EAAE;GAAE;EACjD,QAAQ,KAAK,aAAa,EAAE;EAC5B,OAAO,KAAK,YAAY,EAAE;EAC1B,cAAc,KAAK,mBAAmB,EAAE;EACxC,gBAAgB,KAAK,qBAAqB,EAAE;EAC5C,MAAM,KAAK,WAAW,EAAE;EACxB,GAAI,YAAY,EAAE,WAAW,GAAG,EAAE;EAClC,aAAa,YAAY,KAAK,kBAAkB,qBAAqB;EACtE"}
1
+ {"version":3,"file":"utils.mjs","names":["collectAsync"],"sources":["../../test/test-codec.ts","../../test/utils.ts"],"sourcesContent":["/**\n * Test-only helper that constructs a SQL-family `Codec` instance from author-side encode/decode functions. Replaces the legacy public `mkCodec()` factory (deleted under TML-2357); tests that need a stub codec for behavioural assertions instantiate one through this helper rather than going through `descriptor.factory(...)`.\n *\n * The body is identical in spirit to the retired `mkCodec`: promise-lift sync author functions onto the framework-required `Promise<…>` boundary, default `encodeJson`/`decodeJson` to identity when `TInput` is JSON-safe, fail loudly otherwise.\n */\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { Codec, SqlCodecCallContext } from '@prisma-next/sql-relational-core/ast';\n\ntype JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]\n ? {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n }\n : {\n encodeJson: (value: TInput) => JsonValue;\n decodeJson: (json: JsonValue) => TInput;\n };\n\nexport function defineTestCodec<\n Id extends string,\n const TTraits extends readonly CodecTrait[] = readonly [],\n TWire = unknown,\n TInput = unknown,\n>(\n config: {\n typeId: Id;\n targetTypes?: readonly string[];\n encode: (value: TInput, ctx: SqlCodecCallContext) => TWire | Promise<TWire>;\n decode: (wire: TWire, ctx: SqlCodecCallContext) => TInput | Promise<TInput>;\n traits?: TTraits;\n } & JsonRoundTripConfig<TInput>,\n): Codec<Id, TTraits, TWire, TInput> {\n const identity = (v: unknown) => v;\n const userEncode = config.encode;\n const userDecode = config.decode;\n const widenedConfig = config as {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n };\n return {\n id: config.typeId,\n encode: (value, ctx) => {\n try {\n return Promise.resolve(userEncode(value, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n decode: (wire, ctx) => {\n try {\n return Promise.resolve(userDecode(wire, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,\n decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,\n } as Codec<Id, TTraits, TWire, TInput>;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport type {\n CodecDescriptor,\n CodecMeta,\n CodecTrait,\n} from '@prisma-next/framework-components/codec';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport type { ResultType } from '@prisma-next/framework-components/runtime';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport { SqlStorage, type SqlStorageInput } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n Codec,\n ContractCodecRegistry,\n LoweredStatement,\n SelectAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n APP_SPACE_ID,\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\nimport { defineTestCodec } from './test-codec';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n stability: 'field' as const,\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: SqlExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.\n */\n/**\n * Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.\n */\nexport function buildTestContractCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ContractCodecRegistry {\n const byId = new Map<string, Codec<string>>();\n for (const codec of codecs) {\n byId.set(codec.id, codec);\n }\n // Canonical-key cache: production `forCodecRef` memoizes per `(codecId, canonicalize(typeParams))`. Tests resolve by codecId, but key the cache on the canonical pair so callers passing distinct typeParams get distinct (still codec-id-templated) entries — and so this helper cannot silently coalesce them.\n const byCanonicalKey = new Map<string, Codec<string>>();\n return {\n forColumn: () => undefined,\n forCodecRef: (ref) => {\n const canonicalKey = canonicalizeJson({\n codecId: ref.codecId,\n ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n });\n const cached = byCanonicalKey.get(canonicalKey);\n if (cached) return cached;\n const template = byId.get(ref.codecId);\n if (!template) {\n throw runtimeError(\n 'RUNTIME.CODEC_DESCRIPTOR_MISSING',\n `Test ContractCodecRegistry has no codec for codecId '${ref.codecId}'.`,\n {\n codecId: ref.codecId,\n ...(ref.typeParams !== undefined ? { typeParams: ref.typeParams } : {}),\n },\n );\n }\n byCanonicalKey.set(canonicalKey, template);\n return template;\n },\n };\n}\n\n/**\n * Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry\n * `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.\n */\nexport function descriptorsFromCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ReadonlyArray<CodecDescriptor> {\n // Permissive paramsSchema for synthesized test descriptors: accepts any\n // shape (incl. undefined) and passes it through. Stubs do not encode\n // parameterization, so marking them `isParameterized: true` with this\n // schema lets the runtime integrity check tolerate columns that legitimately\n // carry typeParams (e.g. `sql/char@1` length=36) without re-introducing\n // the legacy \"non-parameterized + typeParams\" silent skip.\n // Permissive schema for synthesized test descriptors. `validate()` always\n // succeeds and discards input, narrowed to `void` to match the\n // `paramsSchema: StandardSchemaV1<void, void>` slot on the descriptor.\n // The factory ignores typeParams, so typing the validated output as `void`\n // is honest about what the stub does with the value.\n const acceptAnyParamsSchema = {\n '~standard': {\n version: 1 as const,\n vendor: 'sql-runtime/test-utils',\n validate: (_value: unknown) => ({ value: undefined }),\n },\n };\n const descriptors: CodecDescriptor[] = [];\n for (const instance of codecs) {\n const legacy = instance as {\n readonly traits?: readonly CodecTrait[];\n readonly targetTypes?: readonly string[];\n readonly meta?: CodecMeta;\n };\n descriptors.push({\n codecId: instance.id,\n traits: legacy.traits ?? [],\n targetTypes: legacy.targetTypes ?? [],\n paramsSchema: acceptAnyParamsSchema,\n isParameterized: true,\n factory: () => () => instance,\n ...(legacy.meta !== undefined ? { meta: legacy.meta } : {}),\n });\n }\n return descriptors;\n}\n\nexport function createTestAdapterDescriptor(\n adapter: StubAdapter,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const descriptors = descriptorsFromCodecs(adapter.__codecs);\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => descriptors,\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: StubAdapter,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Stub-adapter type augments the public {@link Adapter} surface with a `__codecs` slot that exposes the test stub's runtime codec set to descriptor-shaping helpers (`createTestAdapterDescriptor`). Production adapters do not declare this slot — runtime codecs flow through the descriptor list from `SqlRuntimeAdapterDescriptor.codecs()` — so the augmentation is intentionally test-only.\n */\nexport type StubAdapter = Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> & {\n readonly __codecs: ReadonlyArray<Codec<string>>;\n};\n\n/**\n * Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): StubAdapter {\n // Stub codecs for codec IDs that test contracts may reference. The set must\n // be complete enough to satisfy `assertColumnCodecIntegrity` against any\n // emitted test contract; the encode/decode bodies are passthrough since\n // the stub adapter never executes against a real driver.\n // The encode/decode bodies pass through; widen TInput to a JSON-safe type\n // so `defineTestCodec` does not require explicit JSON round-trip helpers.\n const passthroughCodec = (typeId: string, targetType: string): Codec<string> =>\n defineTestCodec({\n typeId,\n targetTypes: [targetType],\n encode: (value: string | number | boolean | null) => value,\n decode: (wire: string | number | boolean | null) => wire,\n });\n const codecs: ReadonlyArray<Codec<string>> = [\n passthroughCodec('pg/bit@1', 'bit'),\n passthroughCodec('pg/bool@1', 'bool'),\n passthroughCodec('pg/bytea@1', 'bytea'),\n passthroughCodec('pg/float4@1', 'float4'),\n passthroughCodec('pg/float8@1', 'float8'),\n passthroughCodec('pg/int2@1', 'int2'),\n defineTestCodec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n passthroughCodec('pg/int8@1', 'int8'),\n passthroughCodec('pg/interval@1', 'interval'),\n passthroughCodec('pg/json@1', 'json'),\n passthroughCodec('pg/jsonb@1', 'jsonb'),\n passthroughCodec('pg/numeric@1', 'numeric'),\n defineTestCodec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n passthroughCodec('pg/time@1', 'time'),\n defineTestCodec({\n typeId: 'pg/timestamp@1',\n targetTypes: ['timestamp'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n defineTestCodec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n // Date is not assignable to JsonValue, so the JSON round-trip pair must be supplied explicitly.\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n passthroughCodec('pg/timetz@1', 'timetz'),\n passthroughCodec('pg/varbit@1', 'varbit'),\n passthroughCodec('pg/uuid@1', 'uuid'),\n passthroughCodec('sql/char@1', 'char'),\n passthroughCodec('sql/varchar@1', 'varchar'),\n ];\n\n return {\n __codecs: codecs,\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n readMarker: async () => ({ kind: 'absent' as const }),\n },\n lower(ast: SelectAst, ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n return Object.freeze({ sql: sqlText, params: ctx.params ? [...ctx.params] : [] });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorageInput, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? new SqlStorage({ ...rest['storage'], storageHash: storageHashValue })\n : new SqlStorage({ storageHash: storageHashValue, tables: {} }),\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;;;AAmBA,SAAgB,gBAMd,QAOmC;CACnC,MAAM,YAAY,MAAe;CACjC,MAAM,aAAa,OAAO;CAC1B,MAAM,aAAa,OAAO;CAC1B,MAAM,gBAAgB;CAItB,OAAO;EACL,IAAI,OAAO;EACX,SAAS,OAAO,QAAQ;GACtB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,OAAO,IAAI,CAAC;YACvC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGhC,SAAS,MAAM,QAAQ;GACrB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,MAAM,IAAI,CAAC;YACtC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGhC,YAAa,cAAc,cAAc;EACzC,YAAa,cAAc,cAAc;EAC1C;;;;ACXH,SAAS,sCAAsC;CAC7C,OAAO,oBAAoB,KAAK,QAAQ;EACtC;EACA,WAAW,WAAqC,WAAW,SAAS;GAAE;GAAI;GAAQ,GAAG,EAAE,IAAI,CAAC;EAC5F,WAAW;EACZ,EAAE;;;;;AAML,eAAsB,sBAEpB,SAA2C,MAAmC;CAE9E,OAAOA,eAAkB,QAAQ,QAAa,KAAK,CAAC;;;;;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name": "@prisma-next/sql-runtime",
3
- "version": "0.8.0",
3
+ "version": "0.9.0-dev.1",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "SQL runtime implementation for Prisma Next",
8
8
  "dependencies": {
9
- "@prisma-next/contract": "0.8.0",
10
- "@prisma-next/utils": "0.8.0",
11
- "@prisma-next/framework-components": "0.8.0",
12
- "@prisma-next/ids": "0.8.0",
13
- "@prisma-next/operations": "0.8.0",
14
- "@prisma-next/sql-contract": "0.8.0",
15
- "@prisma-next/sql-operations": "0.8.0",
16
- "@prisma-next/sql-relational-core": "0.8.0",
9
+ "@prisma-next/contract": "0.9.0-dev.1",
10
+ "@prisma-next/utils": "0.9.0-dev.1",
11
+ "@prisma-next/framework-components": "0.9.0-dev.1",
12
+ "@prisma-next/ids": "0.9.0-dev.1",
13
+ "@prisma-next/operations": "0.9.0-dev.1",
14
+ "@prisma-next/sql-contract": "0.9.0-dev.1",
15
+ "@prisma-next/sql-operations": "0.9.0-dev.1",
16
+ "@prisma-next/sql-relational-core": "0.9.0-dev.1",
17
17
  "arktype": "^2.1.29"
18
18
  },
19
19
  "devDependencies": {
20
- "@prisma-next/test-utils": "0.8.0",
21
- "@prisma-next/tsconfig": "0.8.0",
20
+ "@prisma-next/test-utils": "0.9.0-dev.1",
21
+ "@prisma-next/tsconfig": "0.9.0-dev.1",
22
22
  "@types/pg": "8.20.0",
23
23
  "pg": "8.20.0",
24
- "@prisma-next/tsdown": "0.8.0",
24
+ "@prisma-next/tsdown": "0.9.0-dev.1",
25
25
  "tsdown": "0.22.0",
26
26
  "typescript": "5.9.3",
27
27
  "vitest": "4.1.5"
@@ -24,7 +24,11 @@ import {
24
24
  } from '@prisma-next/framework-components/execution';
25
25
  import { runtimeError } from '@prisma-next/framework-components/runtime';
26
26
  import { canonicalizeJson } from '@prisma-next/framework-components/utils';
27
- import type { SqlStorage } from '@prisma-next/sql-contract/types';
27
+ import {
28
+ isPostgresEnumStorageEntry,
29
+ type SqlStorage,
30
+ type StorageTypeInstance,
31
+ } from '@prisma-next/sql-contract/types';
28
32
  import {
29
33
  createSqlOperationRegistry,
30
34
  type SqlOperationDescriptors,
@@ -217,6 +221,30 @@ export function assertExecutionStackContractRequirements(
217
221
  }
218
222
  }
219
223
 
224
+ /**
225
+ * Resolves codec id + typeParams for a `SqlStorage.types` entry that
226
+ * represents an enum. The canonical contract path always pipes raw JSON
227
+ * through the `SqlStorage` constructor, which rejects raw
228
+ * `kind: 'postgres-enum'` envelopes that bypass the per-target
229
+ * `ContractSerializer.deserializeContract` hydration. By the time this
230
+ * function runs, the entry is a live IR-class instance that
231
+ * structurally satisfies `PostgresEnumStorageEntry` — `codecId` and
232
+ * `values` are enumerable own properties on the instance. Returns
233
+ * `undefined` when the entry is not enum-shaped, so callers fall
234
+ * through to the codec-typed path.
235
+ */
236
+ function readEnumViewIfApplicable(
237
+ typeInstance: unknown,
238
+ ): { readonly codecId: string; readonly typeParams: Record<string, unknown> } | undefined {
239
+ if (!isPostgresEnumStorageEntry(typeInstance)) {
240
+ return undefined;
241
+ }
242
+ return {
243
+ codecId: typeInstance.codecId,
244
+ typeParams: { values: typeInstance.values },
245
+ };
246
+ }
247
+
220
248
  function validateTypeParams(
221
249
  typeParams: Record<string, unknown>,
222
250
  descriptor: RuntimeParameterizedCodecDescriptor,
@@ -315,7 +343,12 @@ function initializeTypeHelpers(
315
343
  const typeRefSites = collectTypeRefSites(storage);
316
344
 
317
345
  for (const [typeName, typeInstance] of Object.entries(storageTypes)) {
318
- const descriptor = codecDescriptors.get(typeInstance.codecId);
346
+ const enumView = readEnumViewIfApplicable(typeInstance);
347
+ const codecId = enumView ? enumView.codecId : (typeInstance as StorageTypeInstance).codecId;
348
+ const typeParams = enumView
349
+ ? enumView.typeParams
350
+ : (typeInstance as StorageTypeInstance).typeParams;
351
+ const descriptor = codecDescriptors.get(codecId);
319
352
 
320
353
  if (!descriptor) {
321
354
  // No parameterized descriptor for this codec id — store the raw type instance for callers that need typeParams metadata.
@@ -323,7 +356,7 @@ function initializeTypeHelpers(
323
356
  continue;
324
357
  }
325
358
 
326
- const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, {
359
+ const validatedParams = validateTypeParams(typeParams, descriptor, {
327
360
  typeName,
328
361
  });
329
362
 
@@ -457,10 +490,16 @@ function buildContractCodecRegistry(
457
490
 
458
491
  const typeRefSites = collectTypeRefSites(contract.storage);
459
492
  for (const [typeName, typeInstance] of Object.entries(contract.storage.types ?? {})) {
460
- const ref: CodecRef = {
461
- codecId: typeInstance.codecId,
462
- typeParams: typeInstance.typeParams as JsonValue,
463
- };
493
+ const enumView = readEnumViewIfApplicable(typeInstance);
494
+ const ref: CodecRef = enumView
495
+ ? {
496
+ codecId: enumView.codecId,
497
+ typeParams: enumView.typeParams as unknown as JsonValue,
498
+ }
499
+ : {
500
+ codecId: (typeInstance as StorageTypeInstance).codecId,
501
+ typeParams: (typeInstance as StorageTypeInstance).typeParams as JsonValue,
502
+ };
464
503
  const key = refKeyOf(ref);
465
504
  const sites = typeRefSites.get(typeName) ?? [];
466
505
  const existing = usedAtByKey.get(key);
@@ -1 +0,0 @@
1
- {"version":3,"file":"exports-5hiLH7NR.mjs","names":["validateTypeParams"],"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/codecs/ast-codec-resolver.ts","../src/sql-context.ts","../src/sql-marker.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 { 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\nexport function validateContractCodecMappings(\n registry: CodecDescriptorRegistry,\n contract: Contract<SqlStorage>,\n): void {\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 (registry.descriptorFor(codecId) === undefined) {\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: 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 {\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 // v8 ignore next 4\n default:\n throw new Error(\n `Unsupported source kind: ${(ast.from satisfies never as { kind: string }).kind}`,\n );\n }\n}\n\nfunction estimateRowsFromAst(\n ast: SelectAst,\n tableRows: Record<string, number>,\n defaultTableRows: number,\n hasAggregateWithoutGroup: boolean,\n): number {\n if (hasAggregateWithoutGroup) {\n return 1;\n }\n\n const tableEstimate = tableRows[primaryTableFromAst(ast)] ?? 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 const details =\n estimated >= maxRows\n ? { source: 'ast', estimatedRows: estimated, maxRows }\n : { source: 'ast', maxRows };\n emitBudgetViolation(\n runtimeError('BUDGET.ROWS_EXCEEDED', 'Unbounded SELECT query exceeds budget', details),\n shouldBlock,\n ctx,\n );\n return;\n }\n\n if (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 case 'raw-sql':\n // Raw-SQL ASTs opt out of structural lints (LIMIT / WHERE etc.) —\n // the embedded SQL fragments are caller-authored and the lint's\n // shape-based heuristics don't apply.\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 const findings: LintFinding[] = [];\n if (isQueryAst(plan.ast)) {\n findings.push(...evaluateAstLints(plan.ast));\n // Raw-SQL ASTs opt out of structural AST lints (no LIMIT /\n // WHERE shape to inspect) but the embedded SQL text still\n // wants the raw-heuristic guardrails. Without this the lint\n // middleware would silently disable both for raw plans.\n if (plan.ast.kind === 'raw-sql') {\n findings.push(...evaluateRawGuardrails(plan).lints);\n }\n } else if (fallback !== 'skip') {\n findings.push(...evaluateRawGuardrails(plan).lints);\n }\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 },\n });\n}\n","import type { CodecRef } from '@prisma-next/framework-components/codec';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport type { Codec, SqlCodecInstanceContext } from '@prisma-next/sql-relational-core/ast';\nimport type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\n\n/**\n * Per-`ExecutionContext` resolver that materialises the {@link Codec} for a {@link CodecRef} carried on an AST node.\n *\n * Wraps `descriptorFor(codecId).factory(typeParams)(ctx)` with a content-keyed cache: lookups are keyed by `${codecId}:${canonicalizeJson(typeParams)}`, so two refs with the same `codecId` and structurally equal `typeParams` (regardless of object key order) resolve to the same memoised codec instance. Non-parameterized codecs key as `${codecId}:undefined` and share one instance per resolver.\n *\n * AST-bound codec resolution dissolves the legacy column-aware dispatch path: every codec-bearing AST node carries the canonical `CodecRef` directly, so the resolver is the single dispatch shape encode and decode share. Refs the contract walk pre-populates hit on first call; refs the AST supplies (e.g. deserialised migration ops) populate the cache lazily.\n */\nexport interface AstCodecResolver {\n /**\n * Resolve the {@link Codec} for the supplied {@link CodecRef}.\n *\n * Throws `RUNTIME.CODEC_DESCRIPTOR_MISSING` when no descriptor is registered for `ref.codecId`. Throws `RUNTIME.TYPE_PARAMS_INVALID` when the descriptor's `paramsSchema` rejects `ref.typeParams` (validated only on cache miss; subsequent lookups for the same canonical key skip validation).\n */\n forCodecRef(ref: CodecRef): Codec;\n}\n\n/**\n * Build an {@link AstCodecResolver} bound to a descriptor registry and a per-call instance-context factory.\n *\n * The instance-context factory lets callers control `name` / `usedAt` for refs the AST supplies (e.g. AST-embedded migration ops where the materialisation site is the AST node, not a contract column). The contract-walk pre-population path constructs its own contexts and invokes the resolver with those refs to seed the cache.\n */\nexport function createAstCodecResolver(\n descriptors: CodecDescriptorRegistry,\n instanceContextFor: (ref: CodecRef) => SqlCodecInstanceContext,\n): AstCodecResolver {\n const cache = new Map<string, Codec>();\n\n return {\n forCodecRef(ref: CodecRef): Codec {\n const key = `${ref.codecId}:${canonicalizeJson(ref.typeParams)}`;\n const cached = cache.get(key);\n if (cached) return cached;\n\n const descriptor = descriptors.descriptorFor(ref.codecId);\n if (!descriptor) {\n throw runtimeError(\n 'RUNTIME.CODEC_DESCRIPTOR_MISSING',\n `No codec descriptor registered for codecId '${ref.codecId}'.`,\n { codecId: ref.codecId },\n );\n }\n\n // Parameterized codecs whose paramsSchema accepts `{}` (every field\n // optional, e.g. `pg/timestamptz@1` precision) tolerate refs that omit\n // `typeParams` entirely. Normalize `undefined` to `{}` at the validation\n // boundary; the integrity check upstream already rejected refs whose\n // schemas reject the empty object.\n const validated = validateTypeParams(\n descriptor.paramsSchema,\n descriptor.isParameterized && ref.typeParams === undefined\n ? { ...ref, typeParams: {} }\n : ref,\n );\n const ctx = instanceContextFor(ref);\n // The descriptor's `factory` is typed against its own `P`; the registry erases `P` to `unknown`, so callers narrow per codec id at the dispatch boundary. The descriptor's `paramsSchema` validates the input above before we forward it, so this narrow is safe by construction.\n const codec = (\n descriptor.factory as (params: unknown) => (ctx: SqlCodecInstanceContext) => Codec\n )(validated)(ctx);\n\n cache.set(key, codec);\n return codec;\n },\n };\n}\n\nfunction validateTypeParams(\n paramsSchema: { '~standard': { validate: (input: unknown) => unknown } },\n ref: CodecRef,\n): unknown {\n const result = paramsSchema['~standard'].validate(ref.typeParams) as\n | { value: unknown }\n | { issues: ReadonlyArray<{ message: string }> }\n | Promise<unknown>;\n\n if (result instanceof Promise) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `paramsSchema for codec '${ref.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`,\n { codecId: ref.codecId, typeParams: ref.typeParams },\n );\n }\n\n if ('issues' in result && result.issues) {\n const messages = result.issues.map((issue) => issue.message).join('; ');\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Invalid typeParams for codec '${ref.codecId}': ${messages}`,\n { codecId: ref.codecId, typeParams: ref.typeParams },\n );\n }\n\n return (result as { value: unknown }).value;\n}\n","import type {\n Contract,\n ExecutionMutationDefaultValue,\n JsonValue,\n} from '@prisma-next/contract/types';\nimport type {\n AnyCodecDescriptor,\n CodecDescriptor,\n CodecRef,\n} 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 { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport {\n createSqlOperationRegistry,\n type SqlOperationDescriptors,\n} from '@prisma-next/sql-operations';\nimport type {\n Adapter,\n AnyQueryAst,\n ContractCodecRegistry,\n LoweredStatement,\n SqlCodecInstanceContext,\n SqlDriver,\n} from '@prisma-next/sql-relational-core/ast';\nimport { buildCodecDescriptorRegistry } from '@prisma-next/sql-relational-core/codec-descriptor-registry';\nimport type {\n AppliedMutationDefault,\n CodecDescriptorRegistry,\n ExecutionContext,\n MutationDefaultsOptions,\n TypeHelperRegistry,\n} from '@prisma-next/sql-relational-core/query-lane-context';\nimport { createAstCodecResolver } from './codecs/ast-codec-resolver';\n\n/**\n * Runtime parameterized codec descriptor.\n *\n * The unified `CodecDescriptor<P>` shape applied to parameterized codecs — `paramsSchema: StandardSchemaV1<P>` for JSON-boundary validation, `factory: (P) => (CodecInstanceContext) => Codec` for the curried higher-order codec. The factory is called once per `storage.types` instance (or once per 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\n/**\n * Contributor protocol for SQL components (target, adapter, extension pack). The unified `codecs:` slot returns the full {@link CodecDescriptor} list — non-parameterized and parameterized descriptors live side-by-side in the same array. The framework dispatches every codec id through the unified descriptor map without branching on parameterization.\n */\nexport interface SqlStaticContributions {\n readonly codecs: () => ReadonlyArray<AnyCodecDescriptor>;\n readonly queryOperations?: () => SqlOperationDescriptors;\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). Cache strategy: no cache; call per defaulting site. Right for per-row identifiers (UUIDs, CUIDs, ULIDs, nanoid, ksuid).\n * - `'row'` — one value across all defaulting sites of one row of one operation. Cache strategy: per-call cache keyed by `generatorId`. Right for correlation ids stamped into multiple columns of one row.\n * - `'query'` — one value across all rows and columns of one ORM operation. Cache strategy: caller-provided cache keyed by `generatorId`. Right for `timestampNow` (a single timestamp per 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 derives the cache strategy from this declaration; generator authors never need to know about cache keys. See `GeneratorStability` for 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. Target clients (for example `postgres()`) validate and construct the concrete binding before calling `driver.connect(binding)`, which keeps runtime behavior safe today. 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, 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 descriptor: RuntimeParameterizedCodecDescriptor,\n context: { typeName?: string; tableName?: string; columnName?: string },\n): Record<string, unknown> {\n const result = descriptor.paramsSchema['~standard'].validate(typeParams);\n if (result instanceof Promise) {\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `paramsSchema for codec '${descriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`,\n { ...context, codecId: descriptor.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: ${descriptor.codecId}): ${messages}`,\n { ...context, codecId: descriptor.codecId, typeParams },\n );\n }\n return result.value as Record<string, unknown>;\n}\n\n/**\n * Collect every {@link CodecDescriptor} contributed by the SQL stack and partition into \"parameterized\" vs \"non-parameterized\" via the descriptor's own {@link CodecDescriptorImpl.isParameterized} getter. The getter is the canonical discriminator — a `paramsSchema` identity check would misroute any descriptor that doesn't reuse the exact `voidParamsSchema` singleton (e.g. a non-parameterized codec authoring its own no-op schema).\n *\n * The unified descriptor list collapses the legacy split (a separate slot used to register parameterized codecs) — every codec id resolves through the same map (codec-registry-unification spec § Decision).\n */\nfunction collectCodecDescriptors(contributors: ReadonlyArray<SqlStaticContributions>): {\n readonly all: ReadonlyArray<AnyCodecDescriptor>;\n readonly parameterized: Map<string, RuntimeParameterizedCodecDescriptor>;\n} {\n const all: AnyCodecDescriptor[] = [];\n const parameterized = new Map<string, RuntimeParameterizedCodecDescriptor>();\n const seen = new Set<string>();\n\n for (const contributor of contributors) {\n for (const descriptor of contributor.codecs()) {\n if (seen.has(descriptor.codecId)) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_CODEC',\n `Duplicate codec descriptor for codecId '${descriptor.codecId}'.`,\n { codecId: descriptor.codecId },\n );\n }\n seen.add(descriptor.codecId);\n all.push(descriptor);\n\n if (descriptor.isParameterized) {\n // Cast widens the descriptor's heterogeneous `P` to the runtime alias surface; consumers narrow per codec id at the dispatch site, where the descriptor's own `paramsSchema` validates JSON-sourced params before the factory ever sees them.\n parameterized.set(\n descriptor.codecId,\n descriptor as unknown as RuntimeParameterizedCodecDescriptor,\n );\n }\n }\n }\n\n return { all, parameterized };\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 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 * Build-time contract-integrity check: every `(table, column)` resolves to a {@link CodecRef} whose `codecId` is registered and whose `typeParams` presence matches the descriptor's `isParameterized` flag.\n *\n * Surfaces three classes of malformed contract that AST-bound codec resolution would otherwise mask silently:\n *\n * - column references a codecId no contributor registered → `RUNTIME.CODEC_DESCRIPTOR_MISSING`.\n * - parameterized codec, no `typeParams` (legacy \"tolerate refs without params\" shape) → `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH`.\n * - non-parameterized codec, `typeParams` supplied → `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH`.\n *\n * Runs unconditionally from `createExecutionContext` so contract bugs fail fast at construction time instead of silently skipping affected columns in the codec registry's pre-population walk.\n */\nfunction assertColumnCodecIntegrity(\n storage: SqlStorage,\n codecDescriptors: CodecDescriptorRegistry,\n): void {\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const columnName of Object.keys(table.columns)) {\n const ref = codecDescriptors.codecRefForColumn(tableName, columnName);\n if (!ref) continue;\n\n const descriptor = codecDescriptors.descriptorFor(ref.codecId);\n if (!descriptor) {\n throw runtimeError(\n 'RUNTIME.CODEC_DESCRIPTOR_MISSING',\n `Column '${tableName}.${columnName}' references codec '${ref.codecId}' but no contributor registered a codec descriptor for that codecId. Add the extension pack that owns the codec to the runtime stack.`,\n { table: tableName, column: columnName, codecId: ref.codecId },\n );\n }\n\n if (descriptor.isParameterized && ref.typeParams === undefined) {\n // Some parameterized codecs declare every paramsSchema field as optional\n // (e.g. `pg/timestamptz@1` precision). Defer to the descriptor's own\n // schema rather than rejecting purely on structural absence: probe the\n // schema with an empty params object and only fail when the schema\n // rejects it (i.e. at least one field is required).\n const probe = descriptor.paramsSchema['~standard'].validate({});\n if (probe instanceof Promise) {\n // Swallow the probe Promise's rejection so Node doesn't warn about an\n // unhandled rejection once we throw synchronously below.\n probe.catch(() => {});\n throw runtimeError(\n 'RUNTIME.TYPE_PARAMS_INVALID',\n `Column '${tableName}.${columnName}' uses parameterized codec '${ref.codecId}' whose paramsSchema returned a Promise; paramsSchema must be a synchronous Standard Schema validator. Return a value/issues result directly instead of a Promise.`,\n { table: tableName, column: columnName, codecId: ref.codecId },\n );\n }\n const rejects = 'issues' in probe && !!probe.issues;\n if (rejects) {\n throw runtimeError(\n 'RUNTIME.CODEC_PARAMETERIZATION_MISMATCH',\n `Column '${tableName}.${columnName}' uses parameterized codec '${ref.codecId}' but no typeParams are supplied. Provide typeParams on the column, or use a typeRef pointing at a storage.types entry that carries them.`,\n {\n table: tableName,\n column: columnName,\n codecId: ref.codecId,\n expected: 'parameterized',\n actual: 'no typeParams',\n },\n );\n }\n }\n\n if (!descriptor.isParameterized && ref.typeParams !== undefined) {\n throw runtimeError(\n 'RUNTIME.CODEC_PARAMETERIZATION_MISMATCH',\n `Column '${tableName}.${columnName}' supplies typeParams to non-parameterized codec '${ref.codecId}'. Remove the typeParams or switch to a parameterized codec id.`,\n {\n table: tableName,\n column: columnName,\n codecId: ref.codecId,\n expected: 'non-parameterized',\n actual: 'has typeParams',\n },\n );\n }\n }\n }\n}\n\n/**\n * Build a {@link ContractCodecRegistry} that resolves codecs exclusively through the `forCodecRef` content-keyed cache.\n *\n * One pre-population pass walks `storage.types` and `storage.tables[].columns[]` to seed the resolver's per-ref instance context with the *aggregated* `usedAt` set for each canonical `(codecId, typeParams)` key. The same codec materialised through `forColumn` or `forCodecRef` is therefore one instance with one `SqlCodecInstanceContext` — stateful codecs reading `usedAt` see the full column set regardless of which surface the caller used.\n *\n * Per-key instance-name policy:\n *\n * - typeRef-shared columns use the `storage.types[name]` name.\n * - inline-`typeParams` columns use `<col:Table.column>` (the first column observed at that key; additional columns sharing the key extend `usedAt`).\n * - non-parameterized codec ids use `<codec:codecId>`, aggregating every column on that codec id into one `usedAt` set.\n * - ad-hoc refs the contract walk did not pre-populate (e.g. AST-supplied refs from deserialised migration ops) fall back to the canonical cache key `${codecId}:${canonicalizeJson(typeParams)}` — the only structurally honest identity for an ad-hoc ref, distinct per `(codecId, typeParams)`.\n *\n * Contract integrity is enforced upstream by {@link assertColumnCodecIntegrity}: every column must reference a registered `codecId` whose `descriptor.isParameterized` flag matches the presence of `typeParams` (via `codecRefForColumn`). The pre-population walk and `forColumn` therefore make no defensive checks — malformed columns fail fast at `createExecutionContext` construction with `RUNTIME.CODEC_DESCRIPTOR_MISSING` or `RUNTIME.CODEC_PARAMETERIZATION_MISMATCH` rather than being silently skipped here.\n *\n * `forColumn(t, c)` is a thin delegate over `forCodecRef(codecRefForColumn(t, c))`; encode/decode hot paths read the resolver directly via `forCodecRef`. The only `undefined` `forColumn` returns is the legitimate \"no such column in the contract\" case.\n */\nfunction buildContractCodecRegistry(\n contract: Contract<SqlStorage>,\n codecDescriptors: CodecDescriptorRegistry,\n): ContractCodecRegistry {\n const refKeyOf = (ref: CodecRef): string => `${ref.codecId}:${canonicalizeJson(ref.typeParams)}`;\n\n const usedAtByKey = new Map<string, Array<{ readonly table: string; readonly column: string }>>();\n const nameByKey = new Map<string, string>();\n\n const typeRefSites = collectTypeRefSites(contract.storage);\n for (const [typeName, typeInstance] of Object.entries(contract.storage.types ?? {})) {\n const ref: CodecRef = {\n codecId: typeInstance.codecId,\n typeParams: typeInstance.typeParams as JsonValue,\n };\n const key = refKeyOf(ref);\n const sites = typeRefSites.get(typeName) ?? [];\n const existing = usedAtByKey.get(key);\n // Two `storage.types` aliases that canonicalize to the same (codecId, typeParams) share a single codec instance via the resolver. Append sites instead of replacing so a stateful codec reading the aggregated site list sees every column behind every alias rather than just the last one.\n if (existing) {\n existing.push(...sites);\n } else {\n usedAtByKey.set(key, [...sites]);\n nameByKey.set(key, typeName);\n }\n }\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeRef !== undefined) continue;\n const ref = codecDescriptors.codecRefForColumn(tableName, columnName);\n if (!ref) continue;\n const key = refKeyOf(ref);\n const site = { table: tableName, column: columnName };\n const existing = usedAtByKey.get(key);\n if (existing) {\n existing.push(site);\n } else {\n usedAtByKey.set(key, [site]);\n const name =\n ref.typeParams !== undefined\n ? `<col:${tableName}.${columnName}>`\n : `<codec:${ref.codecId}>`;\n nameByKey.set(key, name);\n }\n }\n }\n\n const resolver = createAstCodecResolver(codecDescriptors, (ref) => {\n const key = refKeyOf(ref);\n // Fallback uses the canonical cache key as the instance name. Two ad-hoc refs with the same `codecId` but different `typeParams` resolve to distinct codecs (different cache keys) and must therefore expose distinct `name`s; a `codecId`-only fallback would collide and break stateful codecs that key per-instance state on `name`.\n return {\n name: nameByKey.get(key) ?? key,\n usedAt: usedAtByKey.get(key) ?? [],\n };\n });\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n for (const columnName of Object.keys(table.columns)) {\n const ref = codecDescriptors.codecRefForColumn(tableName, columnName);\n if (!ref) continue;\n resolver.forCodecRef(ref);\n }\n }\n\n const registry: ContractCodecRegistry = {\n forColumn(table, column) {\n const ref = codecDescriptors.codecRefForColumn(table, column);\n return ref ? resolver.forCodecRef(ref) : undefined;\n },\n forCodecRef(ref) {\n return resolver.forCodecRef(ref);\n },\n };\n\n return registry;\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 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 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 contributors: Array<SqlStaticContributions & ComponentDescriptor<string>> = [\n stack.target,\n stack.adapter,\n ...stack.extensionPacks,\n ];\n\n const { all: allCodecDescriptors, parameterized: parameterizedCodecDescriptors } =\n collectCodecDescriptors(contributors);\n\n const queryOperationRegistry = createSqlOperationRegistry();\n for (const contributor of contributors) {\n const ops = contributor.queryOperations?.() ?? {};\n for (const [name, op] of Object.entries(ops)) {\n queryOperationRegistry.register(name, op);\n }\n }\n\n const codecDescriptors = buildCodecDescriptorRegistry(allCodecDescriptors, contract.storage);\n assertColumnCodecIntegrity(contract.storage, codecDescriptors);\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 contractCodecs = buildContractCodecRegistry(contract, codecDescriptors);\n\n return {\n contract,\n contractCodecs,\n codecDescriptors,\n queryOperations: queryOperationRegistry,\n types,\n applyMutationDefaults: (options) =>\n applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options),\n };\n}\n","import { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport type { MarkerStatement } from '@prisma-next/sql-relational-core/ast';\n\nexport { APP_SPACE_ID };\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport interface WriteMarkerInput {\n /**\n * Logical space identifier for this marker row. Required at every\n * call site so the type system surfaces every place that needs to\n * thread the value (rather than letting an `?? APP_SPACE_ID`\n * fall-through silently collapse multi-space markers onto the\n * `'app'` row). App-plan callers pass {@link APP_SPACE_ID}\n * (`'app'`); per-extension callers pass the extension's space id.\n */\n readonly space: string;\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\n/**\n * Schema for `prisma_contract.marker`. The `space text` primary key\n * supports one row per loaded contract space (`'app'`,\n * `'<extension-id>'`, …); brand-new databases create this shape\n * directly. Pre-1.0 single-row markers (no `space` column) are not\n * auto-migrated — the target-specific migration runner detects the\n * legacy shape at boot and surfaces a structured `LEGACY_MARKER_SHAPE`\n * failure pointing the operator at re-running `dbInit`.\n *\n * @see specs/framework-mechanism.spec.md § 2.\n */\nexport const ensureTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n space text not null primary key default '${APP_SPACE_ID}',\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(space: string): 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 space = $1`,\n params: [space],\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 `space = $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 `space`; 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[] = [input.space, ...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 = ['space', ...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 space = $1`,\n params,\n },\n };\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 ContractCodecRegistry,\n ProjectionItem,\n SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan } from '@prisma-next/sql-relational-core/plan';\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 if (ast.kind === 'raw-sql') {\n return undefined;\n }\n return ast.returning;\n}\n\nfunction resolveProjectionCodec(\n item: ProjectionItem,\n contractCodecs: ContractCodecRegistry | undefined,\n): Codec | undefined {\n if (item.codec && contractCodecs) {\n return contractCodecs.forCodecRef(item.codec);\n }\n return undefined;\n}\n\nfunction buildDecodeContext(\n plan: SqlExecutionPlan,\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, contractCodecs);\n if (codec) {\n codecs.set(item.alias, codec);\n }\n\n if (item.expr.kind === 'column-ref') {\n columnRefs.set(item.alias, {\n table: item.expr.table,\n column: item.expr.column,\n });\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 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 — `codec.decode → await → return plain value` — so sync- and async-authored codecs are indistinguishable to callers. JSON-Schema validation, when required, lives inside the resolved codec's `decode` body (e.g. `arktype-json` validates against its rehydrated schema and throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` from `decode` directly); there is\n * no separate validator-registry pass.\n *\n * The row-level `rowCtx` is repackaged into a per-cell `SqlCodecCallContext` whose `column = { table, name }` is a structural projection of the per-cell `ColumnRef = { table, column }` resolved from the AST-backed `DecodeContext` (the same resolution `wrapDecodeFailure` uses for envelope construction — one resolution per cell, two consumers). Cells the runtime cannot resolve to a single underlying column (aggregate\n * aliases, computed projections without a simple ref) get `column: undefined`, matching the spec contract that the runtime never silently defaults this field.\n */\nasync function decodeField(\n alias: string,\n wireValue: unknown,\n decodeCtx: DecodeContext,\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 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 try {\n return await codec.decode(wireValue, cellCtx);\n } catch (error) {\n if (isRuntimeError(error)) {\n throw error;\n }\n wrapDecodeFailure(error, alias, ref, codec, wireValue);\n }\n}\n\n/**\n * Decodes a row by dispatching all per-cell codec calls concurrently via `Promise.all`. Each cell follows the single-armed `decodeField` path. Failures are wrapped in `RUNTIME.DECODE_FAILED` with `{ table, column, codec }` (or `{ alias, codec }` when no column ref is resolvable) and the original error attached on `cause`.\n *\n * When `rowCtx.signal` is provided:\n *\n * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED` (`{ phase: 'decode' }`) before any `codec.decode` call is made.\n * - **Mid-flight aborts** race the per-cell `Promise.all` against the signal so the runtime returns promptly even when codec bodies ignore it. In-flight bodies that ignore the signal complete in the background (cooperative cancellation).\n * - Existing `RUNTIME.DECODE_FAILED` envelopes from codec bodies pass through unchanged (no double wrap).\n */\nexport async function decodeRow(\n row: Record<string, unknown>,\n plan: SqlExecutionPlan,\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, 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, rowCtx));\n }\n\n const settled = await raceAgainstAbort(Promise.all(tasks), signal, 'decode');\n\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 isRuntimeError,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport {\n type Codec,\n type CodecRef,\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 codec: CodecRef | undefined;\n readonly name: string | undefined;\n}\n\nconst NO_METADATA: ParamMetadata = Object.freeze({\n codec: undefined,\n name: undefined,\n});\n\nfunction resolveParamCodec(\n metadata: ParamMetadata,\n contractCodecs: ContractCodecRegistry | undefined,\n): Codec | undefined {\n if (metadata.codec && contractCodecs) {\n return contractCodecs.forCodecRef(metadata.codec);\n }\n return undefined;\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 a Promise can never leak into the driver, even if a sync-authored codec is lifted to async by the codec factory. Failures are wrapped in `RUNTIME.ENCODE_FAILED` with `{ label, codec, paramIndex }` and the original error attached on `cause`.\n *\n * `ctx` is forwarded verbatim to `codec.encode` so codec authors who opt into the `(value, ctx)` arity see the same `SqlCodecCallContext` the runtime built for the surrounding `runtime.execute()` call. The ctx is always present; its `signal` field may be `undefined`. Encode call sites do not populate `ctx.column` — encode-time column context is the middleware's domain.\n */\nexport async function encodeParam(\n value: unknown,\n paramRef: {\n readonly codec?: CodecRef;\n readonly name?: string;\n },\n paramIndex: number,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<unknown> {\n return encodeParamValue(\n value,\n { codec: paramRef.codec, name: paramRef.name },\n paramIndex,\n ctx,\n contractCodecs,\n );\n}\n\nasync function encodeParamValue(\n value: unknown,\n metadata: ParamMetadata,\n paramIndex: number,\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, contractCodecs);\n if (!codec) {\n return value;\n }\n\n try {\n return await codec.encode(value, ctx);\n } catch (error) {\n // Any `runtimeError`-built envelope is stable by construction — let\n // it pass through unchanged. This covers codec-authored\n // `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` (per-library JSON-with-\n // schema codecs validate inside `encode` per ADR 208 § Case J),\n // codec-authored `RUNTIME.ENCODE_FAILED` (no double wrap), and any\n // future stable code thrown from a codec body. Symmetric with the\n // decode-side guard.\n if (isRuntimeError(error)) throw error;\n wrapEncodeFailure(error, metadata, paramIndex, codec.id);\n }\n}\n\n/**\n * Encodes all parameters concurrently via `Promise.all`. Per parameter, sync-and async-authored codecs share the same path: `codec.encode → await → 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` (`{ phase: 'encode' }`) before any `codec.encode` call is made — codecs can pin this with a per-call counter that stays at zero.\n * - **Mid-flight abort** races the per-param `Promise.all` against `abortable(ctx.signal)`. The runtime returns `RUNTIME.ABORTED` promptly even if codec bodies ignore the signal; the in-flight bodies are abandoned and run to completion in the background (cooperative cancellation, see ADR 204).\n * - Existing `RUNTIME.ENCODE_FAILED` envelopes that surface from a codec body before the runtime observes the abort pass through unchanged (no double wrap).\n */\nexport async function encodeParams(\n plan: SqlExecutionPlan,\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] = { codec: ref.codec, 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(plan.params[i], metadata[i] ?? NO_METADATA, i, ctx, contractCodecs);\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 type RuntimeMiddlewareContext,\n runBeforeExecuteChain,\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 ContractCodecRegistry,\n LoweredStatement,\n SqlCodecCallContext,\n SqlDriver,\n SqlQueryable,\n SqlTransaction,\n} from '@prisma-next/sql-relational-core/ast';\nimport {\n createSqlParamRefMutator,\n type SqlParamRefMutator,\n type SqlParamRefMutatorInternal,\n} from '@prisma-next/sql-relational-core/middleware';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport type { CodecDescriptorRegistry } 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 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.\n */\n release(): Promise<void>;\n /**\n * 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).\n *\n * 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.\n *\n * `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.\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\n// v8 ignore next 2\nconst noopLogSink = (): void => {};\nconst noopLog: Log = { info: noopLogSink, warn: noopLogSink, error: noopLogSink };\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 contractCodecs: ContractCodecRegistry;\n private readonly codecDescriptors: CodecDescriptorRegistry;\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 ?? noopLog,\n // ctx is only invoked by runWithMiddleware with execs this runtime lowered; the framework parameter type is the cross-family base.\n contentHash: (exec) => computeSqlContentHash(exec as SqlExecutionPlan),\n scope: 'runtime',\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.contractCodecs = context.contractCodecs;\n this.codecDescriptors = context.codecDescriptors;\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`\n * with encoded parameters ready for the driver.\n *\n * Implementation note: SQL splits lower-then-encode across\n * {@link lowerToDraft} + {@link encodeDraftParams} so the runtime\n * can fire the `beforeExecute` middleware chain between them\n * (cipherstash bulk-encrypt, for example, mutates pre-encode\n * `ParamRef.value` slots). This protected hook composes the two\n * back into the cross-family `lower()` shape `RuntimeCore.execute`\n * expects, and is called from the no-middleware fast paths /\n * fixtures that hit `RuntimeCore`'s default template directly.\n * `execute()` overrides the template and uses the split form so\n * `beforeExecute` lands between the two halves.\n *\n * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so\n * per-query cancellation reaches every codec body during parameter\n * encoding. SQL params do not populate `ctx.column` — encode-side\n * column metadata is the middleware's domain.\n */\n protected override async lower(\n plan: SqlQueryPlan,\n ctx: SqlCodecCallContext,\n ): Promise<SqlExecutionPlan> {\n const draft = this.lowerToDraft(plan);\n return await this.encodeDraftParams(draft, ctx);\n }\n\n /**\n * AST → pre-encode draft. The returned plan has `sql` rendered and\n * `params` populated with the user-domain values the lowering site\n * collected from `ParamRef` nodes. No codec encode has happened\n * yet; consumers can mutate `params` via the `SqlParamRefMutator`\n * before {@link encodeDraftParams} runs.\n */\n private lowerToDraft(plan: SqlQueryPlan): SqlExecutionPlan {\n return lowerSqlPlan(this.adapter, this.contract, plan);\n }\n\n /**\n * Encode a draft plan's params through the per-column codecs and\n * freeze the result into the final `SqlExecutionPlan` the driver\n * sees. Errors surface as `RUNTIME.ENCODE_FAILED` envelopes from\n * {@link encodeParams}.\n */\n private async encodeDraftParams(\n draft: SqlExecutionPlan,\n ctx: SqlCodecCallContext,\n ): Promise<SqlExecutionPlan> {\n return Object.freeze({\n ...draft,\n params: await encodeParams(draft, ctx, this.contractCodecs),\n });\n }\n\n /**\n * 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.\n */\n // v8 ignore next 6\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` 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\n * 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 const scope = options?.scope ?? 'runtime';\n // 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).\n const codecCtx: SqlCodecCallContext = signal === undefined ? {} : { signal };\n\n // Per-execute view of the middleware ctx that carries the per-query\n // signal. `self.ctx` is allocated once at construction (no signal); we\n // shallow-clone it here so middleware sees the same `AbortSignal`\n // reference threaded into `codecCtx.signal` (ADR 207 identity).\n //\n // The middleware context for this execution is also scope-narrowed: the\n // top-level runtime path uses the constructor-time `'runtime'` ctx as-is;\n // `connection.execute` and `transaction.execute` produce a derived ctx\n // with the appropriate scope. Middleware that observe `ctx.scope`\n // (e.g. the cache middleware, which only intercepts at `'runtime'`)\n // see the right value without any out-of-band signaling.\n const execMiddlewareCtx: RuntimeMiddlewareContext = {\n ...self.ctx,\n ...ifDefined('signal', signal),\n ...(scope !== 'runtime' ? { scope } : {}),\n };\n\n const generator = async function* (): AsyncGenerator<Row, void, unknown> {\n checkAborted(codecCtx, 'stream');\n\n let exec: SqlExecutionPlan;\n if (isExecutionPlan(plan)) {\n // Pre-lowered fixture path. The plan's params are typically\n // already encoded; we still fire `beforeExecute` so middleware\n // that mutates ParamRef values (e.g. cipherstash bulk-encrypt)\n // gets a chance to run, then re-encode so any mutations land.\n const preEncodeMutator: SqlParamRefMutatorInternal = createSqlParamRefMutator(plan);\n await runBeforeExecuteChain<SqlExecutionPlan, SqlParamRefMutator>(\n plan,\n self.middleware,\n execMiddlewareCtx,\n preEncodeMutator,\n );\n exec = Object.freeze({\n ...plan,\n params: await encodeParams(\n { ...plan, params: preEncodeMutator.currentParams() },\n codecCtx,\n self.contractCodecs,\n ),\n });\n } else {\n // Standard AST → exec path. Split lower from encode so the\n // `beforeExecute` chain fires between them with a mutator built\n // over the pre-encode draft params; encode then renders the\n // (possibly mutated) values through the column codecs.\n const compiled = await self.runBeforeCompile(plan);\n const draft = self.lowerToDraft(compiled);\n const preEncodeMutator: SqlParamRefMutatorInternal = createSqlParamRefMutator(draft);\n await runBeforeExecuteChain<SqlExecutionPlan, SqlParamRefMutator>(\n draft,\n self.middleware,\n execMiddlewareCtx,\n preEncodeMutator,\n );\n const draftWithMutations: SqlExecutionPlan = Object.freeze({\n ...draft,\n params: preEncodeMutator.currentParams(),\n });\n exec = await self.encodeDraftParams(draftWithMutations, codecCtx);\n }\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 execMiddlewareCtx,\n () =>\n queryable.execute<Record<string, unknown>>({\n sql: exec.sql,\n // `beforeExecute` ran on the pre-encode draft (see\n // generator setup above); `exec.params` already carries\n // any mutator-driven replacements through `encodeParams`.\n params: exec.params,\n }),\n );\n\n // 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.\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(next.value, exec, codecCtx, self.contractCodecs);\n yield decodedRow as Row;\n }\n } finally {\n // Best-effort iterator cleanup so the driver can release its resources whether the stream finished normally, threw, or was 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, {\n ...options,\n scope: 'connection',\n });\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, {\n ...options,\n scope: 'transaction',\n });\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 const readResult = await this.familyAdapter.markerReader.readMarker(this.driver);\n\n if (readResult.kind !== 'present') {\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 = readResult.record;\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 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.\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 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.\n //\n // 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.\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', mode),\n ...ifDefined('log', log),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAKA,SAAgB,gBAAgB,UAA6C;CAC3E,MAAM,2BAAW,IAAI,KAAa;CAElC,KAAK,MAAM,SAAS,OAAO,OAAO,SAAS,QAAQ,OAAO,EACxD,KAAK,MAAM,UAAU,OAAO,OAAO,MAAM,QAAQ,EAAE;EACjD,MAAM,UAAU,OAAO;EACvB,SAAS,IAAI,QAAQ;;CAIzB,OAAO;;AAGT,SAAS,2BAA2B,UAAqD;CACvF,MAAM,2B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