@prisma-next/framework-components 0.5.0-dev.7 → 0.5.0-dev.70

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 (94) hide show
  1. package/README.md +63 -3
  2. package/dist/authoring.d.mts +2 -2
  3. package/dist/authoring.mjs +2 -122
  4. package/dist/codec-m_-FAyQn.d.mts +168 -0
  5. package/dist/codec-m_-FAyQn.d.mts.map +1 -0
  6. package/dist/codec.d.mts +48 -2
  7. package/dist/codec.d.mts.map +1 -0
  8. package/dist/codec.mjs +67 -4
  9. package/dist/codec.mjs.map +1 -1
  10. package/dist/components.d.mts +1 -1
  11. package/dist/components.mjs +2 -3
  12. package/dist/control.d.mts +370 -72
  13. package/dist/control.d.mts.map +1 -1
  14. package/dist/control.mjs +82 -49
  15. package/dist/control.mjs.map +1 -1
  16. package/dist/emission-types-BKa4bR9m.d.mts +39 -0
  17. package/dist/emission-types-BKa4bR9m.d.mts.map +1 -0
  18. package/dist/emission.d.mts +2 -2
  19. package/dist/emission.mjs +1 -1
  20. package/dist/execution.d.mts +5 -5
  21. package/dist/execution.d.mts.map +1 -1
  22. package/dist/execution.mjs +4 -6
  23. package/dist/execution.mjs.map +1 -1
  24. package/dist/framework-authoring-BwWNqTlD.mjs +205 -0
  25. package/dist/framework-authoring-BwWNqTlD.mjs.map +1 -0
  26. package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-Cm5f9U64.d.mts} +41 -12
  27. package/dist/framework-authoring-Cm5f9U64.d.mts.map +1 -0
  28. package/dist/{framework-components-EJXe-pum.d.mts → framework-components-DgIEy9eJ.d.mts} +45 -55
  29. package/dist/framework-components-DgIEy9eJ.d.mts.map +1 -0
  30. package/dist/{framework-components-C8ZhSwXe.mjs → framework-components-FdqmlGUj.mjs} +3 -3
  31. package/dist/framework-components-FdqmlGUj.mjs.map +1 -0
  32. package/dist/psl-ast-Ckn_G-jv.d.mts +159 -0
  33. package/dist/psl-ast-Ckn_G-jv.d.mts.map +1 -0
  34. package/dist/psl-ast.d.mts +2 -0
  35. package/dist/psl-ast.mjs +1 -0
  36. package/dist/runtime.d.mts +346 -19
  37. package/dist/runtime.d.mts.map +1 -1
  38. package/dist/runtime.mjs +254 -7
  39. package/dist/runtime.mjs.map +1 -1
  40. package/dist/{types-import-spec-C4sc7wbb.d.mts → types-import-spec-BxI5cSQy.d.mts} +2 -2
  41. package/dist/types-import-spec-BxI5cSQy.d.mts.map +1 -0
  42. package/package.json +11 -8
  43. package/src/control/control-capabilities.ts +95 -0
  44. package/src/{control-descriptors.ts → control/control-descriptors.ts} +7 -7
  45. package/src/{control-instances.ts → control/control-instances.ts} +52 -6
  46. package/src/{control-migration-types.ts → control/control-migration-types.ts} +202 -61
  47. package/src/control/control-operation-preview.ts +23 -0
  48. package/src/control/control-spaces.ts +82 -0
  49. package/src/{control-stack.ts → control/control-stack.ts} +77 -94
  50. package/src/control/emission-types.ts +49 -0
  51. package/src/control/psl-ast.ts +193 -0
  52. package/src/{execution-descriptors.ts → execution/execution-descriptors.ts} +7 -7
  53. package/src/{execution-instances.ts → execution/execution-instances.ts} +1 -1
  54. package/src/{execution-requirements.ts → execution/execution-requirements.ts} +1 -1
  55. package/src/execution/query-plan.ts +53 -0
  56. package/src/execution/race-against-abort.ts +85 -0
  57. package/src/execution/run-with-middleware.ts +132 -0
  58. package/src/execution/runtime-core.ts +133 -0
  59. package/src/execution/runtime-error.ts +83 -0
  60. package/src/execution/runtime-middleware.ts +182 -0
  61. package/src/exports/authoring.ts +5 -2
  62. package/src/exports/codec.ts +27 -2
  63. package/src/exports/components.ts +2 -2
  64. package/src/exports/control.ts +40 -13
  65. package/src/exports/emission.ts +2 -2
  66. package/src/exports/execution.ts +5 -5
  67. package/src/exports/psl-ast.ts +1 -0
  68. package/src/exports/runtime.ts +17 -5
  69. package/src/shared/codec-descriptor.ts +87 -0
  70. package/src/shared/codec-types.ts +79 -0
  71. package/src/shared/codec.ts +80 -0
  72. package/src/shared/column-spec.ts +83 -0
  73. package/src/{framework-authoring.ts → shared/framework-authoring.ts} +202 -23
  74. package/src/{framework-components.ts → shared/framework-components.ts} +22 -48
  75. package/src/{mutation-default-types.ts → shared/mutation-default-types.ts} +22 -2
  76. package/dist/authoring.mjs.map +0 -1
  77. package/dist/codec-types-B58nCJiu.d.mts +0 -40
  78. package/dist/codec-types-B58nCJiu.d.mts.map +0 -1
  79. package/dist/emission-types-BPAALJbF.d.mts +0 -24
  80. package/dist/emission-types-BPAALJbF.d.mts.map +0 -1
  81. package/dist/framework-authoring-D1-JZ37B.d.mts.map +0 -1
  82. package/dist/framework-components-C8ZhSwXe.mjs.map +0 -1
  83. package/dist/framework-components-EJXe-pum.d.mts.map +0 -1
  84. package/dist/types-import-spec-C4sc7wbb.d.mts.map +0 -1
  85. package/src/codec-types.ts +0 -46
  86. package/src/control-capabilities.ts +0 -34
  87. package/src/emission-types.ts +0 -28
  88. package/src/runtime-error.ts +0 -39
  89. package/src/runtime-middleware.ts +0 -83
  90. /package/src/{control-result-types.ts → control/control-result-types.ts} +0 -0
  91. /package/src/{control-schema-view.ts → control/control-schema-view.ts} +0 -0
  92. /package/src/{async-iterable-result.ts → execution/async-iterable-result.ts} +0 -0
  93. /package/src/{execution-stack.ts → execution/execution-stack.ts} +0 -0
  94. /package/src/{types-import-spec.ts → shared/types-import-spec.ts} +0 -0
@@ -0,0 +1,132 @@
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: `intercept(exec, ctx)`. The
10
+ * first non-`undefined` result wins; subsequent middleware's `intercept`
11
+ * does not fire. On a hit, the runtime emits a `middleware.intercept`
12
+ * debug event naming the winning middleware, switches the row source to
13
+ * the intercepted rows, and proceeds with `source: 'middleware'`. On
14
+ * all-passthrough (every `intercept` returns `undefined` or is omitted),
15
+ * `source: 'driver'` is used and the row source is `runDriver()`.
16
+ * 2. If `source === 'driver'`: for each middleware in registration order,
17
+ * `beforeExecute(exec, ctx)`. Skipped on the intercepted hit path —
18
+ * `beforeExecute` semantically means "about to hit the driver".
19
+ * 3. Iterate the row source. On the driver path, for each row, for each
20
+ * middleware in registration order: `onRow(row, exec, ctx)`; then yield
21
+ * the row. On the intercepted hit path, `onRow` is skipped — intercepted
22
+ * rows did not originate from a driver row stream — but rows are still
23
+ * yielded to the consumer in order.
24
+ * 4. On successful completion: for each middleware in registration order:
25
+ * `afterExecute(exec, { rowCount, latencyMs, completed: true, source },
26
+ * ctx)`.
27
+ * 5. On any error thrown during steps 1–3: for each middleware in
28
+ * registration order: `afterExecute(exec, { rowCount, latencyMs,
29
+ * completed: false, source }, ctx)`. Errors thrown by `afterExecute`
30
+ * during the error path are swallowed so they do not mask the original
31
+ * error. The original error is then rethrown.
32
+ *
33
+ * The `source` field on `AfterExecuteResult` lets observers (telemetry,
34
+ * lints, budgets) distinguish driver-served from middleware-served
35
+ * executions without needing their own out-of-band signal.
36
+ *
37
+ * This helper is the single canonical implementation of the middleware
38
+ * orchestration loop; family runtimes should not reimplement it.
39
+ */
40
+ export function runWithMiddleware<TExec extends ExecutionPlan, Row>(
41
+ exec: TExec,
42
+ middleware: ReadonlyArray<RuntimeMiddleware<TExec>>,
43
+ ctx: RuntimeMiddlewareContext,
44
+ runDriver: () => AsyncIterable<Row>,
45
+ ): AsyncIterableResult<Row> {
46
+ const iterator = async function* (): AsyncGenerator<Row, void, unknown> {
47
+ const startedAt = Date.now();
48
+ let rowCount = 0;
49
+ let completed = false;
50
+ let source: 'driver' | 'middleware' = 'driver';
51
+ // Deferred so a winning interceptor can skip `runDriver()` entirely.
52
+ // For factories that lazily produce async generators this is a no-op,
53
+ // but factories that do eager work (e.g. acquiring a connection,
54
+ // sending a query) must not run on the intercepted hit path.
55
+ let rowSource: AsyncIterable<Row> | Iterable<Row> | undefined;
56
+
57
+ try {
58
+ for (const mw of middleware) {
59
+ if (!mw.intercept) {
60
+ continue;
61
+ }
62
+ // Mark the lifecycle as middleware-driven *before* awaiting the
63
+ // hook. If `intercept` throws, the catch block reports the failure
64
+ // as `source: 'middleware'` — the failure originated in the
65
+ // intercept chain, not in the driver. If `intercept` returns
66
+ // `undefined` (passthrough), we revert to `'driver'` and continue.
67
+ source = 'middleware';
68
+ const result = await mw.intercept(exec, ctx);
69
+ if (result === undefined) {
70
+ source = 'driver';
71
+ continue;
72
+ }
73
+ ctx.log.debug?.({ event: 'middleware.intercept', middleware: mw.name });
74
+ // The intercepted rows are typed as `Record<string, unknown>` at
75
+ // the SPI level; the consumer's `Row` type parameter is enforced by
76
+ // the caller (via the plan's phantom `_row`) the same way driver
77
+ // rows are. Cast through unknown to bridge the SPI shape to the
78
+ // caller-supplied Row.
79
+ rowSource = result.rows as unknown as AsyncIterable<Row> | Iterable<Row>;
80
+ break;
81
+ }
82
+
83
+ if (source === 'driver') {
84
+ for (const mw of middleware) {
85
+ if (mw.beforeExecute) {
86
+ await mw.beforeExecute(exec, ctx);
87
+ }
88
+ }
89
+ rowSource = runDriver();
90
+ }
91
+
92
+ // `rowSource` is always assigned by this point: either the intercepted
93
+ // rows (on a hit) or `runDriver()` (on the driver path).
94
+ for await (const row of rowSource as AsyncIterable<Row> | Iterable<Row>) {
95
+ if (source === 'driver') {
96
+ for (const mw of middleware) {
97
+ if (mw.onRow) {
98
+ await mw.onRow(row as Record<string, unknown>, exec, ctx);
99
+ }
100
+ }
101
+ }
102
+ rowCount++;
103
+ yield row;
104
+ }
105
+
106
+ completed = true;
107
+ } catch (error) {
108
+ const latencyMs = Date.now() - startedAt;
109
+ for (const mw of middleware) {
110
+ if (mw.afterExecute) {
111
+ try {
112
+ await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);
113
+ } catch {
114
+ // Swallow afterExecute errors during the error path so they do not
115
+ // mask the original error.
116
+ }
117
+ }
118
+ }
119
+
120
+ throw error;
121
+ }
122
+
123
+ const latencyMs = Date.now() - startedAt;
124
+ for (const mw of middleware) {
125
+ if (mw.afterExecute) {
126
+ await mw.afterExecute(exec, { rowCount, latencyMs, completed, source }, ctx);
127
+ }
128
+ }
129
+ };
130
+
131
+ return new AsyncIterableResult(iterator());
132
+ }
@@ -0,0 +1,133 @@
1
+ import type { CodecCallContext } from '../shared/codec-types';
2
+ import { AsyncIterableResult } from './async-iterable-result';
3
+ import type { ExecutionPlan, QueryPlan } from './query-plan';
4
+ import { checkAborted } from './race-against-abort';
5
+ import { runWithMiddleware } from './run-with-middleware';
6
+ import type {
7
+ RuntimeExecuteOptions,
8
+ RuntimeExecutor,
9
+ RuntimeMiddleware,
10
+ RuntimeMiddlewareContext,
11
+ } from './runtime-middleware';
12
+
13
+ /**
14
+ * Constructor options shared by every concrete `RuntimeCore` subclass.
15
+ *
16
+ * Family runtimes typically build the middleware list and the
17
+ * `RuntimeMiddlewareContext` themselves (running compatibility checks,
18
+ * narrowing the context's `contract` field, etc.) before calling `super`.
19
+ */
20
+ export interface RuntimeCoreOptions<TMiddleware extends RuntimeMiddleware<ExecutionPlan>> {
21
+ readonly middleware: ReadonlyArray<TMiddleware>;
22
+ readonly ctx: RuntimeMiddlewareContext;
23
+ }
24
+
25
+ /**
26
+ * Family-agnostic abstract runtime base.
27
+ *
28
+ * Defines the entire `execute(plan)` template in one place:
29
+ *
30
+ * 1. `runBeforeCompile(plan)` — concrete; defaults to identity. SQL overrides
31
+ * this to run its `beforeCompile` middleware-hook chain.
32
+ * 2. `lower(plan)` — abstract. Each family produces its `*ExecutionPlan`
33
+ * (SQL via `lowerSqlPlan`, Mongo via `adapter.lower`).
34
+ * 3. `runWithMiddleware(exec, this.middleware, this.ctx,
35
+ * () => runDriver(exec))` — concrete; lifts the middleware lifecycle
36
+ * out of the family runtimes into the canonical helper.
37
+ *
38
+ * Concrete subclasses must implement `lower`, `runDriver`, and `close`.
39
+ *
40
+ * The class is generic over:
41
+ * - `TPlan` — the family's pre-lowering plan type.
42
+ * - `TExec` — the family's post-lowering (executable) plan type.
43
+ * - `TMiddleware` — the family's middleware type. Constrained to
44
+ * `RuntimeMiddleware<TExec>` because `runWithMiddleware` invokes the
45
+ * `beforeExecute` / `onRow` / `afterExecute` hooks with the lowered
46
+ * `TExec`. (The spec/plan wording "RuntimeMiddleware<TPlan>" is
47
+ * tightened to `<TExec>` here so the helper call typechecks; the
48
+ * intent is unchanged — middleware sees the post-lowering plan.)
49
+ */
50
+ export abstract class RuntimeCore<
51
+ TPlan extends QueryPlan,
52
+ TExec extends ExecutionPlan,
53
+ TMiddleware extends RuntimeMiddleware<TExec>,
54
+ > implements RuntimeExecutor<TPlan>
55
+ {
56
+ protected readonly middleware: ReadonlyArray<TMiddleware>;
57
+ protected readonly ctx: RuntimeMiddlewareContext;
58
+
59
+ constructor(options: RuntimeCoreOptions<TMiddleware>) {
60
+ this.middleware = options.middleware;
61
+ this.ctx = options.ctx;
62
+ }
63
+
64
+ /**
65
+ * Pre-lowering hook for plan rewriting. Defaults to identity. Subclasses
66
+ * may override to run a `beforeCompile` middleware chain (SQL does this
67
+ * to support typed AST rewrites — see `before-compile-chain.ts`).
68
+ */
69
+ protected runBeforeCompile(plan: TPlan): TPlan | Promise<TPlan> {
70
+ return plan;
71
+ }
72
+
73
+ /**
74
+ * Lower a pre-lowering `TPlan` into the family's executable `TExec`.
75
+ * Family-specific: SQL produces `{ sql, params, ast?, ... }`; Mongo
76
+ * produces `{ command, ... }`.
77
+ *
78
+ * `ctx` carries per-query cancellation (and any future fields on
79
+ * `CodecCallContext`); concrete subclasses forward it to the
80
+ * encode-side codec dispatch site (e.g. SQL's `encodeParams` in m2,
81
+ * Mongo's `resolveValue` in m3). The runtime allocates one ctx per
82
+ * `execute()` call and threads the same reference everywhere; the
83
+ * `signal` field inside may be `undefined`, but the ctx object itself
84
+ * is always present.
85
+ */
86
+ protected abstract lower(plan: TPlan, ctx: CodecCallContext): TExec | Promise<TExec>;
87
+
88
+ /**
89
+ * Drive the underlying transport for a lowered `TExec`. Yields raw rows
90
+ * directly from the driver as `Record<string, unknown>`; codec decoding
91
+ * (if any) is the subclass's responsibility, applied by wrapping
92
+ * `execute()` rather than living inside this hook.
93
+ *
94
+ * The `Row` type parameter on `execute()` is satisfied by the caller via
95
+ * the plan's phantom `_row`; the runtime treats rows as opaque records
96
+ * here and trusts the caller's row typing.
97
+ */
98
+ protected abstract runDriver(exec: TExec): AsyncIterable<Record<string, unknown>>;
99
+
100
+ abstract close(): Promise<void>;
101
+
102
+ execute<Row>(
103
+ plan: TPlan & { readonly _row?: Row },
104
+ options?: RuntimeExecuteOptions,
105
+ ): AsyncIterableResult<Row> {
106
+ const self = this;
107
+ const signal = options?.signal;
108
+ // One ctx per execute() call. The ctx object is always allocated; the
109
+ // `signal` field is only included when a signal was supplied (required
110
+ // under exactOptionalPropertyTypes — `{ signal: undefined }` would not
111
+ // satisfy `signal?: AbortSignal`).
112
+ const codecCtx: CodecCallContext = signal === undefined ? {} : { signal };
113
+
114
+ async function* generator(): AsyncGenerator<Row, void, unknown> {
115
+ // Pre-check the signal at entry so an already-aborted caller observes
116
+ // RUNTIME.ABORTED on the first `next()` without any work being done.
117
+ checkAborted(codecCtx, 'stream');
118
+
119
+ const compiled = await self.runBeforeCompile(plan);
120
+ const exec = await self.lower(compiled, codecCtx);
121
+ // The driver yields raw `Record<string, unknown>`; we cast to `Row` here.
122
+ // The Row contract is enforced by the caller via `plan._row`.
123
+ yield* runWithMiddleware<TExec, Row>(
124
+ exec,
125
+ self.middleware,
126
+ self.ctx,
127
+ () => self.runDriver(exec) as AsyncIterable<Row>,
128
+ );
129
+ }
130
+
131
+ return new AsyncIterableResult(generator());
132
+ }
133
+ }
@@ -0,0 +1,83 @@
1
+ export interface RuntimeErrorEnvelope extends Error {
2
+ readonly code: string;
3
+ readonly category: 'PLAN' | 'CONTRACT' | 'LINT' | 'BUDGET' | 'RUNTIME';
4
+ readonly severity: 'error';
5
+ readonly details?: Record<string, unknown>;
6
+ }
7
+
8
+ /**
9
+ * Stable code emitted by the runtime when an in-flight `execute()`
10
+ * is cancelled via the per-query `AbortSignal`. The envelope's
11
+ * `details.phase` distinguishes where the abort was observed:
12
+ *
13
+ * - `'encode'` — abort fired during `encodeParams` (SQL) or
14
+ * `resolveValue` (Mongo).
15
+ * - `'decode'` — abort fired during `decodeRow` / `decodeField`.
16
+ * - `'stream'` — abort fired between rows or before any codec call
17
+ * (already-aborted at entry).
18
+ */
19
+ export const RUNTIME_ABORTED = 'RUNTIME.ABORTED' as const;
20
+
21
+ /** Discriminator placed in `details.phase` of a `RUNTIME.ABORTED` envelope. */
22
+ export type RuntimeAbortedPhase = 'encode' | 'decode' | 'stream';
23
+
24
+ /**
25
+ * Type guard for the runtime-error envelope produced by `runtimeError`.
26
+ *
27
+ * Prefer this over duck-typing on `error.code` directly so consumers stay
28
+ * insulated from the envelope's internal shape.
29
+ */
30
+ export function isRuntimeError(error: unknown): error is RuntimeErrorEnvelope {
31
+ return (
32
+ error instanceof Error &&
33
+ 'code' in error &&
34
+ typeof (error as { code?: unknown }).code === 'string' &&
35
+ 'category' in error &&
36
+ 'severity' in error
37
+ );
38
+ }
39
+
40
+ export function runtimeError(
41
+ code: string,
42
+ message: string,
43
+ details?: Record<string, unknown>,
44
+ ): RuntimeErrorEnvelope {
45
+ const error = new Error(message) as RuntimeErrorEnvelope;
46
+ Object.defineProperty(error, 'name', {
47
+ value: 'RuntimeError',
48
+ configurable: true,
49
+ });
50
+
51
+ return Object.assign(error, {
52
+ code,
53
+ category: resolveCategory(code),
54
+ severity: 'error' as const,
55
+ message,
56
+ details,
57
+ });
58
+ }
59
+
60
+ function resolveCategory(code: string): RuntimeErrorEnvelope['category'] {
61
+ const prefix = code.split('.')[0] ?? 'RUNTIME';
62
+ switch (prefix) {
63
+ case 'PLAN':
64
+ case 'CONTRACT':
65
+ case 'LINT':
66
+ case 'BUDGET':
67
+ return prefix;
68
+ default:
69
+ return 'RUNTIME';
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Construct a `RUNTIME.ABORTED` envelope. Phase distinguishes where the
75
+ * abort was observed (encode / decode / stream); cause carries `signal.reason`
76
+ * verbatim from the platform — native abort produces a `DOMException`,
77
+ * explicit `controller.abort(reason)` produces whatever the caller passed.
78
+ * No synthesis happens here.
79
+ */
80
+ export function runtimeAborted(phase: RuntimeAbortedPhase, cause?: unknown): RuntimeErrorEnvelope {
81
+ const envelope = runtimeError(RUNTIME_ABORTED, `Operation aborted during ${phase}`, { phase });
82
+ return Object.assign(envelope, { cause });
83
+ }
@@ -0,0 +1,182 @@
1
+ import type { AsyncIterableResult } from './async-iterable-result';
2
+ import type { ExecutionPlan, QueryPlan } from './query-plan';
3
+ import { runtimeError } from './runtime-error';
4
+
5
+ export interface RuntimeLog {
6
+ info(event: unknown): void;
7
+ warn(event: unknown): void;
8
+ error(event: unknown): void;
9
+ debug?(event: unknown): void;
10
+ }
11
+
12
+ export interface RuntimeMiddlewareContext {
13
+ readonly contract: unknown;
14
+ readonly mode: 'strict' | 'permissive';
15
+ readonly now: () => number;
16
+ readonly log: RuntimeLog;
17
+ /**
18
+ * Returns a stable string identifying the (storage, statement, params)
19
+ * tuple of an execution. Two semantically equivalent executions return
20
+ * the same string. Used by middleware that need per-execution identity
21
+ * (caching, request coalescing).
22
+ *
23
+ * The family runtime owns the implementation:
24
+ * - SQL: `meta.storageHash` + `exec.sql` + `canonicalStringify(exec.params)`
25
+ * - Mongo: `meta.storageHash` + `canonicalStringify({ ...exec.command })`
26
+ *
27
+ * The method is `async` because the underlying digest helper
28
+ * (`hashContent`) uses the WebCrypto API, whose `crypto.subtle.digest`
29
+ * primitive is asynchronous by design.
30
+ *
31
+ * The returned string is intended to be consumed directly as a `Map` key
32
+ * — it is not (and should not be) further hashed by callers.
33
+ */
34
+ contentHash(exec: ExecutionPlan): Promise<string>;
35
+ }
36
+
37
+ export interface AfterExecuteResult {
38
+ readonly rowCount: number;
39
+ readonly latencyMs: number;
40
+ readonly completed: boolean;
41
+ /**
42
+ * Indicates where the rows observed during this execution came from.
43
+ *
44
+ * - `'driver'` — the default. Rows came from the underlying driver via
45
+ * `runDriver` / `runWithMiddleware`'s normal path.
46
+ * - `'middleware'` — a `RuntimeMiddleware.intercept` hook short-circuited
47
+ * execution and supplied the rows directly. The driver was not invoked.
48
+ *
49
+ * Observers (telemetry, lints, budgets) that need to distinguish between
50
+ * driver-served and middleware-served executions read this field.
51
+ * Observers that don't care can ignore it.
52
+ */
53
+ readonly source: 'driver' | 'middleware';
54
+ }
55
+
56
+ /**
57
+ * Result of a successful `RuntimeMiddleware.intercept` hook.
58
+ *
59
+ * Carries the rows that the middleware wishes to return in place of
60
+ * invoking the driver. The runtime iterates `rows` in order and yields
61
+ * each row to the consumer; `beforeExecute`, `runDriver`, and `onRow` are
62
+ * all skipped on the hit path. `afterExecute` still fires with
63
+ * `source: 'middleware'`.
64
+ *
65
+ * `rows` accepts both `Iterable` (arrays, sync generators) and
66
+ * `AsyncIterable` (async generators). `for await` natively handles both
67
+ * via `Symbol.asyncIterator` / `Symbol.iterator` fallback, so the
68
+ * orchestrator does not need to branch on the variant. Cached arrays in
69
+ * the cache middleware are the common case; streaming variants support
70
+ * future use cases like mock layers replaying recordings.
71
+ *
72
+ * Row shape is `Record<string, unknown>` — the same untyped shape
73
+ * `onRow` receives. The SQL runtime decodes intercepted rows through its
74
+ * normal codec pass, so interceptors cache and return raw (undecoded)
75
+ * rows.
76
+ */
77
+ export interface InterceptResult {
78
+ readonly rows: AsyncIterable<Record<string, unknown>> | Iterable<Record<string, unknown>>;
79
+ }
80
+
81
+ /**
82
+ * Family-agnostic middleware SPI parameterized over the plan marker.
83
+ *
84
+ * `TPlan` defaults to the framework `QueryPlan` marker so a generic
85
+ * middleware (e.g. cross-family telemetry) can be authored without
86
+ * naming a family. Family-specific middleware (`SqlMiddleware`,
87
+ * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.
88
+ */
89
+ export interface RuntimeMiddleware<TPlan extends QueryPlan = QueryPlan> {
90
+ readonly name: string;
91
+ readonly familyId?: string;
92
+ readonly targetId?: string;
93
+ /**
94
+ * Optional short-circuit hook. Runs inside `runWithMiddleware`, after
95
+ * the orchestrator receives the lowered plan and before any
96
+ * `beforeExecute` hook fires. Middleware run in registration order; the
97
+ * first to return a non-`undefined` `InterceptResult` wins, and
98
+ * subsequent middleware's `intercept` does not fire.
99
+ *
100
+ * On a hit, `beforeExecute`, `runDriver`, and `onRow` are all skipped.
101
+ * `afterExecute` still fires with `source: 'middleware'`.
102
+ *
103
+ * Returning `undefined` (or omitting the hook entirely) signals
104
+ * passthrough — execution proceeds through the normal driver path.
105
+ *
106
+ * Errors thrown inside `intercept` are rethrown by `runWithMiddleware`
107
+ * as the original `Error` — no envelope is guaranteed at this layer.
108
+ * Before rethrowing, `afterExecute` fires with `completed: false` and
109
+ * `source: 'middleware'`. Errors thrown by `afterExecute` during the
110
+ * error path remain swallowed (existing semantics, unchanged).
111
+ *
112
+ * Used by middleware that need to short-circuit execution and supply
113
+ * rows directly: caching, mocks, rate limiting, circuit breaking.
114
+ */
115
+ intercept?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<InterceptResult | undefined>;
116
+ beforeExecute?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;
117
+ onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;
118
+ afterExecute?(
119
+ plan: TPlan,
120
+ result: AfterExecuteResult,
121
+ ctx: RuntimeMiddlewareContext,
122
+ ): Promise<void>;
123
+ }
124
+
125
+ /**
126
+ * Optional per-`execute` options accepted by every family runtime.
127
+ *
128
+ * `signal` is the per-query cancellation signal. The runtime threads the
129
+ * signal through to every codec call for the query and uses it to short-
130
+ * circuit the row stream with `RUNTIME.ABORTED` when the caller aborts.
131
+ * Omitting the option (or passing `undefined`) preserves today's behavior
132
+ * bit-for-bit.
133
+ */
134
+ export interface RuntimeExecuteOptions {
135
+ readonly signal?: AbortSignal;
136
+ }
137
+
138
+ /**
139
+ * Cross-family SPI for any runtime that can execute plans and be shut down.
140
+ * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,
141
+ * Mongo structurally (due to its phantom Row parameter using a unique symbol).
142
+ *
143
+ * The `_row` intersection on `execute` connects the `Row` type parameter to the
144
+ * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.
145
+ */
146
+ export interface RuntimeExecutor<TPlan extends QueryPlan> {
147
+ execute<Row>(
148
+ plan: TPlan & { readonly _row?: Row },
149
+ options?: RuntimeExecuteOptions,
150
+ ): AsyncIterableResult<Row>;
151
+ close(): Promise<void>;
152
+ }
153
+
154
+ export function checkMiddlewareCompatibility(
155
+ middleware: RuntimeMiddleware,
156
+ runtimeFamilyId: string,
157
+ runtimeTargetId: string,
158
+ ): void {
159
+ if (middleware.targetId !== undefined && middleware.familyId === undefined) {
160
+ throw runtimeError(
161
+ 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',
162
+ `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,
163
+ { middleware: middleware.name, targetId: middleware.targetId },
164
+ );
165
+ }
166
+
167
+ if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {
168
+ throw runtimeError(
169
+ 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',
170
+ `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,
171
+ { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },
172
+ );
173
+ }
174
+
175
+ if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {
176
+ throw runtimeError(
177
+ 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',
178
+ `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,
179
+ { middleware: middleware.name, middlewareTargetId: middleware.targetId, runtimeTargetId },
180
+ );
181
+ }
182
+ }
@@ -10,13 +10,16 @@ export type {
10
10
  AuthoringTemplateValue,
11
11
  AuthoringTypeConstructorDescriptor,
12
12
  AuthoringTypeNamespace,
13
- } from '../framework-authoring';
13
+ } from '../shared/framework-authoring';
14
14
  export {
15
+ assertNoCrossRegistryCollisions,
16
+ hasRegisteredFieldNamespace,
15
17
  instantiateAuthoringFieldPreset,
16
18
  instantiateAuthoringTypeConstructor,
17
19
  isAuthoringArgRef,
18
20
  isAuthoringFieldPresetDescriptor,
19
21
  isAuthoringTypeConstructorDescriptor,
22
+ mergeAuthoringNamespaces,
20
23
  resolveAuthoringTemplateValue,
21
24
  validateAuthoringHelperArguments,
22
- } from '../framework-authoring';
25
+ } from '../shared/framework-authoring';
@@ -1,2 +1,27 @@
1
- export type { Codec, CodecLookup, CodecTrait } from '../codec-types';
2
- export { emptyCodecLookup } from '../codec-types';
1
+ /**
2
+ * Codec model: interfaces (consumer surface) plus abstract `Impl` classes (codec-author surface) plus the column packager.
3
+ *
4
+ * Consumers depend on the interfaces: {@link Codec}, {@link CodecDescriptor}, {@link AnyCodecDescriptor}, {@link ColumnSpec}, {@link ColumnTypeDescriptor}.
5
+ *
6
+ * Codec authors `extend` the abstract bases: {@link CodecImpl} and {@link CodecDescriptorImpl}. They write a per-codec column helper that calls `descriptor.factory(...)` directly and tie the helper to its descriptor with `satisfies ColumnHelperFor<D>` (or `ColumnHelperForStrict<D>`).
7
+ */
8
+
9
+ export type { Codec } from '../shared/codec';
10
+ export { CodecImpl } from '../shared/codec';
11
+ export type { AnyCodecDescriptor, CodecDescriptor } from '../shared/codec-descriptor';
12
+ export { CodecDescriptorImpl } from '../shared/codec-descriptor';
13
+ export type {
14
+ CodecCallContext,
15
+ CodecInstanceContext,
16
+ CodecLookup,
17
+ CodecMeta,
18
+ CodecTrait,
19
+ } from '../shared/codec-types';
20
+ export { emptyCodecLookup, voidParamsSchema } from '../shared/codec-types';
21
+ export type {
22
+ ColumnHelperFor,
23
+ ColumnHelperForStrict,
24
+ ColumnSpec,
25
+ ColumnTypeDescriptor,
26
+ } from '../shared/column-spec';
27
+ export { column } from '../shared/column-spec';
@@ -20,5 +20,5 @@ export type {
20
20
  TargetDescriptor,
21
21
  TargetInstance,
22
22
  TargetPackRef,
23
- } from '../framework-components';
24
- export { checkContractComponentRequirements } from '../framework-components';
23
+ } from '../shared/framework-components';
24
+ export { checkContractComponentRequirements } from '../shared/framework-components';