@prisma-next/sql-runtime 0.9.0-dev.8 → 0.9.0-dev.9
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/dist/{exports-DHQOSWty.mjs → exports-BsRNNJxU.mjs} +8 -8
- package/dist/exports-BsRNNJxU.mjs.map +1 -0
- package/dist/index-B2sP_QGE.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/test/utils.mjs +2 -5
- package/dist/test/utils.mjs.map +1 -1
- package/package.json +12 -12
- package/src/codecs/validation.ts +22 -10
- package/src/sql-context.ts +103 -83
- package/dist/exports-DHQOSWty.mjs.map +0 -1
|
@@ -16,7 +16,7 @@ import { createHash } from "node:crypto";
|
|
|
16
16
|
//#region src/codecs/validation.ts
|
|
17
17
|
function extractCodecIds(contract) {
|
|
18
18
|
const codecIds = /* @__PURE__ */ new Set();
|
|
19
|
-
for (const
|
|
19
|
+
for (const ns of Object.values(contract.storage.namespaces)) for (const table of Object.values(ns.tables)) for (const column of Object.values(table.columns)) {
|
|
20
20
|
const codecId = column.codecId;
|
|
21
21
|
codecIds.add(codecId);
|
|
22
22
|
}
|
|
@@ -24,7 +24,7 @@ function extractCodecIds(contract) {
|
|
|
24
24
|
}
|
|
25
25
|
function extractCodecIdsFromColumns(contract) {
|
|
26
26
|
const codecIds = /* @__PURE__ */ new Map();
|
|
27
|
-
for (const [tableName, table] of Object.entries(
|
|
27
|
+
for (const ns of Object.values(contract.storage.namespaces)) for (const [tableName, table] of Object.entries(ns.tables)) for (const [columnName, column] of Object.entries(table.columns)) {
|
|
28
28
|
const codecId = column.codecId;
|
|
29
29
|
const key = `${tableName}.${columnName}`;
|
|
30
30
|
codecIds.set(key, codecId);
|
|
@@ -527,7 +527,7 @@ function collectCodecDescriptors(contributors) {
|
|
|
527
527
|
}
|
|
528
528
|
function collectTypeRefSites(storage) {
|
|
529
529
|
const sites = /* @__PURE__ */ new Map();
|
|
530
|
-
for (const [tableName, table] of Object.entries(
|
|
530
|
+
for (const ns of Object.values(storage.namespaces)) for (const [tableName, table] of Object.entries(ns.tables)) for (const [columnName, column] of Object.entries(table.columns)) {
|
|
531
531
|
if (typeof column.typeRef !== "string") continue;
|
|
532
532
|
const list = sites.get(column.typeRef);
|
|
533
533
|
const entry = {
|
|
@@ -563,7 +563,7 @@ function initializeTypeHelpers(storage, codecDescriptors) {
|
|
|
563
563
|
return helpers;
|
|
564
564
|
}
|
|
565
565
|
function validateColumnTypeParams(storage, codecDescriptors) {
|
|
566
|
-
for (const [tableName, table] of Object.entries(
|
|
566
|
+
for (const ns of Object.values(storage.namespaces)) for (const [tableName, table] of Object.entries(ns.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeParams) {
|
|
567
567
|
const descriptor = codecDescriptors.get(column.codecId);
|
|
568
568
|
if (descriptor) validateTypeParams(column.typeParams, descriptor, {
|
|
569
569
|
tableName,
|
|
@@ -583,7 +583,7 @@ function validateColumnTypeParams(storage, codecDescriptors) {
|
|
|
583
583
|
* 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.
|
|
584
584
|
*/
|
|
585
585
|
function assertColumnCodecIntegrity(storage, codecDescriptors) {
|
|
586
|
-
for (const [tableName, table] of Object.entries(
|
|
586
|
+
for (const ns of Object.values(storage.namespaces)) for (const [tableName, table] of Object.entries(ns.tables)) for (const columnName of Object.keys(table.columns)) {
|
|
587
587
|
const ref = codecDescriptors.codecRefForColumn(tableName, columnName);
|
|
588
588
|
if (!ref) continue;
|
|
589
589
|
const descriptor = codecDescriptors.descriptorFor(ref.codecId);
|
|
@@ -657,7 +657,7 @@ function buildContractCodecRegistry(contract, codecDescriptors) {
|
|
|
657
657
|
nameByKey.set(key, typeName);
|
|
658
658
|
}
|
|
659
659
|
}
|
|
660
|
-
for (const [tableName, table] of Object.entries(
|
|
660
|
+
for (const ns of Object.values(contract.storage.namespaces)) for (const [tableName, table] of Object.entries(ns.tables)) for (const [columnName, column] of Object.entries(table.columns)) {
|
|
661
661
|
if (column.typeRef !== void 0) continue;
|
|
662
662
|
const ref = codecDescriptors.codecRefForColumn(tableName, columnName);
|
|
663
663
|
if (!ref) continue;
|
|
@@ -681,7 +681,7 @@ function buildContractCodecRegistry(contract, codecDescriptors) {
|
|
|
681
681
|
usedAt: usedAtByKey.get(key) ?? []
|
|
682
682
|
};
|
|
683
683
|
});
|
|
684
|
-
for (const [tableName, table] of Object.entries(
|
|
684
|
+
for (const ns of Object.values(contract.storage.namespaces)) for (const [tableName, table] of Object.entries(ns.tables)) for (const columnName of Object.keys(table.columns)) {
|
|
685
685
|
const ref = codecDescriptors.codecRefForColumn(tableName, columnName);
|
|
686
686
|
if (!ref) continue;
|
|
687
687
|
resolver.forCodecRef(ref);
|
|
@@ -1762,4 +1762,4 @@ function createRuntime(options) {
|
|
|
1762
1762
|
//#endregion
|
|
1763
1763
|
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 };
|
|
1764
1764
|
|
|
1765
|
-
//# sourceMappingURL=exports-
|
|
1765
|
+
//# sourceMappingURL=exports-BsRNNJxU.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exports-BsRNNJxU.mjs","names":["validateTypeParams","#ast","#preparedStatementHandles"],"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/prepared/bind-site-params.ts","../src/prepared/encode-prepared.ts","../src/prepared/prepared-statement.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, StorageTable } from '@prisma-next/sql-contract/types';\nimport type { CodecDescriptorRegistry } from '@prisma-next/sql-relational-core/query-lane-context';\n\n// Framework `Namespace.tables` is widened to `Record<string, object>` so\n// emitted `contract.d.ts` table literals (which omit the optional `kind`\n// discriminator) satisfy it structurally. At runtime, every `SqlStorage`\n// namespace holds `StorageTable` instances — the constructor enforces it.\n// Narrowing per-iteration via a single-step cast (not `as unknown as`)\n// keeps Pattern C walks readable without weakening the substrate type.\ntype SqlNamespaceTables = Readonly<Record<string, StorageTable>>;\n\nexport function extractCodecIds(contract: Contract<SqlStorage>): Set<string> {\n const codecIds = new Set<string>();\n\n for (const ns of Object.values(contract.storage.namespaces)) {\n for (const table of Object.values(ns.tables as SqlNamespaceTables)) {\n for (const column of Object.values(table.columns)) {\n const codecId = column.codecId;\n codecIds.add(codecId);\n }\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 ns of Object.values(contract.storage.namespaces)) {\n for (const [tableName, table] of Object.entries(ns.tables as SqlNamespaceTables)) {\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\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 { runtimeError } from '@prisma-next/framework-components/runtime';\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 * Ad-hoc lowerings produce only `{kind: 'literal'}` slots; this helper\n * unwraps them into the bare-value array `SqlExecutionPlan` exposes.\n * Encountering a `{kind: 'bind'}` slot here means the caller passed an\n * AST containing `PreparedParamRef` to the ad-hoc execute path — that's a\n * caller error, surfaced as `RUNTIME.PREPARE_BIND_ON_ADHOC`.\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 const params: unknown[] = lowered.params.map((slot) => {\n if (slot.kind === 'literal') return slot.value;\n throw runtimeError(\n 'RUNTIME.PREPARE_BIND_ON_ADHOC',\n `Ad-hoc execute received a bind-site slot for '${slot.name}' — bind-site references are only valid inside runtime.prepare(...).`,\n { name: slot.name },\n );\n });\n\n return Object.freeze({\n sql: lowered.sql,\n 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 (typeof ast.limit === 'number') {\n return Math.min(ast.limit, tableEstimate);\n }\n\n // Expression-form limit: value is dynamic at execute time (e.g. a prepared\n // bind site). Treat as bounded but unknown — the table estimate is the\n // worst case.\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 StorageTable,\n type StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\n\n// Framework `Namespace.tables` is widened to `Record<string, object>` so\n// emitted `contract.d.ts` table literals satisfy it structurally. At\n// runtime, every `SqlStorage` namespace holds `StorageTable` instances —\n// the constructor enforces it. Narrowing per-iteration with a single-step\n// cast (not `as unknown as`) keeps Pattern C walks readable without\n// weakening the substrate type.\ntype SqlNamespaceTables = Readonly<Record<string, StorageTable>>;\n\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 ns of Object.values(storage.namespaces)) {\n for (const [tableName, table] of Object.entries(ns.tables as SqlNamespaceTables)) {\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 }\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 ns of Object.values(storage.namespaces)) {\n for (const [tableName, table] of Object.entries(ns.tables as SqlNamespaceTables)) {\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/**\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 ns of Object.values(storage.namespaces)) {\n for (const [tableName, table] of Object.entries(ns.tables as SqlNamespaceTables)) {\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/**\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 ns of Object.values(contract.storage.namespaces)) {\n for (const [tableName, table] of Object.entries(ns.tables as SqlNamespaceTables)) {\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\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 ns of Object.values(contract.storage.namespaces)) {\n for (const [tableName, table] of Object.entries(ns.tables as SqlNamespaceTables)) {\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\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';\n\ntype ColumnRef = { table: string; column: string };\n\nexport interface 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 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\nexport function buildDecodeContext(\n ast: AnyQueryAst,\n contractCodecs: ContractCodecRegistry | undefined,\n): DecodeContext {\n const projection = projectionListFromAst(ast);\n if (!projection || projection.length === 0) {\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 decodeCtx: DecodeContext,\n rowCtx: SqlCodecCallContext,\n): Promise<Record<string, unknown>> {\n checkAborted(rowCtx, 'decode');\n const signal = rowCtx.signal;\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 AnyQueryAst,\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\nexport interface 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\n// Indexed by Postgres-style deduped slot order (matches the adapter's\n// `collectOrderedParamRefs` walk). For SQLite's non-deduped renderer,\n// `lowered.params` has one entry per occurrence: positions past\n// `refs.length` fall back to `NO_METADATA` in encodeParamsWithMetadata,\n// so codec'd repeats round-trip unchanged — a limitation that will be\n// revisited when SQLite prepared statements ship and each adapter\n// carries codec metadata on its `LoweredParam` slots directly.\nexport function deriveParamMetadata(ast: AnyQueryAst): readonly ParamMetadata[] {\n return collectOrderedParamRefs(ast).map((ref): ParamMetadata => {\n return { codec: ref.codec, name: ref.name };\n });\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 return encodeParamsWithMetadata(plan.params, deriveParamMetadata(plan.ast), ctx, contractCodecs);\n}\n\nexport async function encodeParamsWithMetadata(\n values: readonly unknown[],\n metadata: readonly ParamMetadata[],\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<readonly unknown[]> {\n checkAborted(ctx, 'encode');\n const signal = ctx.signal;\n\n if (values.length === 0) {\n return values;\n }\n\n const tasks = values.map((value, i) =>\n encodeParamValue(value, 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 {\n AnyExpression as AstExpression,\n CodecRef,\n} from '@prisma-next/sql-relational-core/ast';\nimport { PreparedParamRef } from '@prisma-next/sql-relational-core/ast';\nimport type { Expression, ScopeField } from '@prisma-next/sql-relational-core/expression';\nimport type { BindSiteParams, Declaration, ParamSpec } from './types';\n\nfunction normalizeSpec(spec: ParamSpec): { codec: CodecRef; nullable: boolean } {\n if (typeof spec === 'string') return { codec: { codecId: spec }, nullable: false };\n const codec: CodecRef =\n spec.typeParams !== undefined\n ? { codecId: spec.codecId, typeParams: spec.typeParams }\n : { codecId: spec.codecId };\n return { codec, nullable: spec.nullable === true };\n}\n\nclass BindSiteExpression implements Expression<ScopeField> {\n readonly returnType: ScopeField;\n readonly #ast: AstExpression;\n constructor(ref: PreparedParamRef, returnType: ScopeField) {\n this.#ast = ref;\n this.returnType = returnType;\n }\n buildAst(): AstExpression {\n return this.#ast;\n }\n}\n\nexport function buildBindSiteParams<D extends Declaration>(declaration: D): BindSiteParams<D> {\n const params: Record<string, Expression<ScopeField>> = {};\n for (const [name, spec] of Object.entries(declaration)) {\n const { codec, nullable } = normalizeSpec(spec);\n const ref = PreparedParamRef.of(name, codec);\n params[name] = new BindSiteExpression(ref, { codecId: codec.codecId, nullable });\n }\n // The cast narrows the structurally-equivalent record to the per-key\n // codecId/nullable types declared by D — TypeScript can't relate the\n // mapped-type keys to the runtime keys without reflection.\n return Object.freeze(params) as BindSiteParams<D>;\n}\n","import { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type {\n ContractCodecRegistry,\n SqlCodecCallContext,\n} from '@prisma-next/sql-relational-core/ast';\nimport { encodeParamsWithMetadata } from '../codecs/encoding';\nimport type { PreparedStatementInternals } from './prepared-statement';\n\n/**\n * Resolve a PreparedStatement's slot order to the unencoded values it\n * will carry into encode. Literal slots come from the lowered AST;\n * bind slots are looked up by name on `userParams`. Missing user params\n * surface `RUNTIME.PREPARE_MISSING_PARAM` so the caller cannot silently\n * bind `undefined`.\n */\nexport function resolvePreparedSlotValues(\n ps: PreparedStatementInternals,\n userParams: Record<string, unknown>,\n): unknown[] {\n return ps.slots.map((slot) => {\n if (slot.kind === 'literal') return slot.value;\n if (!Object.hasOwn(userParams, slot.name)) {\n throw runtimeError(\n 'RUNTIME.PREPARE_MISSING_PARAM',\n `Prepared statement execute is missing parameter '${slot.name}'`,\n { name: slot.name },\n );\n }\n return userParams[slot.name];\n });\n}\n\nexport async function encodePreparedParams(\n ps: PreparedStatementInternals,\n userParams: Record<string, unknown>,\n ctx: SqlCodecCallContext,\n contractCodecs?: ContractCodecRegistry,\n): Promise<readonly unknown[]> {\n const resolved = resolvePreparedSlotValues(ps, userParams);\n return encodeParamsWithMetadata(resolved, ps.paramMetadata, ctx, contractCodecs);\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type {\n AsyncIterableResult,\n RuntimeExecuteOptions,\n} from '@prisma-next/framework-components/runtime';\nimport type { AnyQueryAst, LoweredParam } from '@prisma-next/sql-relational-core/ast';\nimport type { DecodeContext } from '../codecs/decoding';\nimport type { ParamMetadata } from '../codecs/encoding';\nimport type { RuntimeQueryable } from '../sql-runtime';\nimport type { ParamsFromDeclaration, PreparedStatement } from './types';\n\nexport interface PreparedStatementInternals {\n readonly sql: string;\n readonly ast: AnyQueryAst;\n readonly meta: PlanMeta;\n readonly slots: readonly LoweredParam[];\n readonly decodeContext: DecodeContext;\n readonly paramMetadata: readonly ParamMetadata[];\n}\n\nexport class PreparedStatementImpl<Params, Row>\n implements PreparedStatement<Params, Row>, PreparedStatementInternals\n{\n readonly sql: string;\n readonly ast: AnyQueryAst;\n readonly meta: PlanMeta;\n readonly slots: readonly LoweredParam[];\n readonly decodeContext: DecodeContext;\n readonly paramMetadata: readonly ParamMetadata[];\n\n constructor(internals: PreparedStatementInternals) {\n this.sql = internals.sql;\n this.ast = internals.ast;\n this.meta = internals.meta;\n this.slots = internals.slots;\n this.decodeContext = internals.decodeContext;\n this.paramMetadata = internals.paramMetadata;\n Object.freeze(this);\n }\n\n execute(\n target: RuntimeQueryable,\n params: Params,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return target.executePrepared(this, params, options);\n }\n}\n\nexport type { ParamsFromDeclaration };\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 PreparedExecuteRequest,\n SqlCodecCallContext,\n SqlDriver,\n SqlQueryable,\n SqlTransaction,\n} from '@prisma-next/sql-relational-core/ast';\nimport { collectOrderedParamRefs } from '@prisma-next/sql-relational-core/ast';\nimport type { CodecTypesBase } from '@prisma-next/sql-relational-core/expression';\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 { buildDecodeContext, type DecodeContext, decodeRow } from './codecs/decoding';\nimport { deriveParamMetadata, encodeParams, encodeParamsWithMetadata } 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 { buildBindSiteParams } from './prepared/bind-site-params';\nimport { resolvePreparedSlotValues } from './prepared/encode-prepared';\nimport {\n PreparedStatementImpl,\n type PreparedStatementInternals,\n} from './prepared/prepared-statement';\nimport type {\n Declaration,\n ParamsFromDeclaration,\n PrepareCallback,\n PreparedStatement,\n} from './prepared/types';\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 /**\n * Build a reusable {@link PreparedStatement}. Throws\n * `RUNTIME.PREPARE_UNUSED_PARAM` if any declared name is unreferenced\n * by the callback's plan.\n */\n prepare<D extends Declaration<CT>, Row, CT extends CodecTypesBase = CodecTypesBase>(\n declaration: D,\n callback: PrepareCallback<D, Row>,\n ): Promise<PreparedStatement<ParamsFromDeclaration<D, CT>, Row>>;\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 /**\n * Run a prepared statement against this scope. Required for the explicit\n * `PreparedStatement.execute(target, params)` API — every scope (top-level\n * runtime, connection, transaction) routes prepared executions through the\n * `SqlQueryable` it is backed by.\n */\n executePrepared<Params, Row>(\n ps: PreparedStatement<Params, Row>,\n params: Params,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row>;\n}\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 readonly #preparedStatementHandles = new WeakMap<object, unknown>();\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 executePrepared<Params, Row>(\n ps: PreparedStatement<Params, Row>,\n params: Params,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return this.executePreparedAgainstQueryable<Params, Row>(\n ps as PreparedStatementImpl<Params, Row>,\n params as Record<string, unknown>,\n this.driver,\n options,\n );\n }\n\n private async *streamRows<Row>(\n exec: SqlExecutionPlan,\n decodeContext: DecodeContext,\n driverCall: () => AsyncIterable<Record<string, unknown>>,\n codecCtx: SqlCodecCallContext,\n execMiddlewareCtx: RuntimeMiddlewareContext,\n ): AsyncGenerator<Row, void, unknown> {\n this.familyAdapter.validatePlan(exec, this.contract);\n this._telemetry = null;\n\n if (!this.startupVerified && this.verify.mode === 'startup') {\n await this.verifyMarker();\n }\n\n if (!this.verified && this.verify.mode === 'onFirstUse') {\n await this.verifyMarker();\n }\n\n const startedAt = Date.now();\n let outcome: TelemetryOutcome | null = null;\n\n try {\n if (this.verify.mode === 'always') {\n await this.verifyMarker();\n }\n\n const stream = runWithMiddleware<SqlExecutionPlan, Record<string, unknown>>(\n exec,\n this.middleware,\n execMiddlewareCtx,\n driverCall,\n );\n\n // Manually drive the driver's async iterator so the between-row\n // abort check fires *before* requesting the next row. With a\n // `for await...of` loop the runtime would await `iterator.next()`\n // first, leaving a window where one extra row is pulled through\n // the driver after the signal aborted.\n const iterator = stream[Symbol.asyncIterator]();\n try {\n while (true) {\n checkAborted(codecCtx, 'stream');\n const next = await iterator.next();\n if (next.done) {\n break;\n }\n const decodedRow = await decodeRow(next.value, decodeContext, codecCtx);\n yield decodedRow as Row;\n }\n } finally {\n // Best-effort iterator cleanup so the driver can release its\n // resources whether the stream finished normally, threw, or was\n // abandoned by the consumer.\n await iterator.return?.();\n }\n\n outcome = 'success';\n } catch (error) {\n outcome = 'runtime-error';\n throw error;\n } finally {\n if (outcome !== null) {\n this.recordTelemetry(exec, outcome, Date.now() - startedAt);\n }\n }\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 const decodeContext = buildDecodeContext(exec.ast, self.contractCodecs);\n\n yield* self.streamRows<Row>(\n exec,\n decodeContext,\n () => queryable.execute<Record<string, unknown>>({ sql: exec.sql, params: exec.params }),\n codecCtx,\n execMiddlewareCtx,\n );\n };\n\n return new AsyncIterableResult(generator());\n }\n\n async prepare<D extends Declaration<CT>, Row, CT extends CodecTypesBase = CodecTypesBase>(\n declaration: D,\n callback: PrepareCallback<D, Row>,\n ): Promise<PreparedStatement<ParamsFromDeclaration<D, CT>, Row>> {\n this.ensureCodecRegistryValidated();\n\n const bindSiteParams = buildBindSiteParams(declaration);\n\n const userPlan = callback(bindSiteParams);\n const finalPlan = await this.runBeforeCompile(userPlan);\n const orderedRefs = collectOrderedParamRefs(finalPlan.ast);\n\n // Type-level detection isn't achievable across chained-builder generics.\n const referencedNames = new Set<string>();\n for (const ref of orderedRefs) {\n if (ref.kind === 'prepared-param-ref') referencedNames.add(ref.name);\n }\n const missing = Object.keys(declaration).filter((name) => !referencedNames.has(name));\n if (missing.length > 0) {\n throw runtimeError(\n 'RUNTIME.PREPARE_UNUSED_PARAM',\n `Prepared statement declaration includes parameter${missing.length === 1 ? '' : 's'} not referenced by the callback's plan: ${missing.join(', ')}`,\n { unused: missing },\n );\n }\n\n const lowered = this.adapter.lower(finalPlan.ast, {\n contract: this.contract,\n params: orderedRefs.map((r) => (r.kind === 'param-ref' ? r.value : undefined)),\n });\n\n const decodeContext = buildDecodeContext(finalPlan.ast, this.contractCodecs);\n const paramMetadata = deriveParamMetadata(finalPlan.ast);\n\n const internals: PreparedStatementInternals = Object.freeze({\n sql: lowered.sql,\n ast: finalPlan.ast,\n meta: finalPlan.meta,\n slots: lowered.params,\n decodeContext,\n paramMetadata,\n });\n\n return new PreparedStatementImpl<ParamsFromDeclaration<D, CT>, Row>(internals);\n }\n\n private executePreparedAgainstQueryable<P, Row>(\n ps: PreparedStatementImpl<P, Row>,\n userParams: Record<string, 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 const codecCtx: SqlCodecCallContext = signal === undefined ? {} : { signal };\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 // Resolve slot order to unencoded values so `beforeExecute`'s\n // mutator sees pre-encode user values for prepared-param slots\n // and can override them before encode runs.\n const preEncodeValues = resolvePreparedSlotValues(ps, userParams);\n const preEncodeExec: SqlExecutionPlan = {\n sql: ps.sql,\n params: preEncodeValues,\n ast: ps.ast,\n meta: ps.meta,\n };\n\n const mutator: SqlParamRefMutatorInternal = createSqlParamRefMutator(preEncodeExec);\n await runBeforeExecuteChain<SqlExecutionPlan, SqlParamRefMutator>(\n preEncodeExec,\n self.middleware,\n execMiddlewareCtx,\n mutator,\n );\n\n const encodedParams = await encodeParamsWithMetadata(\n mutator.currentParams(),\n ps.paramMetadata,\n codecCtx,\n self.contractCodecs,\n );\n const exec: SqlExecutionPlan = {\n sql: ps.sql,\n params: encodedParams,\n ast: ps.ast,\n meta: ps.meta,\n };\n\n const handles = self.#preparedStatementHandles;\n const request: PreparedExecuteRequest = {\n sql: exec.sql,\n params: exec.params,\n handle: {\n get: () => handles.get(ps),\n set: (value) => {\n handles.set(ps, value);\n },\n },\n };\n\n yield* self.streamRows<Row>(\n exec,\n ps.decodeContext,\n () => queryable.executePrepared<Record<string, unknown>>(request),\n codecCtx,\n execMiddlewareCtx,\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 executePrepared<Params, Row>(\n ps: PreparedStatement<Params, Row>,\n params: Params,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executePreparedAgainstQueryable<Params, Row>(\n ps as PreparedStatementImpl<Params, Row>,\n params as Record<string, unknown>,\n driverConn,\n { ...options, 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 executePrepared<Params, Row>(\n ps: PreparedStatement<Params, Row>,\n params: Params,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n return self.executePreparedAgainstQueryable<Params, Row>(\n ps as PreparedStatementImpl<Params, Row>,\n params as Record<string, unknown>,\n driverTx,\n { ...options, 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 executePrepared<Params, Row>(\n ps: PreparedStatement<Params, Row>,\n params: Params,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n if (invalidated) {\n throw transactionClosedError();\n }\n const inner = transaction.executePrepared(ps, params, 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":";;;;;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,UAA6C;CAC3E,MAAM,2BAAW,IAAI,KAAa;CAElC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AAY,gBAAgB,IAAI,QAAQ,QAAQ;GAC9D,MAAM,UAAU,mBAAuD;IACrE,WAAW,MAAM,OAAO,OAAO;KAC7B,IAAI,aACF,MAAM,wBAAwB;KAEhC,MAAM;;;GAGV,OAAO,IAAI,oBAAoB,SAAS,CAAC;;EAE5C;CAED,IAAI,qBAAqB;CACzB,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-B2sP_QGE.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-runtime.ts","../src/prepared/types.ts","../src/sql-marker.ts"],"mappings":";;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index-B2sP_QGE.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-runtime.ts","../src/prepared/types.ts","../src/sql-marker.ts"],"mappings":";;;;;;;;;;;;;;;iBAagB,eAAA,CAAgB,QAAA,EAAU,QAAA,CAAS,UAAA,IAAc,GAAA;AAAA,iBA+BjD,6BAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;AAAA,iBA4BL,iCAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;;;;;;;;;;;;iBC7DL,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;;;iBCgCJ,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,EAAkB,kBAAA,CAAmB,SAAA;EAAA,SACtD,QAAA;EHb+B;;;;;;;;;;AA+B1C;;;;;;;;EGCE,aAAA,EAAe,KAAA,EAAO,SAAA,EA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,EAAuB,YAAA;;;;;;;;;;;AVqCpC;cUrBa,oBAAA,EAAsB,YAAA;AAAA,iBAenB,kBAAA,CAAmB,KAAA,WAAgB,eAAA;AAAA,UAiBlC,6BAAA;EAAA,SACN,MAAA,EAAQ,YAAA;EAAA,SACR,MAAA,EAAQ,YAAA;AAAA;AAAA,iBA2BH,mBAAA,CAAoB,KAAA,EAAO,gBAAA,GAAmB,6BAAA"}
|
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-
|
|
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-BsRNNJxU.mjs";
|
|
2
2
|
export { APP_SPACE_ID, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
|
package/dist/test/utils.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ensureTableStatement, c as createExecutionContext, i as ensureSchemaStatement, l as createSqlExecutionStack, r as APP_SPACE_ID, s as writeContractMarker } from "../exports-
|
|
1
|
+
import { a as ensureTableStatement, c as createExecutionContext, i as ensureSchemaStatement, l as createSqlExecutionStack, r as APP_SPACE_ID, s as writeContractMarker } from "../exports-BsRNNJxU.mjs";
|
|
2
2
|
import { runtimeError } from "@prisma-next/framework-components/runtime";
|
|
3
3
|
import { SelectAst, TableSource } from "@prisma-next/sql-relational-core/ast";
|
|
4
4
|
import { instantiateExecutionStack } from "@prisma-next/framework-components/execution";
|
|
@@ -308,10 +308,7 @@ function createTestContract(contract) {
|
|
|
308
308
|
storage: rest["storage"] ? new SqlStorage({
|
|
309
309
|
...rest["storage"],
|
|
310
310
|
storageHash: storageHashValue
|
|
311
|
-
}) : new SqlStorage({
|
|
312
|
-
storageHash: storageHashValue,
|
|
313
|
-
tables: {}
|
|
314
|
-
}),
|
|
311
|
+
}) : new SqlStorage({ storageHash: storageHashValue }),
|
|
315
312
|
models: rest["models"] ?? {},
|
|
316
313
|
roots: rest["roots"] ?? {},
|
|
317
314
|
capabilities: rest["capabilities"] ?? {},
|