@prisma-next/framework-components 0.5.0-dev.2 → 0.5.0-dev.20

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/runtime.mjs CHANGED
@@ -1,4 +1,13 @@
1
1
  //#region src/runtime-error.ts
2
+ /**
3
+ * Type guard for the runtime-error envelope produced by `runtimeError`.
4
+ *
5
+ * Prefer this over duck-typing on `error.code` directly so consumers stay
6
+ * insulated from the envelope's internal shape.
7
+ */
8
+ function isRuntimeError(error) {
9
+ return error instanceof Error && "code" in error && typeof error.code === "string" && "category" in error && "severity" in error;
10
+ }
2
11
  function runtimeError(code, message, details) {
3
12
  const error = new Error(message);
4
13
  Object.defineProperty(error, "name", {
@@ -71,6 +80,113 @@ var AsyncIterableResult = class {
71
80
  }
72
81
  };
73
82
 
83
+ //#endregion
84
+ //#region src/run-with-middleware.ts
85
+ /**
86
+ * Drives a single execution of `runDriver()` through the middleware lifecycle.
87
+ *
88
+ * Lifecycle, in order:
89
+ * 1. For each middleware in registration order: `beforeExecute(exec, ctx)`.
90
+ * 2. For each row yielded by `runDriver()`: for each middleware in registration
91
+ * order: `onRow(row, exec, ctx)`; then yield the row to the consumer.
92
+ * 3. On successful completion: for each middleware in registration order:
93
+ * `afterExecute(exec, { rowCount, latencyMs, completed: true }, ctx)`.
94
+ * 4. On any error thrown by the driver loop: for each middleware in
95
+ * registration order: `afterExecute(exec, { rowCount, latencyMs,
96
+ * completed: false }, ctx)`. Errors thrown by `afterExecute` during the
97
+ * error path are swallowed so they do not mask the original driver error.
98
+ * The original error is then rethrown.
99
+ *
100
+ * This helper is the single canonical implementation of the middleware
101
+ * orchestration loop; family runtimes should not reimplement it.
102
+ */
103
+ function runWithMiddleware(exec, middleware, ctx, runDriver) {
104
+ const iterator = async function* () {
105
+ const startedAt = Date.now();
106
+ let rowCount = 0;
107
+ let completed = false;
108
+ try {
109
+ for (const mw of middleware) if (mw.beforeExecute) await mw.beforeExecute(exec, ctx);
110
+ for await (const row of runDriver()) {
111
+ for (const mw of middleware) if (mw.onRow) await mw.onRow(row, exec, ctx);
112
+ rowCount++;
113
+ yield row;
114
+ }
115
+ completed = true;
116
+ } catch (error) {
117
+ const latencyMs$1 = Date.now() - startedAt;
118
+ for (const mw of middleware) if (mw.afterExecute) try {
119
+ await mw.afterExecute(exec, {
120
+ rowCount,
121
+ latencyMs: latencyMs$1,
122
+ completed
123
+ }, ctx);
124
+ } catch {}
125
+ throw error;
126
+ }
127
+ const latencyMs = Date.now() - startedAt;
128
+ for (const mw of middleware) if (mw.afterExecute) await mw.afterExecute(exec, {
129
+ rowCount,
130
+ latencyMs,
131
+ completed
132
+ }, ctx);
133
+ };
134
+ return new AsyncIterableResult(iterator());
135
+ }
136
+
137
+ //#endregion
138
+ //#region src/runtime-core.ts
139
+ /**
140
+ * Family-agnostic abstract runtime base.
141
+ *
142
+ * Defines the entire `execute(plan)` template in one place:
143
+ *
144
+ * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides
145
+ * this to run its `beforeCompile` middleware-hook chain.
146
+ * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`
147
+ * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).
148
+ * 3. `runWithMiddleware(exec, this.middleware, this.ctx,
149
+ * () => runDriver(exec))` — concrete; lifts the middleware lifecycle
150
+ * out of the family runtimes into the canonical helper.
151
+ *
152
+ * Concrete subclasses must implement `lower`, `runDriver`, and `close`.
153
+ *
154
+ * The class is generic over:
155
+ * - `TPlan` — the family's pre-lowering plan type.
156
+ * - `TExec` — the family's post-lowering (executable) plan type.
157
+ * - `TMiddleware` — the family's middleware type. Constrained to
158
+ * `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the
159
+ * `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered
160
+ * `TExec`. (The spec/plan wording "RuntimeMiddleware<TPlan>" is
161
+ * tightened to `<TExec>` here so the helper call typechecks; the
162
+ * intent is unchanged — middleware sees the post-lowering plan.)
163
+ */
164
+ var RuntimeCore = class {
165
+ middleware;
166
+ ctx;
167
+ constructor(options) {
168
+ this.middleware = options.middleware;
169
+ this.ctx = options.ctx;
170
+ }
171
+ /**
172
+ * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses
173
+ * may override to run a `beforeCompile` middleware chain (SQL does this
174
+ * to support typed AST rewrites — see `before-compile-chain.ts`).
175
+ */
176
+ runBeforeCompile(plan) {
177
+ return plan;
178
+ }
179
+ execute(plan) {
180
+ const self = this;
181
+ async function* generator() {
182
+ const compiled = await self.runBeforeCompile(plan);
183
+ const exec = await self.lower(compiled);
184
+ yield* runWithMiddleware(exec, self.middleware, self.ctx, () => self.runDriver(exec));
185
+ }
186
+ return new AsyncIterableResult(generator());
187
+ }
188
+ };
189
+
74
190
  //#endregion
75
191
  //#region src/runtime-middleware.ts
76
192
  function checkMiddlewareCompatibility(middleware, runtimeFamilyId, runtimeTargetId) {
@@ -91,5 +207,5 @@ function checkMiddlewareCompatibility(middleware, runtimeFamilyId, runtimeTarget
91
207
  }
92
208
 
93
209
  //#endregion
94
- export { AsyncIterableResult, checkMiddlewareCompatibility, runtimeError };
210
+ export { AsyncIterableResult, RuntimeCore, checkMiddlewareCompatibility, isRuntimeError, runWithMiddleware, runtimeError };
95
211
  //# sourceMappingURL=runtime.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":["out: Row[]"],"sources":["../src/runtime-error.ts","../src/async-iterable-result.ts","../src/runtime-middleware.ts"],"sourcesContent":["export interface RuntimeErrorEnvelope extends Error {\n readonly code: string;\n readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';\n readonly severity: 'error';\n readonly details?: Record<string, unknown>;\n}\n\nexport function runtimeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): RuntimeErrorEnvelope {\n const error = new Error(message) as RuntimeErrorEnvelope;\n Object.defineProperty(error, 'name', {\n value: 'RuntimeError',\n configurable: true,\n });\n\n return Object.assign(error, {\n code,\n category: resolveCategory(code),\n severity: 'error' as const,\n message,\n details,\n });\n}\n\nfunction resolveCategory(code: string): RuntimeErrorEnvelope['category'] {\n const prefix = code.split('.')[0] ?? 'RUNTIME';\n switch (prefix) {\n case 'PLAN':\n case 'CONTRACT':\n case 'LINT':\n case 'BUDGET':\n return prefix;\n default:\n return 'RUNTIME';\n }\n}\n","import { runtimeError } from './runtime-error';\n\nexport class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {\n private readonly generator: AsyncGenerator<Row, void, unknown>;\n private consumed = false;\n private consumedBy: 'bufferedArray' | 'iterator' | undefined;\n private bufferedArrayPromise: Promise<Row[]> | undefined;\n\n constructor(generator: AsyncGenerator<Row, void, unknown>) {\n this.generator = generator;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Row> {\n if (this.consumed) {\n throw runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n `AsyncIterableResult iterator has already been consumed via ${this.consumedBy === 'bufferedArray' ? 'toArray()/then()' : 'for-await loop'}. Each AsyncIterableResult can only be iterated once.`,\n {\n consumedBy: this.consumedBy,\n suggestion:\n this.consumedBy === 'bufferedArray'\n ? 'If you need to iterate multiple times, store the results from toArray() in a variable and reuse that.'\n : 'If you need to iterate multiple times, use toArray() to collect all results first.',\n },\n );\n }\n this.consumed = true;\n this.consumedBy = 'iterator';\n return this.generator;\n }\n\n toArray(): Promise<Row[]> {\n if (this.consumedBy === 'iterator') {\n return Promise.reject(\n runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n 'AsyncIterableResult iterator has already been consumed via for-await loop. Each AsyncIterableResult can only be iterated once.',\n {\n consumedBy: this.consumedBy,\n suggestion:\n 'The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating.',\n },\n ),\n );\n }\n\n if (this.bufferedArrayPromise) {\n return this.bufferedArrayPromise;\n }\n\n this.consumed = true;\n this.consumedBy = 'bufferedArray';\n this.bufferedArrayPromise = (async () => {\n const out: Row[] = [];\n for await (const item of this.generator) {\n out.push(item);\n }\n return out;\n })();\n return this.bufferedArrayPromise;\n }\n\n async first(): Promise<Row | null> {\n const rows = await this.toArray();\n return rows[0] ?? null;\n }\n\n async firstOrThrow(): Promise<Row> {\n const row = await this.first();\n if (row === null)\n throw runtimeError(\n 'RUNTIME.NO_ROWS',\n 'Expected at least one row, but none were returned',\n {},\n );\n return row;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: PromiseLike implementation is intentional for await support.\n then<TResult1 = Row[], TResult2 = never>(\n onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.toArray().then(onfulfilled, onrejected);\n }\n}\n","import type { PlanMeta } from '@prisma-next/contract/types';\nimport type { AsyncIterableResult } from './async-iterable-result';\nimport { runtimeError } from './runtime-error';\n\nexport interface RuntimeLog {\n info(event: unknown): void;\n warn(event: unknown): void;\n error(event: unknown): void;\n debug?(event: unknown): void;\n}\n\nexport interface RuntimeMiddlewareContext {\n readonly contract: unknown;\n readonly mode: 'strict' | 'permissive';\n readonly now: () => number;\n readonly log: RuntimeLog;\n}\n\nexport interface AfterExecuteResult {\n readonly rowCount: number;\n readonly latencyMs: number;\n readonly completed: boolean;\n}\n\nexport interface RuntimeMiddleware {\n readonly name: string;\n readonly familyId?: string;\n readonly targetId?: string;\n beforeExecute?(plan: { readonly meta: PlanMeta }, ctx: RuntimeMiddlewareContext): Promise<void>;\n onRow?(\n row: Record<string, unknown>,\n plan: { readonly meta: PlanMeta },\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n afterExecute?(\n plan: { readonly meta: PlanMeta },\n result: AfterExecuteResult,\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n}\n\n/**\n * Cross-family SPI for any runtime that can execute plans and be shut down.\n * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,\n * Mongo structurally (due to its phantom Row parameter using a unique symbol).\n *\n * The `_row` intersection on `execute` connects the `Row` type parameter to the\n * plan, mirroring how `ExecutionPlan<Row>` carries a phantom `_row?: Row`.\n */\nexport interface RuntimeExecutor<TPlan extends { readonly meta: PlanMeta }> {\n execute<Row>(plan: TPlan & { readonly _row?: Row }): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nexport function checkMiddlewareCompatibility(\n middleware: RuntimeMiddleware,\n runtimeFamilyId: string,\n runtimeTargetId: string,\n): void {\n if (middleware.targetId !== undefined && middleware.familyId === undefined) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',\n `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,\n { middleware: middleware.name, targetId: middleware.targetId },\n );\n }\n\n if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',\n `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,\n { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },\n );\n }\n\n if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',\n `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,\n { middleware: middleware.name, middlewareTargetId: middleware.targetId, runtimeTargetId },\n );\n }\n}\n"],"mappings":";AAOA,SAAgB,aACd,MACA,SACA,SACsB;CACtB,MAAM,QAAQ,IAAI,MAAM,QAAQ;AAChC,QAAO,eAAe,OAAO,QAAQ;EACnC,OAAO;EACP,cAAc;EACf,CAAC;AAEF,QAAO,OAAO,OAAO,OAAO;EAC1B;EACA,UAAU,gBAAgB,KAAK;EAC/B,UAAU;EACV;EACA;EACD,CAAC;;AAGJ,SAAS,gBAAgB,MAAgD;CACvE,MAAM,SA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W,SAAS,qBAC3E;EAAE,YAAY,WAAW;EAAM,UAAU,WAAW;EAAU,CAC/D;AAGH,KAAI,WAAW,aAAa,UAAa,WAAW,aAAa,gBAC/D,OAAM,aACJ,sCACA,eAAe,WAAW,KAAK,qBAAqB,WAAW,SAAS,8CAA8C,gBAAgB,IACtI;EAAE,YAAY,WAAW;EAAM,oBAAoB,WAAW;EAAU;EAAiB,CAC1F;AAGH,KAAI,WAAW,aAAa,UAAa,WAAW,aAAa,gBAC/D,OAAM,aACJ,sCACA,eAAe,WAAW,KAAK,qBAAqB,WAAW,SAAS,8CAA8C,gBAAgB,IACtI;EAAE,YAAY,WAAW;EAAM,oBAAoB,WAAW;EAAU;EAAiB,CAC1F"}
1
+ {"version":3,"file":"runtime.mjs","names":["out: Row[]","latencyMs"],"sources":["../src/runtime-error.ts","../src/async-iterable-result.ts","../src/run-with-middleware.ts","../src/runtime-core.ts","../src/runtime-middleware.ts"],"sourcesContent":["export interface RuntimeErrorEnvelope extends Error {\n readonly code: string;\n readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';\n readonly severity: 'error';\n readonly details?: Record<string, unknown>;\n}\n\n/**\n * Type guard for the runtime-error envelope produced by `runtimeError`.\n *\n * Prefer this over duck-typing on `error.code` directly so consumers stay\n * insulated from the envelope's internal shape.\n */\nexport function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {\n return (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code?: unknown }).code === 'string' &&\n 'category' in error &&\n 'severity' in error\n );\n}\n\nexport function runtimeError(\n code: string,\n message: string,\n details?: Record<string, unknown>,\n): RuntimeErrorEnvelope {\n const error = new Error(message) as RuntimeErrorEnvelope;\n Object.defineProperty(error, 'name', {\n value: 'RuntimeError',\n configurable: true,\n });\n\n return Object.assign(error, {\n code,\n category: resolveCategory(code),\n severity: 'error' as const,\n message,\n details,\n });\n}\n\nfunction resolveCategory(code: string): RuntimeErrorEnvelope['category'] {\n const prefix = code.split('.')[0] ?? 'RUNTIME';\n switch (prefix) {\n case 'PLAN':\n case 'CONTRACT':\n case 'LINT':\n case 'BUDGET':\n return prefix;\n default:\n return 'RUNTIME';\n }\n}\n","import { runtimeError } from './runtime-error';\n\nexport class AsyncIterableResult<Row> implements AsyncIterable<Row>, PromiseLike<Row[]> {\n private readonly generator: AsyncGenerator<Row, void, unknown>;\n private consumed = false;\n private consumedBy: 'bufferedArray' | 'iterator' | undefined;\n private bufferedArrayPromise: Promise<Row[]> | undefined;\n\n constructor(generator: AsyncGenerator<Row, void, unknown>) {\n this.generator = generator;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Row> {\n if (this.consumed) {\n throw runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n `AsyncIterableResult iterator has already been consumed via ${this.consumedBy === 'bufferedArray' ? 'toArray()/then()' : 'for-await loop'}. Each AsyncIterableResult can only be iterated once.`,\n {\n consumedBy: this.consumedBy,\n suggestion:\n this.consumedBy === 'bufferedArray'\n ? 'If you need to iterate multiple times, store the results from toArray() in a variable and reuse that.'\n : 'If you need to iterate multiple times, use toArray() to collect all results first.',\n },\n );\n }\n this.consumed = true;\n this.consumedBy = 'iterator';\n return this.generator;\n }\n\n toArray(): Promise<Row[]> {\n if (this.consumedBy === 'iterator') {\n return Promise.reject(\n runtimeError(\n 'RUNTIME.ITERATOR_CONSUMED',\n 'AsyncIterableResult iterator has already been consumed via for-await loop. Each AsyncIterableResult can only be iterated once.',\n {\n consumedBy: this.consumedBy,\n suggestion:\n 'The iterator was already consumed by a for-await loop. Use toArray() or await the result before iterating.',\n },\n ),\n );\n }\n\n if (this.bufferedArrayPromise) {\n return this.bufferedArrayPromise;\n }\n\n this.consumed = true;\n this.consumedBy = 'bufferedArray';\n this.bufferedArrayPromise = (async () => {\n const out: Row[] = [];\n for await (const item of this.generator) {\n out.push(item);\n }\n return out;\n })();\n return this.bufferedArrayPromise;\n }\n\n async first(): Promise<Row | null> {\n const rows = await this.toArray();\n return rows[0] ?? null;\n }\n\n async firstOrThrow(): Promise<Row> {\n const row = await this.first();\n if (row === null)\n throw runtimeError(\n 'RUNTIME.NO_ROWS',\n 'Expected at least one row, but none were returned',\n {},\n );\n return row;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: PromiseLike implementation is intentional for await support.\n then<TResult1 = Row[], TResult2 = never>(\n onfulfilled?: ((value: Row[]) => TResult1 | PromiseLike<TResult1>) | undefined | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null,\n ): PromiseLike<TResult1 | TResult2> {\n return this.toArray().then(onfulfilled, onrejected);\n }\n}\n","import { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan } from './query-plan';\nimport type { RuntimeMiddleware, RuntimeMiddlewareContext } from './runtime-middleware';\n\n/**\n * Drives a single execution of `runDriver()` through the middleware lifecycle.\n *\n * Lifecycle, in order:\n * 1. For each middleware in registration order: `beforeExecute(exec, ctx)`.\n * 2. For each row yielded by `runDriver()`: for each middleware in registration\n * order: `onRow(row, exec, ctx)`; then yield the row to the consumer.\n * 3. On successful completion: for each middleware in registration order:\n * `afterExecute(exec, { rowCount, latencyMs, completed: true }, ctx)`.\n * 4. On any error thrown by the driver loop: for each middleware in\n * registration order: `afterExecute(exec, { rowCount, latencyMs,\n * completed: false }, ctx)`. Errors thrown by `afterExecute` during the\n * error path are swallowed so they do not mask the original driver error.\n * The original error is then rethrown.\n *\n * This helper is the single canonical implementation of the middleware\n * orchestration loop; family runtimes should not reimplement it.\n */\nexport function runWithMiddleware<TExec extends ExecutionPlan, Row>(\n exec: TExec,\n middleware: ReadonlyArray<RuntimeMiddleware<TExec>>,\n ctx: RuntimeMiddlewareContext,\n runDriver: () => AsyncIterable<Row>,\n): AsyncIterableResult<Row> {\n const iterator = async function* (): AsyncGenerator<Row, void, unknown> {\n const startedAt = Date.now();\n let rowCount = 0;\n let completed = false;\n\n try {\n for (const mw of middleware) {\n if (mw.beforeExecute) {\n await mw.beforeExecute(exec, ctx);\n }\n }\n\n for await (const row of runDriver()) {\n for (const mw of middleware) {\n if (mw.onRow) {\n await mw.onRow(row as Record<string, unknown>, exec, ctx);\n }\n }\n rowCount++;\n yield row;\n }\n\n completed = true;\n } catch (error) {\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n try {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed }, ctx);\n } catch {\n // Swallow afterExecute errors during the error path so they do not\n // mask the original driver error.\n }\n }\n }\n\n throw error;\n }\n\n const latencyMs = Date.now() - startedAt;\n for (const mw of middleware) {\n if (mw.afterExecute) {\n await mw.afterExecute(exec, { rowCount, latencyMs, completed }, ctx);\n }\n }\n };\n\n return new AsyncIterableResult(iterator());\n}\n","import { AsyncIterableResult } from './async-iterable-result';\nimport type { ExecutionPlan, QueryPlan } from './query-plan';\nimport { runWithMiddleware } from './run-with-middleware';\nimport type {\n RuntimeExecutor,\n RuntimeMiddleware,\n RuntimeMiddlewareContext,\n} from './runtime-middleware';\n\n/**\n * Constructor options shared by every concrete `RuntimeCore` subclass.\n *\n * Family runtimes typically build the middleware list and the\n * `RuntimeMiddlewareContext` themselves (running compatibility checks,\n * narrowing the context's `contract` field, etc.) before calling `super`.\n */\nexport interface RuntimeCoreOptions<TMiddleware extends RuntimeMiddleware<ExecutionPlan>> {\n readonly middleware: ReadonlyArray<TMiddleware>;\n readonly ctx: RuntimeMiddlewareContext;\n}\n\n/**\n * Family-agnostic abstract runtime base.\n *\n * Defines the entire `execute(plan)` template in one place:\n *\n * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides\n * this to run its `beforeCompile` middleware-hook chain.\n * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`\n * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).\n * 3. `runWithMiddleware(exec, this.middleware, this.ctx,\n * () => runDriver(exec))` — concrete; lifts the middleware lifecycle\n * out of the family runtimes into the canonical helper.\n *\n * Concrete subclasses must implement `lower`, `runDriver`, and `close`.\n *\n * The class is generic over:\n * - `TPlan` — the family's pre-lowering plan type.\n * - `TExec` — the family's post-lowering (executable) plan type.\n * - `TMiddleware` — the family's middleware type. Constrained to\n * `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the\n * `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered\n * `TExec`. (The spec/plan wording \"RuntimeMiddleware<TPlan>\" is\n * tightened to `<TExec>` here so the helper call typechecks; the\n * intent is unchanged — middleware sees the post-lowering plan.)\n */\nexport abstract class RuntimeCore<\n TPlan extends QueryPlan,\n TExec extends ExecutionPlan,\n TMiddleware extends RuntimeMiddleware<TExec>,\n> implements RuntimeExecutor<TPlan>\n{\n protected readonly middleware: ReadonlyArray<TMiddleware>;\n protected readonly ctx: RuntimeMiddlewareContext;\n\n constructor(options: RuntimeCoreOptions<TMiddleware>) {\n this.middleware = options.middleware;\n this.ctx = options.ctx;\n }\n\n /**\n * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses\n * may override to run a `beforeCompile` middleware chain (SQL does this\n * to support typed AST rewrites — see `before-compile-chain.ts`).\n */\n protected runBeforeCompile(plan: TPlan): TPlan | Promise<TPlan> {\n return plan;\n }\n\n /**\n * Lower a pre-lowering `TPlan` into the family's executable `TExec`.\n * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo\n * produces `{ command, ... }`.\n */\n protected abstract lower(plan: TPlan): TExec | Promise<TExec>;\n\n /**\n * Drive the underlying transport for a lowered `TExec`. Yields raw rows\n * directly from the driver as `Record<string, unknown>`; codec decoding\n * (if any) is the subclass's responsibility, applied by wrapping\n * `execute()` rather than living inside this hook.\n *\n * The `Row` type parameter on `execute()` is satisfied by the caller via\n * the plan's phantom `_row`; the runtime treats rows as opaque records\n * here and trusts the caller's row typing.\n */\n protected abstract runDriver(exec: TExec): AsyncIterable<Record<string, unknown>>;\n\n abstract close(): Promise<void>;\n\n execute<Row>(plan: TPlan & { readonly _row?: Row }): AsyncIterableResult<Row> {\n const self = this;\n\n async function* generator(): AsyncGenerator<Row, void, unknown> {\n const compiled = await self.runBeforeCompile(plan);\n const exec = await self.lower(compiled);\n // The driver yields raw `Record<string, unknown>`; we cast to `Row` here.\n // The Row contract is enforced by the caller via `plan._row`.\n yield* runWithMiddleware<TExec, Row>(\n exec,\n self.middleware,\n self.ctx,\n () => self.runDriver(exec) as AsyncIterable<Row>,\n );\n }\n\n return new AsyncIterableResult(generator());\n }\n}\n","import type { AsyncIterableResult } from './async-iterable-result';\nimport type { QueryPlan } from './query-plan';\nimport { runtimeError } from './runtime-error';\n\nexport interface RuntimeLog {\n info(event: unknown): void;\n warn(event: unknown): void;\n error(event: unknown): void;\n debug?(event: unknown): void;\n}\n\nexport interface RuntimeMiddlewareContext {\n readonly contract: unknown;\n readonly mode: 'strict' | 'permissive';\n readonly now: () => number;\n readonly log: RuntimeLog;\n}\n\nexport interface AfterExecuteResult {\n readonly rowCount: number;\n readonly latencyMs: number;\n readonly completed: boolean;\n}\n\n/**\n * Family-agnostic middleware SPI parameterized over the plan marker.\n *\n * `TPlan` defaults to the framework `QueryPlan` marker so a generic\n * middleware (e.g. cross-family telemetry) can be authored without\n * naming a family. Family-specific middleware (`SqlMiddleware`,\n * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.\n */\nexport interface RuntimeMiddleware<TPlan extends QueryPlan = QueryPlan> {\n readonly name: string;\n readonly familyId?: string;\n readonly targetId?: string;\n beforeExecute?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;\n onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;\n afterExecute?(\n plan: TPlan,\n result: AfterExecuteResult,\n ctx: RuntimeMiddlewareContext,\n ): Promise<void>;\n}\n\n/**\n * Cross-family SPI for any runtime that can execute plans and be shut down.\n * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,\n * Mongo structurally (due to its phantom Row parameter using a unique symbol).\n *\n * The `_row` intersection on `execute` connects the `Row` type parameter to the\n * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.\n */\nexport interface RuntimeExecutor<TPlan extends QueryPlan> {\n execute<Row>(plan: TPlan & { readonly _row?: Row }): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nexport function checkMiddlewareCompatibility(\n middleware: RuntimeMiddleware,\n runtimeFamilyId: string,\n runtimeTargetId: string,\n): void {\n if (middleware.targetId !== undefined && middleware.familyId === undefined) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',\n `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,\n { middleware: middleware.name, targetId: middleware.targetId },\n );\n }\n\n if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',\n `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,\n { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },\n );\n }\n\n if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {\n throw runtimeError(\n 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',\n `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,\n { middleware: middleware.name, middlewareTargetId: middleware.targetId, runtimeTargetId },\n );\n }\n}\n"],"mappings":";;;;;;;AAaA,SAAgB,eAAe,OAA+C;AAC5E,QACE,iBAAiB,SACjB,UAAU,SACV,OAAQ,MAA6B,SAAS,YAC9C,cAAc,SACd,cAAc;;AAIlB,SAAgB,aACd,MACA,SACA,SACsB;CACtB,MAAM,QAAQ,IAAI,MAAM,QAAQ;AAChC,QAAO,eAAe,OAAO,QAAQ;EACnC,OAAO;EACP,cAAc;EACf,CAAC;AAEF,QAAO,OAAO,OAAO,OAAO;EAC1B;EACA,UAAU,gBAAgB,KAAK;EAC/B,UAAU;EACV;EACA;EACD,CAAC;;AAGJ,SAAS,gB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ACJ,mCACA,eAAe,WAAW,KAAK,wBAAwB,WAAW,SAAS,qBAC3E;EAAE,YAAY,WAAW;EAAM,UAAU,WAAW;EAAU,CAC/D;AAGH,KAAI,WAAW,aAAa,UAAa,WAAW,aAAa,gBAC/D,OAAM,aACJ,sCACA,eAAe,WAAW,KAAK,qBAAqB,WAAW,SAAS,8CAA8C,gBAAgB,IACtI;EAAE,YAAY,WAAW;EAAM,oBAAoB,WAAW;EAAU;EAAiB,CAC1F;AAGH,KAAI,WAAW,aAAa,UAAa,WAAW,aAAa,gBAC/D,OAAM,aACJ,sCACA,eAAe,WAAW,KAAK,qBAAqB,WAAW,SAAS,8CAA8C,gBAAgB,IACtI;EAAE,YAAY,WAAW;EAAM,oBAAoB,WAAW;EAAU;EAAiB,CAC1F"}
package/package.json CHANGED
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "@prisma-next/framework-components",
3
- "version": "0.5.0-dev.2",
3
+ "version": "0.5.0-dev.20",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "Framework component types, assembly logic, and stack creation for Prisma Next",
7
7
  "dependencies": {
8
- "@prisma-next/contract": "0.5.0-dev.2",
9
- "@prisma-next/operations": "0.5.0-dev.2",
10
- "@prisma-next/utils": "0.5.0-dev.2"
8
+ "@prisma-next/utils": "0.5.0-dev.20",
9
+ "@prisma-next/operations": "0.5.0-dev.20",
10
+ "@prisma-next/contract": "0.5.0-dev.20"
11
11
  },
12
12
  "devDependencies": {
13
13
  "tsdown": "0.18.4",
14
14
  "typescript": "5.9.3",
15
15
  "vitest": "4.0.17",
16
- "@prisma-next/tsdown": "0.0.0",
17
- "@prisma-next/tsconfig": "0.0.0"
16
+ "@prisma-next/tsconfig": "0.0.0",
17
+ "@prisma-next/tsdown": "0.0.0"
18
18
  },
19
19
  "files": [
20
20
  "dist",
@@ -3,21 +3,39 @@ import type { JsonValue } from '@prisma-next/contract/types';
3
3
  export type CodecTrait = 'equality' | 'order' | 'boolean' | 'numeric' | 'textual';
4
4
 
5
5
  /**
6
- * Base codec interface for all target families.
6
+ * A codec is the contract between an application value and its on-wire and
7
+ * on-contract-disk representations.
7
8
  *
8
- * A codec maps between three representations of a value:
9
- * - **JS** (`TJs`): the JavaScript type used in application code
10
- * - **Wire** (`TWire`): the format sent to/from the database driver
11
- * - **JSON** (`JsonValue`): the JSON-safe form stored in contract artifacts
9
+ * The author's mental model is two JS-side types — `TInput` (the
10
+ * application JS type) and `TWire` (the database driver wire format)
11
+ * plus `JsonValue` for build-time contract artifacts. The codec translates
12
+ * `TInput` to `TWire` on writes and back on reads, and to/from `JsonValue`
13
+ * during contract emission and loading.
12
14
  *
13
- * Family-specific codec interfaces (SQL `Codec`, Mongo `MongoCodec`) extend
14
- * this base to add family-specific metadata.
15
+ * Three representations participate:
16
+ * - **Input** (`TInput`): the JS type at the application boundary.
17
+ * - **Wire** (`TWire`): the format exchanged with the database driver.
18
+ * - **JSON** (`JsonValue`): a JSON-safe form used in contract artifacts.
19
+ *
20
+ * Codec methods split into two groups:
21
+ *
22
+ * - **Query-time** methods (`encode`, `decode`) run per row/parameter at the
23
+ * IO boundary; they are required and Promise-returning. The per-family
24
+ * codec factory accepts sync or async author functions and lifts sync
25
+ * ones to Promise-shaped methods automatically.
26
+ * - **Build-time** methods (`encodeJson`, `decodeJson`, `renderOutputType`)
27
+ * run when the contract is serialized, loaded, or when client types are
28
+ * emitted. They stay synchronous so contract validation and client
29
+ * construction are synchronous.
30
+ *
31
+ * Target-family codec interfaces extend this base with target-shaped
32
+ * metadata.
15
33
  */
16
34
  export interface Codec<
17
35
  Id extends string = string,
18
36
  TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
19
37
  TWire = unknown,
20
- TJs = unknown,
38
+ TInput = unknown,
21
39
  > {
22
40
  /** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). */
23
41
  readonly id: Id;
@@ -25,15 +43,15 @@ export interface Codec<
25
43
  readonly targetTypes: readonly string[];
26
44
  /** Semantic traits for operator gating (e.g. equality, order, numeric). */
27
45
  readonly traits?: TTraits;
28
- /** Converts a JS value to the wire format expected by the database driver. Optional when the driver accepts the JS type directly. */
29
- encode?(value: TJs): TWire;
30
- /** Converts a wire value from the database driver into the JS type. */
31
- decode(wire: TWire): TJs;
32
- /** Converts a JS value to a JSON-safe representation for contract serialization. Called during contract emission. */
33
- encodeJson(value: TJs): JsonValue;
34
- /** Converts a JSON representation back to the JS type. Called during contract loading via `validateContract`. */
35
- decodeJson(json: JsonValue): TJs;
36
- /** Produces the TypeScript output type expression for a field given its `typeParams`. Used during contract.d.ts emission. */
46
+ /** Converts a JS value to the wire format expected by the database driver. Always Promise-returning at the boundary. */
47
+ encode(value: TInput): Promise<TWire>;
48
+ /** Converts a wire value from the database driver into the JS application type. Always Promise-returning at the boundary. */
49
+ decode(wire: TWire): Promise<TInput>;
50
+ /** Converts a JS value to a JSON-safe representation for contract serialization. Synchronous; called during contract emission. */
51
+ encodeJson(value: TInput): JsonValue;
52
+ /** Converts a JSON representation back to the JS input type. Synchronous; called during contract loading via `validateContract`. */
53
+ decodeJson(json: JsonValue): TInput;
54
+ /** Produces the TypeScript output type expression for a field given its `typeParams`. Synchronous; used during contract.d.ts emission. */
37
55
  renderOutputType?(typeParams: Record<string, unknown>): string | undefined;
38
56
  }
39
57
 
@@ -48,20 +48,21 @@ export interface SerializedQueryPlan {
48
48
  * serialized to JSON ASTs at verification time, and rendered to SQL
49
49
  * by the target adapter at apply time.
50
50
  *
51
- * The `name` serves as the invariant identity — it's recorded in the
52
- * ledger and used for invariant-aware routing via environment refs.
53
- *
54
51
  * In draft state (before verification), `check` and `run` are null.
55
52
  * After verification, they contain the serialized query ASTs.
56
53
  */
57
54
  export interface DataTransformOperation extends MigrationPlanOperation {
58
55
  readonly operationClass: 'data';
59
56
  /**
60
- * The invariant name for this data transform.
61
- * Recorded in the ledger on successful edge completion.
62
- * Used by environment refs to declare required invariants.
57
+ * Human-readable label for this data transform.
63
58
  */
64
59
  readonly name: string;
60
+ /**
61
+ * Optional opt-in routing identity. Presence opts the transform into
62
+ * invariant-aware routing; absence means it is path-dependent and
63
+ * not referenceable from refs.
64
+ */
65
+ readonly invariantId?: string;
65
66
  /**
66
67
  * Path to the TypeScript source file that produced this operation.
67
68
  * Not part of edgeId computation — for traceability only.
@@ -335,6 +336,16 @@ export interface MigrationRunner<
335
336
  TFamilyId extends string = string,
336
337
  TTargetId extends string = string,
337
338
  > {
339
+ /**
340
+ * Execute a migration plan against the configured driver.
341
+ *
342
+ * The `plan` parameter is trusted input. Callers are responsible for
343
+ * upstream verification of the originating migration package — typically
344
+ * by obtaining the package via `readMigrationPackage` from
345
+ * `@prisma-next/migration-tools/io`, which performs hash-integrity checks
346
+ * at the load boundary. Runners do not re-verify the plan and assume the
347
+ * `(metadata, ops)` pair on disk has not been tampered with since emit.
348
+ */
338
349
  execute(options: {
339
350
  readonly plan: MigrationPlan;
340
351
  readonly driver: ControlDriverInstance<TFamilyId, TTargetId>;
@@ -1,6 +1,10 @@
1
1
  export { AsyncIterableResult } from '../async-iterable-result';
2
+ export type { ExecutionPlan, QueryPlan, ResultType } from '../query-plan';
3
+ export { runWithMiddleware } from '../run-with-middleware';
4
+ export type { RuntimeCoreOptions } from '../runtime-core';
5
+ export { RuntimeCore } from '../runtime-core';
2
6
  export type { RuntimeErrorEnvelope } from '../runtime-error';
3
- export { runtimeError } from '../runtime-error';
7
+ export { isRuntimeError, runtimeError } from '../runtime-error';
4
8
  export type {
5
9
  AfterExecuteResult,
6
10
  RuntimeExecutor,
@@ -0,0 +1,53 @@
1
+ import type { PlanMeta } from '@prisma-next/contract/types';
2
+
3
+ /**
4
+ * Family-agnostic plan marker.
5
+ *
6
+ * Carries only `meta` (the family-agnostic plan metadata) and the optional
7
+ * phantom `_row` parameter that lets type-level utilities recover the row
8
+ * type from a plan value. SQL and Mongo extend this marker with their own
9
+ * concrete shapes (`SqlQueryPlan`, `MongoQueryPlan`).
10
+ *
11
+ * `QueryPlan` is the *pre-lowering* marker — i.e. the surface a builder
12
+ * produces before family-specific lowering turns it into an executable
13
+ * plan (`ExecutionPlan`).
14
+ */
15
+ export interface QueryPlan<Row = unknown> {
16
+ readonly meta: PlanMeta;
17
+ /**
18
+ * Phantom property to carry the Row generic for type-level utilities.
19
+ * Not set at runtime; used only for `ResultType` extraction.
20
+ */
21
+ readonly _row?: Row;
22
+ }
23
+
24
+ /**
25
+ * Family-agnostic execution-plan marker.
26
+ *
27
+ * Extends `QueryPlan` with no additional structural fields — the marker
28
+ * exists to nominally distinguish executable plans from pre-lowering plans
29
+ * in the type system. Family-specific execution plans (`SqlExecutionPlan`,
30
+ * `MongoExecutionPlan`) extend this marker with their concrete shapes
31
+ * (e.g. `sql + params` for SQL, `wireCommand` for Mongo).
32
+ */
33
+ export interface ExecutionPlan<Row = unknown> extends QueryPlan<Row> {}
34
+
35
+ /**
36
+ * Extracts the `Row` type from a plan via the phantom `_row` property.
37
+ *
38
+ * Works with any plan that extends `QueryPlan<Row>` — including
39
+ * `ExecutionPlan<Row>`, `SqlQueryPlan<Row>`, `SqlExecutionPlan<Row>`,
40
+ * `MongoQueryPlan<Row>`, and `MongoExecutionPlan<Row>`.
41
+ *
42
+ * The `_row` property must be present in the plan's static type for the
43
+ * conditional to bind `R`; objects whose type lacks `_row` resolve to
44
+ * `never`. Without the `keyof` guard, `extends { _row?: infer R }` would
45
+ * silently match any object and infer `unknown`.
46
+ *
47
+ * Example: `type Row = ResultType<typeof plan>`.
48
+ */
49
+ export type ResultType<P> = '_row' extends keyof P
50
+ ? P extends { readonly _row?: infer R }
51
+ ? R
52
+ : never
53
+ : never;
@@ -0,0 +1,77 @@
1
+ import { AsyncIterableResult } from './async-iterable-result';
2
+ import type { ExecutionPlan } from './query-plan';
3
+ import type { RuntimeMiddleware, RuntimeMiddlewareContext } from './runtime-middleware';
4
+
5
+ /**
6
+ * Drives a single execution of `runDriver()` through the middleware lifecycle.
7
+ *
8
+ * Lifecycle, in order:
9
+ * 1. For each middleware in registration order: `beforeExecute(exec, ctx)`.
10
+ * 2. For each row yielded by `runDriver()`: for each middleware in registration
11
+ * order: `onRow(row, exec, ctx)`; then yield the row to the consumer.
12
+ * 3. On successful completion: for each middleware in registration order:
13
+ * `afterExecute(exec, { rowCount, latencyMs, completed: true }, ctx)`.
14
+ * 4. On any error thrown by the driver loop: for each middleware in
15
+ * registration order: `afterExecute(exec, { rowCount, latencyMs,
16
+ * completed: false }, ctx)`. Errors thrown by `afterExecute` during the
17
+ * error path are swallowed so they do not mask the original driver error.
18
+ * The original error is then rethrown.
19
+ *
20
+ * This helper is the single canonical implementation of the middleware
21
+ * orchestration loop; family runtimes should not reimplement it.
22
+ */
23
+ export function runWithMiddleware<TExec extends ExecutionPlan, Row>(
24
+ exec: TExec,
25
+ middleware: ReadonlyArray<RuntimeMiddleware<TExec>>,
26
+ ctx: RuntimeMiddlewareContext,
27
+ runDriver: () => AsyncIterable<Row>,
28
+ ): AsyncIterableResult<Row> {
29
+ const iterator = async function* (): AsyncGenerator<Row, void, unknown> {
30
+ const startedAt = Date.now();
31
+ let rowCount = 0;
32
+ let completed = false;
33
+
34
+ try {
35
+ for (const mw of middleware) {
36
+ if (mw.beforeExecute) {
37
+ await mw.beforeExecute(exec, ctx);
38
+ }
39
+ }
40
+
41
+ for await (const row of runDriver()) {
42
+ for (const mw of middleware) {
43
+ if (mw.onRow) {
44
+ await mw.onRow(row as Record<string, unknown>, exec, ctx);
45
+ }
46
+ }
47
+ rowCount++;
48
+ yield row;
49
+ }
50
+
51
+ completed = true;
52
+ } catch (error) {
53
+ const latencyMs = Date.now() - startedAt;
54
+ for (const mw of middleware) {
55
+ if (mw.afterExecute) {
56
+ try {
57
+ await mw.afterExecute(exec, { rowCount, latencyMs, completed }, ctx);
58
+ } catch {
59
+ // Swallow afterExecute errors during the error path so they do not
60
+ // mask the original driver error.
61
+ }
62
+ }
63
+ }
64
+
65
+ throw error;
66
+ }
67
+
68
+ const latencyMs = Date.now() - startedAt;
69
+ for (const mw of middleware) {
70
+ if (mw.afterExecute) {
71
+ await mw.afterExecute(exec, { rowCount, latencyMs, completed }, ctx);
72
+ }
73
+ }
74
+ };
75
+
76
+ return new AsyncIterableResult(iterator());
77
+ }
@@ -0,0 +1,109 @@
1
+ import { AsyncIterableResult } from './async-iterable-result';
2
+ import type { ExecutionPlan, QueryPlan } from './query-plan';
3
+ import { runWithMiddleware } from './run-with-middleware';
4
+ import type {
5
+ RuntimeExecutor,
6
+ RuntimeMiddleware,
7
+ RuntimeMiddlewareContext,
8
+ } from './runtime-middleware';
9
+
10
+ /**
11
+ * Constructor options shared by every concrete `RuntimeCore` subclass.
12
+ *
13
+ * Family runtimes typically build the middleware list and the
14
+ * `RuntimeMiddlewareContext` themselves (running compatibility checks,
15
+ * narrowing the context's `contract` field, etc.) before calling `super`.
16
+ */
17
+ export interface RuntimeCoreOptions<TMiddleware extends RuntimeMiddleware<ExecutionPlan>> {
18
+ readonly middleware: ReadonlyArray<TMiddleware>;
19
+ readonly ctx: RuntimeMiddlewareContext;
20
+ }
21
+
22
+ /**
23
+ * Family-agnostic abstract runtime base.
24
+ *
25
+ * Defines the entire `execute(plan)` template in one place:
26
+ *
27
+ * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides
28
+ * this to run its `beforeCompile` middleware-hook chain.
29
+ * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`
30
+ * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).
31
+ * 3. `runWithMiddleware(exec, this.middleware, this.ctx,
32
+ * () => runDriver(exec))` — concrete; lifts the middleware lifecycle
33
+ * out of the family runtimes into the canonical helper.
34
+ *
35
+ * Concrete subclasses must implement `lower`, `runDriver`, and `close`.
36
+ *
37
+ * The class is generic over:
38
+ * - `TPlan` — the family's pre-lowering plan type.
39
+ * - `TExec` — the family's post-lowering (executable) plan type.
40
+ * - `TMiddleware` — the family's middleware type. Constrained to
41
+ * `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the
42
+ * `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered
43
+ * `TExec`. (The spec/plan wording "RuntimeMiddleware<TPlan>" is
44
+ * tightened to `<TExec>` here so the helper call typechecks; the
45
+ * intent is unchanged — middleware sees the post-lowering plan.)
46
+ */
47
+ export abstract class RuntimeCore<
48
+ TPlan extends QueryPlan,
49
+ TExec extends ExecutionPlan,
50
+ TMiddleware extends RuntimeMiddleware<TExec>,
51
+ > implements RuntimeExecutor<TPlan>
52
+ {
53
+ protected readonly middleware: ReadonlyArray<TMiddleware>;
54
+ protected readonly ctx: RuntimeMiddlewareContext;
55
+
56
+ constructor(options: RuntimeCoreOptions<TMiddleware>) {
57
+ this.middleware = options.middleware;
58
+ this.ctx = options.ctx;
59
+ }
60
+
61
+ /**
62
+ * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses
63
+ * may override to run a `beforeCompile` middleware chain (SQL does this
64
+ * to support typed AST rewrites — see `before-compile-chain.ts`).
65
+ */
66
+ protected runBeforeCompile(plan: TPlan): TPlan | Promise<TPlan> {
67
+ return plan;
68
+ }
69
+
70
+ /**
71
+ * Lower a pre-lowering `TPlan` into the family's executable `TExec`.
72
+ * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo
73
+ * produces `{ command, ... }`.
74
+ */
75
+ protected abstract lower(plan: TPlan): TExec | Promise<TExec>;
76
+
77
+ /**
78
+ * Drive the underlying transport for a lowered `TExec`. Yields raw rows
79
+ * directly from the driver as `Record<string, unknown>`; codec decoding
80
+ * (if any) is the subclass's responsibility, applied by wrapping
81
+ * `execute()` rather than living inside this hook.
82
+ *
83
+ * The `Row` type parameter on `execute()` is satisfied by the caller via
84
+ * the plan's phantom `_row`; the runtime treats rows as opaque records
85
+ * here and trusts the caller's row typing.
86
+ */
87
+ protected abstract runDriver(exec: TExec): AsyncIterable<Record<string, unknown>>;
88
+
89
+ abstract close(): Promise<void>;
90
+
91
+ execute<Row>(plan: TPlan & { readonly _row?: Row }): AsyncIterableResult<Row> {
92
+ const self = this;
93
+
94
+ async function* generator(): AsyncGenerator<Row, void, unknown> {
95
+ const compiled = await self.runBeforeCompile(plan);
96
+ const exec = await self.lower(compiled);
97
+ // The driver yields raw `Record<string, unknown>`; we cast to `Row` here.
98
+ // The Row contract is enforced by the caller via `plan._row`.
99
+ yield* runWithMiddleware<TExec, Row>(
100
+ exec,
101
+ self.middleware,
102
+ self.ctx,
103
+ () => self.runDriver(exec) as AsyncIterable<Row>,
104
+ );
105
+ }
106
+
107
+ return new AsyncIterableResult(generator());
108
+ }
109
+ }
@@ -5,6 +5,22 @@ export interface RuntimeErrorEnvelope extends Error {
5
5
  readonly details?: Record<string, unknown>;
6
6
  }
7
7
 
8
+ /**
9
+ * Type guard for the runtime-error envelope produced by `runtimeError`.
10
+ *
11
+ * Prefer this over duck-typing on `error.code` directly so consumers stay
12
+ * insulated from the envelope's internal shape.
13
+ */
14
+ export function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {
15
+ return (
16
+ error instanceof Error &&
17
+ 'code' in error &&
18
+ typeof (error as { code?: unknown }).code === 'string' &&
19
+ 'category' in error &&
20
+ 'severity' in error
21
+ );
22
+ }
23
+
8
24
  export function runtimeError(
9
25
  code: string,
10
26
  message: string,