@prisma-next/mongo-runtime 0.5.0-dev.9 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,9 +12,42 @@ MongoDB runtime executor for Prisma Next.
12
12
 
13
13
  The Mongo runtime package implements the Mongo family runtime by extending the abstract `RuntimeCore` base class from `@prisma-next/framework-components/runtime` with Mongo-specific lowering and driver dispatch. It provides the public runtime API for MongoDB, layering Mongo concerns (adapter lowering and wire-command dispatch) on top of the shared middleware lifecycle.
14
14
 
15
+ ## Usage
16
+
17
+ The runtime takes a **`MongoExecutionContext`** built from a **`MongoExecutionStack`** (target + adapter + optional driver + extension packs). The context aggregates codec contributions from each stack component into a single registry — users do not construct or thread a `MongoCodecRegistry` themselves. This mirrors the SQL pattern (see `packages/2-sql/5-runtime/src/sql-context.ts`).
18
+
19
+ Typed reads that attach a **`resultShape`** on the query plan are decoded after the driver yields each row: scalars and scalar arrays run through their `codecId` entries; `kind: 'unknown'` subtrees are passed through unchanged; plans without `resultShape` (for example raw commands) leave rows as the driver returned them.
20
+
21
+ Example:
22
+
23
+ ```ts
24
+ import mongoRuntimeAdapter from '@prisma-next/adapter-mongo/runtime';
25
+ import { createMongoDriver } from '@prisma-next/driver-mongo';
26
+ import {
27
+ createMongoExecutionContext,
28
+ createMongoExecutionStack,
29
+ createMongoRuntime,
30
+ } from '@prisma-next/mongo-runtime';
31
+ import mongoRuntimeTarget from '@prisma-next/target-mongo/runtime';
32
+
33
+ const stack = createMongoExecutionStack({
34
+ target: mongoRuntimeTarget,
35
+ adapter: mongoRuntimeAdapter,
36
+ });
37
+ const context = createMongoExecutionContext({ contract, stack });
38
+
39
+ const runtime = createMongoRuntime({
40
+ context,
41
+ driver: await createMongoDriver(url, dbName),
42
+ });
43
+ ```
44
+
45
+ Custom or third-party codecs (encryption, vendor scalars) are contributed via an extension-pack descriptor whose `codecs` slot returns the codec descriptors; `createMongoExecutionContext` folds them into the same registry. Duplicate codec ids across contributors throw `RUNTIME.DUPLICATE_CODEC` at composition time.
46
+
15
47
  ## Responsibilities
16
48
 
17
- - **Runtime executor**: `createMongoRuntime()` composes adapter and driver into a `MongoRuntime` with a single `execute(plan)` entry point accepting `MongoQueryPlan<Row>` from `@prisma-next/mongo-query-ast`. Execution is one path for reads and writes: `adapter.lower(plan)` produces a wire command, then the driver runs it.
49
+ - **Stack/context composition**: `createMongoExecutionStack` and `createMongoExecutionContext` mirror SQL's `createSqlExecutionStack` / `createExecutionContext`. The context aggregates codec contributions from `[stack.target, stack.adapter, ...stack.extensionPacks]` into a single `MongoCodecRegistry`.
50
+ - **Runtime executor**: `createMongoRuntime({ context, driver, ... })` composes context and driver into a `MongoRuntime` with a single `execute(plan)` entry point accepting `MongoQueryPlan<Row>` from `@prisma-next/mongo-query-ast`. The adapter is reached via `context.stack.adapter` (instantiated lazily through the stack's `create(stack)` factory). Execution lowers the plan through the adapter, runs the wire command on the driver, then **optionally decodes** each row when `plan.resultShape` is present.
18
51
  - **Unified flow**: There is no separate `execute` vs `executeCommand`; all operations use `execute(plan)`.
19
52
  - **Lowering**: Happens in the adapter (`lower(plan)`), wrapped by the runtime's `lower` override into a `MongoExecutionPlan`.
20
53
  - **Middleware lifecycle inheritance**: `MongoRuntime` extends `RuntimeCore<MongoQueryPlan, MongoExecutionPlan, MongoMiddleware>` and inherits the `beforeExecute` / `onRow` / `afterExecute` lifecycle from the framework via `runWithMiddleware`. Mongo does **not** override `runBeforeCompile` (Mongo middleware has no `beforeCompile` hook today).
@@ -23,9 +56,10 @@ The Mongo runtime package implements the Mongo family runtime by extending the a
23
56
  ## Dependencies
24
57
 
25
58
  - **Depends on**:
59
+ - `@prisma-next/mongo-codec` (`MongoCodecRegistry` for decode)
26
60
  - `@prisma-next/mongo-lowering` (`MongoAdapter`, `MongoDriver` interfaces)
27
61
  - `@prisma-next/mongo-query-ast` (`MongoQueryPlan`, `AnyMongoCommand` — the typed plan shape)
28
- - `@prisma-next/framework-components` (`RuntimeCore` base class, `runWithMiddleware` helper, `RuntimeMiddleware` SPI, `AsyncIterableResult` return type)
62
+ - `@prisma-next/framework-components` (`RuntimeCore` base class, `runWithMiddleware` helper, `RuntimeMiddleware` SPI, `AsyncIterableResult` return type, `RuntimeAdapterDescriptor` / `ExecutionStack` for the stack composition model)
29
63
  - **Depended on by**:
30
64
  - Integration tests (`test/integration/test/mongo/` and `test/integration/test/cross-package/cross-family-middleware.test.ts`)
31
65
 
@@ -37,7 +71,9 @@ The Mongo runtime package implements the Mongo family runtime by extending the a
37
71
  - `runDriver(exec)` — dispatches the wire command to the Mongo driver via `driver.execute(exec.command)`.
38
72
  - `close()` — closes the underlying driver.
39
73
 
40
- The execution template (`execute(plan)` `lower` `runWithMiddleware` `runDriver`) is inherited from `RuntimeCore`. The four inline middleware lifecycle loops (`beforeExecute`, `onRow`, `afterExecute`, plus the error-path `afterExecute`) that previously lived in `MongoRuntimeImpl.execute` are now delegated to the shared `runWithMiddleware` helper.
74
+ `MongoRuntimeImpl` extends `RuntimeCore` but **overrides `execute`** so that after `runWithMiddleware` yields a raw driver row, the runtime can **`decodeMongoRow`** when the lowered plan carries `resultShape`, then yield the decoded row. `lower(plan)` copies `resultShape` from the query plan onto `MongoExecutionPlan`. Middleware `onRow` still sees the raw driver row (decode happens after the middleware loop for that row, before the consumer receives the value).
75
+
76
+ The execution template is: `lower` → `runWithMiddleware` (driver loop + middleware) → **per-row decode when `exec.resultShape` is set** → yield to consumer.
41
77
 
42
78
  ```mermaid
43
79
  flowchart LR
package/dist/index.d.mts CHANGED
@@ -1,10 +1,11 @@
1
- import { AfterExecuteResult, AsyncIterableResult, ExecutionPlan, RuntimeMiddleware, RuntimeMiddlewareContext } from "@prisma-next/framework-components/runtime";
1
+ import { RuntimeAdapterDescriptor, RuntimeAdapterInstance, RuntimeDriverDescriptor, RuntimeDriverInstance, RuntimeExtensionDescriptor, RuntimeExtensionInstance, RuntimeTargetDescriptor, RuntimeTargetInstance, RuntimeTargetInstance as RuntimeTargetInstance$1 } from "@prisma-next/framework-components/execution";
2
+ import { AfterExecuteResult, AsyncIterableResult, ExecutionPlan, ParamRefMutator, RuntimeExecuteOptions, RuntimeMiddleware, RuntimeMiddlewareContext } from "@prisma-next/framework-components/runtime";
3
+ import { MongoCodec, MongoCodecRegistry } from "@prisma-next/mongo-codec";
4
+ import { MongoQueryPlan, MongoResultShape } from "@prisma-next/mongo-query-ast/execution";
2
5
  import { AnyMongoWireCommand } from "@prisma-next/mongo-wire";
3
6
  import { MongoAdapter, MongoDriver } from "@prisma-next/mongo-lowering";
4
- import { MongoQueryPlan } from "@prisma-next/mongo-query-ast/execution";
5
7
 
6
8
  //#region src/mongo-execution-plan.d.ts
7
-
8
9
  /**
9
10
  * Mongo-domain execution plan: a query lowered to the wire-command shape
10
11
  * that a Mongo driver can run.
@@ -23,13 +24,70 @@ import { MongoQueryPlan } from "@prisma-next/mongo-query-ast/execution";
23
24
  * Lives in the runtime layer (alongside `MongoRuntime`) because the wire
24
25
  * command shape lives in the transport layer (`@prisma-next/mongo-wire`),
25
26
  * which the lanes layer (`mongo-query-ast`, where `MongoQueryPlan` lives)
26
- * cannot depend on. M1 establishes this type; `MongoRuntime.execute` does
27
- * not yet accept it as input — that adoption lands in M4.
27
+ * cannot depend on.
28
28
  */
29
29
  interface MongoExecutionPlan<Row = unknown> extends ExecutionPlan<Row> {
30
30
  readonly command: AnyMongoWireCommand;
31
+ readonly resultShape?: MongoResultShape;
31
32
  }
32
33
  //#endregion
34
+ //#region src/mongo-execution-stack.d.ts
35
+ /**
36
+ * Mongo-specific static contributions a runtime descriptor declares.
37
+ *
38
+ * Mirrors `SqlStaticContributions` in shape: a `codecs()` getter that yields a `MongoCodecRegistry` populated with this contributor's codecs. The registry is then walked by `createMongoExecutionContext` and folded into the single per-execution registry the runtime reads from at decode time.
39
+ */
40
+ interface MongoStaticContributions {
41
+ readonly codecs: () => MongoCodecRegistry;
42
+ }
43
+ interface MongoRuntimeTargetDescriptor<TTargetId extends string = 'mongo', TTargetInstance extends RuntimeTargetInstance$1<'mongo', TTargetId> = RuntimeTargetInstance$1<'mongo', TTargetId>> extends RuntimeTargetDescriptor<'mongo', TTargetId, TTargetInstance>, MongoStaticContributions {}
44
+ interface MongoRuntimeAdapterInstance<TTargetId extends string = 'mongo'> extends RuntimeAdapterInstance<'mongo', TTargetId>, MongoAdapter {}
45
+ interface MongoRuntimeAdapterDescriptor<TTargetId extends string = 'mongo', TAdapterInstance extends RuntimeAdapterInstance<'mongo', TTargetId> = MongoRuntimeAdapterInstance<TTargetId>> extends RuntimeAdapterDescriptor<'mongo', TTargetId, TAdapterInstance>, MongoStaticContributions {}
46
+ interface MongoRuntimeExtensionInstance<TTargetId extends string = 'mongo'> extends RuntimeExtensionInstance<'mongo', TTargetId> {}
47
+ interface MongoRuntimeExtensionDescriptor<TTargetId extends string = 'mongo'> extends RuntimeExtensionDescriptor<'mongo', TTargetId, MongoRuntimeExtensionInstance<TTargetId>>, MongoStaticContributions {
48
+ create(): MongoRuntimeExtensionInstance<TTargetId>;
49
+ }
50
+ /**
51
+ * The Mongo execution stack: target + adapter + optional driver + extension packs. Mirrors `SqlExecutionStack`. Constructed via `createMongoExecutionStack`.
52
+ */
53
+ interface MongoExecutionStack<TTargetId extends string = 'mongo'> {
54
+ readonly target: MongoRuntimeTargetDescriptor<TTargetId>;
55
+ readonly adapter: MongoRuntimeAdapterDescriptor<TTargetId>;
56
+ readonly driver: RuntimeDriverDescriptor<'mongo', TTargetId, unknown, RuntimeDriverInstance<'mongo', TTargetId>> | undefined;
57
+ readonly extensionPacks: readonly MongoRuntimeExtensionDescriptor<TTargetId>[];
58
+ }
59
+ declare function createMongoExecutionStack<TTargetId extends string = 'mongo'>(options: {
60
+ readonly target: MongoRuntimeTargetDescriptor<TTargetId>;
61
+ readonly adapter: MongoRuntimeAdapterDescriptor<TTargetId>;
62
+ readonly driver?: RuntimeDriverDescriptor<'mongo', TTargetId, unknown, RuntimeDriverInstance<'mongo', TTargetId>> | undefined;
63
+ readonly extensionPacks?: readonly MongoRuntimeExtensionDescriptor<TTargetId>[] | undefined;
64
+ }): MongoExecutionStack<TTargetId>;
65
+ /**
66
+ * Read-only view of the codec registry exposed on `MongoExecutionContext`.
67
+ *
68
+ * Hides `register()` and the iterator from public surface — users do not mutate the per-execution codec registry. Internal aggregation in `createMongoExecutionContext` keeps using the full `MongoCodecRegistry` (it needs `register()`).
69
+ */
70
+ interface MongoCodecLookup {
71
+ get(id: string): MongoCodec<string> | undefined;
72
+ has(id: string): boolean;
73
+ }
74
+ /**
75
+ * Per-execution context aggregated from a `MongoExecutionStack`.
76
+ *
77
+ * Carries the user's contract, a read-only lookup over the codec registry composed from every stack contributor, and a back-reference to the stack itself so the runtime can reach the adapter without users threading it explicitly.
78
+ *
79
+ * Mirrors SQL's `ExecutionContext` in role; Mongo's flavour is leaner because there are no parameterised codecs, JSON-schema validators, or mutation-default generators in scope yet.
80
+ */
81
+ interface MongoExecutionContext<TTargetId extends string = 'mongo'> {
82
+ readonly contract: unknown;
83
+ readonly codecs: MongoCodecLookup;
84
+ readonly stack: MongoExecutionStack<TTargetId>;
85
+ }
86
+ declare function createMongoExecutionContext<TTargetId extends string = 'mongo'>(options: {
87
+ readonly contract: unknown;
88
+ readonly stack: MongoExecutionStack<TTargetId>;
89
+ }): MongoExecutionContext<TTargetId>;
90
+ //#endregion
33
91
  //#region src/mongo-middleware.d.ts
34
92
  interface MongoMiddlewareContext extends RuntimeMiddlewareContext {}
35
93
  /**
@@ -45,25 +103,55 @@ interface MongoMiddlewareContext extends RuntimeMiddlewareContext {}
45
103
  */
46
104
  interface MongoMiddleware extends RuntimeMiddleware<MongoExecutionPlan> {
47
105
  readonly familyId?: 'mongo';
48
- beforeExecute?(plan: MongoExecutionPlan, ctx: MongoMiddlewareContext): Promise<void>;
106
+ beforeExecute?(plan: MongoExecutionPlan, ctx: MongoMiddlewareContext, params?: ParamRefMutator): void | Promise<void>;
49
107
  onRow?(row: Record<string, unknown>, plan: MongoExecutionPlan, ctx: MongoMiddlewareContext): Promise<void>;
50
108
  afterExecute?(plan: MongoExecutionPlan, result: AfterExecuteResult, ctx: MongoMiddlewareContext): Promise<void>;
51
109
  }
52
110
  //#endregion
53
111
  //#region src/mongo-runtime.d.ts
112
+ /**
113
+ * Mongo runtime options.
114
+ *
115
+ * The runtime takes a {@link MongoExecutionContext} (built via
116
+ * `createMongoExecutionContext`) and a driver. Codec resolution flows from
117
+ * the context — there is no `codecs` field on this options bag. The adapter
118
+ * is reached via `context.stack.adapter` (instantiated lazily through the
119
+ * stack's `create(stack)` factory). See ADR — Mongo result-shape as a
120
+ * structural plan field, § Codec registry: stack aggregation, not user
121
+ * threading.
122
+ */
54
123
  interface MongoRuntimeOptions {
55
- readonly adapter: MongoAdapter;
124
+ readonly context: MongoExecutionContext;
56
125
  readonly driver: MongoDriver;
57
- readonly contract: unknown;
58
- readonly targetId: string;
59
126
  readonly middleware?: readonly MongoMiddleware[];
60
127
  readonly mode?: 'strict' | 'permissive';
61
128
  }
62
129
  interface MongoRuntime {
63
- execute<Row>(plan: MongoQueryPlan<Row>): AsyncIterableResult<Row>;
130
+ /**
131
+ * Execute a `MongoQueryPlan` and return an async iterable of rows.
132
+ *
133
+ * The optional `options.signal` is threaded through
134
+ * `lower → adapter.lower → resolveValue → codec.encode` so codec authors
135
+ * who forward the signal to their underlying SDK get true cancellation
136
+ * of in-flight network calls. The runtime additionally observes the
137
+ * signal at two boundaries:
138
+ *
139
+ * - **Already-aborted at entry** — first `next()` throws
140
+ * `RUNTIME.ABORTED { phase: 'stream' }` before any work is done.
141
+ * (Inherited from `RuntimeCore.execute`.)
142
+ * - **Mid-encode abort** — surfaces as
143
+ * `RUNTIME.ABORTED { phase: 'encode' }` from inside `resolveValue`'s
144
+ * per-level `Promise.all` race.
145
+ *
146
+ * Mongo's read path decodes rows via `resultShape` (per ADR 209). The
147
+ * same `CodecCallContext` is forwarded into each `codec.decode(wire, ctx)`
148
+ * call, so async decoders that respect the signal get cancellation; the
149
+ * runtime itself does not currently emit a `phase: 'decode'` envelope.
150
+ */
151
+ execute<Row>(plan: MongoQueryPlan<Row>, options?: RuntimeExecuteOptions): AsyncIterableResult<Row>;
64
152
  close(): Promise<void>;
65
153
  }
66
154
  declare function createMongoRuntime(options: MongoRuntimeOptions): MongoRuntime;
67
155
  //#endregion
68
- export { type MongoExecutionPlan, type MongoMiddleware, type MongoMiddlewareContext, type MongoRuntime, type MongoRuntimeOptions, createMongoRuntime };
156
+ export { type MongoCodecLookup, type MongoExecutionContext, type MongoExecutionPlan, type MongoExecutionStack, type MongoMiddleware, type MongoMiddlewareContext, type MongoRuntime, type MongoRuntimeAdapterDescriptor, type MongoRuntimeAdapterInstance, type MongoRuntimeExtensionDescriptor, type MongoRuntimeExtensionInstance, type MongoRuntimeOptions, type MongoRuntimeTargetDescriptor, type MongoStaticContributions, type RuntimeTargetInstance, createMongoExecutionContext, createMongoExecutionStack, createMongoRuntime };
69
157
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/mongo-execution-plan.ts","../src/mongo-middleware.ts","../src/mongo-runtime.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;AAwBA;;;;;;;;ACjBA;AAaA;;;;;;;;AAOK,UDHY,kBCGZ,CAAA,MAAA,OAAA,CAAA,SDHsD,aCGtD,CDHoE,GCGpE,CAAA,CAAA;EAEK,SAAA,OAAA,EDJU,mBCIV;;;;UAtBO,sBAAA,SAA+B;;;ADiBhD;;;;;;;;ACjBA;AAaiB,UAAA,eAAA,SAAwB,iBAAR,CAA0B,kBAA1B,CAAA,CAAA;EAA0B,SAAA,QAAA,CAAA,EAAA,OAAA;EAEpC,aAAA,EAAA,IAAA,EAAA,kBAAA,EAAA,GAAA,EAAyB,sBAAzB,CAAA,EAAkD,OAAlD,CAAA,IAAA,CAAA;EAAyB,KAAA,EAAA,GAAA,EAEvC,MAFuC,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,IAAA,EAGtC,kBAHsC,EAAA,GAAA,EAIvC,sBAJuC,CAAA,EAK3C,OAL2C,CAAA,IAAA,CAAA;EAAyB,YAAA,EAAA,IAAA,EAO/D,kBAP+D,EAAA,MAAA,EAQ7D,kBAR6D,EAAA,GAAA,EAShE,sBATgE,CAAA,EAUpE,OAVoE,CAAA,IAAA,CAAA;;;;UCVxD,mBAAA;oBACG;EFWH,SAAA,MAAA,EEVE,WFUgB;EAAsC,SAAA,QAAA,EAAA,OAAA;EACrD,SAAA,QAAA,EAAA,MAAA;EADuC,SAAA,UAAA,CAAA,EAAA,SEP1B,eFO0B,EAAA;EAAa,SAAA,IAAA,CAAA,EAAA,QAAA,GAAA,YAAA;;UEHvD,YAAA;qBACI,eAAe,OAAO,oBAAoB;EDf9C,KAAA,EAAA,ECgBN,ODhBM,CAAA,IAAA,CAAA;AAajB;AAA2D,iBCgD3C,kBAAA,CDhD2C,OAAA,ECgDf,mBDhDe,CAAA,ECgDO,YDhDP"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/mongo-execution-plan.ts","../src/mongo-execution-stack.ts","../src/mongo-middleware.ts","../src/mongo-runtime.ts"],"mappings":";;;;;;;;;;;;;AAwBA;;;;;;;;;;;;;;;UAAiB,kBAAA,wBAA0C,aAAA,CAAc,GAAA;EAAA,SAC9D,OAAA,EAAS,mBAAA;EAAA,SACT,WAAA,GAAc,gBAAA;AAAA;;;;;;;AAFzB;UCFiB,wBAAA;EAAA,SACN,MAAA,QAAc,kBAAA;AAAA;AAAA,UAGR,4BAAA,6DAES,uBAAA,UAA+B,SAAA,IAAa,uBAAA,UAElE,SAAA,WAEM,uBAAA,UAAiC,SAAA,EAAW,eAAA,GAClD,wBAAA;AAAA,UAEa,2BAAA,6CACP,sBAAA,UAAgC,SAAA,GACtC,YAAA;AAAA,UAEa,6BAAA,8DAEU,sBAAA,UAEvB,SAAA,IACE,2BAAA,CAA4B,SAAA,WACxB,wBAA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AA,EACL,MAAA,GAAS,eAAA,UACD,OAAA;EACV,KAAA,EACE,GAAA,EAAK,MAAA,mBACL,IAAA,EAAM,kBAAA,EACN,GAAA,EAAK,sBAAA,GACJ,OAAA;EACH,YAAA,EACE,IAAA,EAAM,kBAAA,EACN,MAAA,EAAQ,kBAAA,EACR,GAAA,EAAK,sBAAA,GACJ,OAAA;AAAA;;;;;;AFbL;;;;;;;;UGOiB,mBAAA;EAAA,SACN,OAAA,EAAS,qBAAA;EAAA,SACT,MAAA,EAAQ,WAAA;EAAA,SACR,UAAA,YAAsB,eAAA;EAAA,SACtB,IAAA;AAAA;AAAA,UAGM,YAAA;EHZQ;;;;;;ACJzB;;;;;AAIA;;;;;;;;;;EEkCE,OAAA,MACE,IAAA,EAAM,cAAA,CAAe,GAAA,GACrB,OAAA,GAAU,qBAAA,GACT,mBAAA,CAAoB,GAAA;EACvB,KAAA,IAAS,OAAA;AAAA;AAAA,iBAiGK,kBAAA,CAAmB,OAAA,EAAS,mBAAA,GAAsB,YAAA"}
package/dist/index.mjs CHANGED
@@ -1,39 +1,242 @@
1
- import { RuntimeCore, checkMiddlewareCompatibility } from "@prisma-next/framework-components/runtime";
2
-
1
+ import { createExecutionStack } from "@prisma-next/framework-components/execution";
2
+ import { AsyncIterableResult, RuntimeCore, checkAborted, checkMiddlewareCompatibility, runWithMiddleware, runtimeError } from "@prisma-next/framework-components/runtime";
3
+ import { newMongoCodecRegistry } from "@prisma-next/mongo-codec";
4
+ import { ifDefined } from "@prisma-next/utils/defined";
5
+ import { canonicalStringify } from "@prisma-next/utils/canonical-stringify";
6
+ import { hashContent } from "@prisma-next/utils/hash-content";
7
+ //#region src/mongo-execution-stack.ts
8
+ function createMongoExecutionStack(options) {
9
+ return createExecutionStack({
10
+ target: options.target,
11
+ adapter: options.adapter,
12
+ driver: options.driver,
13
+ extensionPacks: options.extensionPacks
14
+ });
15
+ }
16
+ function createMongoExecutionContext(options) {
17
+ const registry = newMongoCodecRegistry();
18
+ const owners = /* @__PURE__ */ new Map();
19
+ const contributors = [
20
+ options.stack.target,
21
+ options.stack.adapter,
22
+ ...options.stack.extensionPacks
23
+ ];
24
+ for (const contributor of contributors) {
25
+ const contributed = contributor.codecs();
26
+ for (const codec of iterateCodecs(contributed)) {
27
+ const existingOwner = owners.get(codec.id);
28
+ if (existingOwner !== void 0) throw runtimeError("RUNTIME.DUPLICATE_CODEC", `Duplicate Mongo codec id '${codec.id}' contributed by '${contributor.id}' (already registered by '${existingOwner}').`, {
29
+ codecId: codec.id,
30
+ existingOwner,
31
+ incomingOwner: contributor.id
32
+ });
33
+ registry.register(codec);
34
+ owners.set(codec.id, contributor.id);
35
+ }
36
+ }
37
+ return Object.freeze({
38
+ contract: options.contract,
39
+ codecs: registry,
40
+ stack: options.stack
41
+ });
42
+ }
43
+ function* iterateCodecs(registry) {
44
+ yield* registry.values();
45
+ }
46
+ //#endregion
47
+ //#region src/codecs/decoding.ts
48
+ const WIRE_PREVIEW_LIMIT = 100;
49
+ function previewWireValue(wireValue) {
50
+ if (typeof wireValue === "string") return wireValue.length > WIRE_PREVIEW_LIMIT ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...` : wireValue;
51
+ return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);
52
+ }
53
+ function wrapDecodeFailure(error, collection, path, codecId, wireValue) {
54
+ const wrapped = runtimeError("RUNTIME.DECODE_FAILED", `Failed to decode field ${path} in collection '${collection}' with codec '${codecId}': ${error instanceof Error ? error.message : String(error)}`, {
55
+ collection,
56
+ path,
57
+ codec: codecId,
58
+ wirePreview: previewWireValue(wireValue)
59
+ });
60
+ wrapped.cause = error;
61
+ throw wrapped;
62
+ }
63
+ async function decodeMongoRow(row, shape, registry, collection, ctx = {}) {
64
+ if (shape.kind === "unknown") return row;
65
+ if (typeof row !== "object" || row === null) return row;
66
+ const rowObj = row;
67
+ const out = {};
68
+ const tasks = [];
69
+ function scheduleLeaf(path, codecId, wire, assign) {
70
+ const codec = registry.get(codecId);
71
+ if (!codec) {
72
+ assign(wire);
73
+ return;
74
+ }
75
+ tasks.push((async () => {
76
+ try {
77
+ assign(await codec.decode(wire, ctx));
78
+ } catch (error) {
79
+ wrapDecodeFailure(error, collection, path, codecId, wire);
80
+ }
81
+ })());
82
+ }
83
+ function walkField(value, fieldShape, path, assign) {
84
+ switch (fieldShape.kind) {
85
+ case "unknown":
86
+ assign(value);
87
+ return;
88
+ case "leaf":
89
+ if (value === null || value === void 0) {
90
+ assign(value);
91
+ return;
92
+ }
93
+ scheduleLeaf(path, fieldShape.codecId, value, assign);
94
+ return;
95
+ case "document": {
96
+ if (value === null || value === void 0) {
97
+ assign(value);
98
+ return;
99
+ }
100
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
101
+ assign(value);
102
+ return;
103
+ }
104
+ const vObj = value;
105
+ const nested = { ...vObj };
106
+ assign(nested);
107
+ for (const [fk, fShape] of Object.entries(fieldShape.fields)) walkField(vObj[fk], fShape, `${path}.${fk}`, (v) => {
108
+ nested[fk] = v;
109
+ });
110
+ return;
111
+ }
112
+ case "array": {
113
+ if (value === null || value === void 0) {
114
+ assign(value);
115
+ return;
116
+ }
117
+ if (!Array.isArray(value)) {
118
+ assign(value);
119
+ return;
120
+ }
121
+ const arr = [];
122
+ assign(arr);
123
+ for (let i = 0; i < value.length; i++) {
124
+ const el = value[i];
125
+ walkField(el, fieldShape.element, `${path}.${i}`, (v) => {
126
+ arr[i] = v;
127
+ });
128
+ }
129
+ return;
130
+ }
131
+ }
132
+ /* v8 ignore stop */
133
+ }
134
+ for (const [k, fShape] of Object.entries(shape.fields)) walkField(rowObj[k], fShape, k, (v) => {
135
+ out[k] = v;
136
+ });
137
+ for (const k of Object.keys(rowObj)) if (!Object.hasOwn(shape.fields, k)) out[k] = rowObj[k];
138
+ await Promise.all(tasks);
139
+ return out;
140
+ }
141
+ //#endregion
142
+ //#region src/content-hash.ts
143
+ /**
144
+ * Computes a stable content hash for a lowered Mongo execution plan.
145
+ *
146
+ * Internally builds an unambiguous canonical-stringified preimage from
147
+ * two components:
148
+ *
149
+ * 1. `meta.storageHash` — discriminates by schema. A migration changes the
150
+ * storage hash, which invalidates cached entries automatically (no
151
+ * per-app invalidation logic needed for schema changes).
152
+ * 2. `exec.command` — the wire command. `canonicalStringify` produces a
153
+ * deterministic serialization that is stable across object key
154
+ * insertion order and that distinguishes types JSON would otherwise
155
+ * conflate (e.g. `BigInt(1)` vs `1`, `Date` vs ISO string, `Buffer`
156
+ * vs number array). The spread converts the frozen wire-command
157
+ * class instance (`InsertOneWireCommand`, `AggregateWireCommand`, …)
158
+ * into a plain object exposing its own enumerable properties
159
+ * (`kind`, `collection`, plus the payload-specific fields like
160
+ * `document`/`filter`/`update`/`pipeline`/…), which is what
161
+ * `canonicalStringify` accepts; class instances are rejected
162
+ * outright to prevent silent collisions.
163
+ *
164
+ * Unlike SQL, there is no separate "rendered statement" component because
165
+ * a Mongo `MongoExecutionPlan.command` is the wire command itself —
166
+ * canonicalizing it captures both structure and parameters in one pass.
167
+ *
168
+ * The components are wrapped in an object and canonicalized as a single
169
+ * unit (rather than concatenated with a delimiter) so component
170
+ * boundaries are unambiguous and cannot collide with a different split
171
+ * of the same characters.
172
+ *
173
+ * The canonical string is then piped through `hashContent` to produce a
174
+ * bounded, opaque digest. See `@prisma-next/utils/hash-content` for the
175
+ * rationale.
176
+ *
177
+ * @internal
178
+ */
179
+ function computeMongoContentHash(exec) {
180
+ return hashContent(canonicalStringify({
181
+ storageHash: exec.meta.storageHash,
182
+ command: { ...exec.command }
183
+ }));
184
+ }
185
+ //#endregion
3
186
  //#region src/mongo-runtime.ts
4
187
  function noop() {}
5
188
  var MongoRuntimeImpl = class extends RuntimeCore {
6
189
  #adapter;
7
190
  #driver;
191
+ #codecs;
8
192
  constructor(options) {
9
193
  const middleware = options.middleware ? [...options.middleware] : [];
10
- for (const mw of middleware) checkMiddlewareCompatibility(mw, "mongo", options.targetId);
194
+ const targetId = options.context.stack.target.targetId;
195
+ for (const mw of middleware) checkMiddlewareCompatibility(mw, "mongo", targetId);
11
196
  const ctx = {
12
- contract: options.contract,
197
+ contract: options.context.contract,
13
198
  mode: options.mode ?? "strict",
14
199
  now: () => Date.now(),
15
200
  log: {
16
201
  info: noop,
17
202
  warn: noop,
18
203
  error: noop
19
- }
204
+ },
205
+ contentHash: (exec) => computeMongoContentHash(exec)
20
206
  };
21
207
  super({
22
208
  middleware,
23
209
  ctx
24
210
  });
25
- this.#adapter = options.adapter;
211
+ const adapterInstance = options.context.stack.adapter.create(options.context.stack);
212
+ this.#adapter = adapterInstance;
26
213
  this.#driver = options.driver;
214
+ this.#codecs = options.context.codecs;
27
215
  }
28
- async lower(plan) {
216
+ async lower(plan, ctx) {
29
217
  return {
30
- command: await this.#adapter.lower(plan),
31
- meta: plan.meta
218
+ command: await this.#adapter.lower(plan, ctx),
219
+ meta: plan.meta,
220
+ ...ifDefined("resultShape", plan.resultShape)
32
221
  };
33
222
  }
34
223
  runDriver(exec) {
35
224
  return this.#driver.execute(exec.command);
36
225
  }
226
+ execute(plan, options) {
227
+ const self = this;
228
+ const signal = options?.signal;
229
+ const codecCtx = signal === void 0 ? {} : { signal };
230
+ const generator = async function* () {
231
+ checkAborted(codecCtx, "stream");
232
+ const compiled = await self.runBeforeCompile(plan);
233
+ const exec = await self.lower(compiled, codecCtx);
234
+ const stream = runWithMiddleware(exec, self.middleware, self.ctx, () => self.runDriver(exec));
235
+ for await (const rawRow of stream) if (exec.resultShape === void 0) yield rawRow;
236
+ else yield await decodeMongoRow(rawRow, exec.resultShape, self.#codecs, exec.command.collection, codecCtx);
237
+ };
238
+ return new AsyncIterableResult(generator());
239
+ }
37
240
  async close() {
38
241
  await this.#driver.close();
39
242
  }
@@ -41,7 +244,7 @@ var MongoRuntimeImpl = class extends RuntimeCore {
41
244
  function createMongoRuntime(options) {
42
245
  return new MongoRuntimeImpl(options);
43
246
  }
44
-
45
247
  //#endregion
46
- export { createMongoRuntime };
248
+ export { createMongoExecutionContext, createMongoExecutionStack, createMongoRuntime };
249
+
47
250
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["#adapter","#driver","ctx: MongoMiddlewareContext"],"sources":["../src/mongo-runtime.ts"],"sourcesContent":["import type { AsyncIterableResult } from '@prisma-next/framework-components/runtime';\nimport {\n checkMiddlewareCompatibility,\n RuntimeCore,\n} from '@prisma-next/framework-components/runtime';\nimport type { MongoAdapter, MongoDriver } from '@prisma-next/mongo-lowering';\nimport type { MongoQueryPlan } from '@prisma-next/mongo-query-ast/execution';\nimport type { MongoExecutionPlan } from './mongo-execution-plan';\nimport type { MongoMiddleware, MongoMiddlewareContext } from './mongo-middleware';\n\nfunction noop() {}\n\nexport interface MongoRuntimeOptions {\n readonly adapter: MongoAdapter;\n readonly driver: MongoDriver;\n readonly contract: unknown;\n readonly targetId: string;\n readonly middleware?: readonly MongoMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n}\n\nexport interface MongoRuntime {\n execute<Row>(plan: MongoQueryPlan<Row>): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nclass MongoRuntimeImpl\n extends RuntimeCore<MongoQueryPlan, MongoExecutionPlan, MongoMiddleware>\n implements MongoRuntime\n{\n readonly #adapter: MongoAdapter;\n readonly #driver: MongoDriver;\n\n constructor(options: MongoRuntimeOptions) {\n const middleware = options.middleware ? [...options.middleware] : [];\n for (const mw of middleware) {\n checkMiddlewareCompatibility(mw, 'mongo', options.targetId);\n }\n\n const ctx: MongoMiddlewareContext = {\n contract: options.contract,\n mode: options.mode ?? 'strict',\n now: () => Date.now(),\n log: { info: noop, warn: noop, error: noop },\n };\n\n super({ middleware, ctx });\n\n this.#adapter = options.adapter;\n this.#driver = options.driver;\n }\n\n protected override async lower(plan: MongoQueryPlan): Promise<MongoExecutionPlan> {\n return {\n command: await this.#adapter.lower(plan),\n meta: plan.meta,\n };\n }\n\n protected override runDriver(exec: MongoExecutionPlan): AsyncIterable<Record<string, unknown>> {\n return this.#driver.execute<Record<string, unknown>>(exec.command);\n }\n\n override async close(): Promise<void> {\n await this.#driver.close();\n }\n}\n\nexport function createMongoRuntime(options: MongoRuntimeOptions): MongoRuntime {\n return new MongoRuntimeImpl(options);\n}\n"],"mappings":";;;AAUA,SAAS,OAAO;AAgBhB,IAAM,mBAAN,cACU,YAEV;CACE,CAASA;CACT,CAASC;CAET,YAAY,SAA8B;EACxC,MAAM,aAAa,QAAQ,aAAa,CAAC,GAAG,QAAQ,WAAW,GAAG,EAAE;AACpE,OAAK,MAAM,MAAM,WACf,8BAA6B,IAAI,SAAS,QAAQ,SAAS;EAG7D,MAAMC,MAA8B;GAClC,UAAU,QAAQ;GAClB,MAAM,QAAQ,QAAQ;GACtB,WAAW,KAAK,KAAK;GACrB,KAAK;IAAE,MAAM;IAAM,MAAM;IAAM,OAAO;IAAM;GAC7C;AAED,QAAM;GAAE;GAAY;GAAK,CAAC;AAE1B,QAAKF,UAAW,QAAQ;AACxB,QAAKC,SAAU,QAAQ;;CAGzB,MAAyB,MAAM,MAAmD;AAChF,SAAO;GACL,SAAS,MAAM,MAAKD,QAAS,MAAM,KAAK;GACxC,MAAM,KAAK;GACZ;;CAGH,AAAmB,UAAU,MAAkE;AAC7F,SAAO,MAAKC,OAAQ,QAAiC,KAAK,QAAQ;;CAGpE,MAAe,QAAuB;AACpC,QAAM,MAAKA,OAAQ,OAAO;;;AAI9B,SAAgB,mBAAmB,SAA4C;AAC7E,QAAO,IAAI,iBAAiB,QAAQ"}
1
+ {"version":3,"file":"index.mjs","names":["#adapter","#driver","#codecs"],"sources":["../src/mongo-execution-stack.ts","../src/codecs/decoding.ts","../src/content-hash.ts","../src/mongo-runtime.ts"],"sourcesContent":["import {\n createExecutionStack,\n type ExecutionStack,\n type RuntimeAdapterDescriptor,\n type RuntimeAdapterInstance,\n type RuntimeDriverDescriptor,\n type RuntimeDriverInstance,\n type RuntimeExtensionDescriptor,\n type RuntimeExtensionInstance,\n type RuntimeTargetDescriptor,\n type RuntimeTargetInstance,\n} from '@prisma-next/framework-components/execution';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { MongoCodec } from '@prisma-next/mongo-codec';\nimport { type MongoCodecRegistry, newMongoCodecRegistry } from '@prisma-next/mongo-codec';\nimport type { MongoAdapter } from '@prisma-next/mongo-lowering';\n\n/**\n * Mongo-specific static contributions a runtime descriptor declares.\n *\n * Mirrors `SqlStaticContributions` in shape: a `codecs()` getter that yields a `MongoCodecRegistry` populated with this contributor's codecs. The registry is then walked by `createMongoExecutionContext` and folded into the single per-execution registry the runtime reads from at decode time.\n */\nexport interface MongoStaticContributions {\n readonly codecs: () => MongoCodecRegistry;\n}\n\nexport interface MongoRuntimeTargetDescriptor<\n TTargetId extends string = 'mongo',\n TTargetInstance extends RuntimeTargetInstance<'mongo', TTargetId> = RuntimeTargetInstance<\n 'mongo',\n TTargetId\n >,\n> extends RuntimeTargetDescriptor<'mongo', TTargetId, TTargetInstance>,\n MongoStaticContributions {}\n\nexport interface MongoRuntimeAdapterInstance<TTargetId extends string = 'mongo'>\n extends RuntimeAdapterInstance<'mongo', TTargetId>,\n MongoAdapter {}\n\nexport interface MongoRuntimeAdapterDescriptor<\n TTargetId extends string = 'mongo',\n TAdapterInstance extends RuntimeAdapterInstance<\n 'mongo',\n TTargetId\n > = MongoRuntimeAdapterInstance<TTargetId>,\n> extends RuntimeAdapterDescriptor<'mongo', TTargetId, TAdapterInstance>,\n MongoStaticContributions {}\n\nexport interface MongoRuntimeExtensionInstance<TTargetId extends string = 'mongo'>\n extends RuntimeExtensionInstance<'mongo', TTargetId> {}\n\nexport interface MongoRuntimeExtensionDescriptor<TTargetId extends string = 'mongo'>\n extends RuntimeExtensionDescriptor<'mongo', TTargetId, MongoRuntimeExtensionInstance<TTargetId>>,\n MongoStaticContributions {\n create(): MongoRuntimeExtensionInstance<TTargetId>;\n}\n\n/**\n * The Mongo execution stack: target + adapter + optional driver + extension packs. Mirrors `SqlExecutionStack`. Constructed via `createMongoExecutionStack`.\n */\nexport interface MongoExecutionStack<TTargetId extends string = 'mongo'> {\n readonly target: MongoRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: MongoRuntimeAdapterDescriptor<TTargetId>;\n readonly driver:\n | RuntimeDriverDescriptor<\n 'mongo',\n TTargetId,\n unknown,\n RuntimeDriverInstance<'mongo', TTargetId>\n >\n | undefined;\n readonly extensionPacks: readonly MongoRuntimeExtensionDescriptor<TTargetId>[];\n}\n\nexport function createMongoExecutionStack<TTargetId extends string = 'mongo'>(options: {\n readonly target: MongoRuntimeTargetDescriptor<TTargetId>;\n readonly adapter: MongoRuntimeAdapterDescriptor<TTargetId>;\n readonly driver?:\n | RuntimeDriverDescriptor<\n 'mongo',\n TTargetId,\n unknown,\n RuntimeDriverInstance<'mongo', TTargetId>\n >\n | undefined;\n readonly extensionPacks?: readonly MongoRuntimeExtensionDescriptor<TTargetId>[] | undefined;\n}): MongoExecutionStack<TTargetId> {\n const stack = createExecutionStack({\n target: options.target,\n adapter: options.adapter,\n driver: options.driver,\n extensionPacks: options.extensionPacks,\n });\n return stack as ExecutionStack<'mongo', TTargetId> as MongoExecutionStack<TTargetId>;\n}\n\n/**\n * Read-only view of the codec registry exposed on `MongoExecutionContext`.\n *\n * Hides `register()` and the iterator from public surface — users do not mutate the per-execution codec registry. Internal aggregation in `createMongoExecutionContext` keeps using the full `MongoCodecRegistry` (it needs `register()`).\n */\nexport interface MongoCodecLookup {\n get(id: string): MongoCodec<string> | undefined;\n has(id: string): boolean;\n}\n\n/**\n * Per-execution context aggregated from a `MongoExecutionStack`.\n *\n * Carries the user's contract, a read-only lookup over the codec registry composed from every stack contributor, and a back-reference to the stack itself so the runtime can reach the adapter without users threading it explicitly.\n *\n * Mirrors SQL's `ExecutionContext` in role; Mongo's flavour is leaner because there are no parameterised codecs, JSON-schema validators, or mutation-default generators in scope yet.\n */\nexport interface MongoExecutionContext<TTargetId extends string = 'mongo'> {\n readonly contract: unknown;\n readonly codecs: MongoCodecLookup;\n readonly stack: MongoExecutionStack<TTargetId>;\n}\n\nexport function createMongoExecutionContext<TTargetId extends string = 'mongo'>(options: {\n readonly contract: unknown;\n readonly stack: MongoExecutionStack<TTargetId>;\n}): MongoExecutionContext<TTargetId> {\n const registry = newMongoCodecRegistry();\n const owners = new Map<string, string>();\n\n const contributors: ReadonlyArray<MongoStaticContributions & { readonly id: string }> = [\n options.stack.target,\n options.stack.adapter,\n ...options.stack.extensionPacks,\n ];\n\n for (const contributor of contributors) {\n const contributed = contributor.codecs();\n for (const codec of iterateCodecs(contributed)) {\n const existingOwner = owners.get(codec.id);\n if (existingOwner !== undefined) {\n throw runtimeError(\n 'RUNTIME.DUPLICATE_CODEC',\n `Duplicate Mongo codec id '${codec.id}' contributed by '${contributor.id}' (already registered by '${existingOwner}').`,\n { codecId: codec.id, existingOwner, incomingOwner: contributor.id },\n );\n }\n registry.register(codec);\n owners.set(codec.id, contributor.id);\n }\n }\n\n return Object.freeze({\n contract: options.contract,\n codecs: registry,\n stack: options.stack,\n });\n}\n\nfunction* iterateCodecs(registry: MongoCodecRegistry): Iterable<MongoCodec<string>> {\n yield* registry.values();\n}\n","import type { CodecCallContext } from '@prisma-next/framework-components/codec';\nimport { runtimeError } from '@prisma-next/framework-components/runtime';\nimport type { MongoFieldShape, MongoResultShape } from '@prisma-next/mongo-query-ast/execution';\nimport type { MongoCodecLookup } from '../mongo-execution-stack';\n\nconst WIRE_PREVIEW_LIMIT = 100;\n\nfunction previewWireValue(wireValue: unknown): string {\n if (typeof wireValue === 'string') {\n return wireValue.length > WIRE_PREVIEW_LIMIT\n ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...`\n : wireValue;\n }\n return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);\n}\n\nfunction wrapDecodeFailure(\n error: unknown,\n collection: string,\n path: string,\n codecId: string,\n wireValue: unknown,\n): never {\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.DECODE_FAILED',\n `Failed to decode field ${path} in collection '${collection}' with codec '${codecId}': ${message}`,\n {\n collection,\n path,\n codec: codecId,\n wirePreview: previewWireValue(wireValue),\n },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n\nexport async function decodeMongoRow(\n row: unknown,\n shape: MongoResultShape,\n registry: MongoCodecLookup,\n collection: string,\n ctx: CodecCallContext = {},\n): Promise<unknown> {\n if (shape.kind === 'unknown') {\n return row;\n }\n if (typeof row !== 'object' || row === null) {\n return row;\n }\n const rowObj = row as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n const tasks: Array<Promise<void>> = [];\n\n function scheduleLeaf(\n path: string,\n codecId: string,\n wire: unknown,\n assign: (v: unknown) => void,\n ): void {\n const codec = registry.get(codecId);\n if (!codec) {\n assign(wire);\n return;\n }\n tasks.push(\n (async () => {\n try {\n assign(await codec.decode(wire, ctx));\n } catch (error) {\n wrapDecodeFailure(error, collection, path, codecId, wire);\n }\n })(),\n );\n }\n\n function walkField(\n value: unknown,\n fieldShape: MongoFieldShape,\n path: string,\n assign: (v: unknown) => void,\n ): void {\n // Exhaustive over `MongoFieldShape['kind']` by construction:\n // adding a new variant must add a corresponding arm or the\n // `satisfies never` below would error at type-check time.\n switch (fieldShape.kind) {\n case 'unknown':\n assign(value);\n return;\n case 'leaf':\n if (value === null || value === undefined) {\n assign(value);\n return;\n }\n scheduleLeaf(path, fieldShape.codecId, value, assign);\n return;\n case 'document': {\n if (value === null || value === undefined) {\n assign(value);\n return;\n }\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n assign(value);\n return;\n }\n const vObj = value as Record<string, unknown>;\n // Pre-seed with a shallow copy so unshaped subdocument keys\n // round-trip verbatim. Subsequent walkField assignments overwrite\n // shaped keys with their decoded values. Mirrors the top-level\n // pass-through invariant — the decode path is structurally\n // additive at every nesting depth, not just the root.\n const nested: Record<string, unknown> = { ...vObj };\n assign(nested);\n for (const [fk, fShape] of Object.entries(fieldShape.fields)) {\n walkField(vObj[fk], fShape, `${path}.${fk}`, (v) => {\n nested[fk] = v;\n });\n }\n return;\n }\n case 'array': {\n if (value === null || value === undefined) {\n assign(value);\n return;\n }\n if (!Array.isArray(value)) {\n assign(value);\n return;\n }\n const arr: unknown[] = [];\n assign(arr);\n for (let i = 0; i < value.length; i++) {\n const el = value[i];\n walkField(el, fieldShape.element, `${path}.${i}`, (v) => {\n arr[i] = v;\n });\n }\n return;\n }\n }\n // The switch above is exhaustive over `MongoFieldShape['kind']`. The\n // `satisfies never` below is a compile-time guard that fails if a new\n // variant is added without a corresponding arm.\n /* v8 ignore start */\n fieldShape satisfies never;\n /* v8 ignore stop */\n }\n\n for (const [k, fShape] of Object.entries(shape.fields)) {\n walkField(rowObj[k], fShape, k, (v) => {\n out[k] = v;\n });\n }\n\n // Pass through any row fields the shape does not describe. The shape is a\n // partial, lane-vouched description of what the runtime knows how to decode;\n // fields outside that description (e.g. polymorphic variant fields the base\n // model's shape doesn't enumerate, sidecar fields a future schema migration\n // adds) round-trip verbatim. Drop semantics belongs to explicit projection\n // (`select` / `$project`), not to the structural decode path.\n for (const k of Object.keys(rowObj)) {\n if (!Object.hasOwn(shape.fields, k)) {\n out[k] = rowObj[k];\n }\n }\n\n await Promise.all(tasks);\n return out;\n}\n","import { canonicalStringify } from '@prisma-next/utils/canonical-stringify';\nimport { hashContent } from '@prisma-next/utils/hash-content';\nimport type { MongoExecutionPlan } from './mongo-execution-plan';\n\n/**\n * Computes a stable content hash for a lowered Mongo execution plan.\n *\n * Internally builds an unambiguous canonical-stringified preimage from\n * two components:\n *\n * 1. `meta.storageHash` — discriminates by schema. A migration changes the\n * storage hash, which invalidates cached entries automatically (no\n * per-app invalidation logic needed for schema changes).\n * 2. `exec.command` — the wire command. `canonicalStringify` produces a\n * deterministic serialization that is stable across object key\n * insertion order and that distinguishes types JSON would otherwise\n * conflate (e.g. `BigInt(1)` vs `1`, `Date` vs ISO string, `Buffer`\n * vs number array). The spread converts the frozen wire-command\n * class instance (`InsertOneWireCommand`, `AggregateWireCommand`, …)\n * into a plain object exposing its own enumerable properties\n * (`kind`, `collection`, plus the payload-specific fields like\n * `document`/`filter`/`update`/`pipeline`/…), which is what\n * `canonicalStringify` accepts; class instances are rejected\n * outright to prevent silent collisions.\n *\n * Unlike SQL, there is no separate \"rendered statement\" component because\n * a Mongo `MongoExecutionPlan.command` is the wire command itself —\n * canonicalizing it captures both structure and parameters in one pass.\n *\n * The components are wrapped in an object and canonicalized as a single\n * unit (rather than concatenated with a delimiter) so component\n * boundaries are unambiguous and cannot collide with a different split\n * of the same characters.\n *\n * The canonical string is then piped through `hashContent` to produce a\n * bounded, opaque digest. See `@prisma-next/utils/hash-content` for the\n * rationale.\n *\n * @internal\n */\nexport function computeMongoContentHash(exec: MongoExecutionPlan): Promise<string> {\n // Spread `exec.command` to a plain object: `canonicalStringify`\n // rejects class instances by design (so `Map`/`Set`/class instances\n // cannot collapse to `{}` and silently collide). All wire-command\n // data lives on own enumerable properties, so this preserves the\n // same canonical form and therefore the same hash.\n return hashContent(\n canonicalStringify({\n storageHash: exec.meta.storageHash,\n command: { ...exec.command },\n }),\n );\n}\n","import type { CodecCallContext } from '@prisma-next/framework-components/codec';\nimport {\n AsyncIterableResult,\n checkAborted,\n checkMiddlewareCompatibility,\n RuntimeCore,\n type RuntimeExecuteOptions,\n runWithMiddleware,\n} from '@prisma-next/framework-components/runtime';\nimport type { MongoAdapter, MongoDriver } from '@prisma-next/mongo-lowering';\nimport type { MongoQueryPlan } from '@prisma-next/mongo-query-ast/execution';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { decodeMongoRow } from './codecs/decoding';\nimport { computeMongoContentHash } from './content-hash';\nimport type { MongoExecutionPlan } from './mongo-execution-plan';\nimport type { MongoCodecLookup, MongoExecutionContext } from './mongo-execution-stack';\nimport type { MongoMiddleware, MongoMiddlewareContext } from './mongo-middleware';\n\nfunction noop() {}\n\n/**\n * Mongo runtime options.\n *\n * The runtime takes a {@link MongoExecutionContext} (built via\n * `createMongoExecutionContext`) and a driver. Codec resolution flows from\n * the context — there is no `codecs` field on this options bag. The adapter\n * is reached via `context.stack.adapter` (instantiated lazily through the\n * stack's `create(stack)` factory). See ADR — Mongo result-shape as a\n * structural plan field, § Codec registry: stack aggregation, not user\n * threading.\n */\nexport interface MongoRuntimeOptions {\n readonly context: MongoExecutionContext;\n readonly driver: MongoDriver;\n readonly middleware?: readonly MongoMiddleware[];\n readonly mode?: 'strict' | 'permissive';\n}\n\nexport interface MongoRuntime {\n /**\n * Execute a `MongoQueryPlan` and return an async iterable of rows.\n *\n * The optional `options.signal` is threaded through\n * `lower → adapter.lower → resolveValue → codec.encode` so codec authors\n * who forward the signal to their underlying SDK get true cancellation\n * of in-flight network calls. The runtime additionally observes the\n * signal at two boundaries:\n *\n * - **Already-aborted at entry** — first `next()` throws\n * `RUNTIME.ABORTED { phase: 'stream' }` before any work is done.\n * (Inherited from `RuntimeCore.execute`.)\n * - **Mid-encode abort** — surfaces as\n * `RUNTIME.ABORTED { phase: 'encode' }` from inside `resolveValue`'s\n * per-level `Promise.all` race.\n *\n * Mongo's read path decodes rows via `resultShape` (per ADR 209). The\n * same `CodecCallContext` is forwarded into each `codec.decode(wire, ctx)`\n * call, so async decoders that respect the signal get cancellation; the\n * runtime itself does not currently emit a `phase: 'decode'` envelope.\n */\n execute<Row>(\n plan: MongoQueryPlan<Row>,\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row>;\n close(): Promise<void>;\n}\n\nclass MongoRuntimeImpl\n extends RuntimeCore<MongoQueryPlan, MongoExecutionPlan, MongoMiddleware>\n implements MongoRuntime\n{\n readonly #adapter: MongoAdapter;\n readonly #driver: MongoDriver;\n readonly #codecs: MongoCodecLookup;\n\n constructor(options: MongoRuntimeOptions) {\n const middleware = options.middleware ? [...options.middleware] : [];\n const targetId = options.context.stack.target.targetId;\n for (const mw of middleware) {\n checkMiddlewareCompatibility(mw, 'mongo', targetId);\n }\n\n const ctx: MongoMiddlewareContext = {\n contract: options.context.contract,\n mode: options.mode ?? 'strict',\n now: () => Date.now(),\n log: { info: noop, warn: noop, error: noop },\n // ctx is only invoked by runWithMiddleware with execs this runtime lowered;\n // the framework parameter type is the cross-family base.\n contentHash: (exec) => computeMongoContentHash(exec as MongoExecutionPlan),\n };\n\n super({ middleware, ctx });\n\n const adapterDescriptor = options.context.stack.adapter;\n const adapterInstance = adapterDescriptor.create(options.context.stack);\n this.#adapter = adapterInstance;\n this.#driver = options.driver;\n this.#codecs = options.context.codecs;\n }\n\n protected override async lower(\n plan: MongoQueryPlan,\n ctx: CodecCallContext,\n ): Promise<MongoExecutionPlan> {\n return {\n command: await this.#adapter.lower(plan, ctx),\n meta: plan.meta,\n ...ifDefined('resultShape', plan.resultShape),\n };\n }\n\n protected override runDriver(exec: MongoExecutionPlan): AsyncIterable<Record<string, unknown>> {\n return this.#driver.execute<Record<string, unknown>>(exec.command);\n }\n\n override execute<Row>(\n plan: MongoQueryPlan & { readonly _row?: Row },\n options?: RuntimeExecuteOptions,\n ): AsyncIterableResult<Row> {\n const self = this;\n const signal = options?.signal;\n const codecCtx: CodecCallContext = signal === undefined ? {} : { signal };\n const generator = async function* (): AsyncGenerator<Row, void, unknown> {\n checkAborted(codecCtx, 'stream');\n const compiled = await self.runBeforeCompile(plan);\n const exec = await self.lower(compiled, codecCtx);\n const stream = runWithMiddleware<MongoExecutionPlan, Record<string, unknown>>(\n exec,\n self.middleware,\n self.ctx,\n () => self.runDriver(exec),\n );\n for await (const rawRow of stream) {\n if (exec.resultShape === undefined) {\n yield rawRow as Row;\n } else {\n // Source the collection from the lowered exec rather than the\n // pre-lowering plan: a `runBeforeCompile` middleware is allowed to\n // rewrite collection names during compilation, and the wire\n // command carried by `exec` is always authoritative for what just\n // ran.\n const decoded = await decodeMongoRow(\n rawRow,\n exec.resultShape,\n self.#codecs,\n exec.command.collection,\n codecCtx,\n );\n yield decoded as Row;\n }\n }\n };\n return new AsyncIterableResult(generator());\n }\n\n override async close(): Promise<void> {\n await this.#driver.close();\n }\n}\n\nex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o-runtime",
3
- "version": "0.5.0-dev.9",
3
+ "version": "0.5.0",
4
+ "license": "Apache-2.0",
4
5
  "type": "module",
5
6
  "sideEffects": false,
6
7
  "description": "MongoDB runtime implementation for Prisma Next",
7
8
  "dependencies": {
8
- "@prisma-next/mongo-lowering": "0.5.0-dev.9",
9
- "@prisma-next/contract": "0.5.0-dev.9",
10
- "@prisma-next/framework-components": "0.5.0-dev.9",
11
- "@prisma-next/mongo-query-ast": "0.5.0-dev.9",
12
- "@prisma-next/mongo-wire": "0.5.0-dev.9"
9
+ "@prisma-next/framework-components": "0.5.0",
10
+ "@prisma-next/contract": "0.5.0",
11
+ "@prisma-next/mongo-codec": "0.5.0",
12
+ "@prisma-next/mongo-lowering": "0.5.0",
13
+ "@prisma-next/mongo-query-ast": "0.5.0",
14
+ "@prisma-next/utils": "0.5.0",
15
+ "@prisma-next/mongo-wire": "0.5.0"
13
16
  },
14
17
  "devDependencies": {
15
18
  "mongodb": "^6.16.0",
16
- "mongodb-memory-server": "10.4.3",
17
- "tsdown": "0.18.4",
19
+ "mongodb-memory-server": "11.0.1",
20
+ "tsdown": "0.22.0",
18
21
  "typescript": "5.9.3",
19
- "vitest": "4.0.17",
20
- "@prisma-next/middleware-telemetry": "0.5.0-dev.9",
21
- "@prisma-next/adapter-mongo": "0.5.0-dev.9",
22
- "@prisma-next/family-mongo": "0.5.0-dev.9",
23
- "@prisma-next/mongo-contract-ts": "0.5.0-dev.9",
24
- "@prisma-next/mongo-query-builder": "0.5.0-dev.9",
25
- "@prisma-next/mongo-value": "0.5.0-dev.9",
26
- "@prisma-next/driver-mongo": "0.5.0-dev.9",
27
- "@prisma-next/mongo-contract": "0.5.0-dev.9",
28
- "@prisma-next/target-mongo": "0.5.0-dev.9",
29
- "@prisma-next/tsconfig": "0.0.0",
22
+ "vitest": "4.1.5",
23
+ "@prisma-next/adapter-mongo": "0.5.0",
24
+ "@prisma-next/middleware-telemetry": "0.5.0",
25
+ "@prisma-next/mongo-contract-ts": "0.5.0",
26
+ "@prisma-next/family-mongo": "0.5.0",
27
+ "@prisma-next/mongo-query-builder": "0.5.0",
28
+ "@prisma-next/mongo-value": "0.5.0",
29
+ "@prisma-next/driver-mongo": "0.5.0",
30
+ "@prisma-next/mongo-contract": "0.5.0",
31
+ "@prisma-next/target-mongo": "0.5.0",
32
+ "@prisma-next/test-utils": "0.0.1",
30
33
  "@prisma-next/tsdown": "0.0.0",
31
- "@prisma-next/test-utils": "0.0.1"
34
+ "@prisma-next/tsconfig": "0.0.0"
32
35
  },
33
36
  "files": [
34
37
  "dist",
@@ -0,0 +1,170 @@
1
+ import type { CodecCallContext } from '@prisma-next/framework-components/codec';
2
+ import { runtimeError } from '@prisma-next/framework-components/runtime';
3
+ import type { MongoFieldShape, MongoResultShape } from '@prisma-next/mongo-query-ast/execution';
4
+ import type { MongoCodecLookup } from '../mongo-execution-stack';
5
+
6
+ const WIRE_PREVIEW_LIMIT = 100;
7
+
8
+ function previewWireValue(wireValue: unknown): string {
9
+ if (typeof wireValue === 'string') {
10
+ return wireValue.length > WIRE_PREVIEW_LIMIT
11
+ ? `${wireValue.substring(0, WIRE_PREVIEW_LIMIT)}...`
12
+ : wireValue;
13
+ }
14
+ return String(wireValue).substring(0, WIRE_PREVIEW_LIMIT);
15
+ }
16
+
17
+ function wrapDecodeFailure(
18
+ error: unknown,
19
+ collection: string,
20
+ path: string,
21
+ codecId: string,
22
+ wireValue: unknown,
23
+ ): never {
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ const wrapped = runtimeError(
26
+ 'RUNTIME.DECODE_FAILED',
27
+ `Failed to decode field ${path} in collection '${collection}' with codec '${codecId}': ${message}`,
28
+ {
29
+ collection,
30
+ path,
31
+ codec: codecId,
32
+ wirePreview: previewWireValue(wireValue),
33
+ },
34
+ );
35
+ wrapped.cause = error;
36
+ throw wrapped;
37
+ }
38
+
39
+ export async function decodeMongoRow(
40
+ row: unknown,
41
+ shape: MongoResultShape,
42
+ registry: MongoCodecLookup,
43
+ collection: string,
44
+ ctx: CodecCallContext = {},
45
+ ): Promise<unknown> {
46
+ if (shape.kind === 'unknown') {
47
+ return row;
48
+ }
49
+ if (typeof row !== 'object' || row === null) {
50
+ return row;
51
+ }
52
+ const rowObj = row as Record<string, unknown>;
53
+ const out: Record<string, unknown> = {};
54
+ const tasks: Array<Promise<void>> = [];
55
+
56
+ function scheduleLeaf(
57
+ path: string,
58
+ codecId: string,
59
+ wire: unknown,
60
+ assign: (v: unknown) => void,
61
+ ): void {
62
+ const codec = registry.get(codecId);
63
+ if (!codec) {
64
+ assign(wire);
65
+ return;
66
+ }
67
+ tasks.push(
68
+ (async () => {
69
+ try {
70
+ assign(await codec.decode(wire, ctx));
71
+ } catch (error) {
72
+ wrapDecodeFailure(error, collection, path, codecId, wire);
73
+ }
74
+ })(),
75
+ );
76
+ }
77
+
78
+ function walkField(
79
+ value: unknown,
80
+ fieldShape: MongoFieldShape,
81
+ path: string,
82
+ assign: (v: unknown) => void,
83
+ ): void {
84
+ // Exhaustive over `MongoFieldShape['kind']` by construction:
85
+ // adding a new variant must add a corresponding arm or the
86
+ // `satisfies never` below would error at type-check time.
87
+ switch (fieldShape.kind) {
88
+ case 'unknown':
89
+ assign(value);
90
+ return;
91
+ case 'leaf':
92
+ if (value === null || value === undefined) {
93
+ assign(value);
94
+ return;
95
+ }
96
+ scheduleLeaf(path, fieldShape.codecId, value, assign);
97
+ return;
98
+ case 'document': {
99
+ if (value === null || value === undefined) {
100
+ assign(value);
101
+ return;
102
+ }
103
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
104
+ assign(value);
105
+ return;
106
+ }
107
+ const vObj = value as Record<string, unknown>;
108
+ // Pre-seed with a shallow copy so unshaped subdocument keys
109
+ // round-trip verbatim. Subsequent walkField assignments overwrite
110
+ // shaped keys with their decoded values. Mirrors the top-level
111
+ // pass-through invariant — the decode path is structurally
112
+ // additive at every nesting depth, not just the root.
113
+ const nested: Record<string, unknown> = { ...vObj };
114
+ assign(nested);
115
+ for (const [fk, fShape] of Object.entries(fieldShape.fields)) {
116
+ walkField(vObj[fk], fShape, `${path}.${fk}`, (v) => {
117
+ nested[fk] = v;
118
+ });
119
+ }
120
+ return;
121
+ }
122
+ case 'array': {
123
+ if (value === null || value === undefined) {
124
+ assign(value);
125
+ return;
126
+ }
127
+ if (!Array.isArray(value)) {
128
+ assign(value);
129
+ return;
130
+ }
131
+ const arr: unknown[] = [];
132
+ assign(arr);
133
+ for (let i = 0; i < value.length; i++) {
134
+ const el = value[i];
135
+ walkField(el, fieldShape.element, `${path}.${i}`, (v) => {
136
+ arr[i] = v;
137
+ });
138
+ }
139
+ return;
140
+ }
141
+ }
142
+ // The switch above is exhaustive over `MongoFieldShape['kind']`. The
143
+ // `satisfies never` below is a compile-time guard that fails if a new
144
+ // variant is added without a corresponding arm.
145
+ /* v8 ignore start */
146
+ fieldShape satisfies never;
147
+ /* v8 ignore stop */
148
+ }
149
+
150
+ for (const [k, fShape] of Object.entries(shape.fields)) {
151
+ walkField(rowObj[k], fShape, k, (v) => {
152
+ out[k] = v;
153
+ });
154
+ }
155
+
156
+ // Pass through any row fields the shape does not describe. The shape is a
157
+ // partial, lane-vouched description of what the runtime knows how to decode;
158
+ // fields outside that description (e.g. polymorphic variant fields the base
159
+ // model's shape doesn't enumerate, sidecar fields a future schema migration
160
+ // adds) round-trip verbatim. Drop semantics belongs to explicit projection
161
+ // (`select` / `$project`), not to the structural decode path.
162
+ for (const k of Object.keys(rowObj)) {
163
+ if (!Object.hasOwn(shape.fields, k)) {
164
+ out[k] = rowObj[k];
165
+ }
166
+ }
167
+
168
+ await Promise.all(tasks);
169
+ return out;
170
+ }
@@ -0,0 +1,53 @@
1
+ import { canonicalStringify } from '@prisma-next/utils/canonical-stringify';
2
+ import { hashContent } from '@prisma-next/utils/hash-content';
3
+ import type { MongoExecutionPlan } from './mongo-execution-plan';
4
+
5
+ /**
6
+ * Computes a stable content hash for a lowered Mongo execution plan.
7
+ *
8
+ * Internally builds an unambiguous canonical-stringified preimage from
9
+ * two components:
10
+ *
11
+ * 1. `meta.storageHash` — discriminates by schema. A migration changes the
12
+ * storage hash, which invalidates cached entries automatically (no
13
+ * per-app invalidation logic needed for schema changes).
14
+ * 2. `exec.command` — the wire command. `canonicalStringify` produces a
15
+ * deterministic serialization that is stable across object key
16
+ * insertion order and that distinguishes types JSON would otherwise
17
+ * conflate (e.g. `BigInt(1)` vs `1`, `Date` vs ISO string, `Buffer`
18
+ * vs number array). The spread converts the frozen wire-command
19
+ * class instance (`InsertOneWireCommand`, `AggregateWireCommand`, …)
20
+ * into a plain object exposing its own enumerable properties
21
+ * (`kind`, `collection`, plus the payload-specific fields like
22
+ * `document`/`filter`/`update`/`pipeline`/…), which is what
23
+ * `canonicalStringify` accepts; class instances are rejected
24
+ * outright to prevent silent collisions.
25
+ *
26
+ * Unlike SQL, there is no separate "rendered statement" component because
27
+ * a Mongo `MongoExecutionPlan.command` is the wire command itself —
28
+ * canonicalizing it captures both structure and parameters in one pass.
29
+ *
30
+ * The components are wrapped in an object and canonicalized as a single
31
+ * unit (rather than concatenated with a delimiter) so component
32
+ * boundaries are unambiguous and cannot collide with a different split
33
+ * of the same characters.
34
+ *
35
+ * The canonical string is then piped through `hashContent` to produce a
36
+ * bounded, opaque digest. See `@prisma-next/utils/hash-content` for the
37
+ * rationale.
38
+ *
39
+ * @internal
40
+ */
41
+ export function computeMongoContentHash(exec: MongoExecutionPlan): Promise<string> {
42
+ // Spread `exec.command` to a plain object: `canonicalStringify`
43
+ // rejects class instances by design (so `Map`/`Set`/class instances
44
+ // cannot collapse to `{}` and silently collide). All wire-command
45
+ // data lives on own enumerable properties, so this preserves the
46
+ // same canonical form and therefore the same hash.
47
+ return hashContent(
48
+ canonicalStringify({
49
+ storageHash: exec.meta.storageHash,
50
+ command: { ...exec.command },
51
+ }),
52
+ );
53
+ }
@@ -1,4 +1,20 @@
1
+ export type { RuntimeTargetInstance } from '@prisma-next/framework-components/execution';
1
2
  export type { MongoExecutionPlan } from '../mongo-execution-plan';
3
+ export type {
4
+ MongoCodecLookup,
5
+ MongoExecutionContext,
6
+ MongoExecutionStack,
7
+ MongoRuntimeAdapterDescriptor,
8
+ MongoRuntimeAdapterInstance,
9
+ MongoRuntimeExtensionDescriptor,
10
+ MongoRuntimeExtensionInstance,
11
+ MongoRuntimeTargetDescriptor,
12
+ MongoStaticContributions,
13
+ } from '../mongo-execution-stack';
14
+ export {
15
+ createMongoExecutionContext,
16
+ createMongoExecutionStack,
17
+ } from '../mongo-execution-stack';
2
18
  export type { MongoMiddleware, MongoMiddlewareContext } from '../mongo-middleware';
3
19
  export type { MongoRuntime, MongoRuntimeOptions } from '../mongo-runtime';
4
20
  export { createMongoRuntime } from '../mongo-runtime';
@@ -1,4 +1,5 @@
1
1
  import type { ExecutionPlan } from '@prisma-next/framework-components/runtime';
2
+ import type { MongoResultShape } from '@prisma-next/mongo-query-ast/execution';
2
3
  import type { AnyMongoWireCommand } from '@prisma-next/mongo-wire';
3
4
 
4
5
  /**
@@ -19,9 +20,9 @@ import type { AnyMongoWireCommand } from '@prisma-next/mongo-wire';
19
20
  * Lives in the runtime layer (alongside `MongoRuntime`) because the wire
20
21
  * command shape lives in the transport layer (`@prisma-next/mongo-wire`),
21
22
  * which the lanes layer (`mongo-query-ast`, where `MongoQueryPlan` lives)
22
- * cannot depend on. M1 establishes this type; `MongoRuntime.execute` does
23
- * not yet accept it as input — that adoption lands in M4.
23
+ * cannot depend on.
24
24
  */
25
25
  export interface MongoExecutionPlan<Row = unknown> extends ExecutionPlan<Row> {
26
26
  readonly command: AnyMongoWireCommand;
27
+ readonly resultShape?: MongoResultShape;
27
28
  }
@@ -0,0 +1,158 @@
1
+ import {
2
+ createExecutionStack,
3
+ type ExecutionStack,
4
+ type RuntimeAdapterDescriptor,
5
+ type RuntimeAdapterInstance,
6
+ type RuntimeDriverDescriptor,
7
+ type RuntimeDriverInstance,
8
+ type RuntimeExtensionDescriptor,
9
+ type RuntimeExtensionInstance,
10
+ type RuntimeTargetDescriptor,
11
+ type RuntimeTargetInstance,
12
+ } from '@prisma-next/framework-components/execution';
13
+ import { runtimeError } from '@prisma-next/framework-components/runtime';
14
+ import type { MongoCodec } from '@prisma-next/mongo-codec';
15
+ import { type MongoCodecRegistry, newMongoCodecRegistry } from '@prisma-next/mongo-codec';
16
+ import type { MongoAdapter } from '@prisma-next/mongo-lowering';
17
+
18
+ /**
19
+ * Mongo-specific static contributions a runtime descriptor declares.
20
+ *
21
+ * Mirrors `SqlStaticContributions` in shape: a `codecs()` getter that yields a `MongoCodecRegistry` populated with this contributor's codecs. The registry is then walked by `createMongoExecutionContext` and folded into the single per-execution registry the runtime reads from at decode time.
22
+ */
23
+ export interface MongoStaticContributions {
24
+ readonly codecs: () => MongoCodecRegistry;
25
+ }
26
+
27
+ export interface MongoRuntimeTargetDescriptor<
28
+ TTargetId extends string = 'mongo',
29
+ TTargetInstance extends RuntimeTargetInstance<'mongo', TTargetId> = RuntimeTargetInstance<
30
+ 'mongo',
31
+ TTargetId
32
+ >,
33
+ > extends RuntimeTargetDescriptor<'mongo', TTargetId, TTargetInstance>,
34
+ MongoStaticContributions {}
35
+
36
+ export interface MongoRuntimeAdapterInstance<TTargetId extends string = 'mongo'>
37
+ extends RuntimeAdapterInstance<'mongo', TTargetId>,
38
+ MongoAdapter {}
39
+
40
+ export interface MongoRuntimeAdapterDescriptor<
41
+ TTargetId extends string = 'mongo',
42
+ TAdapterInstance extends RuntimeAdapterInstance<
43
+ 'mongo',
44
+ TTargetId
45
+ > = MongoRuntimeAdapterInstance<TTargetId>,
46
+ > extends RuntimeAdapterDescriptor<'mongo', TTargetId, TAdapterInstance>,
47
+ MongoStaticContributions {}
48
+
49
+ export interface MongoRuntimeExtensionInstance<TTargetId extends string = 'mongo'>
50
+ extends RuntimeExtensionInstance<'mongo', TTargetId> {}
51
+
52
+ export interface MongoRuntimeExtensionDescriptor<TTargetId extends string = 'mongo'>
53
+ extends RuntimeExtensionDescriptor<'mongo', TTargetId, MongoRuntimeExtensionInstance<TTargetId>>,
54
+ MongoStaticContributions {
55
+ create(): MongoRuntimeExtensionInstance<TTargetId>;
56
+ }
57
+
58
+ /**
59
+ * The Mongo execution stack: target + adapter + optional driver + extension packs. Mirrors `SqlExecutionStack`. Constructed via `createMongoExecutionStack`.
60
+ */
61
+ export interface MongoExecutionStack<TTargetId extends string = 'mongo'> {
62
+ readonly target: MongoRuntimeTargetDescriptor<TTargetId>;
63
+ readonly adapter: MongoRuntimeAdapterDescriptor<TTargetId>;
64
+ readonly driver:
65
+ | RuntimeDriverDescriptor<
66
+ 'mongo',
67
+ TTargetId,
68
+ unknown,
69
+ RuntimeDriverInstance<'mongo', TTargetId>
70
+ >
71
+ | undefined;
72
+ readonly extensionPacks: readonly MongoRuntimeExtensionDescriptor<TTargetId>[];
73
+ }
74
+
75
+ export function createMongoExecutionStack<TTargetId extends string = 'mongo'>(options: {
76
+ readonly target: MongoRuntimeTargetDescriptor<TTargetId>;
77
+ readonly adapter: MongoRuntimeAdapterDescriptor<TTargetId>;
78
+ readonly driver?:
79
+ | RuntimeDriverDescriptor<
80
+ 'mongo',
81
+ TTargetId,
82
+ unknown,
83
+ RuntimeDriverInstance<'mongo', TTargetId>
84
+ >
85
+ | undefined;
86
+ readonly extensionPacks?: readonly MongoRuntimeExtensionDescriptor<TTargetId>[] | undefined;
87
+ }): MongoExecutionStack<TTargetId> {
88
+ const stack = createExecutionStack({
89
+ target: options.target,
90
+ adapter: options.adapter,
91
+ driver: options.driver,
92
+ extensionPacks: options.extensionPacks,
93
+ });
94
+ return stack as ExecutionStack<'mongo', TTargetId> as MongoExecutionStack<TTargetId>;
95
+ }
96
+
97
+ /**
98
+ * Read-only view of the codec registry exposed on `MongoExecutionContext`.
99
+ *
100
+ * Hides `register()` and the iterator from public surface — users do not mutate the per-execution codec registry. Internal aggregation in `createMongoExecutionContext` keeps using the full `MongoCodecRegistry` (it needs `register()`).
101
+ */
102
+ export interface MongoCodecLookup {
103
+ get(id: string): MongoCodec<string> | undefined;
104
+ has(id: string): boolean;
105
+ }
106
+
107
+ /**
108
+ * Per-execution context aggregated from a `MongoExecutionStack`.
109
+ *
110
+ * Carries the user's contract, a read-only lookup over the codec registry composed from every stack contributor, and a back-reference to the stack itself so the runtime can reach the adapter without users threading it explicitly.
111
+ *
112
+ * Mirrors SQL's `ExecutionContext` in role; Mongo's flavour is leaner because there are no parameterised codecs, JSON-schema validators, or mutation-default generators in scope yet.
113
+ */
114
+ export interface MongoExecutionContext<TTargetId extends string = 'mongo'> {
115
+ readonly contract: unknown;
116
+ readonly codecs: MongoCodecLookup;
117
+ readonly stack: MongoExecutionStack<TTargetId>;
118
+ }
119
+
120
+ export function createMongoExecutionContext<TTargetId extends string = 'mongo'>(options: {
121
+ readonly contract: unknown;
122
+ readonly stack: MongoExecutionStack<TTargetId>;
123
+ }): MongoExecutionContext<TTargetId> {
124
+ const registry = newMongoCodecRegistry();
125
+ const owners = new Map<string, string>();
126
+
127
+ const contributors: ReadonlyArray<MongoStaticContributions & { readonly id: string }> = [
128
+ options.stack.target,
129
+ options.stack.adapter,
130
+ ...options.stack.extensionPacks,
131
+ ];
132
+
133
+ for (const contributor of contributors) {
134
+ const contributed = contributor.codecs();
135
+ for (const codec of iterateCodecs(contributed)) {
136
+ const existingOwner = owners.get(codec.id);
137
+ if (existingOwner !== undefined) {
138
+ throw runtimeError(
139
+ 'RUNTIME.DUPLICATE_CODEC',
140
+ `Duplicate Mongo codec id '${codec.id}' contributed by '${contributor.id}' (already registered by '${existingOwner}').`,
141
+ { codecId: codec.id, existingOwner, incomingOwner: contributor.id },
142
+ );
143
+ }
144
+ registry.register(codec);
145
+ owners.set(codec.id, contributor.id);
146
+ }
147
+ }
148
+
149
+ return Object.freeze({
150
+ contract: options.contract,
151
+ codecs: registry,
152
+ stack: options.stack,
153
+ });
154
+ }
155
+
156
+ function* iterateCodecs(registry: MongoCodecRegistry): Iterable<MongoCodec<string>> {
157
+ yield* registry.values();
158
+ }
@@ -1,5 +1,6 @@
1
1
  import type {
2
2
  AfterExecuteResult,
3
+ ParamRefMutator,
3
4
  RuntimeMiddleware,
4
5
  RuntimeMiddlewareContext,
5
6
  } from '@prisma-next/framework-components/runtime';
@@ -20,7 +21,11 @@ export interface MongoMiddlewareContext extends RuntimeMiddlewareContext {}
20
21
  */
21
22
  export interface MongoMiddleware extends RuntimeMiddleware<MongoExecutionPlan> {
22
23
  readonly familyId?: 'mongo';
23
- beforeExecute?(plan: MongoExecutionPlan, ctx: MongoMiddlewareContext): Promise<void>;
24
+ beforeExecute?(
25
+ plan: MongoExecutionPlan,
26
+ ctx: MongoMiddlewareContext,
27
+ params?: ParamRefMutator,
28
+ ): void | Promise<void>;
24
29
  onRow?(
25
30
  row: Record<string, unknown>,
26
31
  plan: MongoExecutionPlan,
@@ -1,26 +1,67 @@
1
- import type { AsyncIterableResult } from '@prisma-next/framework-components/runtime';
1
+ import type { CodecCallContext } from '@prisma-next/framework-components/codec';
2
2
  import {
3
+ AsyncIterableResult,
4
+ checkAborted,
3
5
  checkMiddlewareCompatibility,
4
6
  RuntimeCore,
7
+ type RuntimeExecuteOptions,
8
+ runWithMiddleware,
5
9
  } from '@prisma-next/framework-components/runtime';
6
10
  import type { MongoAdapter, MongoDriver } from '@prisma-next/mongo-lowering';
7
11
  import type { MongoQueryPlan } from '@prisma-next/mongo-query-ast/execution';
12
+ import { ifDefined } from '@prisma-next/utils/defined';
13
+ import { decodeMongoRow } from './codecs/decoding';
14
+ import { computeMongoContentHash } from './content-hash';
8
15
  import type { MongoExecutionPlan } from './mongo-execution-plan';
16
+ import type { MongoCodecLookup, MongoExecutionContext } from './mongo-execution-stack';
9
17
  import type { MongoMiddleware, MongoMiddlewareContext } from './mongo-middleware';
10
18
 
11
19
  function noop() {}
12
20
 
21
+ /**
22
+ * Mongo runtime options.
23
+ *
24
+ * The runtime takes a {@link MongoExecutionContext} (built via
25
+ * `createMongoExecutionContext`) and a driver. Codec resolution flows from
26
+ * the context — there is no `codecs` field on this options bag. The adapter
27
+ * is reached via `context.stack.adapter` (instantiated lazily through the
28
+ * stack's `create(stack)` factory). See ADR — Mongo result-shape as a
29
+ * structural plan field, § Codec registry: stack aggregation, not user
30
+ * threading.
31
+ */
13
32
  export interface MongoRuntimeOptions {
14
- readonly adapter: MongoAdapter;
33
+ readonly context: MongoExecutionContext;
15
34
  readonly driver: MongoDriver;
16
- readonly contract: unknown;
17
- readonly targetId: string;
18
35
  readonly middleware?: readonly MongoMiddleware[];
19
36
  readonly mode?: 'strict' | 'permissive';
20
37
  }
21
38
 
22
39
  export interface MongoRuntime {
23
- execute<Row>(plan: MongoQueryPlan<Row>): AsyncIterableResult<Row>;
40
+ /**
41
+ * Execute a `MongoQueryPlan` and return an async iterable of rows.
42
+ *
43
+ * The optional `options.signal` is threaded through
44
+ * `lower → adapter.lower → resolveValue → codec.encode` so codec authors
45
+ * who forward the signal to their underlying SDK get true cancellation
46
+ * of in-flight network calls. The runtime additionally observes the
47
+ * signal at two boundaries:
48
+ *
49
+ * - **Already-aborted at entry** — first `next()` throws
50
+ * `RUNTIME.ABORTED { phase: 'stream' }` before any work is done.
51
+ * (Inherited from `RuntimeCore.execute`.)
52
+ * - **Mid-encode abort** — surfaces as
53
+ * `RUNTIME.ABORTED { phase: 'encode' }` from inside `resolveValue`'s
54
+ * per-level `Promise.all` race.
55
+ *
56
+ * Mongo's read path decodes rows via `resultShape` (per ADR 209). The
57
+ * same `CodecCallContext` is forwarded into each `codec.decode(wire, ctx)`
58
+ * call, so async decoders that respect the signal get cancellation; the
59
+ * runtime itself does not currently emit a `phase: 'decode'` envelope.
60
+ */
61
+ execute<Row>(
62
+ plan: MongoQueryPlan<Row>,
63
+ options?: RuntimeExecuteOptions,
64
+ ): AsyncIterableResult<Row>;
24
65
  close(): Promise<void>;
25
66
  }
26
67
 
@@ -30,30 +71,42 @@ class MongoRuntimeImpl
30
71
  {
31
72
  readonly #adapter: MongoAdapter;
32
73
  readonly #driver: MongoDriver;
74
+ readonly #codecs: MongoCodecLookup;
33
75
 
34
76
  constructor(options: MongoRuntimeOptions) {
35
77
  const middleware = options.middleware ? [...options.middleware] : [];
78
+ const targetId = options.context.stack.target.targetId;
36
79
  for (const mw of middleware) {
37
- checkMiddlewareCompatibility(mw, 'mongo', options.targetId);
80
+ checkMiddlewareCompatibility(mw, 'mongo', targetId);
38
81
  }
39
82
 
40
83
  const ctx: MongoMiddlewareContext = {
41
- contract: options.contract,
84
+ contract: options.context.contract,
42
85
  mode: options.mode ?? 'strict',
43
86
  now: () => Date.now(),
44
87
  log: { info: noop, warn: noop, error: noop },
88
+ // ctx is only invoked by runWithMiddleware with execs this runtime lowered;
89
+ // the framework parameter type is the cross-family base.
90
+ contentHash: (exec) => computeMongoContentHash(exec as MongoExecutionPlan),
45
91
  };
46
92
 
47
93
  super({ middleware, ctx });
48
94
 
49
- this.#adapter = options.adapter;
95
+ const adapterDescriptor = options.context.stack.adapter;
96
+ const adapterInstance = adapterDescriptor.create(options.context.stack);
97
+ this.#adapter = adapterInstance;
50
98
  this.#driver = options.driver;
99
+ this.#codecs = options.context.codecs;
51
100
  }
52
101
 
53
- protected override async lower(plan: MongoQueryPlan): Promise<MongoExecutionPlan> {
102
+ protected override async lower(
103
+ plan: MongoQueryPlan,
104
+ ctx: CodecCallContext,
105
+ ): Promise<MongoExecutionPlan> {
54
106
  return {
55
- command: await this.#adapter.lower(plan),
107
+ command: await this.#adapter.lower(plan, ctx),
56
108
  meta: plan.meta,
109
+ ...ifDefined('resultShape', plan.resultShape),
57
110
  };
58
111
  }
59
112
 
@@ -61,6 +114,46 @@ class MongoRuntimeImpl
61
114
  return this.#driver.execute<Record<string, unknown>>(exec.command);
62
115
  }
63
116
 
117
+ override execute<Row>(
118
+ plan: MongoQueryPlan & { readonly _row?: Row },
119
+ options?: RuntimeExecuteOptions,
120
+ ): AsyncIterableResult<Row> {
121
+ const self = this;
122
+ const signal = options?.signal;
123
+ const codecCtx: CodecCallContext = signal === undefined ? {} : { signal };
124
+ const generator = async function* (): AsyncGenerator<Row, void, unknown> {
125
+ checkAborted(codecCtx, 'stream');
126
+ const compiled = await self.runBeforeCompile(plan);
127
+ const exec = await self.lower(compiled, codecCtx);
128
+ const stream = runWithMiddleware<MongoExecutionPlan, Record<string, unknown>>(
129
+ exec,
130
+ self.middleware,
131
+ self.ctx,
132
+ () => self.runDriver(exec),
133
+ );
134
+ for await (const rawRow of stream) {
135
+ if (exec.resultShape === undefined) {
136
+ yield rawRow as Row;
137
+ } else {
138
+ // Source the collection from the lowered exec rather than the
139
+ // pre-lowering plan: a `runBeforeCompile` middleware is allowed to
140
+ // rewrite collection names during compilation, and the wire
141
+ // command carried by `exec` is always authoritative for what just
142
+ // ran.
143
+ const decoded = await decodeMongoRow(
144
+ rawRow,
145
+ exec.resultShape,
146
+ self.#codecs,
147
+ exec.command.collection,
148
+ codecCtx,
149
+ );
150
+ yield decoded as Row;
151
+ }
152
+ }
153
+ };
154
+ return new AsyncIterableResult(generator());
155
+ }
156
+
64
157
  override async close(): Promise<void> {
65
158
  await this.#driver.close();
66
159
  }