@prisma-next/adapter-mongo 0.11.0-dev.9 → 0.12.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.
@@ -1,12 +1,11 @@
1
1
  import type { CodecCallContext } from '@prisma-next/framework-components/codec';
2
2
  import type { MongoCodecRegistry } from '@prisma-next/mongo-codec';
3
- import type { MongoAdapter } from '@prisma-next/mongo-lowering';
3
+ import type { MongoAdapter, MongoLoweredDraft } from '@prisma-next/mongo-lowering';
4
4
  import type {
5
5
  MongoQueryPlan,
6
6
  MongoUpdatePipelineStage,
7
7
  MongoUpdateSpec,
8
8
  } from '@prisma-next/mongo-query-ast/execution';
9
- import type { Document, MongoExpr } from '@prisma-next/mongo-value';
10
9
  import type { AnyMongoWireCommand } from '@prisma-next/mongo-wire';
11
10
  import {
12
11
  AggregateWireCommand,
@@ -19,9 +18,10 @@ import {
19
18
  UpdateManyWireCommand,
20
19
  UpdateOneWireCommand,
21
20
  } from '@prisma-next/mongo-wire';
21
+ import { blindCast } from '@prisma-next/utils/casts';
22
22
  import { buildStandardCodecRegistry } from './core/codecs';
23
- import { lowerFilter, lowerPipeline, lowerStage } from './lowering';
24
- import { resolveValue } from './resolve-value';
23
+ import { structuralLowerFilter, structuralLowerPipeline } from './lowering';
24
+ import { resolveDraftDoc } from './resolve-value';
25
25
 
26
26
  function isUpdatePipeline(
27
27
  update: MongoUpdateSpec,
@@ -29,6 +29,23 @@ function isUpdatePipeline(
29
29
  return Array.isArray(update);
30
30
  }
31
31
 
32
+ function isDraftUpdatePipeline(
33
+ update: Record<string, unknown> | ReadonlyArray<Record<string, unknown>>,
34
+ ): update is ReadonlyArray<Record<string, unknown>> {
35
+ return Array.isArray(update);
36
+ }
37
+
38
+ async function resolveUpdate(
39
+ update: Record<string, unknown> | ReadonlyArray<Record<string, unknown>>,
40
+ codecs: MongoCodecRegistry,
41
+ ctx: CodecCallContext,
42
+ ): Promise<Record<string, unknown> | ReadonlyArray<Record<string, unknown>>> {
43
+ if (isDraftUpdatePipeline(update)) {
44
+ return Promise.all(update.map((stage) => resolveDraftDoc(stage, codecs, ctx)));
45
+ }
46
+ return resolveDraftDoc(update, codecs, ctx);
47
+ }
48
+
32
49
  class MongoAdapterImpl implements MongoAdapter {
33
50
  readonly #codecs: MongoCodecRegistry;
34
51
 
@@ -36,125 +53,237 @@ class MongoAdapterImpl implements MongoAdapter {
36
53
  this.#codecs = codecs;
37
54
  }
38
55
 
39
- async #resolveDocument(expr: MongoExpr, ctx: CodecCallContext): Promise<Document> {
40
- const entries = Object.entries(expr);
41
- const resolved = await Promise.all(
42
- entries.map(([, val]) => resolveValue(val, this.#codecs, ctx)),
43
- );
44
- const result: Record<string, unknown> = {};
45
- for (let i = 0; i < entries.length; i++) {
46
- const entry = entries[i];
47
- if (entry) {
48
- result[entry[0]] = resolved[i];
56
+ structuralLower(plan: MongoQueryPlan): MongoLoweredDraft {
57
+ const { command } = plan;
58
+ switch (command.kind) {
59
+ case 'insertOne':
60
+ return { kind: 'insertOne', collection: command.collection, document: command.document };
61
+ case 'insertMany':
62
+ return {
63
+ kind: 'insertMany',
64
+ collection: command.collection,
65
+ documents: command.documents,
66
+ };
67
+ case 'updateOne':
68
+ return {
69
+ kind: 'updateOne',
70
+ collection: command.collection,
71
+ filter: structuralLowerFilter(command.filter),
72
+ update: isUpdatePipeline(command.update)
73
+ ? structuralLowerPipeline(command.update)
74
+ : command.update,
75
+ upsert: command.upsert,
76
+ };
77
+ case 'updateMany':
78
+ return {
79
+ kind: 'updateMany',
80
+ collection: command.collection,
81
+ filter: structuralLowerFilter(command.filter),
82
+ update: isUpdatePipeline(command.update)
83
+ ? structuralLowerPipeline(command.update)
84
+ : command.update,
85
+ upsert: command.upsert,
86
+ };
87
+ case 'deleteOne':
88
+ return {
89
+ kind: 'deleteOne',
90
+ collection: command.collection,
91
+ filter: structuralLowerFilter(command.filter),
92
+ };
93
+ case 'deleteMany':
94
+ return {
95
+ kind: 'deleteMany',
96
+ collection: command.collection,
97
+ filter: structuralLowerFilter(command.filter),
98
+ };
99
+ case 'findOneAndUpdate':
100
+ return {
101
+ kind: 'findOneAndUpdate',
102
+ collection: command.collection,
103
+ filter: structuralLowerFilter(command.filter),
104
+ update: isUpdatePipeline(command.update)
105
+ ? structuralLowerPipeline(command.update)
106
+ : command.update,
107
+ upsert: command.upsert,
108
+ sort: command.sort,
109
+ returnDocument: command.returnDocument,
110
+ };
111
+ case 'findOneAndDelete':
112
+ return {
113
+ kind: 'findOneAndDelete',
114
+ collection: command.collection,
115
+ filter: structuralLowerFilter(command.filter),
116
+ sort: command.sort,
117
+ };
118
+ case 'aggregate':
119
+ return {
120
+ kind: 'aggregate',
121
+ collection: command.collection,
122
+ pipeline: structuralLowerPipeline(command.pipeline),
123
+ };
124
+ case 'rawAggregate':
125
+ return { kind: 'rawAggregate', collection: command.collection, pipeline: command.pipeline };
126
+ case 'rawInsertOne':
127
+ return {
128
+ kind: 'rawInsertOne',
129
+ collection: command.collection,
130
+ document: command.document,
131
+ };
132
+ case 'rawInsertMany':
133
+ return {
134
+ kind: 'rawInsertMany',
135
+ collection: command.collection,
136
+ documents: command.documents,
137
+ };
138
+ case 'rawUpdateOne':
139
+ return {
140
+ kind: 'rawUpdateOne',
141
+ collection: command.collection,
142
+ filter: command.filter,
143
+ update: command.update,
144
+ };
145
+ case 'rawUpdateMany':
146
+ return {
147
+ kind: 'rawUpdateMany',
148
+ collection: command.collection,
149
+ filter: command.filter,
150
+ update: command.update,
151
+ };
152
+ case 'rawDeleteOne':
153
+ return { kind: 'rawDeleteOne', collection: command.collection, filter: command.filter };
154
+ case 'rawDeleteMany':
155
+ return { kind: 'rawDeleteMany', collection: command.collection, filter: command.filter };
156
+ case 'rawFindOneAndUpdate':
157
+ return {
158
+ kind: 'rawFindOneAndUpdate',
159
+ collection: command.collection,
160
+ filter: command.filter,
161
+ update: command.update,
162
+ upsert: command.upsert,
163
+ sort: command.sort,
164
+ returnDocument: command.returnDocument,
165
+ };
166
+ case 'rawFindOneAndDelete':
167
+ return {
168
+ kind: 'rawFindOneAndDelete',
169
+ collection: command.collection,
170
+ filter: command.filter,
171
+ sort: command.sort,
172
+ };
173
+ // v8 ignore next 4
174
+ default: {
175
+ const _exhaustive: never = command;
176
+ throw new Error(
177
+ `Unknown command kind: ${blindCast<{ kind: string }, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,
178
+ );
49
179
  }
50
180
  }
51
- return result;
52
181
  }
53
182
 
54
- async #lowerUpdate(
55
- update: MongoUpdateSpec,
183
+ async resolveParams(
184
+ draft: MongoLoweredDraft,
56
185
  ctx: CodecCallContext,
57
- ): Promise<Document | ReadonlyArray<Document>> {
58
- if (isUpdatePipeline(update)) {
59
- return Promise.all(update.map((stage) => lowerStage(stage, this.#codecs, ctx)));
60
- }
61
- return this.#resolveDocument(update, ctx);
62
- }
63
-
64
- async lower(plan: MongoQueryPlan, ctx: CodecCallContext): Promise<AnyMongoWireCommand> {
65
- const { command } = plan;
66
- switch (command.kind) {
186
+ ): Promise<AnyMongoWireCommand> {
187
+ switch (draft.kind) {
67
188
  case 'insertOne':
68
189
  return new InsertOneWireCommand(
69
- command.collection,
70
- await this.#resolveDocument(command.document, ctx),
190
+ draft.collection,
191
+ await resolveDraftDoc(draft.document, this.#codecs, ctx),
192
+ );
193
+ case 'insertMany':
194
+ return new InsertManyWireCommand(
195
+ draft.collection,
196
+ await Promise.all(draft.documents.map((doc) => resolveDraftDoc(doc, this.#codecs, ctx))),
71
197
  );
72
198
  case 'updateOne': {
73
199
  const [filter, update] = await Promise.all([
74
- lowerFilter(command.filter, this.#codecs, ctx),
75
- this.#lowerUpdate(command.update, ctx),
200
+ resolveDraftDoc(draft.filter, this.#codecs, ctx),
201
+ resolveUpdate(draft.update, this.#codecs, ctx),
76
202
  ]);
77
- return new UpdateOneWireCommand(command.collection, filter, update, command.upsert);
203
+ return new UpdateOneWireCommand(draft.collection, filter, update, draft.upsert);
78
204
  }
79
- case 'insertMany':
80
- return new InsertManyWireCommand(
81
- command.collection,
82
- await Promise.all(command.documents.map((doc) => this.#resolveDocument(doc, ctx))),
83
- );
84
205
  case 'updateMany': {
85
206
  const [filter, update] = await Promise.all([
86
- lowerFilter(command.filter, this.#codecs, ctx),
87
- this.#lowerUpdate(command.update, ctx),
207
+ resolveDraftDoc(draft.filter, this.#codecs, ctx),
208
+ resolveUpdate(draft.update, this.#codecs, ctx),
88
209
  ]);
89
- return new UpdateManyWireCommand(command.collection, filter, update, command.upsert);
210
+ return new UpdateManyWireCommand(draft.collection, filter, update, draft.upsert);
90
211
  }
91
212
  case 'deleteOne':
92
213
  return new DeleteOneWireCommand(
93
- command.collection,
94
- await lowerFilter(command.filter, this.#codecs, ctx),
214
+ draft.collection,
215
+ await resolveDraftDoc(draft.filter, this.#codecs, ctx),
95
216
  );
96
217
  case 'deleteMany':
97
218
  return new DeleteManyWireCommand(
98
- command.collection,
99
- await lowerFilter(command.filter, this.#codecs, ctx),
219
+ draft.collection,
220
+ await resolveDraftDoc(draft.filter, this.#codecs, ctx),
100
221
  );
101
222
  case 'findOneAndUpdate': {
102
223
  const [filter, update] = await Promise.all([
103
- lowerFilter(command.filter, this.#codecs, ctx),
104
- this.#lowerUpdate(command.update, ctx),
224
+ resolveDraftDoc(draft.filter, this.#codecs, ctx),
225
+ resolveUpdate(draft.update, this.#codecs, ctx),
105
226
  ]);
106
227
  return new FindOneAndUpdateWireCommand(
107
- command.collection,
228
+ draft.collection,
108
229
  filter,
109
230
  update,
110
- command.upsert,
111
- command.sort,
112
- command.returnDocument,
231
+ draft.upsert,
232
+ draft.sort,
233
+ draft.returnDocument,
113
234
  );
114
235
  }
115
236
  case 'findOneAndDelete':
116
237
  return new FindOneAndDeleteWireCommand(
117
- command.collection,
118
- await lowerFilter(command.filter, this.#codecs, ctx),
119
- command.sort,
238
+ draft.collection,
239
+ await resolveDraftDoc(draft.filter, this.#codecs, ctx),
240
+ draft.sort,
120
241
  );
121
242
  case 'aggregate':
122
243
  return new AggregateWireCommand(
123
- command.collection,
124
- await lowerPipeline(command.pipeline, this.#codecs, ctx),
244
+ draft.collection,
245
+ await Promise.all(
246
+ draft.pipeline.map((stage) => resolveDraftDoc(stage, this.#codecs, ctx)),
247
+ ),
125
248
  );
126
249
  case 'rawAggregate':
127
- return new AggregateWireCommand(command.collection, command.pipeline);
250
+ return new AggregateWireCommand(draft.collection, draft.pipeline);
128
251
  case 'rawInsertOne':
129
- return new InsertOneWireCommand(command.collection, command.document);
252
+ return new InsertOneWireCommand(draft.collection, draft.document);
130
253
  case 'rawInsertMany':
131
- return new InsertManyWireCommand(command.collection, command.documents);
254
+ return new InsertManyWireCommand(draft.collection, draft.documents);
132
255
  case 'rawUpdateOne':
133
- return new UpdateOneWireCommand(command.collection, command.filter, command.update);
256
+ return new UpdateOneWireCommand(draft.collection, draft.filter, draft.update);
134
257
  case 'rawUpdateMany':
135
- return new UpdateManyWireCommand(command.collection, command.filter, command.update);
258
+ return new UpdateManyWireCommand(draft.collection, draft.filter, draft.update);
136
259
  case 'rawDeleteOne':
137
- return new DeleteOneWireCommand(command.collection, command.filter);
260
+ return new DeleteOneWireCommand(draft.collection, draft.filter);
138
261
  case 'rawDeleteMany':
139
- return new DeleteManyWireCommand(command.collection, command.filter);
262
+ return new DeleteManyWireCommand(draft.collection, draft.filter);
140
263
  case 'rawFindOneAndUpdate':
141
264
  return new FindOneAndUpdateWireCommand(
142
- command.collection,
143
- command.filter,
144
- command.update,
145
- command.upsert,
146
- command.sort,
147
- command.returnDocument,
265
+ draft.collection,
266
+ draft.filter,
267
+ draft.update,
268
+ draft.upsert,
269
+ draft.sort,
270
+ draft.returnDocument,
148
271
  );
149
272
  case 'rawFindOneAndDelete':
150
- return new FindOneAndDeleteWireCommand(command.collection, command.filter, command.sort);
273
+ return new FindOneAndDeleteWireCommand(draft.collection, draft.filter, draft.sort);
151
274
  // v8 ignore next 4
152
275
  default: {
153
- const _exhaustive: never = command;
154
- throw new Error(`Unknown command kind: ${(_exhaustive as { kind: string }).kind}`);
276
+ const _exhaustive: never = draft;
277
+ throw new Error(
278
+ `Unknown draft kind: ${blindCast<{ kind: string }, 'exhaustive switch fallback for error message'>(_exhaustive).kind}`,
279
+ );
155
280
  }
156
281
  }
157
282
  }
283
+
284
+ lower(plan: MongoQueryPlan, ctx: CodecCallContext): Promise<AnyMongoWireCommand> {
285
+ return this.resolveParams(this.structuralLower(plan), ctx);
286
+ }
158
287
  }
159
288
 
160
289
  /**
@@ -5,8 +5,9 @@ import {
5
5
  runtimeError,
6
6
  } from '@prisma-next/framework-components/runtime';
7
7
  import type { MongoCodecRegistry } from '@prisma-next/mongo-codec';
8
- import type { MongoValue } from '@prisma-next/mongo-value';
8
+ import type { Document, MongoValue } from '@prisma-next/mongo-value';
9
9
  import { MongoParamRef } from '@prisma-next/mongo-value';
10
+ import { blindCast } from '@prisma-next/utils/casts';
10
11
 
11
12
  /**
12
13
  * Resolves a `MongoValue` (which may contain `MongoParamRef` leaves) into the
@@ -90,16 +91,73 @@ export async function resolveValue(
90
91
  return result;
91
92
  }
92
93
 
94
+ /**
95
+ * Resolves a draft slot value — which may be `MongoParamRef`, a primitive, a
96
+ * nested plain-object, or an array — into the corresponding wire value.
97
+ * Mirrors `resolveValue`'s traversal strategy but accepts `unknown` so it can
98
+ * handle pipeline stage documents whose field types cannot be narrowed to
99
+ * `MongoValue` statically (e.g. `$geoNear.near: unknown`).
100
+ */
101
+ async function resolveDraftSlot(
102
+ value: unknown,
103
+ codecs: MongoCodecRegistry,
104
+ ctx: CodecCallContext,
105
+ ): Promise<unknown> {
106
+ if (value instanceof MongoParamRef) {
107
+ return resolveValue(value, codecs, ctx);
108
+ }
109
+ if (value === null || typeof value !== 'object') return value;
110
+ if (value instanceof Date) return value;
111
+ if (Array.isArray(value)) {
112
+ const tasks = Promise.all(value.map((v: unknown) => resolveDraftSlot(v, codecs, ctx)));
113
+ return raceAgainstAbort(tasks, ctx.signal, 'encode');
114
+ }
115
+ return resolveDraftDoc(
116
+ blindCast<
117
+ Record<string, unknown>,
118
+ 'narrowed by instanceof/typeof guards: non-null, non-Date, non-array object'
119
+ >(value),
120
+ codecs,
121
+ ctx,
122
+ );
123
+ }
124
+
125
+ /**
126
+ * Resolves a pipeline stage draft document by walking every entry and
127
+ * forwarding to {@link resolveDraftSlot}. Used by `MongoAdapterImpl.resolveParams`
128
+ * for aggregate pipeline stages, which carry `unknown`-typed fields (e.g.
129
+ * `$geoNear.near`) alongside filter sub-documents that may contain
130
+ * `MongoParamRef` leaves.
131
+ */
132
+ export async function resolveDraftDoc(
133
+ doc: Record<string, unknown>,
134
+ codecs: MongoCodecRegistry,
135
+ ctx: CodecCallContext,
136
+ ): Promise<Document> {
137
+ checkAborted(ctx, 'encode');
138
+ const entries = Object.entries(doc);
139
+ const all = Promise.all(entries.map(([, val]) => resolveDraftSlot(val, codecs, ctx)));
140
+ const resolved = await raceAgainstAbort(all, ctx.signal, 'encode');
141
+ const result: Record<string, unknown> = {};
142
+ for (let i = 0; i < entries.length; i++) {
143
+ const entry = entries[i];
144
+ if (entry) {
145
+ result[entry[0]] = resolved[i];
146
+ }
147
+ }
148
+ return result;
149
+ }
150
+
93
151
  function paramRefLabel(ref: MongoParamRef, codecId: string): string {
94
152
  return ref.name ?? codecId;
95
153
  }
96
154
 
155
+ function isErrorWithCode(error: unknown): error is Error & { code: unknown } {
156
+ return error instanceof Error && 'code' in error;
157
+ }
158
+
97
159
  function isAlreadyEncodeFailure(error: unknown): boolean {
98
- return (
99
- error instanceof Error &&
100
- 'code' in error &&
101
- (error as Error & { code?: unknown }).code === 'RUNTIME.ENCODE_FAILED'
102
- );
160
+ return isErrorWithCode(error) && error.code === 'RUNTIME.ENCODE_FAILED';
103
161
  }
104
162
 
105
163
  function wrapEncodeFailure(error: unknown, ref: MongoParamRef, codecId: string): never {
@@ -1 +0,0 @@
1
- {"version":3,"file":"mongo-adapter-DfCmEYHR.mjs","names":["_exhaustive","#codecs","#resolveDocument","#lowerUpdate","_exhaustive"],"sources":["../src/core/codec-ids.ts","../src/resolve-value.ts","../src/lowering.ts","../src/core/codecs.ts","../src/mongo-adapter.ts"],"sourcesContent":["export const MONGO_OBJECTID_CODEC_ID = 'mongo/objectId@1' as const;\nexport const MONGO_STRING_CODEC_ID = 'mongo/string@1' as const;\nexport const MONGO_DOUBLE_CODEC_ID = 'mongo/double@1' as const;\nexport const MONGO_INT32_CODEC_ID = 'mongo/int32@1' as const;\nexport const MONGO_BOOLEAN_CODEC_ID = 'mongo/bool@1' as const;\nexport const MONGO_DATE_CODEC_ID = 'mongo/date@1' as const;\nexport const MONGO_VECTOR_CODEC_ID = 'mongo/vector@1' as const;\n","import type { CodecCallContext } from '@prisma-next/framework-components/codec';\nimport {\n checkAborted,\n raceAgainstAbort,\n runtimeError,\n} from '@prisma-next/framework-components/runtime';\nimport type { MongoCodecRegistry } from '@prisma-next/mongo-codec';\nimport type { MongoValue } from '@prisma-next/mongo-value';\nimport { MongoParamRef } from '@prisma-next/mongo-value';\n\n/**\n * Resolves a `MongoValue` (which may contain `MongoParamRef` leaves) into the\n * driver-ready wire shape. When a leaf has a `codecId` and the registry has a\n * codec for it, the codec's async `encode` is awaited so codecs may perform\n * asynchronous work (e.g. lookups, key derivations).\n *\n * Object/array nodes dispatch their child resolutions concurrently via\n * `Promise.all` so independent leaves encode in parallel.\n *\n * Codec encode failures are wrapped in a `RUNTIME.ENCODE_FAILED` envelope\n * (mirroring SQL's `wrapEncodeFailure` shape) with `{ label, codec }` details\n * and the original error attached on `cause`. An already-wrapped envelope is\n * re-thrown verbatim so nested resolvers don't double-wrap.\n *\n * `ctx: CodecCallContext` is forwarded verbatim to every\n * `codec.encode(value, ctx)` call. The same `ctx` reference is also passed\n * to nested `resolveValue` invocations so codec authors observe **signal\n * identity** across the entire recursive walk for one `runtime.execute()`.\n *\n * Abort observation (only when `ctx.signal` is provided):\n *\n * - **Already-aborted at entry** — every recursive call pre-checks\n * `ctx.signal.aborted` and short-circuits with\n * `RUNTIME.ABORTED { phase: 'encode' }` before any codec is invoked.\n * - **Mid-flight abort** — each per-level `Promise.all` races against the\n * signal via `raceAgainstAbort`. The runtime returns\n * `RUNTIME.ABORTED { phase: 'encode' }` promptly even if codec bodies\n * ignore the signal; in-flight bodies run to completion in the background\n * (cooperative cancellation, see ADR 204).\n * - `RUNTIME.ENCODE_FAILED` envelopes thrown by a codec body before the\n * runtime sees the abort pass through unchanged (AC-ERR4).\n */\nexport async function resolveValue(\n value: MongoValue,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<unknown> {\n checkAborted(ctx, 'encode');\n const signal = ctx.signal;\n\n if (value instanceof MongoParamRef) {\n if (value.codecId) {\n const codec = codecs.get(value.codecId);\n if (codec?.encode) {\n try {\n // Race even leaf scalar encodes against the signal so a leaf\n // `MongoParamRef` (e.g. a simple field filter, or any leaf reached\n // from `MongoAdapterImpl.#resolveDocument()` outside an enclosing\n // `Promise.all`) surfaces `RUNTIME.ABORTED` promptly instead of\n // blocking on a slow codec body.\n const encoded = codec.encode(value.value, ctx);\n return await raceAgainstAbort(encoded, signal, 'encode');\n } catch (error) {\n wrapEncodeFailure(error, value, codec.id);\n }\n }\n }\n return value.value;\n }\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (value instanceof Date) {\n return value;\n }\n if (Array.isArray(value)) {\n const tasks = Promise.all(value.map((v) => resolveValue(v, codecs, ctx)));\n return raceAgainstAbort(tasks, signal, 'encode');\n }\n const entries = Object.entries(value);\n const all = Promise.all(entries.map(([, val]) => resolveValue(val, codecs, ctx)));\n const resolved = await raceAgainstAbort(all, signal, 'encode');\n const result: Record<string, unknown> = {};\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (entry) {\n result[entry[0]] = resolved[i];\n }\n }\n return result;\n}\n\nfunction paramRefLabel(ref: MongoParamRef, codecId: string): string {\n return ref.name ?? codecId;\n}\n\nfunction isAlreadyEncodeFailure(error: unknown): boolean {\n return (\n error instanceof Error &&\n 'code' in error &&\n (error as Error & { code?: unknown }).code === 'RUNTIME.ENCODE_FAILED'\n );\n}\n\nfunction wrapEncodeFailure(error: unknown, ref: MongoParamRef, codecId: string): never {\n if (isAlreadyEncodeFailure(error)) {\n throw error;\n }\n const label = paramRefLabel(ref, codecId);\n const message = error instanceof Error ? error.message : String(error);\n const wrapped = runtimeError(\n 'RUNTIME.ENCODE_FAILED',\n `Failed to encode parameter ${label} with codec '${codecId}': ${message}`,\n { label, codec: codecId },\n );\n wrapped.cause = error;\n throw wrapped;\n}\n","import type { CodecCallContext } from '@prisma-next/framework-components/codec';\nimport type { MongoCodecRegistry } from '@prisma-next/mongo-codec';\nimport type {\n MongoAggExpr,\n MongoAggExprVisitor,\n MongoFilterExpr,\n MongoGroupId,\n MongoPipelineStage,\n MongoProjectionValue,\n MongoWindowField,\n} from '@prisma-next/mongo-query-ast/execution';\nimport { isExprArray, isRecordArgs } from '@prisma-next/mongo-query-ast/execution';\nimport type { Document } from '@prisma-next/mongo-value';\nimport { resolveValue } from './resolve-value';\n\n// Biome flags `{ then: ... }` as a thenable object (noThenProperty). Build via Object.fromEntries to avoid.\nconst THEN_KEY = 'then';\n\nfunction condBranch(\n caseOrIf: MongoAggExpr,\n thenExpr: MongoAggExpr,\n elseExpr?: MongoAggExpr,\n): Record<string, unknown> {\n const entries: Array<[string, unknown]> = [\n [elseExpr ? 'if' : 'case', lowerAggExpr(caseOrIf)],\n [THEN_KEY, lowerAggExpr(thenExpr)],\n ];\n if (elseExpr) {\n entries.push(['else', lowerAggExpr(elseExpr)]);\n }\n return Object.fromEntries(entries);\n}\n\nconst aggExprLoweringVisitor: MongoAggExprVisitor<unknown> = {\n fieldRef(expr) {\n return `$${expr.path}`;\n },\n\n literal(expr) {\n return needsLiteralWrap(expr.value) ? { $literal: expr.value } : expr.value;\n },\n\n operator(expr) {\n const { args } = expr;\n let loweredArgs: unknown;\n if (isExprArray(args)) {\n loweredArgs = args.map((a) => lowerAggExpr(a));\n } else if (isRecordArgs(args)) {\n loweredArgs = lowerExprRecord(args);\n } else {\n loweredArgs = lowerAggExpr(args);\n }\n return { [expr.op]: loweredArgs };\n },\n\n accumulator(expr) {\n if (expr.arg === null) {\n return { [expr.op]: {} };\n }\n if (isRecordArgs(expr.arg)) {\n return { [expr.op]: lowerExprRecord(expr.arg) };\n }\n return { [expr.op]: lowerAggExpr(expr.arg) };\n },\n\n cond(expr) {\n return { $cond: condBranch(expr.condition, expr.then_, expr.else_) };\n },\n\n switch_(expr) {\n return {\n $switch: {\n branches: expr.branches.map((b) => condBranch(b.case_, b.then_)),\n default: lowerAggExpr(expr.default_),\n },\n };\n },\n\n filter(expr) {\n return {\n $filter: {\n input: lowerAggExpr(expr.input),\n cond: lowerAggExpr(expr.cond),\n as: expr.as,\n },\n };\n },\n\n map(expr) {\n return {\n $map: {\n input: lowerAggExpr(expr.input),\n in: lowerAggExpr(expr.in_),\n as: expr.as,\n },\n };\n },\n\n reduce(expr) {\n return {\n $reduce: {\n input: lowerAggExpr(expr.input),\n initialValue: lowerAggExpr(expr.initialValue),\n in: lowerAggExpr(expr.in_),\n },\n };\n },\n\n let_(expr) {\n const vars: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(expr.vars)) {\n vars[key] = lowerAggExpr(val);\n }\n return { $let: { vars, in: lowerAggExpr(expr.in_) } };\n },\n\n mergeObjects(expr) {\n return { $mergeObjects: expr.exprs.map((e) => lowerAggExpr(e)) };\n },\n};\n\nfunction needsLiteralWrap(value: unknown): boolean {\n if (typeof value === 'string' && value.startsWith('$')) {\n return true;\n }\n if (Array.isArray(value)) {\n return value.some((v) => needsLiteralWrap(v));\n }\n if (value !== null && typeof value === 'object') {\n return Object.entries(value as Record<string, unknown>).some(\n ([k, v]) => k.startsWith('$') || needsLiteralWrap(v),\n );\n }\n return false;\n}\n\nexport function lowerAggExpr(expr: MongoAggExpr): unknown {\n return expr.accept(aggExprLoweringVisitor);\n}\n\nexport async function lowerFilter(\n filter: MongoFilterExpr,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<Document> {\n switch (filter.kind) {\n case 'field':\n return { [filter.field]: { [filter.op]: await resolveValue(filter.value, codecs, ctx) } };\n case 'and':\n return { $and: await Promise.all(filter.exprs.map((e) => lowerFilter(e, codecs, ctx))) };\n case 'or':\n return { $or: await Promise.all(filter.exprs.map((e) => lowerFilter(e, codecs, ctx))) };\n case 'not':\n return { $nor: [await lowerFilter(filter.expr, codecs, ctx)] };\n case 'exists':\n return { [filter.field]: { $exists: filter.exists } };\n case 'expr':\n return { $expr: lowerAggExpr(filter.aggExpr) };\n default: {\n const _exhaustive: never = filter;\n throw new Error(`Unhandled filter kind: ${(_exhaustive as MongoFilterExpr).kind}`);\n }\n }\n}\n\nfunction isAggExprNode(value: object): value is MongoAggExpr {\n return 'accept' in value && typeof value.accept === 'function';\n}\n\nfunction lowerGroupId(groupId: MongoGroupId): unknown {\n if (groupId === null) return null;\n if (isAggExprNode(groupId)) return lowerAggExpr(groupId);\n return lowerExprRecord(groupId);\n}\n\nfunction lowerExprRecord(\n fields: Readonly<Record<string, MongoAggExpr | ReadonlyArray<MongoAggExpr>>>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(fields)) {\n if (Array.isArray(val)) {\n result[key] = val.map((v: MongoAggExpr) => lowerAggExpr(v));\n } else {\n result[key] = lowerAggExpr(val as MongoAggExpr);\n }\n }\n return result;\n}\n\nfunction lowerProjectionValue(value: MongoProjectionValue): unknown {\n if (typeof value === 'number') return value;\n return lowerAggExpr(value);\n}\n\nfunction lowerWindowField(wf: MongoWindowField): Record<string, unknown> {\n const lowered = lowerAggExpr(wf.operator);\n if (typeof lowered !== 'object' || lowered === null) {\n throw new Error('Window field operator must lower to an object');\n }\n const result: Record<string, unknown> = { ...lowered };\n if (wf.window) {\n result['window'] = { ...wf.window };\n }\n return result;\n}\n\nexport async function lowerStage(\n stage: MongoPipelineStage,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<Record<string, unknown>> {\n switch (stage.kind) {\n case 'match':\n return { $match: await lowerFilter(stage.filter, codecs, ctx) };\n case 'project': {\n const projection: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(stage.projection)) {\n projection[key] = lowerProjectionValue(val);\n }\n return { $project: projection };\n }\n case 'sort':\n return { $sort: { ...stage.sort } };\n case 'limit':\n return { $limit: stage.limit };\n case 'skip':\n return { $skip: stage.skip };\n case 'lookup': {\n const lookup: Record<string, unknown> = {\n from: stage.from,\n as: stage.as,\n };\n if (stage.localField !== undefined) lookup['localField'] = stage.localField;\n if (stage.foreignField !== undefined) lookup['foreignField'] = stage.foreignField;\n if (stage.pipeline) {\n lookup['pipeline'] = await Promise.all(\n stage.pipeline.map((s) => lowerStage(s, codecs, ctx)),\n );\n }\n if (stage.let_) {\n lookup['let'] = lowerExprRecord(stage.let_);\n }\n return { $lookup: lookup };\n }\n case 'unwind': {\n const unwind: Record<string, unknown> = {\n path: stage.path,\n preserveNullAndEmptyArrays: stage.preserveNullAndEmptyArrays,\n };\n if (stage.includeArrayIndex !== undefined) {\n unwind['includeArrayIndex'] = stage.includeArrayIndex;\n }\n return { $unwind: unwind };\n }\n case 'group': {\n const group: Record<string, unknown> = { _id: lowerGroupId(stage.groupId) };\n for (const [key, acc] of Object.entries(stage.accumulators)) {\n group[key] = lowerAggExpr(acc);\n }\n return { $group: group };\n }\n case 'addFields':\n return { $addFields: lowerExprRecord(stage.fields) };\n case 'replaceRoot':\n return { $replaceRoot: { newRoot: lowerAggExpr(stage.newRoot) } };\n case 'count':\n return { $count: stage.field };\n case 'sortByCount':\n return { $sortByCount: lowerAggExpr(stage.expr) };\n case 'sample':\n return { $sample: { size: stage.size } };\n case 'redact':\n return { $redact: lowerAggExpr(stage.expr) };\n case 'out':\n return { $out: stage.db ? { db: stage.db, coll: stage.collection } : stage.collection };\n case 'unionWith': {\n const unionWith: Record<string, unknown> = { coll: stage.collection };\n if (stage.pipeline) {\n unionWith['pipeline'] = await Promise.all(\n stage.pipeline.map((s) => lowerStage(s, codecs, ctx)),\n );\n }\n return { $unionWith: unionWith };\n }\n case 'bucket': {\n const bucket: Record<string, unknown> = {\n groupBy: lowerAggExpr(stage.groupBy),\n boundaries: [...stage.boundaries],\n };\n if (stage.default_ !== undefined) bucket['default'] = stage.default_;\n if (stage.output) bucket['output'] = lowerExprRecord(stage.output);\n return { $bucket: bucket };\n }\n case 'bucketAuto': {\n const bucketAuto: Record<string, unknown> = {\n groupBy: lowerAggExpr(stage.groupBy),\n buckets: stage.buckets,\n };\n if (stage.output) bucketAuto['output'] = lowerExprRecord(stage.output);\n if (stage.granularity !== undefined) bucketAuto['granularity'] = stage.granularity;\n return { $bucketAuto: bucketAuto };\n }\n case 'geoNear': {\n const geoNear: Record<string, unknown> = {\n near: stage.near,\n distanceField: stage.distanceField,\n };\n if (stage.spherical !== undefined) geoNear['spherical'] = stage.spherical;\n if (stage.maxDistance !== undefined) geoNear['maxDistance'] = stage.maxDistance;\n if (stage.minDistance !== undefined) geoNear['minDistance'] = stage.minDistance;\n if (stage.query) geoNear['query'] = await lowerFilter(stage.query, codecs, ctx);\n if (stage.key !== undefined) geoNear['key'] = stage.key;\n if (stage.distanceMultiplier !== undefined)\n geoNear['distanceMultiplier'] = stage.distanceMultiplier;\n if (stage.includeLocs !== undefined) geoNear['includeLocs'] = stage.includeLocs;\n return { $geoNear: geoNear };\n }\n case 'facet': {\n const facetEntries = Object.entries(stage.facets);\n const facetPipelines = await Promise.all(\n facetEntries.map(([, pipeline]) =>\n Promise.all(pipeline.map((s) => lowerStage(s, codecs, ctx))),\n ),\n );\n const facet: Record<string, unknown> = {};\n for (let i = 0; i < facetEntries.length; i++) {\n const entry = facetEntries[i];\n if (entry) {\n facet[entry[0]] = facetPipelines[i];\n }\n }\n return { $facet: facet };\n }\n case 'graphLookup': {\n const graphLookup: Record<string, unknown> = {\n from: stage.from,\n startWith: lowerAggExpr(stage.startWith),\n connectFromField: stage.connectFromField,\n connectToField: stage.connectToField,\n as: stage.as,\n };\n if (stage.maxDepth !== undefined) graphLookup['maxDepth'] = stage.maxDepth;\n if (stage.depthField !== undefined) graphLookup['depthField'] = stage.depthField;\n if (stage.restrictSearchWithMatch)\n graphLookup['restrictSearchWithMatch'] = await lowerFilter(\n stage.restrictSearchWithMatch,\n codecs,\n ctx,\n );\n return { $graphLookup: graphLookup };\n }\n case 'merge': {\n const merge: Record<string, unknown> = { into: stage.into };\n if (stage.on !== undefined) merge['on'] = stage.on;\n if (stage.whenMatched !== undefined) {\n merge['whenMatched'] = Array.isArray(stage.whenMatched)\n ? await Promise.all(stage.whenMatched.map((s) => lowerStage(s, codecs, ctx)))\n : stage.whenMatched;\n }\n if (stage.whenNotMatched !== undefined) merge['whenNotMatched'] = stage.whenNotMatched;\n return { $merge: merge };\n }\n case 'setWindowFields': {\n const swf: Record<string, unknown> = {};\n if (stage.partitionBy) swf['partitionBy'] = lowerAggExpr(stage.partitionBy);\n if (stage.sortBy) swf['sortBy'] = { ...stage.sortBy };\n const output: Record<string, unknown> = {};\n for (const [key, wf] of Object.entries(stage.output)) {\n output[key] = lowerWindowField(wf);\n }\n swf['output'] = output;\n return { $setWindowFields: swf };\n }\n case 'densify': {\n const densify: Record<string, unknown> = {\n field: stage.field,\n range: { ...stage.range },\n };\n if (stage.partitionByFields) densify['partitionByFields'] = [...stage.partitionByFields];\n return { $densify: densify };\n }\n case 'fill': {\n const fill: Record<string, unknown> = {};\n if (stage.partitionBy) fill['partitionBy'] = lowerAggExpr(stage.partitionBy);\n if (stage.partitionByFields) fill['partitionByFields'] = [...stage.partitionByFields];\n if (stage.sortBy) fill['sortBy'] = { ...stage.sortBy };\n const output: Record<string, unknown> = {};\n for (const [key, fo] of Object.entries(stage.output)) {\n const entry: Record<string, unknown> = {};\n if (fo.method !== undefined) entry['method'] = fo.method;\n if (fo.value !== undefined) entry['value'] = lowerAggExpr(fo.value);\n output[key] = entry;\n }\n fill['output'] = output;\n return { $fill: fill };\n }\n case 'search': {\n const search: Record<string, unknown> = { ...stage.config };\n if (stage.index !== undefined) search['index'] = stage.index;\n return { $search: search };\n }\n case 'searchMeta': {\n const searchMeta: Record<string, unknown> = { ...stage.config };\n if (stage.index !== undefined) searchMeta['index'] = stage.index;\n return { $searchMeta: searchMeta };\n }\n case 'vectorSearch': {\n const vs: Record<string, unknown> = {\n index: stage.index,\n path: stage.path,\n queryVector: [...stage.queryVector],\n numCandidates: stage.numCandidates,\n limit: stage.limit,\n };\n if (stage.filter) vs['filter'] = { ...stage.filter };\n return { $vectorSearch: vs };\n }\n default: {\n const _exhaustive: never = stage;\n throw new Error(`Unhandled stage kind: ${(_exhaustive as MongoPipelineStage).kind}`);\n }\n }\n}\n\nexport async function lowerPipeline(\n stages: ReadonlyArray<MongoPipelineStage>,\n codecs: MongoCodecRegistry,\n ctx: CodecCallContext,\n): Promise<Array<Record<string, unknown>>> {\n return Promise.all(stages.map((s) => lowerStage(s, codecs, ctx)));\n}\n","import type { CodecDescriptor, CodecTrait } from '@prisma-next/framework-components/codec';\nimport { voidParamsSchema } from '@prisma-next/framework-components/codec';\nimport {\n type MongoCodec,\n type MongoCodecRegistry,\n mongoCodec,\n newMongoCodecRegistry,\n} from '@prisma-next/mongo-codec';\nimport { ObjectId } from 'mongodb';\nimport {\n MONGO_BOOLEAN_CODEC_ID,\n MONGO_DATE_CODEC_ID,\n MONGO_DOUBLE_CODEC_ID,\n MONGO_INT32_CODEC_ID,\n MONGO_OBJECTID_CODEC_ID,\n MONGO_STRING_CODEC_ID,\n MONGO_VECTOR_CODEC_ID,\n} from './codec-ids';\n\nexport const mongoObjectIdCodec = mongoCodec({\n typeId: MONGO_OBJECTID_CODEC_ID,\n decode: (wire: ObjectId) => wire.toHexString(),\n encode: (value: string) => new ObjectId(value),\n});\n\nexport const mongoStringCodec = mongoCodec({\n typeId: MONGO_STRING_CODEC_ID,\n decode: (wire: string) => wire,\n encode: (value: string) => value,\n});\n\nexport const mongoDoubleCodec = mongoCodec({\n typeId: MONGO_DOUBLE_CODEC_ID,\n decode: (wire: number) => wire,\n encode: (value: number) => value,\n});\n\nexport const mongoInt32Codec = mongoCodec({\n typeId: MONGO_INT32_CODEC_ID,\n decode: (wire: number) => wire,\n encode: (value: number) => value,\n});\n\nexport const mongoBooleanCodec = mongoCodec({\n typeId: MONGO_BOOLEAN_CODEC_ID,\n decode: (wire: boolean) => wire,\n encode: (value: boolean) => value,\n});\n\nexport const mongoDateCodec = mongoCodec({\n typeId: MONGO_DATE_CODEC_ID,\n decode: (wire: Date) => wire,\n encode: (value: Date) => value,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n});\n\nexport const mongoVectorCodec = mongoCodec({\n typeId: MONGO_VECTOR_CODEC_ID,\n decode: (wire: readonly number[]) => wire,\n encode: (value: readonly number[]) => value,\n});\n\n/**\n * The canonical set of Mongo wire-type codecs.\n *\n * Single source of truth for both control- and runtime-plane adapter descriptors. Don't duplicate this list — import it.\n */\nexport const mongoStandardCodecs = [\n mongoObjectIdCodec,\n mongoStringCodec,\n mongoDoubleCodec,\n mongoInt32Codec,\n mongoBooleanCodec,\n mongoDateCodec,\n mongoVectorCodec,\n] as const;\n\n/**\n * Build a {@link CodecDescriptor} for a Mongo wire-type codec.\n *\n * Wraps an existing {@link MongoCodec} instance into a descriptor whose factory hands out the same shared codec. Mongo's full migration to descriptor-first authoring is tracked under TML-2324; for now the descriptor view is composed from the existing `mongoCodec()` outputs.\n */\nfunction descriptorFor<Id extends string>(\n codec: MongoCodec<Id, readonly CodecTrait[]>,\n metadata: {\n readonly traits: readonly CodecTrait[];\n readonly targetTypes: readonly string[];\n readonly renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;\n },\n): CodecDescriptor {\n // The descriptor's `P` is structurally `Record<string, unknown>` for codecs that take params (Mongo `vector`); non-parameterized codecs ignore the slot. Cast through `unknown` to fit the `CodecDescriptor` slot's `(params: P) => …` typing without leaking a per-codec `P` into the heterogeneous descriptor list.\n const renderOutputType = metadata.renderOutputType as\n | CodecDescriptor['renderOutputType']\n | undefined;\n return {\n codecId: codec.id,\n traits: metadata.traits,\n targetTypes: metadata.targetTypes,\n paramsSchema: voidParamsSchema as CodecDescriptor['paramsSchema'],\n isParameterized: false,\n factory: (() => () => codec) as CodecDescriptor['factory'],\n ...(renderOutputType !== undefined ? { renderOutputType } : {}),\n };\n}\n\nconst renderVectorOutputType = (typeParams: Record<string, unknown>): string | undefined => {\n const length = typeParams['length'];\n if (length === undefined) return undefined;\n if (\n typeof length !== 'number' ||\n !Number.isFinite(length) ||\n !Number.isInteger(length) ||\n length <= 0\n ) {\n throw new Error('renderOutputType: expected positive integer \"length\" for Vector');\n }\n return `Vector<${length}>`;\n};\n\n/**\n * Mongo wire-type codec descriptors. Static metadata for `traits`, `targetTypes`, and `renderOutputType` lives here (the descriptor shape) — `MongoCodec` itself is narrow and only carries the four conversion methods (TML-2357).\n */\nexport const mongoCodecDescriptors: ReadonlyArray<CodecDescriptor> = [\n descriptorFor(mongoObjectIdCodec, { traits: ['equality'], targetTypes: ['objectId'] }),\n descriptorFor(mongoStringCodec, {\n traits: ['equality', 'order', 'textual'],\n targetTypes: ['string'],\n }),\n descriptorFor(mongoDoubleCodec, {\n traits: ['equality', 'order', 'numeric'],\n targetTypes: ['double'],\n }),\n descriptorFor(mongoInt32Codec, {\n traits: ['equality', 'order', 'numeric'],\n targetTypes: ['int'],\n }),\n descriptorFor(mongoBooleanCodec, { traits: ['equality', 'boolean'], targetTypes: ['bool'] }),\n descriptorFor(mongoDateCodec, { traits: ['equality', 'order'], targetTypes: ['date'] }),\n descriptorFor(mongoVectorCodec, {\n traits: ['equality'],\n targetTypes: ['vector'],\n renderOutputType: renderVectorOutputType,\n }),\n];\n\n/**\n * Lookup descriptor metadata by codec id — used by tests and for descriptor-side reads of static metadata.\n */\nexport function mongoDescriptorById(codecId: string): CodecDescriptor | undefined {\n return mongoCodecDescriptors.find((d) => d.codecId === codecId);\n}\n\n/**\n * Build a {@link MongoCodecRegistry} preloaded with the standard Mongo wire-type codecs.\n *\n * Single point of truth for adapter-side codec construction: used by the legacy synchronous `createMongoAdapter()` factory and by the runtime adapter descriptor's `codecs()` getter. Userland code obtains a registry via the framework's execution-stack composition (see `createMongoExecutionContext`) instead of calling this directly.\n */\nexport function buildStandardCodecRegistry(): MongoCodecRegistry {\n const registry = newMongoCodecRegistry();\n for (const codec of mongoStandardCodecs) {\n registry.register(codec);\n }\n return registry;\n}\n","import type { CodecCallContext } from '@prisma-next/framework-components/codec';\nimport type { MongoCodecRegistry } from '@prisma-next/mongo-codec';\nimport type { MongoAdapter } from '@prisma-next/mongo-lowering';\nimport type {\n MongoQueryPlan,\n MongoUpdatePipelineStage,\n MongoUpdateSpec,\n} from '@prisma-next/mongo-query-ast/execution';\nimport type { Document, MongoExpr } from '@prisma-next/mongo-value';\nimport type { AnyMongoWireCommand } from '@prisma-next/mongo-wire';\nimport {\n AggregateWireCommand,\n DeleteManyWireCommand,\n DeleteOneWireCommand,\n FindOneAndDeleteWireCommand,\n FindOneAndUpdateWireCommand,\n InsertManyWireCommand,\n InsertOneWireCommand,\n UpdateManyWireCommand,\n UpdateOneWireCommand,\n} from '@prisma-next/mongo-wire';\nimport { buildStandardCodecRegistry } from './core/codecs';\nimport { lowerFilter, lowerPipeline, lowerStage } from './lowering';\nimport { resolveValue } from './resolve-value';\n\nfunction isUpdatePipeline(\n update: MongoUpdateSpec,\n): update is ReadonlyArray<MongoUpdatePipelineStage> {\n return Array.isArray(update);\n}\n\nclass MongoAdapterImpl implements MongoAdapter {\n readonly #codecs: MongoCodecRegistry;\n\n constructor(codecs: MongoCodecRegistry) {\n this.#codecs = codecs;\n }\n\n async #resolveDocument(expr: MongoExpr, ctx: CodecCallContext): Promise<Document> {\n const entries = Object.entries(expr);\n const resolved = await Promise.all(\n entries.map(([, val]) => resolveValue(val, this.#codecs, ctx)),\n );\n const result: Record<string, unknown> = {};\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (entry) {\n result[entry[0]] = resolved[i];\n }\n }\n return result;\n }\n\n async #lowerUpdate(\n update: MongoUpdateSpec,\n ctx: CodecCallContext,\n ): Promise<Document | ReadonlyArray<Document>> {\n if (isUpdatePipeline(update)) {\n return Promise.all(update.map((stage) => lowerStage(stage, this.#codecs, ctx)));\n }\n return this.#resolveDocument(update, ctx);\n }\n\n async lower(plan: MongoQueryPlan, ctx: CodecCallContext): Promise<AnyMongoWireCommand> {\n const { command } = plan;\n switch (command.kind) {\n case 'insertOne':\n return new InsertOneWireCommand(\n command.collection,\n await this.#resolveDocument(command.document, ctx),\n );\n case 'updateOne': {\n const [filter, update] = await Promise.all([\n lowerFilter(command.filter, this.#codecs, ctx),\n this.#lowerUpdate(command.update, ctx),\n ]);\n return new UpdateOneWireCommand(command.collection, filter, update, command.upsert);\n }\n case 'insertMany':\n return new InsertManyWireCommand(\n command.collection,\n await Promise.all(command.documents.map((doc) => this.#resolveDocument(doc, ctx))),\n );\n case 'updateMany': {\n const [filter, update] = await Promise.all([\n lowerFilter(command.filter, this.#codecs, ctx),\n this.#lowerUpdate(command.update, ctx),\n ]);\n return new UpdateManyWireCommand(command.collection, filter, update, command.upsert);\n }\n case 'deleteOne':\n return new DeleteOneWireCommand(\n command.collection,\n await lowerFilter(command.filter, this.#codecs, ctx),\n );\n case 'deleteMany':\n return new DeleteManyWireCommand(\n command.collection,\n await lowerFilter(command.filter, this.#codecs, ctx),\n );\n case 'findOneAndUpdate': {\n const [filter, update] = await Promise.all([\n lowerFilter(command.filter, this.#codecs, ctx),\n this.#lowerUpdate(command.update, ctx),\n ]);\n return new FindOneAndUpdateWireCommand(\n command.collection,\n filter,\n update,\n command.upsert,\n command.sort,\n command.returnDocument,\n );\n }\n case 'findOneAndDelete':\n return new FindOneAndDeleteWireCommand(\n command.collection,\n await lowerFilter(command.filter, this.#codecs, ctx),\n command.sort,\n );\n case 'aggregate':\n return new AggregateWireCommand(\n command.collection,\n await lowerPipeline(command.pipeline, this.#codecs, ctx),\n );\n case 'rawAggregate':\n return new AggregateWireCommand(command.collection, command.pipeline);\n case 'rawInsertOne':\n return new InsertOneWireCommand(command.collection, command.document);\n case 'rawInsertMany':\n return new InsertManyWireCommand(command.collection, command.documents);\n case 'rawUpdateOne':\n return new UpdateOneWireCommand(command.collection, command.filter, command.update);\n case 'rawUpdateMany':\n return new UpdateManyWireCommand(command.collection, command.filter, command.update);\n case 'rawDeleteOne':\n return new DeleteOneWireCommand(command.collection, command.filter);\n case 'rawDeleteMany':\n return new DeleteManyWireCommand(command.collection, command.filter);\n case 'rawFindOneAndUpdate':\n return new FindOneAndUpdateWireCommand(\n command.collection,\n command.filter,\n command.update,\n command.upsert,\n command.sort,\n command.returnDocument,\n );\n case 'rawFindOneAndDelete':\n return new FindOneAndDeleteWireCommand(command.collection, command.filter, command.sort);\n // v8 ignore next 4\n default: {\n const _exhaustive: never = command;\n throw new Error(`Unknown command kind: ${(_exhaustive as { kind: string }).kind}`);\n }\n }\n }\n}\n\n/**\n * Construct a Mongo adapter with the standard wire-type codecs registered\n * for encode-side dispatch (`MongoParamRef.codecId` lookups).\n *\n * The runtime-side codec registry the runtime decodes against is composed\n * separately by `createMongoExecutionContext`. This factory exists for\n * direct adapter use (the runtime descriptor's `create(stack)` calls\n * through it). User code should compose a stack/context instead.\n */\nexport function createMongoAdapter(): MongoAdapter {\n return new MongoAdapterImpl(buildStandardCodecRegistry());\n}\n\n/**\n * Internal escape hatch — direct adapter construction with a caller-supplied\n * codec registry, used only by adapter unit tests that exercise the\n * encode-side codec-dispatch path with synthetic codecs. Not re-exported\n * from the package's public surface and not for production use; production\n * callers compose a `MongoExecutionStack` and `MongoExecutionContext`.\n */\nexport function _unstable_createMongoAdapterWithCodecs(codecs: MongoCodecRegistry): MongoAdapter {\n return new MongoAdapterImpl(codecs);\n}\n"],"mappings":";;;;;;;;AAAA,MAAa,0BAA0B;AACvC,MAAa,wBAAwB;AACrC,MAAa,wBAAwB;AACrC,MA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