@prisma-next/sql-runtime 0.5.0-dev.5 → 0.5.0-dev.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +29 -21
  2. package/dist/exports-Boy5W7kg.mjs +1608 -0
  3. package/dist/exports-Boy5W7kg.mjs.map +1 -0
  4. package/dist/{index-yb51L_1h.d.mts → index-_dXSGeho.d.mts} +78 -25
  5. package/dist/index-_dXSGeho.d.mts.map +1 -0
  6. package/dist/index.d.mts +2 -2
  7. package/dist/index.mjs +2 -2
  8. package/dist/test/utils.d.mts +6 -5
  9. package/dist/test/utils.d.mts.map +1 -1
  10. package/dist/test/utils.mjs +11 -5
  11. package/dist/test/utils.mjs.map +1 -1
  12. package/package.json +10 -12
  13. package/src/codecs/decoding.ts +294 -173
  14. package/src/codecs/encoding.ts +162 -37
  15. package/src/codecs/validation.ts +22 -3
  16. package/src/content-hash.ts +44 -0
  17. package/src/exports/index.ts +11 -7
  18. package/src/fingerprint.ts +22 -0
  19. package/src/guardrails/raw.ts +165 -0
  20. package/src/lower-sql-plan.ts +3 -3
  21. package/src/marker.ts +75 -0
  22. package/src/middleware/before-compile-chain.ts +1 -0
  23. package/src/middleware/budgets.ts +26 -96
  24. package/src/middleware/lints.ts +3 -3
  25. package/src/middleware/sql-middleware.ts +6 -5
  26. package/src/runtime-spi.ts +44 -0
  27. package/src/sql-context.ts +332 -78
  28. package/src/sql-family-adapter.ts +3 -2
  29. package/src/sql-marker.ts +62 -47
  30. package/src/sql-runtime.ts +336 -113
  31. package/dist/exports-BQZSVXXt.mjs +0 -981
  32. package/dist/exports-BQZSVXXt.mjs.map +0 -1
  33. package/dist/index-yb51L_1h.d.mts.map +0 -1
  34. package/test/async-iterable-result.test.ts +0 -141
  35. package/test/before-compile-chain.test.ts +0 -223
  36. package/test/budgets.test.ts +0 -431
  37. package/test/context.types.test-d.ts +0 -68
  38. package/test/execution-stack.test.ts +0 -161
  39. package/test/json-schema-validation.test.ts +0 -571
  40. package/test/lints.test.ts +0 -160
  41. package/test/mutation-default-generators.test.ts +0 -254
  42. package/test/parameterized-types.test.ts +0 -529
  43. package/test/sql-context.test.ts +0 -384
  44. package/test/sql-family-adapter.test.ts +0 -103
  45. package/test/sql-runtime.test.ts +0 -792
  46. package/test/utils.ts +0 -297
@@ -0,0 +1,1608 @@
1
+ import { AsyncIterableResult, RuntimeCore, checkAborted, checkMiddlewareCompatibility, isRuntimeError, raceAgainstAbort, runWithMiddleware, runtimeError } from "@prisma-next/framework-components/runtime";
2
+ import { type } from "arktype";
3
+ import { collectOrderedParamRefs, createCodecRegistry, isQueryAst } from "@prisma-next/sql-relational-core/ast";
4
+ import { ifDefined } from "@prisma-next/utils/defined";
5
+ import { synthesizeNonParameterizedDescriptor } from "@prisma-next/framework-components/codec";
6
+ import { checkContractComponentRequirements } from "@prisma-next/framework-components/components";
7
+ import { createExecutionStack } from "@prisma-next/framework-components/execution";
8
+ import { createSqlOperationRegistry } from "@prisma-next/sql-operations";
9
+ import { canonicalStringify } from "@prisma-next/utils/canonical-stringify";
10
+ import { hashContent } from "@prisma-next/utils/hash-content";
11
+ import { createHash } from "node:crypto";
12
+
13
+ //#region src/codecs/validation.ts
14
+ function extractCodecIds(contract) {
15
+ const codecIds = /* @__PURE__ */ new Set();
16
+ for (const table of Object.values(contract.storage.tables)) for (const column of Object.values(table.columns)) {
17
+ const codecId = column.codecId;
18
+ codecIds.add(codecId);
19
+ }
20
+ return codecIds;
21
+ }
22
+ function extractCodecIdsFromColumns(contract) {
23
+ const codecIds = /* @__PURE__ */ new Map();
24
+ for (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) {
25
+ const codecId = column.codecId;
26
+ const key = `${tableName}.${columnName}`;
27
+ codecIds.set(key, codecId);
28
+ }
29
+ return codecIds;
30
+ }
31
+ function adaptDescriptorRegistry(registry) {
32
+ return { has: (id) => registry.descriptorFor(id) !== void 0 };
33
+ }
34
+ function isDescriptorRegistry(registry) {
35
+ return "descriptorFor" in registry;
36
+ }
37
+ function validateContractCodecMappings(registry, contract) {
38
+ const lookup = isDescriptorRegistry(registry) ? adaptDescriptorRegistry(registry) : registry;
39
+ const codecIds = extractCodecIdsFromColumns(contract);
40
+ const invalidCodecs = [];
41
+ for (const [key, codecId] of codecIds.entries()) if (!lookup.has(codecId)) {
42
+ const parts = key.split(".");
43
+ const table = parts[0] ?? "";
44
+ const column = parts[1] ?? "";
45
+ invalidCodecs.push({
46
+ table,
47
+ column,
48
+ codecId
49
+ });
50
+ }
51
+ if (invalidCodecs.length > 0) {
52
+ const details = {
53
+ contractTarget: contract.target,
54
+ invalidCodecs
55
+ };
56
+ throw runtimeError("RUNTIME.CODEC_MISSING", `Missing codec implementations for column codecIds: ${invalidCodecs.map((c) => `${c.table}.${c.column} (${c.codecId})`).join(", ")}`, details);
57
+ }
58
+ }
59
+ function validateCodecRegistryCompleteness(registry, contract) {
60
+ validateContractCodecMappings(registry, contract);
61
+ }
62
+
63
+ //#endregion
64
+ //#region src/lower-sql-plan.ts
65
+ /**
66
+ * Lowers a SQL query plan to an executable Plan by calling the adapter's lower method.
67
+ *
68
+ * @param adapter - Adapter to lower AST to SQL
69
+ * @param contract - Contract for lowering context
70
+ * @param queryPlan - SQL query plan from a lane (contains AST, params, meta, but no SQL)
71
+ * @returns Fully executable Plan with SQL string
72
+ */
73
+ function lowerSqlPlan(adapter, contract, queryPlan) {
74
+ const lowered = adapter.lower(queryPlan.ast, {
75
+ contract,
76
+ params: queryPlan.params
77
+ });
78
+ return Object.freeze({
79
+ sql: lowered.sql,
80
+ params: lowered.params ?? queryPlan.params,
81
+ ast: queryPlan.ast,
82
+ meta: queryPlan.meta
83
+ });
84
+ }
85
+
86
+ //#endregion
87
+ //#region src/marker.ts
88
+ const MetaSchema = type({ "[string]": "unknown" });
89
+ function parseMeta(meta) {
90
+ if (meta === null || meta === void 0) return {};
91
+ let parsed;
92
+ if (typeof meta === "string") try {
93
+ parsed = JSON.parse(meta);
94
+ } catch {
95
+ return {};
96
+ }
97
+ else parsed = meta;
98
+ const result = MetaSchema(parsed);
99
+ if (result instanceof type.errors) return {};
100
+ return result;
101
+ }
102
+ const ContractMarkerRowSchema = type({
103
+ core_hash: "string",
104
+ profile_hash: "string",
105
+ "contract_json?": "unknown | null",
106
+ "canonical_version?": "number | null",
107
+ "updated_at?": "Date | string",
108
+ "app_tag?": "string | null",
109
+ "meta?": "unknown | null",
110
+ invariants: type("string").array()
111
+ });
112
+ function parseContractMarkerRow(row) {
113
+ const result = ContractMarkerRowSchema(row);
114
+ if (result instanceof type.errors) {
115
+ const messages = result.map((p) => p.message).join("; ");
116
+ throw new Error(`Invalid contract marker row: ${messages}`);
117
+ }
118
+ const updatedAt = result.updated_at ? result.updated_at instanceof Date ? result.updated_at : new Date(result.updated_at) : /* @__PURE__ */ new Date();
119
+ return {
120
+ storageHash: result.core_hash,
121
+ profileHash: result.profile_hash,
122
+ contractJson: result.contract_json ?? null,
123
+ canonicalVersion: result.canonical_version ?? null,
124
+ updatedAt,
125
+ appTag: result.app_tag ?? null,
126
+ meta: parseMeta(result.meta),
127
+ invariants: result.invariants
128
+ };
129
+ }
130
+
131
+ //#endregion
132
+ //#region src/middleware/budgets.ts
133
+ function hasAggregateWithoutGroupBy(ast) {
134
+ if (ast.groupBy !== void 0) return false;
135
+ return ast.projection.some((item) => item.expr.kind === "aggregate");
136
+ }
137
+ function primaryTableFromAst(ast) {
138
+ switch (ast.from.kind) {
139
+ case "table-source": return ast.from.name;
140
+ case "derived-table-source": return ast.from.alias;
141
+ default: return;
142
+ }
143
+ }
144
+ function estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggregateWithoutGroup) {
145
+ if (hasAggregateWithoutGroup) return 1;
146
+ const table = primaryTableFromAst(ast);
147
+ if (!table) return null;
148
+ const tableEstimate = tableRows[table] ?? defaultTableRows;
149
+ if (ast.limit !== void 0) return Math.min(ast.limit, tableEstimate);
150
+ return tableEstimate;
151
+ }
152
+ function emitBudgetViolation(error, shouldBlock, ctx) {
153
+ if (shouldBlock) throw error;
154
+ ctx.log.warn({
155
+ code: error.code,
156
+ message: error.message,
157
+ details: error.details
158
+ });
159
+ }
160
+ function budgets(options) {
161
+ const maxRows = options?.maxRows ?? 1e4;
162
+ const defaultTableRows = options?.defaultTableRows ?? 1e4;
163
+ const tableRows = options?.tableRows ?? {};
164
+ const maxLatencyMs = options?.maxLatencyMs ?? 1e3;
165
+ const rowSeverity = options?.severities?.rowCount ?? "error";
166
+ const observedRowsByPlan = /* @__PURE__ */ new WeakMap();
167
+ return Object.freeze({
168
+ name: "budgets",
169
+ familyId: "sql",
170
+ async beforeExecute(plan, ctx) {
171
+ observedRowsByPlan.set(plan, { count: 0 });
172
+ if (isQueryAst(plan.ast) && plan.ast.kind === "select") return evaluateSelectAst(plan.ast, ctx);
173
+ },
174
+ async onRow(_row, plan, _ctx) {
175
+ const state = observedRowsByPlan.get(plan);
176
+ if (!state) return;
177
+ state.count += 1;
178
+ if (state.count > maxRows) throw runtimeError("BUDGET.ROWS_EXCEEDED", "Observed row count exceeds budget", {
179
+ source: "observed",
180
+ observedRows: state.count,
181
+ maxRows
182
+ });
183
+ },
184
+ async afterExecute(_plan, result, ctx) {
185
+ const latencyMs = result.latencyMs;
186
+ if (latencyMs > maxLatencyMs) {
187
+ const shouldBlock = ctx.mode === "strict";
188
+ emitBudgetViolation(runtimeError("BUDGET.TIME_EXCEEDED", "Query latency exceeds budget", {
189
+ latencyMs,
190
+ maxLatencyMs
191
+ }), shouldBlock, ctx);
192
+ }
193
+ }
194
+ });
195
+ function evaluateSelectAst(ast, ctx) {
196
+ const hasAggNoGroup = hasAggregateWithoutGroupBy(ast);
197
+ const estimated = estimateRowsFromAst(ast, tableRows, defaultTableRows, hasAggNoGroup);
198
+ const isUnbounded = ast.limit === void 0 && !hasAggNoGroup;
199
+ const shouldBlock = rowSeverity === "error" || ctx.mode === "strict";
200
+ if (isUnbounded) {
201
+ if (estimated !== null && estimated >= maxRows) {
202
+ emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Unbounded SELECT query exceeds budget", {
203
+ source: "ast",
204
+ estimatedRows: estimated,
205
+ maxRows
206
+ }), shouldBlock, ctx);
207
+ return;
208
+ }
209
+ emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Unbounded SELECT query exceeds budget", {
210
+ source: "ast",
211
+ maxRows
212
+ }), shouldBlock, ctx);
213
+ return;
214
+ }
215
+ if (estimated !== null && estimated > maxRows) emitBudgetViolation(runtimeError("BUDGET.ROWS_EXCEEDED", "Estimated row count exceeds budget", {
216
+ source: "ast",
217
+ estimatedRows: estimated,
218
+ maxRows
219
+ }), shouldBlock, ctx);
220
+ }
221
+ }
222
+
223
+ //#endregion
224
+ //#region src/guardrails/raw.ts
225
+ const SELECT_STAR_REGEX = /select\s+\*/i;
226
+ const LIMIT_REGEX = /\blimit\b/i;
227
+ const MUTATION_PREFIX_REGEX = /^(insert|update|delete|create|alter|drop|truncate)\b/i;
228
+ const READ_ONLY_INTENTS = new Set([
229
+ "read",
230
+ "report",
231
+ "readonly"
232
+ ]);
233
+ function evaluateRawGuardrails(plan, config) {
234
+ const lints$1 = [];
235
+ const budgets$1 = [];
236
+ const normalized = normalizeWhitespace(plan.sql);
237
+ const statementType = classifyStatement(normalized);
238
+ if (statementType === "select") {
239
+ if (SELECT_STAR_REGEX.test(normalized)) lints$1.push(createLint("LINT.SELECT_STAR", "error", "Raw SQL plan selects all columns via *", { sql: snippet(plan.sql) }));
240
+ if (!LIMIT_REGEX.test(normalized)) {
241
+ const severity = config?.budgets?.unboundedSelectSeverity ?? "error";
242
+ lints$1.push(createLint("LINT.NO_LIMIT", "warn", "Raw SQL plan omits LIMIT clause", { sql: snippet(plan.sql) }));
243
+ budgets$1.push(createBudget("BUDGET.ROWS_EXCEEDED", severity, "Raw SQL plan is unbounded and may exceed row budget", {
244
+ sql: snippet(plan.sql),
245
+ ...config?.budgets?.estimatedRows !== void 0 ? { estimatedRows: config.budgets.estimatedRows } : {}
246
+ }));
247
+ }
248
+ }
249
+ if (isMutationStatement(statementType) && isReadOnlyIntent(plan.meta)) lints$1.push(createLint("LINT.READ_ONLY_MUTATION", "error", "Raw SQL plan mutates data despite read-only intent", {
250
+ sql: snippet(plan.sql),
251
+ intent: plan.meta.annotations?.["intent"]
252
+ }));
253
+ return {
254
+ lints: lints$1,
255
+ budgets: budgets$1,
256
+ statement: statementType
257
+ };
258
+ }
259
+ function classifyStatement(sql) {
260
+ const trimmed = sql.trim();
261
+ const lower = trimmed.toLowerCase();
262
+ if (lower.startsWith("with")) {
263
+ if (lower.includes("select")) return "select";
264
+ }
265
+ if (lower.startsWith("select")) return "select";
266
+ if (MUTATION_PREFIX_REGEX.test(trimmed)) return "mutation";
267
+ return "other";
268
+ }
269
+ function isMutationStatement(statement) {
270
+ return statement === "mutation";
271
+ }
272
+ function isReadOnlyIntent(meta) {
273
+ const annotations = meta.annotations;
274
+ const intent = typeof annotations?.intent === "string" ? annotations.intent.toLowerCase() : void 0;
275
+ return intent !== void 0 && READ_ONLY_INTENTS.has(intent);
276
+ }
277
+ function normalizeWhitespace(value) {
278
+ return value.replace(/\s+/g, " ").trim();
279
+ }
280
+ function snippet(sql) {
281
+ return normalizeWhitespace(sql).slice(0, 200);
282
+ }
283
+ function createLint(code, severity, message, details) {
284
+ return {
285
+ code,
286
+ severity,
287
+ message,
288
+ ...details ? { details } : {}
289
+ };
290
+ }
291
+ function createBudget(code, severity, message, details) {
292
+ return {
293
+ code,
294
+ severity,
295
+ message,
296
+ ...details ? { details } : {}
297
+ };
298
+ }
299
+
300
+ //#endregion
301
+ //#region src/middleware/lints.ts
302
+ function getFromSourceTableDetail(source) {
303
+ switch (source.kind) {
304
+ case "table-source": return source.name;
305
+ case "derived-table-source": return source.alias;
306
+ default: throw new Error(`Unsupported source kind: ${source.kind}`);
307
+ }
308
+ }
309
+ function evaluateAstLints(ast) {
310
+ const findings = [];
311
+ switch (ast.kind) {
312
+ case "delete":
313
+ if (ast.where === void 0) findings.push({
314
+ code: "LINT.DELETE_WITHOUT_WHERE",
315
+ severity: "error",
316
+ message: "DELETE without WHERE clause blocks execution to prevent accidental full-table deletion",
317
+ details: { table: ast.table.name }
318
+ });
319
+ break;
320
+ case "update":
321
+ if (ast.where === void 0) findings.push({
322
+ code: "LINT.UPDATE_WITHOUT_WHERE",
323
+ severity: "error",
324
+ message: "UPDATE without WHERE clause blocks execution to prevent accidental full-table update",
325
+ details: { table: ast.table.name }
326
+ });
327
+ break;
328
+ case "select":
329
+ if (ast.limit === void 0) {
330
+ const table = getFromSourceTableDetail(ast.from);
331
+ findings.push({
332
+ code: "LINT.NO_LIMIT",
333
+ severity: "warn",
334
+ message: "Unbounded SELECT may return large result sets",
335
+ ...ifDefined("details", table !== void 0 ? { table } : void 0)
336
+ });
337
+ }
338
+ if (ast.selectAllIntent !== void 0) {
339
+ const table = ast.selectAllIntent.table;
340
+ findings.push({
341
+ code: "LINT.SELECT_STAR",
342
+ severity: "warn",
343
+ message: "Query selects all columns via selectAll intent",
344
+ ...ifDefined("details", table !== void 0 ? { table } : void 0)
345
+ });
346
+ }
347
+ break;
348
+ case "insert": break;
349
+ default: throw new Error(`Unsupported AST kind: ${ast.kind}`);
350
+ }
351
+ return findings;
352
+ }
353
+ function getConfiguredSeverity(code, options) {
354
+ const severities = options?.severities;
355
+ if (!severities) return void 0;
356
+ switch (code) {
357
+ case "LINT.SELECT_STAR": return severities.selectStar;
358
+ case "LINT.NO_LIMIT": return severities.noLimit;
359
+ case "LINT.DELETE_WITHOUT_WHERE": return severities.deleteWithoutWhere;
360
+ case "LINT.UPDATE_WITHOUT_WHERE": return severities.updateWithoutWhere;
361
+ case "LINT.READ_ONLY_MUTATION": return severities.readOnlyMutation;
362
+ case "LINT.UNINDEXED_PREDICATE": return severities.unindexedPredicate;
363
+ default: return;
364
+ }
365
+ }
366
+ /**
367
+ * AST-first lint middleware for SQL plans. When `plan.ast` is a SQL QueryAst, inspects
368
+ * the AST structurally. When `plan.ast` is missing, falls back to raw heuristic
369
+ * guardrails or skips linting depending on `fallbackWhenAstMissing`.
370
+ *
371
+ * Rules (AST-based):
372
+ * - DELETE without WHERE: blocks execution (configurable severity, default error)
373
+ * - UPDATE without WHERE: blocks execution (configurable severity, default error)
374
+ * - Unbounded SELECT: warn/error (severity from noLimit)
375
+ * - SELECT * intent: warn/error (severity from selectStar)
376
+ *
377
+ * Fallback: When ast is missing, `fallbackWhenAstMissing: 'raw'` uses heuristic
378
+ * SQL parsing; `'skip'` skips all lints. Default is `'raw'`.
379
+ */
380
+ function lints(options) {
381
+ const fallback = options?.fallbackWhenAstMissing ?? "raw";
382
+ return Object.freeze({
383
+ name: "lints",
384
+ familyId: "sql",
385
+ async beforeExecute(plan, ctx) {
386
+ if (isQueryAst(plan.ast)) {
387
+ const findings = evaluateAstLints(plan.ast);
388
+ for (const lint of findings) {
389
+ const effectiveSeverity = getConfiguredSeverity(lint.code, options) ?? lint.severity;
390
+ if (effectiveSeverity === "error") throw runtimeError(lint.code, lint.message, lint.details);
391
+ if (effectiveSeverity === "warn") ctx.log.warn({
392
+ code: lint.code,
393
+ message: lint.message,
394
+ details: lint.details
395
+ });
396
+ }
397
+ return;
398
+ }
399
+ if (fallback === "skip") return;
400
+ const evaluation = evaluateRawGuardrails(plan);
401
+ for (const lint of evaluation.lints) {
402
+ const effectiveSeverity = getConfiguredSeverity(lint.code, options) ?? lint.severity;
403
+ if (effectiveSeverity === "error") throw runtimeError(lint.code, lint.message, lint.details);
404
+ if (effectiveSeverity === "warn") ctx.log.warn({
405
+ code: lint.code,
406
+ message: lint.message,
407
+ details: lint.details
408
+ });
409
+ }
410
+ }
411
+ });
412
+ }
413
+
414
+ //#endregion
415
+ //#region src/sql-context.ts
416
+ function createSqlExecutionStack(options) {
417
+ return createExecutionStack({
418
+ target: options.target,
419
+ adapter: options.adapter,
420
+ driver: options.driver,
421
+ extensionPacks: options.extensionPacks
422
+ });
423
+ }
424
+ function assertExecutionStackContractRequirements(contract, stack) {
425
+ const providedComponentIds = new Set([
426
+ stack.target.id,
427
+ stack.adapter.id,
428
+ ...stack.extensionPacks.map((pack) => pack.id)
429
+ ]);
430
+ const result = checkContractComponentRequirements({
431
+ contract,
432
+ expectedTargetFamily: "sql",
433
+ expectedTargetId: stack.target.targetId,
434
+ providedComponentIds
435
+ });
436
+ if (result.familyMismatch) throw runtimeError("RUNTIME.CONTRACT_FAMILY_MISMATCH", `Contract target family '${result.familyMismatch.actual}' does not match runtime family '${result.familyMismatch.expected}'.`, {
437
+ actual: result.familyMismatch.actual,
438
+ expected: result.familyMismatch.expected
439
+ });
440
+ if (result.targetMismatch) throw runtimeError("RUNTIME.CONTRACT_TARGET_MISMATCH", `Contract target '${result.targetMismatch.actual}' does not match runtime target descriptor '${result.targetMismatch.expected}'.`, {
441
+ actual: result.targetMismatch.actual,
442
+ expected: result.targetMismatch.expected
443
+ });
444
+ if (result.missingExtensionPackIds.length > 0) {
445
+ const packIds = result.missingExtensionPackIds;
446
+ throw runtimeError("RUNTIME.MISSING_EXTENSION_PACK", `Contract requires extension pack(s) ${packIds.map((id) => `'${id}'`).join(", ")}, but runtime descriptors do not provide matching component(s).`, { packIds });
447
+ }
448
+ }
449
+ function validateTypeParams(typeParams, codecDescriptor, context) {
450
+ const result = codecDescriptor.paramsSchema["~standard"].validate(typeParams);
451
+ if (result instanceof Promise) throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `paramsSchema for codec '${codecDescriptor.codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`, {
452
+ ...context,
453
+ codecId: codecDescriptor.codecId,
454
+ typeParams
455
+ });
456
+ if (result.issues) {
457
+ const messages = result.issues.map((issue) => issue.message).join("; ");
458
+ throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `Invalid typeParams for ${context.typeName ? `type '${context.typeName}'` : `column '${context.tableName}.${context.columnName}'`} (codecId: ${codecDescriptor.codecId}): ${messages}`, {
459
+ ...context,
460
+ codecId: codecDescriptor.codecId,
461
+ typeParams
462
+ });
463
+ }
464
+ return result.value;
465
+ }
466
+ function collectParameterizedCodecDescriptors(contributors) {
467
+ const descriptors = /* @__PURE__ */ new Map();
468
+ for (const contributor of contributors) for (const descriptor of contributor.parameterizedCodecs()) {
469
+ if (descriptors.has(descriptor.codecId)) throw runtimeError("RUNTIME.DUPLICATE_PARAMETERIZED_CODEC", `Duplicate parameterized codec descriptor for codecId '${descriptor.codecId}'.`, { codecId: descriptor.codecId });
470
+ descriptors.set(descriptor.codecId, descriptor);
471
+ }
472
+ return descriptors;
473
+ }
474
+ /**
475
+ * Build the unified descriptor map. Combines parameterized descriptors
476
+ * (which already ship as `CodecDescriptor`s) with synthesized descriptors
477
+ * for non-parameterized codecs registered through the legacy `codecs:`
478
+ * slot. Codec ids that ship a parameterized descriptor take precedence —
479
+ * even when the legacy registry registers a representative codec under
480
+ * the same id, the parameterized descriptor is the authoritative source.
481
+ *
482
+ * Codec-registry-unification spec § Decision: every codec resolves
483
+ * through one descriptor map; reads are non-branching.
484
+ */
485
+ function buildCodecDescriptorRegistry(codecRegistry, parameterizedDescriptors) {
486
+ const byId = /* @__PURE__ */ new Map();
487
+ const byTargetType = /* @__PURE__ */ new Map();
488
+ function registerInIndices(descriptor) {
489
+ byId.set(descriptor.codecId, descriptor);
490
+ for (const targetType of descriptor.targetTypes) {
491
+ const list = byTargetType.get(targetType);
492
+ if (list) list.push(descriptor);
493
+ else byTargetType.set(targetType, [descriptor]);
494
+ }
495
+ }
496
+ for (const descriptor of parameterizedDescriptors.values()) registerInIndices(descriptor);
497
+ for (const codec$1 of codecRegistry.values()) {
498
+ if (byId.has(codec$1.id)) continue;
499
+ registerInIndices(synthesizeNonParameterizedDescriptor(codec$1));
500
+ }
501
+ return {
502
+ descriptorFor(codecId) {
503
+ return byId.get(codecId);
504
+ },
505
+ *values() {
506
+ yield* byId.values();
507
+ },
508
+ byTargetType(targetType) {
509
+ return byTargetType.get(targetType) ?? Object.freeze([]);
510
+ }
511
+ };
512
+ }
513
+ function collectTypeRefSites(storage) {
514
+ const sites = /* @__PURE__ */ new Map();
515
+ for (const [tableName, table] of Object.entries(storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) {
516
+ if (typeof column.typeRef !== "string") continue;
517
+ const list = sites.get(column.typeRef);
518
+ const entry = {
519
+ table: tableName,
520
+ column: columnName
521
+ };
522
+ if (list) list.push(entry);
523
+ else sites.set(column.typeRef, [entry]);
524
+ }
525
+ return sites;
526
+ }
527
+ function initializeTypeHelpers(storage, codecDescriptors) {
528
+ const helpers = {};
529
+ const storageTypes = storage.types;
530
+ if (!storageTypes) return helpers;
531
+ const typeRefSites = collectTypeRefSites(storage);
532
+ for (const [typeName, typeInstance] of Object.entries(storageTypes)) {
533
+ const descriptor = codecDescriptors.get(typeInstance.codecId);
534
+ if (!descriptor) {
535
+ helpers[typeName] = typeInstance;
536
+ continue;
537
+ }
538
+ const validatedParams = validateTypeParams(typeInstance.typeParams, descriptor, { typeName });
539
+ const ctx = {
540
+ name: typeName,
541
+ usedAt: typeRefSites.get(typeName) ?? []
542
+ };
543
+ helpers[typeName] = descriptor.factory(validatedParams)(ctx);
544
+ }
545
+ return helpers;
546
+ }
547
+ function validateColumnTypeParams(storage, codecDescriptors) {
548
+ for (const [tableName, table] of Object.entries(storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeParams) {
549
+ const descriptor = codecDescriptors.get(column.codecId);
550
+ if (descriptor) validateTypeParams(column.typeParams, descriptor, {
551
+ tableName,
552
+ columnName
553
+ });
554
+ }
555
+ }
556
+ function hasJsonValidatorTrait(candidate) {
557
+ if (candidate === null || typeof candidate !== "object") return false;
558
+ const traits = candidate.traits;
559
+ if (!Array.isArray(traits)) return false;
560
+ if (!traits.includes("json-validator")) return false;
561
+ return typeof candidate.validate === "function";
562
+ }
563
+ function extractValidator(candidate) {
564
+ return hasJsonValidatorTrait(candidate) ? candidate.validate : void 0;
565
+ }
566
+ function isResolvedCodec(candidate) {
567
+ return candidate !== null && typeof candidate === "object" && "id" in candidate && "decode" in candidate;
568
+ }
569
+ /**
570
+ * Walk the contract's `storage.tables[].columns[]` and resolve each
571
+ * column to a `Codec` through the unified descriptor map. Per-instance
572
+ * behavior:
573
+ *
574
+ * - **typeRef columns**: reuse the resolved codec materialized once by
575
+ * `initializeTypeHelpers` for the `storage.types` entry. Multiple
576
+ * columns sharing one typeRef share one codec instance.
577
+ * - **inline-typeParams columns**: call `descriptor.factory(typeParams)
578
+ * (ctx)` once per column (per-column anonymous instance).
579
+ * - **non-parameterized columns**: call `descriptor.factory()(ctx)`
580
+ * once. The synthesized descriptor's factory is constant — every call
581
+ * returns the same shared codec instance — so columns sharing a non-
582
+ * parameterized codec id share one resolved codec without explicit
583
+ * caching.
584
+ *
585
+ * Combines what `initializeTypeHelpers` (named-instance walk) and the
586
+ * old `buildJsonSchemaValidatorRegistry` (per-column walk) used to do
587
+ * separately: one walk over all columns, one resolved codec per column,
588
+ * one trait-gated validator extraction per column. The result drives
589
+ * both the dispatch registry (`ContractCodecRegistry.forColumn`) and the
590
+ * validator registry.
591
+ *
592
+ * Codec-registry-unification spec § AC-4: every column resolves through
593
+ * one descriptor map without branching on parameterization.
594
+ */
595
+ function buildContractCodecRegistry(contract, codecDescriptors, legacyCodecRegistry, types, parameterizedDescriptors) {
596
+ const byColumn = /* @__PURE__ */ new Map();
597
+ const byCodecId = /* @__PURE__ */ new Map();
598
+ const ambiguousCodecIds = /* @__PURE__ */ new Set();
599
+ const validators = /* @__PURE__ */ new Map();
600
+ for (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) {
601
+ const columnKey = `${tableName}.${columnName}`;
602
+ const descriptor = codecDescriptors.descriptorFor(column.codecId);
603
+ let resolvedCodec;
604
+ if (descriptor) {
605
+ const isParameterized = parameterizedDescriptors.has(column.codecId);
606
+ if (column.typeRef) {
607
+ const helper = types[column.typeRef];
608
+ if (isResolvedCodec(helper)) resolvedCodec = helper;
609
+ } else if (column.typeParams && isParameterized) {
610
+ const parameterizedDescriptor = parameterizedDescriptors.get(column.codecId);
611
+ if (parameterizedDescriptor) {
612
+ const validatedParams = validateTypeParams(column.typeParams, parameterizedDescriptor, {
613
+ tableName,
614
+ columnName
615
+ });
616
+ const ctx = {
617
+ name: `<anon:${tableName}.${columnName}>`,
618
+ usedAt: [{
619
+ table: tableName,
620
+ column: columnName
621
+ }]
622
+ };
623
+ resolvedCodec = parameterizedDescriptor.factory(validatedParams)(ctx);
624
+ }
625
+ } else if (!isParameterized) {
626
+ let cached = byCodecId.get(column.codecId);
627
+ if (!cached) {
628
+ const ctx = {
629
+ name: `<shared:${column.codecId}>`,
630
+ usedAt: [{
631
+ table: tableName,
632
+ column: columnName
633
+ }]
634
+ };
635
+ const voidFactory = descriptor.factory;
636
+ cached = voidFactory(void 0)(ctx);
637
+ byCodecId.set(column.codecId, cached);
638
+ }
639
+ resolvedCodec = cached;
640
+ }
641
+ }
642
+ if (resolvedCodec) {
643
+ byColumn.set(columnKey, resolvedCodec);
644
+ const validate = extractValidator(resolvedCodec);
645
+ if (validate) validators.set(columnKey, validate);
646
+ const existing = byCodecId.get(column.codecId);
647
+ if (existing === void 0) byCodecId.set(column.codecId, resolvedCodec);
648
+ else if (existing !== resolvedCodec && parameterizedDescriptors.has(column.codecId)) ambiguousCodecIds.add(column.codecId);
649
+ }
650
+ }
651
+ return {
652
+ registry: {
653
+ forColumn(table, column) {
654
+ return byColumn.get(`${table}.${column}`);
655
+ },
656
+ forCodecId(codecId) {
657
+ if (ambiguousCodecIds.has(codecId)) throw runtimeError("RUNTIME.TYPE_PARAMS_INVALID", `Codec '${codecId}' resolves to multiple parameterized instances; column-aware dispatch is required.`, { codecId });
658
+ return byCodecId.get(codecId) ?? legacyCodecRegistry.get(codecId);
659
+ }
660
+ },
661
+ jsonValidators: validators.size > 0 ? {
662
+ get: (key) => validators.get(key),
663
+ size: validators.size
664
+ } : void 0
665
+ };
666
+ }
667
+ function collectMutationDefaultGenerators(contributors) {
668
+ const generators = /* @__PURE__ */ new Map();
669
+ const owners = /* @__PURE__ */ new Map();
670
+ for (const contributor of contributors) {
671
+ const nextGenerators = contributor.mutationDefaultGenerators?.() ?? [];
672
+ for (const generator of nextGenerators) {
673
+ const existingOwner = owners.get(generator.id);
674
+ if (existingOwner !== void 0) throw runtimeError("RUNTIME.DUPLICATE_MUTATION_DEFAULT_GENERATOR", `Duplicate mutation default generator '${generator.id}'.`, {
675
+ id: generator.id,
676
+ existingOwner,
677
+ incomingOwner: contributor.id
678
+ });
679
+ generators.set(generator.id, generator);
680
+ owners.set(generator.id, contributor.id);
681
+ }
682
+ }
683
+ return generators;
684
+ }
685
+ function computeExecutionDefaultValue(spec, generatorRegistry) {
686
+ switch (spec.kind) {
687
+ case "generator": {
688
+ const generator = generatorRegistry.get(spec.id);
689
+ if (!generator) throw runtimeError("RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING", `Contract references mutation default generator '${spec.id}' but no runtime component provides it.`, { id: spec.id });
690
+ return generator.generate(spec.params);
691
+ }
692
+ }
693
+ }
694
+ function applyMutationDefaults(contract, generatorRegistry, options) {
695
+ const defaults = contract.execution?.mutations.defaults ?? [];
696
+ if (defaults.length === 0) return [];
697
+ const applied = [];
698
+ const appliedColumns = /* @__PURE__ */ new Set();
699
+ for (const mutationDefault of defaults) {
700
+ if (mutationDefault.ref.table !== options.table) continue;
701
+ const defaultSpec = options.op === "create" ? mutationDefault.onCreate : mutationDefault.onUpdate;
702
+ if (!defaultSpec) continue;
703
+ const columnName = mutationDefault.ref.column;
704
+ if (Object.hasOwn(options.values, columnName) || appliedColumns.has(columnName)) continue;
705
+ applied.push({
706
+ column: columnName,
707
+ value: computeExecutionDefaultValue(defaultSpec, generatorRegistry)
708
+ });
709
+ appliedColumns.add(columnName);
710
+ }
711
+ return applied;
712
+ }
713
+ function createExecutionContext(options) {
714
+ const { contract, stack } = options;
715
+ assertExecutionStackContractRequirements(contract, stack);
716
+ const codecRegistry = createCodecRegistry();
717
+ const contributors = [
718
+ stack.target,
719
+ stack.adapter,
720
+ ...stack.extensionPacks
721
+ ];
722
+ for (const contributor of contributors) for (const c of contributor.codecs().values()) codecRegistry.register(c);
723
+ const queryOperationRegistry = createSqlOperationRegistry();
724
+ for (const contributor of contributors) for (const op of contributor.queryOperations?.() ?? []) queryOperationRegistry.register(op);
725
+ const parameterizedCodecDescriptors = collectParameterizedCodecDescriptors(contributors);
726
+ const codecDescriptors = buildCodecDescriptorRegistry(codecRegistry, parameterizedCodecDescriptors);
727
+ const mutationDefaultGeneratorRegistry = collectMutationDefaultGenerators(contributors);
728
+ if (parameterizedCodecDescriptors.size > 0) validateColumnTypeParams(contract.storage, parameterizedCodecDescriptors);
729
+ const types = initializeTypeHelpers(contract.storage, parameterizedCodecDescriptors);
730
+ const { registry: contractCodecs, jsonValidators: jsonSchemaValidators } = buildContractCodecRegistry(contract, codecDescriptors, codecRegistry, types, parameterizedCodecDescriptors);
731
+ return {
732
+ contract,
733
+ codecs: codecRegistry,
734
+ contractCodecs,
735
+ codecDescriptors,
736
+ queryOperations: queryOperationRegistry,
737
+ types,
738
+ ...jsonSchemaValidators ? { jsonSchemaValidators } : {},
739
+ applyMutationDefaults: (options$1) => applyMutationDefaults(contract, mutationDefaultGeneratorRegistry, options$1)
740
+ };
741
+ }
742
+
743
+ //#endregion
744
+ //#region src/sql-marker.ts
745
+ const ensureSchemaStatement = {
746
+ sql: "create schema if not exists prisma_contract",
747
+ params: []
748
+ };
749
+ const ensureTableStatement = {
750
+ sql: `create table if not exists prisma_contract.marker (
751
+ id smallint primary key default 1,
752
+ core_hash text not null,
753
+ profile_hash text not null,
754
+ contract_json jsonb,
755
+ canonical_version int,
756
+ updated_at timestamptz not null default now(),
757
+ app_tag text,
758
+ meta jsonb not null default '{}',
759
+ invariants text[] not null default '{}'
760
+ )`,
761
+ params: []
762
+ };
763
+ function readContractMarker() {
764
+ return {
765
+ sql: `select
766
+ core_hash,
767
+ profile_hash,
768
+ contract_json,
769
+ canonical_version,
770
+ updated_at,
771
+ app_tag,
772
+ meta,
773
+ invariants
774
+ from prisma_contract.marker
775
+ where id = $1`,
776
+ params: [1]
777
+ };
778
+ }
779
+ /**
780
+ * Variable columns that participate in INSERT/UPDATE alongside the
781
+ * always-on `id = $1` and `updated_at = now()`. Each column declares
782
+ * its name, optional cast type, and parameter value; the placeholder
783
+ * (`$N`) is computed positionally below — adding or reordering a
784
+ * column doesn't desync indices. `invariants` only appears when the
785
+ * caller supplies it — see `WriteMarkerInput.invariants`.
786
+ */
787
+ function markerColumns(input) {
788
+ return [
789
+ {
790
+ name: "core_hash",
791
+ param: input.storageHash
792
+ },
793
+ {
794
+ name: "profile_hash",
795
+ param: input.profileHash
796
+ },
797
+ {
798
+ name: "contract_json",
799
+ type: "jsonb",
800
+ param: input.contractJson ?? null
801
+ },
802
+ {
803
+ name: "canonical_version",
804
+ param: input.canonicalVersion ?? null
805
+ },
806
+ {
807
+ name: "app_tag",
808
+ param: input.appTag ?? null
809
+ },
810
+ {
811
+ name: "meta",
812
+ type: "jsonb",
813
+ param: JSON.stringify(input.meta ?? {})
814
+ },
815
+ ...input.invariants !== void 0 ? [{
816
+ name: "invariants",
817
+ type: "text[]",
818
+ param: input.invariants
819
+ }] : []
820
+ ];
821
+ }
822
+ function writeContractMarker(input) {
823
+ const placed = markerColumns(input).map((c, i) => ({
824
+ name: c.name,
825
+ expr: c.type ? `$${i + 2}::${c.type}` : `$${i + 2}`,
826
+ param: c.param
827
+ }));
828
+ const params = [1, ...placed.map((c) => c.param)];
829
+ const insertColumns = [
830
+ "id",
831
+ ...placed.map((c) => c.name),
832
+ "updated_at"
833
+ ].join(", ");
834
+ const insertValues = [
835
+ "$1",
836
+ ...placed.map((c) => c.expr),
837
+ "now()"
838
+ ].join(", ");
839
+ const setClauses = [...placed.map((c) => `${c.name} = ${c.expr}`), "updated_at = now()"].join(", ");
840
+ return {
841
+ insert: {
842
+ sql: `insert into prisma_contract.marker (${insertColumns}) values (${insertValues})`,
843
+ params
844
+ },
845
+ update: {
846
+ sql: `update prisma_contract.marker set ${setClauses} where id = $1`,
847
+ params
848
+ }
849
+ };
850
+ }
851
+
852
+ //#endregion
853
+ //#region src/codecs/json-schema-validation.ts
854
+ /**
855
+ * Validates a JSON value against its column's JSON Schema, if a validator exists.
856
+ *
857
+ * Throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` on validation failure.
858
+ * No-ops if no validator is registered for the column.
859
+ */
860
+ function validateJsonValue(registry, table, column, value, direction, codecId) {
861
+ const key = `${table}.${column}`;
862
+ const validate = registry.get(key);
863
+ if (!validate) return;
864
+ const result = validate(value);
865
+ if (result.valid) return;
866
+ throw createJsonSchemaValidationError(table, column, direction, result.errors, codecId);
867
+ }
868
+ function createJsonSchemaValidationError(table, column, direction, errors, codecId) {
869
+ return runtimeError("RUNTIME.JSON_SCHEMA_VALIDATION_FAILED", `JSON schema validation failed for column '${table}.${column}' (${direction}): ${formatErrorSummary(errors)}`, {
870
+ table,
871
+ column,
872
+ codecId,
873
+ direction,
874
+ errors: [...errors]
875
+ });
876
+ }
877
+ function formatErrorSummary(errors) {
878
+ if (errors.length === 0) return "unknown validation error";
879
+ if (errors.length === 1) {
880
+ const err = errors[0];
881
+ return err.path === "/" ? err.message : `${err.path}: ${err.message}`;
882
+ }
883
+ return errors.map((err) => err.path === "/" ? err.message : `${err.path}: ${err.message}`).join("; ");
884
+ }
885
+
886
+ //#endregion
887
+ //#region src/codecs/decoding.ts
888
+ const WIRE_PREVIEW_LIMIT = 100;
889
+ const EMPTY_INCLUDE_ALIASES = /* @__PURE__ */ new Set();
890
+ function isAstBackedPlan(plan) {
891
+ return plan.ast !== void 0;
892
+ }
893
+ function projectionListFromAst(ast) {
894
+ if (ast.kind === "select") return ast.projection;
895
+ return ast.returning;
896
+ }
897
+ /**
898
+ * Resolve the per-cell codec for a projection item.
899
+ *
900
+ * Phase B: when a `(table, column)` ref is available for the projection,
901
+ * prefer `contractCodecs.forColumn(table, column)` — that's the per-
902
+ * instance resolved codec materialized from the codec descriptor's
903
+ * factory at context-construction time (carries any per-instance state
904
+ * such as the compiled JSON-Schema validator). When the projection
905
+ * resolves to a non-`column-ref` expression (computed projections, raw
906
+ * SQL aliases) but still carries a codec id (ADR 205 stamps every
907
+ * `ProjectionItem` with the producer's codec id), fall back to the
908
+ * codec-id-keyed `forCodecId(codecId)` lookup, which itself falls back
909
+ * to the legacy `CodecRegistry` for codec ids the contract walk
910
+ * couldn't resolve.
911
+ *
912
+ * Codec-registry-unification spec § AC-4.
913
+ */
914
+ function resolveProjectionCodec(item, registry, contractCodecs) {
915
+ if (item.expr.kind === "column-ref" && contractCodecs) {
916
+ const byColumn = contractCodecs.forColumn(item.expr.table, item.expr.column);
917
+ if (byColumn) return byColumn;
918
+ }
919
+ if (item.codecId) {
920
+ const fromContract = contractCodecs?.forCodecId(item.codecId);
921
+ if (fromContract) return fromContract;
922
+ return registry.get(item.codecId);
923
+ }
924
+ }
925
+ function buildDecodeContext(plan, registry, contractCodecs) {
926
+ if (!isAstBackedPlan(plan)) return {
927
+ aliases: void 0,
928
+ codecs: /* @__PURE__ */ new Map(),
929
+ columnRefs: /* @__PURE__ */ new Map(),
930
+ includeAliases: EMPTY_INCLUDE_ALIASES
931
+ };
932
+ const projection = projectionListFromAst(plan.ast);
933
+ if (!projection) return {
934
+ aliases: void 0,
935
+ codecs: /* @__PURE__ */ new Map(),
936
+ columnRefs: /* @__PURE__ */ new Map(),
937
+ includeAliases: EMPTY_INCLUDE_ALIASES
938
+ };
939
+ const aliases = [];
940
+ const codecs = /* @__PURE__ */ new Map();
941
+ const columnRefs = /* @__PURE__ */ new Map();
942
+ const includeAliases = /* @__PURE__ */ new Set();
943
+ for (const item of projection) {
944
+ aliases.push(item.alias);
945
+ const codec$1 = resolveProjectionCodec(item, registry, contractCodecs);
946
+ if (codec$1) codecs.set(item.alias, codec$1);
947
+ if (item.expr.kind === "column-ref") columnRefs.set(item.alias, {
948
+ table: item.expr.table,
949
+ column: item.expr.column
950
+ });
951
+ else if (item.expr.kind === "subquery" || item.expr.kind === "json-array-agg") includeAliases.add(item.alias);
952
+ }
953
+ return {
954
+ aliases,
955
+ codecs,
956
+ columnRefs,
957
+ includeAliases
958
+ };
959
+ }
960
+ function previewWireValue(wireValue) {
961
+ if (typeof wireValue === "string") return wireValue.length > WIRE_PREVIEW_LIMIT ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...` : wireValue;
962
+ return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);
963
+ }
964
+ function isJsonSchemaValidationError(error) {
965
+ return isRuntimeError(error) && error.code === "RUNTIME.JSON_SCHEMA_VALIDATION_FAILED";
966
+ }
967
+ function wrapDecodeFailure(error, alias, ref, codec$1, wireValue) {
968
+ const message = error instanceof Error ? error.message : String(error);
969
+ const wrapped = runtimeError("RUNTIME.DECODE_FAILED", `Failed to decode column ${ref ? `${ref.table}.${ref.column}` : alias} with codec '${codec$1.id}': ${message}`, {
970
+ ...ref ? {
971
+ table: ref.table,
972
+ column: ref.column
973
+ } : { alias },
974
+ codec: codec$1.id,
975
+ wirePreview: previewWireValue(wireValue)
976
+ });
977
+ wrapped.cause = error;
978
+ throw wrapped;
979
+ }
980
+ function wrapIncludeAggregateFailure(error, alias, wireValue) {
981
+ const wrapped = runtimeError("RUNTIME.DECODE_FAILED", `Failed to parse JSON array for include alias '${alias}': ${error instanceof Error ? error.message : String(error)}`, {
982
+ alias,
983
+ wirePreview: previewWireValue(wireValue)
984
+ });
985
+ wrapped.cause = error;
986
+ throw wrapped;
987
+ }
988
+ function decodeIncludeAggregate(alias, wireValue) {
989
+ if (wireValue === null || wireValue === void 0) return [];
990
+ try {
991
+ let parsed;
992
+ if (typeof wireValue === "string") parsed = JSON.parse(wireValue);
993
+ else if (Array.isArray(wireValue)) parsed = wireValue;
994
+ else parsed = JSON.parse(String(wireValue));
995
+ if (!Array.isArray(parsed)) throw new Error(`Expected array for include alias '${alias}', got ${typeof parsed}`);
996
+ return parsed;
997
+ } catch (error) {
998
+ wrapIncludeAggregateFailure(error, alias, wireValue);
999
+ }
1000
+ }
1001
+ /**
1002
+ * Decodes a single field. Single-armed: every cell takes the same path —
1003
+ * `codec.decode → await → JSON-Schema validate → return plain value` — so
1004
+ * sync- and async-authored codecs are indistinguishable to callers.
1005
+ *
1006
+ * The row-level `rowCtx` is repackaged into a per-cell
1007
+ * `SqlCodecCallContext` whose `column = { table, name }` is a structural
1008
+ * projection of the per-cell `ColumnRef = { table, column }` resolved from
1009
+ * the AST-backed `DecodeContext` (the same resolution `wrapDecodeFailure`
1010
+ * uses for envelope construction — one resolution per cell, two consumers).
1011
+ * Cells the runtime cannot resolve to a single underlying column (aggregate
1012
+ * aliases, computed projections without a simple ref) get
1013
+ * `column: undefined`, matching the spec contract that the runtime never
1014
+ * silently defaults this field.
1015
+ */
1016
+ async function decodeField(alias, wireValue, decodeCtx, jsonValidators, rowCtx) {
1017
+ if (wireValue === null) return null;
1018
+ const codec$1 = decodeCtx.codecs.get(alias);
1019
+ if (!codec$1) return wireValue;
1020
+ const ref = decodeCtx.columnRefs.get(alias);
1021
+ let cellCtx;
1022
+ if (ref) cellCtx = {
1023
+ ...rowCtx,
1024
+ column: {
1025
+ table: ref.table,
1026
+ name: ref.column
1027
+ }
1028
+ };
1029
+ else {
1030
+ const { column: _drop, ...rowCtxWithoutColumn } = rowCtx;
1031
+ cellCtx = rowCtxWithoutColumn;
1032
+ }
1033
+ let decoded;
1034
+ try {
1035
+ decoded = await codec$1.decode(wireValue, cellCtx);
1036
+ } catch (error) {
1037
+ wrapDecodeFailure(error, alias, ref, codec$1, wireValue);
1038
+ }
1039
+ if (jsonValidators && ref) try {
1040
+ validateJsonValue(jsonValidators, ref.table, ref.column, decoded, "decode", codec$1.id);
1041
+ } catch (error) {
1042
+ if (isJsonSchemaValidationError(error)) throw error;
1043
+ wrapDecodeFailure(error, alias, ref, codec$1, wireValue);
1044
+ }
1045
+ return decoded;
1046
+ }
1047
+ /**
1048
+ * Decodes a row by dispatching all per-cell codec calls concurrently via
1049
+ * `Promise.all`. Each cell follows the single-armed `decodeField` path.
1050
+ * Failures are wrapped in `RUNTIME.DECODE_FAILED` with `{ table, column,
1051
+ * codec }` (or `{ alias, codec }` when no column ref is resolvable) and the
1052
+ * original error attached on `cause`.
1053
+ *
1054
+ * When `rowCtx.signal` is provided:
1055
+ *
1056
+ * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED`
1057
+ * (`{ phase: 'decode' }`) before any `codec.decode` call is made.
1058
+ * - **Mid-flight aborts** race the per-cell `Promise.all` against the
1059
+ * signal so the runtime returns promptly even when codec bodies ignore
1060
+ * it. In-flight bodies that ignore the signal complete in the
1061
+ * background (cooperative cancellation).
1062
+ * - Existing `RUNTIME.DECODE_FAILED` envelopes from codec bodies pass
1063
+ * through unchanged (no double wrap).
1064
+ */
1065
+ async function decodeRow(row, plan, registry, jsonValidators, rowCtx, contractCodecs) {
1066
+ checkAborted(rowCtx, "decode");
1067
+ const signal = rowCtx.signal;
1068
+ const decodeCtx = buildDecodeContext(plan, registry, contractCodecs);
1069
+ const aliases = decodeCtx.aliases ?? Object.keys(row);
1070
+ if (decodeCtx.aliases !== void 0) {
1071
+ for (const alias of decodeCtx.aliases) if (!Object.hasOwn(row, alias)) throw runtimeError("RUNTIME.DECODE_FAILED", `Row missing projection alias "${alias}"`, {
1072
+ alias,
1073
+ expectedAliases: decodeCtx.aliases,
1074
+ presentKeys: Object.keys(row)
1075
+ });
1076
+ }
1077
+ const tasks = [];
1078
+ const includeIndices = [];
1079
+ for (let i = 0; i < aliases.length; i++) {
1080
+ const alias = aliases[i];
1081
+ const wireValue = row[alias];
1082
+ if (decodeCtx.includeAliases.has(alias)) {
1083
+ includeIndices.push({
1084
+ index: i,
1085
+ alias,
1086
+ value: wireValue
1087
+ });
1088
+ tasks.push(Promise.resolve(void 0));
1089
+ continue;
1090
+ }
1091
+ tasks.push(decodeField(alias, wireValue, decodeCtx, jsonValidators, rowCtx));
1092
+ }
1093
+ const settled = await raceAgainstAbort(Promise.all(tasks), signal, "decode");
1094
+ for (const entry of includeIndices) settled[entry.index] = decodeIncludeAggregate(entry.alias, entry.value);
1095
+ const decoded = {};
1096
+ for (let i = 0; i < aliases.length; i++) decoded[aliases[i]] = settled[i];
1097
+ return decoded;
1098
+ }
1099
+
1100
+ //#endregion
1101
+ //#region src/codecs/encoding.ts
1102
+ const NO_METADATA = Object.freeze({
1103
+ codecId: void 0,
1104
+ name: void 0
1105
+ });
1106
+ /**
1107
+ * Resolve the codec for an outgoing param.
1108
+ *
1109
+ * Phase B (and AC-5-deferred carve-out): `ParamRef` does not carry a
1110
+ * `(table, column)` ref today — every `ParamRef` carries `codecId` but
1111
+ * not the column it relates to. Encode-side dispatch therefore consults
1112
+ * `contractCodecs.forCodecId(codecId)` (which itself prefers the
1113
+ * contract-walk-derived shared codec, falling back to the legacy
1114
+ * `CodecRegistry.get` for parameterized codec ids whose contracts don't
1115
+ * have a column the walk could resolve through).
1116
+ *
1117
+ * For the parameterized codecs shipped at Phase B (pgvector, postgres
1118
+ * json/jsonb), encode is per-instance-stateless w.r.t. params:
1119
+ * - pgvector formats `[v1,v2,...]` regardless of declared length;
1120
+ * - postgres json/jsonb encode is `JSON.stringify` regardless of schema.
1121
+ *
1122
+ * So the codec-id-keyed lookup yields a structurally equivalent encoder
1123
+ * even when the resolved per-instance codec carries extra state (e.g. a
1124
+ * compiled JSON-Schema validator used only by `decode`). TML-2357 retires
1125
+ * the fallback by threading `ParamRef.refs` through column-bound
1126
+ * construction sites.
1127
+ */
1128
+ function resolveParamCodec(metadata, registry, contractCodecs) {
1129
+ if (!metadata.codecId) return void 0;
1130
+ const fromContract = contractCodecs?.forCodecId(metadata.codecId);
1131
+ if (fromContract) return fromContract;
1132
+ return registry.get(metadata.codecId);
1133
+ }
1134
+ function paramLabel(metadata, paramIndex) {
1135
+ return metadata.name ?? `param[${paramIndex}]`;
1136
+ }
1137
+ function wrapEncodeFailure(error, metadata, paramIndex, codecId) {
1138
+ const label = paramLabel(metadata, paramIndex);
1139
+ const wrapped = runtimeError("RUNTIME.ENCODE_FAILED", `Failed to encode parameter ${label} with codec '${codecId}': ${error instanceof Error ? error.message : String(error)}`, {
1140
+ label,
1141
+ codec: codecId,
1142
+ paramIndex
1143
+ });
1144
+ wrapped.cause = error;
1145
+ throw wrapped;
1146
+ }
1147
+ async function encodeParamValue(value, metadata, paramIndex, registry, ctx, contractCodecs) {
1148
+ if (value === null || value === void 0) return null;
1149
+ const codec$1 = resolveParamCodec(metadata, registry, contractCodecs);
1150
+ if (!codec$1) return value;
1151
+ try {
1152
+ return await codec$1.encode(value, ctx);
1153
+ } catch (error) {
1154
+ wrapEncodeFailure(error, metadata, paramIndex, codec$1.id);
1155
+ }
1156
+ }
1157
+ /**
1158
+ * Encodes all parameters concurrently via `Promise.all`. Per parameter, sync-
1159
+ * and async-authored codecs share the same path: `codec.encode → await →
1160
+ * return`. Param-level failures are wrapped in `RUNTIME.ENCODE_FAILED`.
1161
+ *
1162
+ * When `ctx.signal` is provided:
1163
+ *
1164
+ * - **Already-aborted at entry** short-circuits with `RUNTIME.ABORTED`
1165
+ * (`{ phase: 'encode' }`) before any `codec.encode` call is made — codecs
1166
+ * can pin this with a per-call counter that stays at zero.
1167
+ * - **Mid-flight abort** races the per-param `Promise.all` against
1168
+ * `abortable(ctx.signal)`. The runtime returns `RUNTIME.ABORTED` promptly
1169
+ * even if codec bodies ignore the signal; the in-flight bodies are
1170
+ * abandoned and run to completion in the background (cooperative
1171
+ * cancellation, see ADR 204).
1172
+ * - Existing `RUNTIME.ENCODE_FAILED` envelopes that surface from a codec
1173
+ * body before the runtime observes the abort pass through unchanged
1174
+ * (no double wrap).
1175
+ */
1176
+ async function encodeParams(plan, registry, ctx, contractCodecs) {
1177
+ checkAborted(ctx, "encode");
1178
+ const signal = ctx.signal;
1179
+ if (plan.params.length === 0) return plan.params;
1180
+ const paramCount = plan.params.length;
1181
+ const metadata = new Array(paramCount).fill(NO_METADATA);
1182
+ if (plan.ast) {
1183
+ const refs = collectOrderedParamRefs(plan.ast);
1184
+ for (let i = 0; i < paramCount && i < refs.length; i++) {
1185
+ const ref = refs[i];
1186
+ if (ref) metadata[i] = {
1187
+ codecId: ref.codecId,
1188
+ name: ref.name
1189
+ };
1190
+ }
1191
+ }
1192
+ const tasks = new Array(paramCount);
1193
+ for (let i = 0; i < paramCount; i++) tasks[i] = encodeParamValue(plan.params[i], metadata[i] ?? NO_METADATA, i, registry, ctx, contractCodecs);
1194
+ const settled = await raceAgainstAbort(Promise.all(tasks), signal, "encode");
1195
+ return Object.freeze(settled);
1196
+ }
1197
+
1198
+ //#endregion
1199
+ //#region src/content-hash.ts
1200
+ /**
1201
+ * Computes a stable content hash for a lowered SQL execution plan.
1202
+ *
1203
+ * Internally builds an unambiguous canonical-stringified preimage from
1204
+ * three components:
1205
+ *
1206
+ * 1. `meta.storageHash` — discriminates by schema. A migration changes the
1207
+ * storage hash, which invalidates cached entries automatically.
1208
+ * 2. `exec.sql` — the raw lowered SQL text. Two queries with different
1209
+ * structure produce different keys. Note that we deliberately do **not**
1210
+ * use `computeSqlFingerprint` here: that helper strips literals to group
1211
+ * executions by statement shape (used by telemetry), which is the
1212
+ * opposite of what a content hash needs — we want per-execution
1213
+ * discrimination, not per-statement-shape grouping.
1214
+ * 3. `exec.params` — the bound parameters. `canonicalStringify` produces a
1215
+ * deterministic serialization that is stable across object key
1216
+ * insertion order and that distinguishes types JSON would otherwise
1217
+ * conflate (e.g. `BigInt(1)` vs `1`).
1218
+ *
1219
+ * The components are wrapped in an object and canonicalized as a single
1220
+ * unit (rather than concatenated with a delimiter) so component
1221
+ * boundaries are unambiguous: any character appearing inside `sql` or
1222
+ * `storageHash` cannot bleed across components and produce a collision
1223
+ * with a different split of the same characters.
1224
+ *
1225
+ * The canonical string is then piped through `hashContent` to produce a
1226
+ * bounded, opaque digest. See `@prisma-next/utils/hash-content` for the
1227
+ * rationale.
1228
+ *
1229
+ * @internal
1230
+ */
1231
+ function computeSqlContentHash(exec) {
1232
+ return hashContent(canonicalStringify({
1233
+ storageHash: exec.meta.storageHash,
1234
+ sql: exec.sql,
1235
+ params: exec.params
1236
+ }));
1237
+ }
1238
+
1239
+ //#endregion
1240
+ //#region src/fingerprint.ts
1241
+ const STRING_LITERAL_REGEX = /'(?:''|[^'])*'/g;
1242
+ const NUMERIC_LITERAL_REGEX = /\b\d+(?:\.\d+)?\b/g;
1243
+ const WHITESPACE_REGEX = /\s+/g;
1244
+ /**
1245
+ * Computes a literal-stripped, normalized fingerprint of a SQL statement.
1246
+ *
1247
+ * The function strips string and numeric literals, collapses whitespace, and
1248
+ * lowercases the result before hashing — so two structurally equivalent
1249
+ * statements (with different parameter values) produce the same fingerprint.
1250
+ * Used by SQL telemetry to group queries.
1251
+ */
1252
+ function computeSqlFingerprint(sql) {
1253
+ const normalized = sql.replace(STRING_LITERAL_REGEX, "?").replace(NUMERIC_LITERAL_REGEX, "?").replace(WHITESPACE_REGEX, " ").trim().toLowerCase();
1254
+ return `sha256:${createHash("sha256").update(normalized).digest("hex")}`;
1255
+ }
1256
+
1257
+ //#endregion
1258
+ //#region src/middleware/before-compile-chain.ts
1259
+ async function runBeforeCompileChain(middleware, initial, ctx) {
1260
+ let current = initial;
1261
+ for (const mw of middleware) {
1262
+ if (!mw.beforeCompile) continue;
1263
+ const result = await mw.beforeCompile(current, ctx);
1264
+ if (result === void 0) continue;
1265
+ if (result.ast === current.ast) continue;
1266
+ ctx.log.debug?.({
1267
+ event: "middleware.rewrite",
1268
+ middleware: mw.name,
1269
+ lane: current.meta.lane
1270
+ });
1271
+ current = result;
1272
+ }
1273
+ return current;
1274
+ }
1275
+
1276
+ //#endregion
1277
+ //#region src/sql-family-adapter.ts
1278
+ var SqlFamilyAdapter = class {
1279
+ contract;
1280
+ markerReader;
1281
+ constructor(contract, adapterProfile) {
1282
+ this.contract = contract;
1283
+ this.markerReader = adapterProfile;
1284
+ }
1285
+ validatePlan(plan, contract) {
1286
+ if (plan.meta.target !== contract.target) throw runtimeError("PLAN.TARGET_MISMATCH", "Plan target does not match runtime target", {
1287
+ planTarget: plan.meta.target,
1288
+ runtimeTarget: contract.target
1289
+ });
1290
+ if (plan.meta.storageHash !== contract.storage.storageHash) throw runtimeError("PLAN.HASH_MISMATCH", "Plan storage hash does not match runtime contract", {
1291
+ planStorageHash: plan.meta.storageHash,
1292
+ runtimeStorageHash: contract.storage.storageHash
1293
+ });
1294
+ }
1295
+ };
1296
+
1297
+ //#endregion
1298
+ //#region src/sql-runtime.ts
1299
+ function isExecutionPlan(plan) {
1300
+ return "sql" in plan;
1301
+ }
1302
+ var SqlRuntimeImpl = class extends RuntimeCore {
1303
+ contract;
1304
+ adapter;
1305
+ driver;
1306
+ familyAdapter;
1307
+ codecRegistry;
1308
+ contractCodecs;
1309
+ codecDescriptors;
1310
+ jsonSchemaValidators;
1311
+ sqlCtx;
1312
+ verify;
1313
+ codecRegistryValidated;
1314
+ verified;
1315
+ startupVerified;
1316
+ _telemetry;
1317
+ constructor(options) {
1318
+ const { context, adapter, driver, verify, middleware, mode, log } = options;
1319
+ if (middleware) for (const mw of middleware) checkMiddlewareCompatibility(mw, "sql", context.contract.target);
1320
+ const sqlCtx = {
1321
+ contract: context.contract,
1322
+ mode: mode ?? "strict",
1323
+ now: () => Date.now(),
1324
+ log: log ?? {
1325
+ info: () => {},
1326
+ warn: () => {},
1327
+ error: () => {}
1328
+ },
1329
+ contentHash: (exec) => computeSqlContentHash(exec)
1330
+ };
1331
+ super({
1332
+ middleware: middleware ?? [],
1333
+ ctx: sqlCtx
1334
+ });
1335
+ this.contract = context.contract;
1336
+ this.adapter = adapter;
1337
+ this.driver = driver;
1338
+ this.familyAdapter = new SqlFamilyAdapter(context.contract, adapter.profile);
1339
+ this.codecRegistry = context.codecs;
1340
+ this.contractCodecs = context.contractCodecs;
1341
+ this.codecDescriptors = context.codecDescriptors;
1342
+ this.jsonSchemaValidators = context.jsonSchemaValidators;
1343
+ this.sqlCtx = sqlCtx;
1344
+ this.verify = verify;
1345
+ this.codecRegistryValidated = false;
1346
+ this.verified = verify.mode === "startup" ? false : verify.mode === "always";
1347
+ this.startupVerified = false;
1348
+ this._telemetry = null;
1349
+ if (verify.mode === "startup") {
1350
+ validateCodecRegistryCompleteness(this.codecDescriptors, context.contract);
1351
+ this.codecRegistryValidated = true;
1352
+ }
1353
+ }
1354
+ /**
1355
+ * Lower a `SqlQueryPlan` (AST + meta) into a `SqlExecutionPlan` with
1356
+ * encoded parameters ready for the driver. This is the single point at
1357
+ * which params transition from app-layer values to driver wire-format.
1358
+ *
1359
+ * `ctx: SqlCodecCallContext` is forwarded to `encodeParams` so per-query
1360
+ * cancellation reaches every codec body during parameter encoding. The
1361
+ * framework abstract typed this as `CodecCallContext`; the SQL family
1362
+ * narrows it to the SQL-specific extension. SQL params do not populate
1363
+ * `ctx.column` — encode-side column metadata is the middleware's domain.
1364
+ */
1365
+ async lower(plan, ctx) {
1366
+ const lowered = lowerSqlPlan(this.adapter, this.contract, plan);
1367
+ return Object.freeze({
1368
+ ...lowered,
1369
+ params: await encodeParams(lowered, this.codecRegistry, ctx, this.contractCodecs)
1370
+ });
1371
+ }
1372
+ /**
1373
+ * Default driver invocation. Production execution paths override the
1374
+ * queryable target (e.g. transaction or connection) by going through
1375
+ * `executeAgainstQueryable`; this implementation supports any caller of
1376
+ * `super.execute(plan)` and the abstract-base contract.
1377
+ */
1378
+ runDriver(exec) {
1379
+ return this.driver.execute({
1380
+ sql: exec.sql,
1381
+ params: exec.params
1382
+ });
1383
+ }
1384
+ /**
1385
+ * SQL pre-compile hook. Runs the registered middleware `beforeCompile`
1386
+ * chain over the plan's draft (AST + meta). Returns the original plan
1387
+ * unchanged when no middleware rewrote the AST; otherwise returns a new
1388
+ * plan carrying the rewritten AST and meta. The AST is the authoritative
1389
+ * source of execution metadata, so a rewrite needs no sidecar
1390
+ * reconciliation here — the lowering adapter and the encoder both walk
1391
+ * the rewritten AST directly.
1392
+ */
1393
+ async runBeforeCompile(plan) {
1394
+ const rewrittenDraft = await runBeforeCompileChain(this.middleware, {
1395
+ ast: plan.ast,
1396
+ meta: plan.meta
1397
+ }, this.sqlCtx);
1398
+ return rewrittenDraft.ast === plan.ast ? plan : {
1399
+ ...plan,
1400
+ ast: rewrittenDraft.ast,
1401
+ meta: rewrittenDraft.meta
1402
+ };
1403
+ }
1404
+ execute(plan, options) {
1405
+ return this.executeAgainstQueryable(plan, this.driver, options);
1406
+ }
1407
+ executeAgainstQueryable(plan, queryable, options) {
1408
+ this.ensureCodecRegistryValidated();
1409
+ const self = this;
1410
+ const signal = options?.signal;
1411
+ const codecCtx = signal === void 0 ? {} : { signal };
1412
+ const generator = async function* () {
1413
+ checkAborted(codecCtx, "stream");
1414
+ const exec = isExecutionPlan(plan) ? Object.freeze({
1415
+ ...plan,
1416
+ params: await encodeParams(plan, self.codecRegistry, codecCtx, self.contractCodecs)
1417
+ }) : await self.lower(await self.runBeforeCompile(plan), codecCtx);
1418
+ self.familyAdapter.validatePlan(exec, self.contract);
1419
+ self._telemetry = null;
1420
+ if (!self.startupVerified && self.verify.mode === "startup") await self.verifyMarker();
1421
+ if (!self.verified && self.verify.mode === "onFirstUse") await self.verifyMarker();
1422
+ const startedAt = Date.now();
1423
+ let outcome = null;
1424
+ try {
1425
+ if (self.verify.mode === "always") await self.verifyMarker();
1426
+ const iterator = runWithMiddleware(exec, self.middleware, self.ctx, () => queryable.execute({
1427
+ sql: exec.sql,
1428
+ params: exec.params
1429
+ }))[Symbol.asyncIterator]();
1430
+ try {
1431
+ while (true) {
1432
+ checkAborted(codecCtx, "stream");
1433
+ const next = await iterator.next();
1434
+ if (next.done) break;
1435
+ yield await decodeRow(next.value, exec, self.codecRegistry, self.jsonSchemaValidators, codecCtx, self.contractCodecs);
1436
+ }
1437
+ } finally {
1438
+ await iterator.return?.();
1439
+ }
1440
+ outcome = "success";
1441
+ } catch (error) {
1442
+ outcome = "runtime-error";
1443
+ throw error;
1444
+ } finally {
1445
+ if (outcome !== null) self.recordTelemetry(exec, outcome, Date.now() - startedAt);
1446
+ }
1447
+ };
1448
+ return new AsyncIterableResult(generator());
1449
+ }
1450
+ async connection() {
1451
+ const driverConn = await this.driver.acquireConnection();
1452
+ const self = this;
1453
+ return {
1454
+ async transaction() {
1455
+ const driverTx = await driverConn.beginTransaction();
1456
+ return self.wrapTransaction(driverTx);
1457
+ },
1458
+ async release() {
1459
+ await driverConn.release();
1460
+ },
1461
+ async destroy(reason) {
1462
+ await driverConn.destroy(reason);
1463
+ },
1464
+ execute(plan, options) {
1465
+ return self.executeAgainstQueryable(plan, driverConn, options);
1466
+ }
1467
+ };
1468
+ }
1469
+ wrapTransaction(driverTx) {
1470
+ const self = this;
1471
+ return {
1472
+ async commit() {
1473
+ await driverTx.commit();
1474
+ },
1475
+ async rollback() {
1476
+ await driverTx.rollback();
1477
+ },
1478
+ execute(plan, options) {
1479
+ return self.executeAgainstQueryable(plan, driverTx, options);
1480
+ }
1481
+ };
1482
+ }
1483
+ telemetry() {
1484
+ return this._telemetry;
1485
+ }
1486
+ async close() {
1487
+ await this.driver.close();
1488
+ }
1489
+ ensureCodecRegistryValidated() {
1490
+ if (!this.codecRegistryValidated) {
1491
+ validateCodecRegistryCompleteness(this.codecDescriptors, this.contract);
1492
+ this.codecRegistryValidated = true;
1493
+ }
1494
+ }
1495
+ async verifyMarker() {
1496
+ if (this.verify.mode === "always") this.verified = false;
1497
+ if (this.verified) return;
1498
+ const readStatement = this.familyAdapter.markerReader.readMarkerStatement();
1499
+ const result = await this.driver.query(readStatement.sql, readStatement.params);
1500
+ if (result.rows.length === 0) {
1501
+ if (this.verify.requireMarker) throw runtimeError("CONTRACT.MARKER_MISSING", "Contract marker not found in database");
1502
+ this.verified = true;
1503
+ return;
1504
+ }
1505
+ const marker = this.familyAdapter.markerReader.parseMarkerRow(result.rows[0]);
1506
+ const contract = this.contract;
1507
+ if (marker.storageHash !== contract.storage.storageHash) throw runtimeError("CONTRACT.MARKER_MISMATCH", "Database storage hash does not match contract", {
1508
+ expected: contract.storage.storageHash,
1509
+ actual: marker.storageHash
1510
+ });
1511
+ const expectedProfile = contract.profileHash ?? null;
1512
+ if (expectedProfile !== null && marker.profileHash !== expectedProfile) throw runtimeError("CONTRACT.MARKER_MISMATCH", "Database profile hash does not match contract", {
1513
+ expectedProfile,
1514
+ actualProfile: marker.profileHash
1515
+ });
1516
+ this.verified = true;
1517
+ this.startupVerified = true;
1518
+ }
1519
+ recordTelemetry(plan, outcome, durationMs) {
1520
+ const contract = this.contract;
1521
+ this._telemetry = Object.freeze({
1522
+ lane: plan.meta.lane,
1523
+ target: contract.target,
1524
+ fingerprint: computeSqlFingerprint(plan.sql),
1525
+ outcome,
1526
+ ...durationMs !== void 0 ? { durationMs } : {}
1527
+ });
1528
+ }
1529
+ };
1530
+ function transactionClosedError() {
1531
+ return runtimeError("RUNTIME.TRANSACTION_CLOSED", "Cannot read from a query result after the transaction has ended. Await the result or call .toArray() inside the transaction callback.", {});
1532
+ }
1533
+ async function withTransaction(runtime, fn) {
1534
+ const connection = await runtime.connection();
1535
+ const transaction = await connection.transaction();
1536
+ let invalidated = false;
1537
+ const txContext = {
1538
+ get invalidated() {
1539
+ return invalidated;
1540
+ },
1541
+ execute(plan, options) {
1542
+ if (invalidated) throw transactionClosedError();
1543
+ const inner = transaction.execute(plan, options);
1544
+ const guarded = async function* () {
1545
+ for await (const row of inner) {
1546
+ if (invalidated) throw transactionClosedError();
1547
+ yield row;
1548
+ }
1549
+ };
1550
+ return new AsyncIterableResult(guarded());
1551
+ }
1552
+ };
1553
+ let connectionDisposed = false;
1554
+ const destroyConnection = async (reason) => {
1555
+ if (connectionDisposed) return;
1556
+ connectionDisposed = true;
1557
+ await connection.destroy(reason).catch(() => void 0);
1558
+ };
1559
+ try {
1560
+ let result;
1561
+ try {
1562
+ result = await fn(txContext);
1563
+ } catch (error) {
1564
+ try {
1565
+ await transaction.rollback();
1566
+ } catch (rollbackError) {
1567
+ await destroyConnection(rollbackError);
1568
+ const wrapped = runtimeError("RUNTIME.TRANSACTION_ROLLBACK_FAILED", "Transaction rollback failed after callback error", { rollbackError });
1569
+ wrapped.cause = error;
1570
+ throw wrapped;
1571
+ }
1572
+ throw error;
1573
+ } finally {
1574
+ invalidated = true;
1575
+ }
1576
+ try {
1577
+ await transaction.commit();
1578
+ } catch (commitError) {
1579
+ try {
1580
+ await transaction.rollback();
1581
+ } catch {
1582
+ await destroyConnection(commitError);
1583
+ }
1584
+ const wrapped = runtimeError("RUNTIME.TRANSACTION_COMMIT_FAILED", "Transaction commit failed", { commitError });
1585
+ wrapped.cause = commitError;
1586
+ throw wrapped;
1587
+ }
1588
+ return result;
1589
+ } finally {
1590
+ if (!connectionDisposed) await connection.release();
1591
+ }
1592
+ }
1593
+ function createRuntime(options) {
1594
+ const { stackInstance, context, driver, verify, middleware, mode, log } = options;
1595
+ return new SqlRuntimeImpl({
1596
+ context,
1597
+ adapter: stackInstance.adapter,
1598
+ driver,
1599
+ verify,
1600
+ ...ifDefined("middleware", middleware),
1601
+ ...ifDefined("mode", mode),
1602
+ ...ifDefined("log", log)
1603
+ });
1604
+ }
1605
+
1606
+ //#endregion
1607
+ export { readContractMarker as a, createSqlExecutionStack as c, parseContractMarkerRow as d, lowerSqlPlan as f, validateContractCodecMappings as h, ensureTableStatement as i, lints as l, validateCodecRegistryCompleteness as m, withTransaction as n, writeContractMarker as o, extractCodecIds as p, ensureSchemaStatement as r, createExecutionContext as s, createRuntime as t, budgets as u };
1608
+ //# sourceMappingURL=exports-Boy5W7kg.mjs.map