@prisma-next/mongo-codec 0.5.0-dev.5 → 0.5.0-dev.51

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
@@ -4,10 +4,58 @@ Codec interface and registry for MongoDB value serialization.
4
4
 
5
5
  ## Responsibilities
6
6
 
7
- - **Codec interface**: `MongoCodec<Id, TTraits, TWire, TJs>` — defines encode/decode between wire (BSON) and JS representations, with trait annotations (`equality`, `order`, `boolean`, `numeric`, `textual`, `vector`)
8
- - **Codec factory**: `mongoCodec()` — creates frozen codec instances from a config object
7
+ - **Codec interface**: `MongoCodec<Id, TTraits, TWire, TInput>` — declares how a JS value translates to and from the BSON-shaped wire format the Mongo driver exchanges, plus the JSON-safe form stored in contract artifacts. Carries trait annotations (`equality`, `order`, `boolean`, `numeric`, `textual`, `vector`) for operator gating. Same four generics as the framework `Codec` base.
8
+ - **Codec factory**: `mongoCodec()` — creates frozen codec instances from a config object. Both `encode` and `decode` are required so `TInput` and `TWire` are always covered by an explicit author function — the factory installs no identity fallback. `encode` and `decode` may be authored as sync or async functions and are lifted to Promise-returning query-time methods automatically. Build-time methods (`encodeJson`, `decodeJson`) are synchronous and default to identity when omitted.
9
9
  - **Codec registry**: `MongoCodecRegistry` and `createMongoCodecRegistry()` — a map-based container that stores and retrieves codecs by ID, with duplicate-ID protection
10
- - **Type-level helpers**: `MongoCodecJsType<T>` and `MongoCodecTraits<T>` for extracting JS types and traits from codec types
10
+ - **Type-level helpers**: `MongoCodecInput<T>` and `MongoCodecTraits<T>` for extracting the input JS type and traits from codec types
11
+
12
+ ## Examples
13
+
14
+ ```ts
15
+ // Sync authoring:
16
+ const intCodec = mongoCodec({
17
+ typeId: 'mongo/int@1',
18
+ targetTypes: ['int'],
19
+ encode: (v: number) => v,
20
+ decode: (w: number) => w,
21
+ encodeJson: (v: number) => v,
22
+ decodeJson: (j: number) => j,
23
+ });
24
+
25
+ // Async authoring (e.g. KMS-backed encryption): same factory, same shape.
26
+ const secretCodec = mongoCodec({
27
+ typeId: 'mongo/secret@1',
28
+ targetTypes: ['string'],
29
+ encode: async (v: string) => encrypt(v, await getKey()),
30
+ decode: async (w: string) => decrypt(w, await getKey()),
31
+ encodeJson: (v: string) => v,
32
+ decodeJson: (j: string) => j,
33
+ });
34
+ ```
35
+
36
+ ### Codec call context (`ctx`)
37
+
38
+ Codecs receive a second `ctx` options argument; you may ignore it. The Mongo runtime allocates one `CodecCallContext` per `mongoRuntime.execute(plan, { signal })` call and threads the same reference to every codec dispatch site as a non-optional argument — when no `signal` is supplied the runtime still threads an empty `{}`, never `undefined`. Mongo uses the framework `CodecCallContext` directly (signal-only); column metadata is SQL-family-specific and isn't part of Mongo's per-call shape today. The internal `MongoCodec` interface declares the parameter as required (`encode(value, ctx: CodecCallContext)` / `decode(wire, ctx: CodecCallContext)`); single-arg author functions `(value) => …` continue to compile via TypeScript's bivariance for trailing parameters, so codec ergonomics are unchanged. The `signal` field on the ctx may be `undefined` when the caller didn't supply one.
39
+
40
+ ```ts
41
+ // Forward ctx.signal to a network SDK so aborted queries stop the round-trip.
42
+ const kmsSecretCodec = mongoCodec({
43
+ typeId: 'mongo/kms-secret@1',
44
+ targetTypes: ['string'],
45
+ encode: async (v: string, ctx) =>
46
+ kms.encrypt({ plaintext: v }, { signal: ctx?.signal }),
47
+ decode: async (w: string, ctx) =>
48
+ kms.decrypt({ ciphertext: w }, { signal: ctx?.signal }),
49
+ encodeJson: (v: string) => v,
50
+ decodeJson: (j: string) => j,
51
+ });
52
+ ```
53
+
54
+ > **Note.** Mongo's read path doesn't go through `codec.decode` (per ADR 204 cross-family scope notes), so the `decode` signature above accepts `ctx` for parity with the codec interface but the runtime doesn't currently invoke `decode` on the Mongo read side. Encode-side `ctx.signal` is observed at every recursion level of `resolveValue` so a mid-encode abort surfaces as `RUNTIME.ABORTED { phase: 'encode' }`.
55
+
56
+ Codec bodies that ignore `ctx.signal` complete in the background (cooperative cancellation); aborts still surface to the caller as `RUNTIME.ABORTED`.
57
+
58
+ See [ADR 204 — Single-Path Async Codec Runtime](../../../../docs/architecture%20docs/adrs/ADR%20204%20-%20Single-Path%20Async%20Codec%20Runtime.md) for the codec runtime's async boundary contract, and [ADR 207 — Codec call context: per-query `AbortSignal` and column metadata](../../../../docs/architecture%20docs/adrs/ADR%20207%20-%20Codec%20call%20context%20per-query%20AbortSignal%20and%20column%20metadata.md) for the per-call context shape.
11
59
 
12
60
  ## Dependencies
13
61
 
package/dist/index.d.mts CHANGED
@@ -1,22 +1,58 @@
1
1
  import { JsonValue } from "@prisma-next/contract/types";
2
- import { Codec, CodecTrait } from "@prisma-next/framework-components/codec";
2
+ import { Codec, CodecCallContext, CodecTrait } from "@prisma-next/framework-components/codec";
3
3
 
4
4
  //#region src/codecs.d.ts
5
5
  type MongoCodecTrait = CodecTrait;
6
- interface MongoCodec<Id extends string = string, TTraits$1 extends readonly MongoCodecTrait[] = readonly MongoCodecTrait[], TWire = unknown, TJs = unknown> extends Codec<Id, TTraits$1, TWire, TJs> {
7
- readonly traits: TTraits$1;
8
- }
9
- declare function mongoCodec<Id extends string, const TTraits$1 extends readonly MongoCodecTrait[] = readonly [], TWire = unknown, TJs = unknown>(config: {
6
+ /**
7
+ * A codec for the Mongo target. Translates between an application value
8
+ * and the BSON-shaped wire form the Mongo driver exchanges, and between
9
+ * an application value and the JSON form stored in contract artifacts.
10
+ *
11
+ * Same shape as the framework codec base — see `Codec` in
12
+ * `@prisma-next/framework-components/codec` for the contract. The alias
13
+ * exists so Mongo-specific metadata can be added here in future without
14
+ * touching the framework base.
15
+ */
16
+ type MongoCodec<Id extends string = string, TTraits$1 extends readonly MongoCodecTrait[] = readonly MongoCodecTrait[], TWire = unknown, TInput = unknown> = Codec<Id, TTraits$1, TWire, TInput>;
17
+ /**
18
+ * Conditional bundle for `encodeJson`/`decodeJson`: when `TInput` is
19
+ * structurally assignable to `JsonValue` the identity defaults are
20
+ * sound and both fields are optional; otherwise both fields are
21
+ * required so an author cannot silently produce a non-JSON-safe
22
+ * contract artifact.
23
+ */
24
+ type JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue] ? {
25
+ encodeJson?: (value: TInput) => JsonValue;
26
+ decodeJson?: (json: JsonValue) => TInput;
27
+ } : {
28
+ encodeJson: (value: TInput) => JsonValue;
29
+ decodeJson: (json: JsonValue) => TInput;
30
+ };
31
+ /**
32
+ * Construct a Mongo codec from author functions.
33
+ *
34
+ * Author `encode` and `decode` as sync or async functions; the factory
35
+ * produces a {@link MongoCodec} whose query-time methods follow the
36
+ * boundary contract documented on the framework {@link BaseCodec}.
37
+ * Authors receive a second `ctx` options argument carrying the per-call
38
+ * context; ignore it if you don't need it.
39
+ *
40
+ * Both `encode` and `decode` are required so `TInput` and `TWire` are
41
+ * always covered by an explicit author function — the factory installs
42
+ * no identity fallback. `encodeJson` and `decodeJson` default to identity
43
+ * **only when `TInput` is assignable to `JsonValue`**; otherwise both are
44
+ * required so the contract artifact stays JSON-safe.
45
+ */
46
+ declare function mongoCodec<Id extends string, const TTraits$1 extends readonly MongoCodecTrait[] = readonly [], TWire = unknown, TInput = unknown>(config: {
10
47
  typeId: Id;
11
48
  targetTypes: readonly string[];
12
49
  traits?: TTraits$1;
13
- encode: (value: TJs) => TWire;
14
- decode: (wire: TWire) => TJs;
15
- encodeJson?: (value: TJs) => JsonValue;
16
- decodeJson?: (json: JsonValue) => TJs;
50
+ encode: (value: TInput, ctx: CodecCallContext) => TWire | Promise<TWire>;
51
+ decode: (wire: TWire, ctx: CodecCallContext) => TInput | Promise<TInput>;
17
52
  renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;
18
- }): MongoCodec<Id, TTraits$1, TWire, TJs>;
19
- type MongoCodecJsType<T> = T extends MongoCodec<string, readonly MongoCodecTrait[], unknown, infer TJs> ? TJs : never;
53
+ } & JsonRoundTripConfig<TInput>): MongoCodec<Id, TTraits$1, TWire, TInput>;
54
+ /** Extract the JS application type carried by a Mongo codec used both as `encode` input and as `decode` output. */
55
+ type MongoCodecInput<T> = T extends MongoCodec<string, readonly MongoCodecTrait[], unknown, infer TInput> ? TInput : never;
20
56
  type MongoCodecTraits<T> = T extends MongoCodec<string, infer TTraits> ? TTraits[number] & MongoCodecTrait : never;
21
57
  //#endregion
22
58
  //#region src/codec-registry.d.ts
@@ -29,5 +65,5 @@ interface MongoCodecRegistry {
29
65
  }
30
66
  declare function createMongoCodecRegistry(): MongoCodecRegistry;
31
67
  //#endregion
32
- export { type MongoCodec, type MongoCodecJsType, type MongoCodecRegistry, type MongoCodecTrait, type MongoCodecTraits, createMongoCodecRegistry, mongoCodec };
68
+ export { type MongoCodec, type MongoCodecInput, type MongoCodecRegistry, type MongoCodecTrait, type MongoCodecTraits, createMongoCodecRegistry, mongoCodec };
33
69
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/codecs.ts","../src/codec-registry.ts"],"sourcesContent":[],"mappings":";;;;KAGY,eAAA,GAAkB;UAEb,kEAEU,6BAA6B,2DAG9C,MAAU,IAAI,WAAS,OAAO;EAP5B,SAAA,MAAA,EAQO,SARQ;AAE3B;AAE2B,iBAOX,UAPW,CAAA,WAAA,MAAA,EAAA,wBAAA,SASM,eATN,EAAA,GAAA,SAAA,EAAA,EAAA,QAAA,OAAA,EAAA,MAAA,OAAA,CAAA,CAAA,MAAA,EAAA;EAA6B,MAAA,EAa9C,EAb8C;EAGpC,WAAA,EAAA,SAAA,MAAA,EAAA;EAAI,MAAA,CAAA,EAYb,SAZa;EAAS,MAAA,EAAA,CAAA,KAAA,EAaf,GAbe,EAAA,GAaP,KAbO;EAAO,MAAA,EAAA,CAAA,IAAA,EAcvB,KAduB,EAAA,GAcb,GAda;EACrB,UAAA,CAAA,EAAA,CAAA,KAAA,EAcI,GAdJ,EAAA,GAcY,SAdZ;EADT,UAAA,CAAA,EAAA,CAAA,IAAA,EAgBY,SAhBZ,EAAA,GAgB0B,GAhB1B;EAAS,g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,MAAA,GAAA,KAAA;AAAU,KAEV,gBAFU,CAAA,CAAA,CAAA,GAGpB,CAHoB,SAGV,UAHU,CAAA,MAAA,EAAA,KAAA,QAAA,CAAA,GAG0B,OAH1B,CAAA,MAAA,CAAA,GAG4C,eAH5C,GAAA,KAAA;;;UClHL,kBAAA;mBACE;;EDKP,QAAA,CAAA,KAAA,ECHM,UDGS,CAAA,MAAG,CAAA,CAAA,EAAA,IAAU;EAY5B,CAAA,MAAA,CAAA,QAAU,GAAA,ECdC,QDcD,CCdU,UDcV,CAAA,MAAA,CAAA,CAAA;EAEK,MAAA,EAAA,ECff,gBDee,CCfE,UDeF,CAAA,MAAA,CAAA,CAAA;;AAGb,iBCYE,wBAAA,CAAA,CDZF,ECY8B,kBDZ9B"}
package/dist/index.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { ifDefined } from "@prisma-next/utils/defined";
2
+
1
3
  //#region src/codec-registry.ts
2
4
  var MongoCodecRegistryImpl = class {
3
5
  #byId = /* @__PURE__ */ new Map();
@@ -24,18 +26,47 @@ function createMongoCodecRegistry() {
24
26
 
25
27
  //#endregion
26
28
  //#region src/codecs.ts
29
+ /**
30
+ * Construct a Mongo codec from author functions.
31
+ *
32
+ * Author `encode` and `decode` as sync or async functions; the factory
33
+ * produces a {@link MongoCodec} whose query-time methods follow the
34
+ * boundary contract documented on the framework {@link BaseCodec}.
35
+ * Authors receive a second `ctx` options argument carrying the per-call
36
+ * context; ignore it if you don't need it.
37
+ *
38
+ * Both `encode` and `decode` are required so `TInput` and `TWire` are
39
+ * always covered by an explicit author function — the factory installs
40
+ * no identity fallback. `encodeJson` and `decodeJson` default to identity
41
+ * **only when `TInput` is assignable to `JsonValue`**; otherwise both are
42
+ * required so the contract artifact stays JSON-safe.
43
+ */
27
44
  function mongoCodec(config) {
28
- const traits = config.traits ? Object.freeze([...config.traits]) : Object.freeze([]);
29
45
  const identity = (v) => v;
46
+ const userEncode = config.encode;
47
+ const userDecode = config.decode;
48
+ const widenedConfig = config;
30
49
  return {
31
50
  id: config.typeId,
32
51
  targetTypes: config.targetTypes,
33
- traits,
34
- decode: config.decode,
35
- encode: config.encode,
36
- encodeJson: config.encodeJson ?? identity,
37
- decodeJson: config.decodeJson ?? identity,
38
- ...config.renderOutputType ? { renderOutputType: config.renderOutputType } : {}
52
+ ...ifDefined("traits", config.traits ? Object.freeze([...config.traits]) : void 0),
53
+ ...ifDefined("renderOutputType", config.renderOutputType),
54
+ encode: (value, ctx) => {
55
+ try {
56
+ return Promise.resolve(userEncode(value, ctx));
57
+ } catch (error) {
58
+ return Promise.reject(error);
59
+ }
60
+ },
61
+ decode: (wire, ctx) => {
62
+ try {
63
+ return Promise.resolve(userDecode(wire, ctx));
64
+ } catch (error) {
65
+ return Promise.reject(error);
66
+ }
67
+ },
68
+ encodeJson: widenedConfig.encodeJson ?? identity,
69
+ decodeJson: widenedConfig.decodeJson ?? identity
39
70
  };
40
71
  }
41
72
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["#byId"],"sources":["../src/codec-registry.ts","../src/codecs.ts"],"sourcesContent":["import type { MongoCodec } from './codecs';\n\nexport interface MongoCodecRegistry {\n get(id: string): MongoCodec<string> | undefined;\n has(id: string): boolean;\n register(codec: MongoCodec<string>): void;\n [Symbol.iterator](): Iterator<MongoCodec<string>>;\n values(): IterableIterator<MongoCodec<string>>;\n}\n\nclass MongoCodecRegistryImpl implements MongoCodecRegistry {\n readonly #byId = new Map<string, MongoCodec<string>>();\n\n get(id: string): MongoCodec<string> | undefined {\n return this.#byId.get(id);\n }\n\n has(id: string): boolean {\n return this.#byId.has(id);\n }\n\n register(codec: MongoCodec<string>): void {\n if (this.#byId.has(codec.id)) {\n throw new Error(`Codec with ID '${codec.id}' is already registered`);\n }\n this.#byId.set(codec.id, codec);\n }\n\n *[Symbol.iterator](): Iterator<MongoCodec<string>> {\n yield* this.#byId.values();\n }\n\n values(): IterableIterator<MongoCodec<string>> {\n return this.#byId.values();\n }\n}\n\nexport function createMongoCodecRegistry(): MongoCodecRegistry {\n return new MongoCodecRegistryImpl();\n}\n","import type { JsonValue } from '@prisma-next/contract/types';\nimport type { Codec as BaseCodec, CodecTrait } from '@prisma-next/framework-components/codec';\n\nexport type MongoCodecTrait = CodecTrait;\n\nexport interface MongoCodec<\n Id extends string = string,\n TTraits extends readonly MongoCodecTrait[] = readonly MongoCodecTrait[],\n TWire = unknown,\n TJs = unknown,\n> extends BaseCodec<Id, TTraits, TWire, TJs> {\n readonly traits: TTraits;\n}\n\nexport function mongoCodec<\n Id extends string,\n const TTraits extends readonly MongoCodecTrait[] = readonly [],\n TWire = unknown,\n TJs = unknown,\n>(config: {\n typeId: Id;\n targetTypes: readonly string[];\n traits?: TTraits;\n encode: (value: TJs) => TWire;\n decode: (wire: TWire) => TJs;\n encodeJson?: (value: TJs) => JsonValue;\n decodeJson?: (json: JsonValue) => TJs;\n renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;\n}): MongoCodec<Id, TTraits, TWire, TJs> {\n const traits = config.traits\n ? (Object.freeze([...config.traits]) as TTraits)\n : (Object.freeze([] as const) as unknown as TTraits);\n const identity = (v: unknown) => v;\n return {\n id: config.typeId,\n targetTypes: config.targetTypes,\n traits,\n decode: config.decode,\n encode: config.encode,\n encodeJson: (config.encodeJson ?? identity) as (value: TJs) => JsonValue,\n decodeJson: (config.decodeJson ?? identity) as (json: JsonValue) => TJs,\n ...(config.renderOutputType ? { renderOutputType: config.renderOutputType } : {}),\n };\n}\n\nexport type MongoCodecJsType<T> =\n T extends MongoCodec<string, readonly MongoCodecTrait[], unknown, infer TJs> ? TJs : never;\n\nexport type MongoCodecTraits<T> =\n T extends MongoCodec<string, infer TTraits> ? TTraits[number] & MongoCodecTrait : never;\n"],"mappings":";AAUA,IAAM,yBAAN,MAA2D;CACzD,CAASA,uBAAQ,IAAI,KAAiC;CAEtD,IAAI,IAA4C;AAC9C,SAAO,MAAKA,KAAM,IAAI,GAAG;;CAG3B,IAAI,IAAqB;AACvB,SAAO,MAAKA,KAAM,IAAI,GAAG;;CAG3B,SAAS,OAAiC;AACxC,MAAI,MAAKA,KAAM,IAAI,MAAM,GAAG,CAC1B,OAAM,IAAI,MAAM,kBAAkB,MAAM,GAAG,yBAAyB;AAEtE,QAAKA,KAAM,IAAI,MAAM,IAAI,MAAM;;CAGjC,EAAE,OAAO,YAA0C;AACjD,SAAO,MAAKA,KAAM,QAAQ;;CAG5B,SAA+C;AAC7C,SAAO,MAAKA,KAAM,QAAQ;;;AAI9B,SAAgB,2BAA+C;AAC7D,QAAO,IAAI,wBAAwB;;;;;ACxBrC,SAAgB,WAKd,QASsC;CACtC,MAAM,SAAS,OAAO,SACjB,OAAO,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC,GACjC,OAAO,OAAO,EAAE,CAAU;CAC/B,MAAM,YAAY,MAAe;AACjC,QAAO;EACL,IAAI,OAAO;EACX,aAAa,OAAO;EACpB;EACA,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf,YAAa,OAAO,cAAc;EAClC,YAAa,OAAO,cAAc;EAClC,GAAI,OAAO,mBAAmB,EAAE,kBAAkB,OAAO,kBAAkB,GAAG,EAAE;EACjF"}
1
+ {"version":3,"file":"index.mjs","names":["#byId"],"sources":["../src/codec-registry.ts","../src/codecs.ts"],"sourcesContent":["import type { MongoCodec } from './codecs';\n\nexport interface MongoCodecRegistry {\n get(id: string): MongoCodec<string> | undefined;\n has(id: string): boolean;\n register(codec: MongoCodec<string>): void;\n [Symbol.iterator](): Iterator<MongoCodec<string>>;\n values(): IterableIterator<MongoCodec<string>>;\n}\n\nclass MongoCodecRegistryImpl implements MongoCodecRegistry {\n readonly #byId = new Map<string, MongoCodec<string>>();\n\n get(id: string): MongoCodec<string> | undefined {\n return this.#byId.get(id);\n }\n\n has(id: string): boolean {\n return this.#byId.has(id);\n }\n\n register(codec: MongoCodec<string>): void {\n if (this.#byId.has(codec.id)) {\n throw new Error(`Codec with ID '${codec.id}' is already registered`);\n }\n this.#byId.set(codec.id, codec);\n }\n\n *[Symbol.iterator](): Iterator<MongoCodec<string>> {\n yield* this.#byId.values();\n }\n\n values(): IterableIterator<MongoCodec<string>> {\n return this.#byId.values();\n }\n}\n\nexport function createMongoCodecRegistry(): MongoCodecRegistry {\n return new MongoCodecRegistryImpl();\n}\n","import type { JsonValue } from '@prisma-next/contract/types';\nimport type {\n Codec as BaseCodec,\n CodecCallContext,\n CodecTrait,\n} from '@prisma-next/framework-components/codec';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\nexport type MongoCodecTrait = CodecTrait;\n\n/**\n * A codec for the Mongo target. Translates between an application value\n * and the BSON-shaped wire form the Mongo driver exchanges, and between\n * an application value and the JSON form stored in contract artifacts.\n *\n * Same shape as the framework codec base — see `Codec` in\n * `@prisma-next/framework-components/codec` for the contract. The alias\n * exists so Mongo-specific metadata can be added here in future without\n * touching the framework base.\n */\nexport type MongoCodec<\n Id extends string = string,\n TTraits extends readonly MongoCodecTrait[] = readonly MongoCodecTrait[],\n TWire = unknown,\n TInput = unknown,\n> = BaseCodec<Id, TTraits, TWire, TInput>;\n\n/**\n * Conditional bundle for `encodeJson`/`decodeJson`: when `TInput` is\n * structurally assignable to `JsonValue` the identity defaults are\n * sound and both fields are optional; otherwise both fields are\n * required so an author cannot silently produce a non-JSON-safe\n * contract artifact.\n */\ntype JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]\n ? {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n }\n : {\n encodeJson: (value: TInput) => JsonValue;\n decodeJson: (json: JsonValue) => TInput;\n };\n\n/**\n * Construct a Mongo codec from author functions.\n *\n * Author `encode` and `decode` as sync or async functions; the factory\n * produces a {@link MongoCodec} whose query-time methods follow the\n * boundary contract documented on the framework {@link BaseCodec}.\n * Authors receive a second `ctx` options argument carrying the per-call\n * context; ignore it if you don't need it.\n *\n * Both `encode` and `decode` are required so `TInput` and `TWire` are\n * always covered by an explicit author function — the factory installs\n * no identity fallback. `encodeJson` and `decodeJson` default to identity\n * **only when `TInput` is assignable to `JsonValue`**; otherwise both are\n * required so the contract artifact stays JSON-safe.\n */\nexport function mongoCodec<\n Id extends string,\n const TTraits extends readonly MongoCodecTrait[] = readonly [],\n TWire = unknown,\n TInput = unknown,\n>(\n config: {\n typeId: Id;\n targetTypes: readonly string[];\n traits?: TTraits;\n encode: (value: TInput, ctx: CodecCallContext) => TWire | Promise<TWire>;\n decode: (wire: TWire, ctx: CodecCallContext) => TInput | Promise<TInput>;\n renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;\n } & JsonRoundTripConfig<TInput>,\n): MongoCodec<Id, TTraits, TWire, TInput> {\n const identity = (v: unknown) => v;\n // The runtime allocates one `CodecCallContext` per `runtime.execute()`\n // call (no caller-supplied `signal` produces `{}` instead of `undefined`)\n // and threads it as a non-optional reference to every codec call. The\n // author surface keeps the second parameter optional so single-arg\n // `(value) => …` authors continue to satisfy the signature via\n // TypeScript's bivariance for trailing parameters.\n const userEncode = config.encode;\n const userDecode = config.decode;\n const widenedConfig = config as {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n };\n return {\n id: config.typeId,\n targetTypes: config.targetTypes,\n ...ifDefined(\n 'traits',\n config.traits ? (Object.freeze([...config.traits]) as TTraits) : undefined,\n ),\n ...ifDefined('renderOutputType', config.renderOutputType),\n encode: (value, ctx) => {\n try {\n return Promise.resolve(userEncode(value, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n decode: (wire, ctx) => {\n try {\n return Promise.resolve(userDecode(wire, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,\n decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,\n };\n}\n\n/** Extract the JS application type carried by a Mongo codec — used both as `encode` input and as `decode` output. */\nexport type MongoCodecInput<T> =\n T extends MongoCodec<string, readonly MongoCodecTrait[], unknown, infer TInput> ? TInput : never;\n\nexport type MongoCodecTraits<T> =\n T extends MongoCodec<string, infer TTraits> ? TTraits[number] & MongoCodecTrait : never;\n"],"mappings":";;;AAUA,IAAM,yBAAN,MAA2D;CACzD,CAASA,uBAAQ,IAAI,KAAiC;CAEtD,IAAI,IAA4C;AAC9C,SAAO,MAAKA,KAAM,IAAI,GAAG;;CAG3B,IAAI,IAAqB;AACvB,SAAO,MAAKA,KAAM,IAAI,GAAG;;CAG3B,SAAS,OAAiC;AACxC,MAAI,MAAKA,KAAM,IAAI,MAAM,GAAG,CAC1B,OAAM,IAAI,MAAM,kBAAkB,MAAM,GAAG,yBAAyB;AAEtE,QAAKA,KAAM,IAAI,MAAM,IAAI,MAAM;;CAGjC,EAAE,OAAO,YAA0C;AACjD,SAAO,MAAKA,KAAM,QAAQ;;CAG5B,SAA+C;AAC7C,SAAO,MAAKA,KAAM,QAAQ;;;AAI9B,SAAgB,2BAA+C;AAC7D,QAAO,IAAI,wBAAwB;;;;;;;;;;;;;;;;;;;;ACqBrC,SAAgB,WAMd,QAQwC;CACxC,MAAM,YAAY,MAAe;CAOjC,MAAM,aAAa,OAAO;CAC1B,MAAM,aAAa,OAAO;CAC1B,MAAM,gBAAgB;AAItB,QAAO;EACL,IAAI,OAAO;EACX,aAAa,OAAO;EACpB,GAAG,UACD,UACA,OAAO,SAAU,OAAO,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC,GAAe,OAClE;EACD,GAAG,UAAU,oBAAoB,OAAO,iBAAiB;EACzD,SAAS,OAAO,QAAQ;AACtB,OAAI;AACF,WAAO,QAAQ,QAAQ,WAAW,OAAO,IAAI,CAAC;YACvC,OAAO;AACd,WAAO,QAAQ,OAAO,MAAM;;;EAGhC,SAAS,MAAM,QAAQ;AACrB,OAAI;AACF,WAAO,QAAQ,QAAQ,WAAW,MAAM,IAAI,CAAC;YACtC,OAAO;AACd,WAAO,QAAQ,OAAO,MAAM;;;EAGhC,YAAa,cAAc,cAAc;EACzC,YAAa,cAAc,cAAc;EAC1C"}
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@prisma-next/mongo-codec",
3
- "version": "0.5.0-dev.5",
3
+ "version": "0.5.0-dev.51",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "Codec interface and registry for Prisma Next MongoDB support",
7
7
  "dependencies": {
8
- "@prisma-next/contract": "0.5.0-dev.5",
9
- "@prisma-next/framework-components": "0.5.0-dev.5"
8
+ "@prisma-next/framework-components": "0.5.0-dev.51",
9
+ "@prisma-next/utils": "0.5.0-dev.51",
10
+ "@prisma-next/contract": "0.5.0-dev.51"
10
11
  },
11
12
  "devDependencies": {
12
13
  "tsdown": "0.18.4",
package/src/codecs.ts CHANGED
@@ -1,50 +1,120 @@
1
1
  import type { JsonValue } from '@prisma-next/contract/types';
2
- import type { Codec as BaseCodec, CodecTrait } from '@prisma-next/framework-components/codec';
2
+ import type {
3
+ Codec as BaseCodec,
4
+ CodecCallContext,
5
+ CodecTrait,
6
+ } from '@prisma-next/framework-components/codec';
7
+ import { ifDefined } from '@prisma-next/utils/defined';
3
8
 
4
9
  export type MongoCodecTrait = CodecTrait;
5
10
 
6
- export interface MongoCodec<
11
+ /**
12
+ * A codec for the Mongo target. Translates between an application value
13
+ * and the BSON-shaped wire form the Mongo driver exchanges, and between
14
+ * an application value and the JSON form stored in contract artifacts.
15
+ *
16
+ * Same shape as the framework codec base — see `Codec` in
17
+ * `@prisma-next/framework-components/codec` for the contract. The alias
18
+ * exists so Mongo-specific metadata can be added here in future without
19
+ * touching the framework base.
20
+ */
21
+ export type MongoCodec<
7
22
  Id extends string = string,
8
23
  TTraits extends readonly MongoCodecTrait[] = readonly MongoCodecTrait[],
9
24
  TWire = unknown,
10
- TJs = unknown,
11
- > extends BaseCodec<Id, TTraits, TWire, TJs> {
12
- readonly traits: TTraits;
13
- }
25
+ TInput = unknown,
26
+ > = BaseCodec<Id, TTraits, TWire, TInput>;
27
+
28
+ /**
29
+ * Conditional bundle for `encodeJson`/`decodeJson`: when `TInput` is
30
+ * structurally assignable to `JsonValue` the identity defaults are
31
+ * sound and both fields are optional; otherwise both fields are
32
+ * required so an author cannot silently produce a non-JSON-safe
33
+ * contract artifact.
34
+ */
35
+ type JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]
36
+ ? {
37
+ encodeJson?: (value: TInput) => JsonValue;
38
+ decodeJson?: (json: JsonValue) => TInput;
39
+ }
40
+ : {
41
+ encodeJson: (value: TInput) => JsonValue;
42
+ decodeJson: (json: JsonValue) => TInput;
43
+ };
14
44
 
45
+ /**
46
+ * Construct a Mongo codec from author functions.
47
+ *
48
+ * Author `encode` and `decode` as sync or async functions; the factory
49
+ * produces a {@link MongoCodec} whose query-time methods follow the
50
+ * boundary contract documented on the framework {@link BaseCodec}.
51
+ * Authors receive a second `ctx` options argument carrying the per-call
52
+ * context; ignore it if you don't need it.
53
+ *
54
+ * Both `encode` and `decode` are required so `TInput` and `TWire` are
55
+ * always covered by an explicit author function — the factory installs
56
+ * no identity fallback. `encodeJson` and `decodeJson` default to identity
57
+ * **only when `TInput` is assignable to `JsonValue`**; otherwise both are
58
+ * required so the contract artifact stays JSON-safe.
59
+ */
15
60
  export function mongoCodec<
16
61
  Id extends string,
17
62
  const TTraits extends readonly MongoCodecTrait[] = readonly [],
18
63
  TWire = unknown,
19
- TJs = unknown,
20
- >(config: {
21
- typeId: Id;
22
- targetTypes: readonly string[];
23
- traits?: TTraits;
24
- encode: (value: TJs) => TWire;
25
- decode: (wire: TWire) => TJs;
26
- encodeJson?: (value: TJs) => JsonValue;
27
- decodeJson?: (json: JsonValue) => TJs;
28
- renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;
29
- }): MongoCodec<Id, TTraits, TWire, TJs> {
30
- const traits = config.traits
31
- ? (Object.freeze([...config.traits]) as TTraits)
32
- : (Object.freeze([] as const) as unknown as TTraits);
64
+ TInput = unknown,
65
+ >(
66
+ config: {
67
+ typeId: Id;
68
+ targetTypes: readonly string[];
69
+ traits?: TTraits;
70
+ encode: (value: TInput, ctx: CodecCallContext) => TWire | Promise<TWire>;
71
+ decode: (wire: TWire, ctx: CodecCallContext) => TInput | Promise<TInput>;
72
+ renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;
73
+ } & JsonRoundTripConfig<TInput>,
74
+ ): MongoCodec<Id, TTraits, TWire, TInput> {
33
75
  const identity = (v: unknown) => v;
76
+ // The runtime allocates one `CodecCallContext` per `runtime.execute()`
77
+ // call (no caller-supplied `signal` produces `{}` instead of `undefined`)
78
+ // and threads it as a non-optional reference to every codec call. The
79
+ // author surface keeps the second parameter optional so single-arg
80
+ // `(value) => …` authors continue to satisfy the signature via
81
+ // TypeScript's bivariance for trailing parameters.
82
+ const userEncode = config.encode;
83
+ const userDecode = config.decode;
84
+ const widenedConfig = config as {
85
+ encodeJson?: (value: TInput) => JsonValue;
86
+ decodeJson?: (json: JsonValue) => TInput;
87
+ };
34
88
  return {
35
89
  id: config.typeId,
36
90
  targetTypes: config.targetTypes,
37
- traits,
38
- decode: config.decode,
39
- encode: config.encode,
40
- encodeJson: (config.encodeJson ?? identity) as (value: TJs) => JsonValue,
41
- decodeJson: (config.decodeJson ?? identity) as (json: JsonValue) => TJs,
42
- ...(config.renderOutputType ? { renderOutputType: config.renderOutputType } : {}),
91
+ ...ifDefined(
92
+ 'traits',
93
+ config.traits ? (Object.freeze([...config.traits]) as TTraits) : undefined,
94
+ ),
95
+ ...ifDefined('renderOutputType', config.renderOutputType),
96
+ encode: (value, ctx) => {
97
+ try {
98
+ return Promise.resolve(userEncode(value, ctx));
99
+ } catch (error) {
100
+ return Promise.reject(error);
101
+ }
102
+ },
103
+ decode: (wire, ctx) => {
104
+ try {
105
+ return Promise.resolve(userDecode(wire, ctx));
106
+ } catch (error) {
107
+ return Promise.reject(error);
108
+ }
109
+ },
110
+ encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,
111
+ decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,
43
112
  };
44
113
  }
45
114
 
46
- export type MongoCodecJsType<T> =
47
- T extends MongoCodec<string, readonly MongoCodecTrait[], unknown, infer TJs> ? TJs : never;
115
+ /** Extract the JS application type carried by a Mongo codec — used both as `encode` input and as `decode` output. */
116
+ export type MongoCodecInput<T> =
117
+ T extends MongoCodec<string, readonly MongoCodecTrait[], unknown, infer TInput> ? TInput : never;
48
118
 
49
119
  export type MongoCodecTraits<T> =
50
120
  T extends MongoCodec<string, infer TTraits> ? TTraits[number] & MongoCodecTrait : never;
@@ -1,4 +1,9 @@
1
1
  export type { MongoCodecRegistry } from '../codec-registry';
2
2
  export { createMongoCodecRegistry } from '../codec-registry';
3
- export type { MongoCodec, MongoCodecJsType, MongoCodecTrait, MongoCodecTraits } from '../codecs';
3
+ export type {
4
+ MongoCodec,
5
+ MongoCodecInput,
6
+ MongoCodecTrait,
7
+ MongoCodecTraits,
8
+ } from '../codecs';
4
9
  export { mongoCodec } from '../codecs';