@prisma-next/mongo-codec 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 +26 -7
- package/dist/index.d.mts +18 -33
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +28 -43
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -8
- package/src/codec-registry.ts +19 -29
- package/src/codecs.ts +22 -47
- package/src/exports/index.ts +2 -7
package/README.md
CHANGED
|
@@ -4,10 +4,10 @@ Codec interface and registry for MongoDB value serialization.
|
|
|
4
4
|
|
|
5
5
|
## Responsibilities
|
|
6
6
|
|
|
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.
|
|
8
|
-
- **Codec factory**: `mongoCodec()` — creates frozen codec instances from a config object. `encode`
|
|
9
|
-
- **Codec registry**: `MongoCodecRegistry` and `
|
|
10
|
-
- **Type-level
|
|
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. Same four generics as the framework `Codec` base; the codec instance carries only `id` plus the four conversion methods. Trait annotations (`equality`, `order`, `boolean`, `numeric`, `textual`, `vector`) for operator gating live on the unified `CodecDescriptor` (see [ADR 208](../../../../docs/architecture%20docs/adrs/ADR%20208%20-%20Higher-order%20codecs%20for%20parameterized%20types.md)).
|
|
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
|
+
- **Codec registry**: `MongoCodecRegistry` and `newMongoCodecRegistry()` — a map-based container that stores and retrieves codecs by ID, with duplicate-ID protection
|
|
10
|
+
- **Type-level helper**: `MongoCodecInput<T>` for extracting the JS application type from a codec type. Trait metadata lives on the unified `CodecDescriptor` (see [ADR 208](../../../../docs/architecture%20docs/adrs/ADR%20208%20-%20Higher-order%20codecs%20for%20parameterized%20types.md)).
|
|
11
11
|
|
|
12
12
|
## Examples
|
|
13
13
|
|
|
@@ -15,7 +15,6 @@ Codec interface and registry for MongoDB value serialization.
|
|
|
15
15
|
// Sync authoring:
|
|
16
16
|
const intCodec = mongoCodec({
|
|
17
17
|
typeId: 'mongo/int@1',
|
|
18
|
-
targetTypes: ['int'],
|
|
19
18
|
encode: (v: number) => v,
|
|
20
19
|
decode: (w: number) => w,
|
|
21
20
|
encodeJson: (v: number) => v,
|
|
@@ -25,7 +24,6 @@ const intCodec = mongoCodec({
|
|
|
25
24
|
// Async authoring (e.g. KMS-backed encryption): same factory, same shape.
|
|
26
25
|
const secretCodec = mongoCodec({
|
|
27
26
|
typeId: 'mongo/secret@1',
|
|
28
|
-
targetTypes: ['string'],
|
|
29
27
|
encode: async (v: string) => encrypt(v, await getKey()),
|
|
30
28
|
decode: async (w: string) => decrypt(w, await getKey()),
|
|
31
29
|
encodeJson: (v: string) => v,
|
|
@@ -33,7 +31,28 @@ const secretCodec = mongoCodec({
|
|
|
33
31
|
});
|
|
34
32
|
```
|
|
35
33
|
|
|
36
|
-
|
|
34
|
+
### Codec call context (`ctx`)
|
|
35
|
+
|
|
36
|
+
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.
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
// Forward ctx.signal to a network SDK so aborted queries stop the round-trip.
|
|
40
|
+
const kmsSecretCodec = mongoCodec({
|
|
41
|
+
typeId: 'mongo/kms-secret@1',
|
|
42
|
+
encode: async (v: string, ctx) =>
|
|
43
|
+
kms.encrypt({ plaintext: v }, { signal: ctx?.signal }),
|
|
44
|
+
decode: async (w: string, ctx) =>
|
|
45
|
+
kms.decrypt({ ciphertext: w }, { signal: ctx?.signal }),
|
|
46
|
+
encodeJson: (v: string) => v,
|
|
47
|
+
decodeJson: (j: string) => j,
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
> **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' }`.
|
|
52
|
+
|
|
53
|
+
Codec bodies that ignore `ctx.signal` complete in the background (cooperative cancellation); aborts still surface to the caller as `RUNTIME.ABORTED`.
|
|
54
|
+
|
|
55
|
+
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.
|
|
37
56
|
|
|
38
57
|
## Dependencies
|
|
39
58
|
|
package/dist/index.d.mts
CHANGED
|
@@ -1,25 +1,16 @@
|
|
|
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
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.
|
|
7
|
+
* A codec for the Mongo target. Translates between an application value and the BSON-shaped wire form the Mongo driver exchanges, and between an application value and the JSON form stored in contract artifacts.
|
|
10
8
|
*
|
|
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.
|
|
9
|
+
* Same shape as the framework codec base — see `Codec` in `@prisma-next/framework-components/codec` for the contract. Codec-id-keyed static metadata (`traits`, `targetTypes`, `renderOutputType`) lives on the unified {@link import('@prisma-next/framework-components/codec').CodecDescriptor}; Mongo's full migration to descriptor-side registration is tracked under TML-2324.
|
|
15
10
|
*/
|
|
16
|
-
|
|
11
|
+
interface MongoCodec<Id extends string = string, TTraits extends readonly MongoCodecTrait[] = readonly MongoCodecTrait[], TWire = unknown, TInput = unknown> extends Codec<Id, TTraits, TWire, TInput> {}
|
|
17
12
|
/**
|
|
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.
|
|
13
|
+
* Conditional bundle for `encodeJson`/`decodeJson`: when `TInput` is structurally assignable to `JsonValue` the identity defaults are sound and both fields are optional; otherwise both fields are required so an author cannot silently produce a non-JSON-safe contract artifact.
|
|
23
14
|
*/
|
|
24
15
|
type JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue] ? {
|
|
25
16
|
encodeJson?: (value: TInput) => JsonValue;
|
|
@@ -31,28 +22,19 @@ type JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue] ? {
|
|
|
31
22
|
/**
|
|
32
23
|
* Construct a Mongo codec from author functions.
|
|
33
24
|
*
|
|
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}.
|
|
25
|
+
* Author `encode` and `decode` as sync or async functions; the factory produces a {@link MongoCodec} whose query-time methods follow the boundary contract documented on the framework {@link BaseCodec}. Authors receive a second `ctx` options argument carrying the per-call context; ignore it if you don't need it.
|
|
37
26
|
*
|
|
38
|
-
* `encode`
|
|
39
|
-
*
|
|
40
|
-
* `
|
|
41
|
-
* required. `encodeJson` and `decodeJson` default to identity **only when
|
|
42
|
-
* `TInput` is assignable to `JsonValue`**; otherwise both are required so
|
|
43
|
-
* the contract artifact stays JSON-safe.
|
|
27
|
+
* Both `encode` and `decode` are required so `TInput` and `TWire` are always covered by an explicit author function — the factory installs no identity fallback. `encodeJson` and `decodeJson` default to identity **only when `TInput` is assignable to `JsonValue`**; otherwise both are required so the contract artifact stays JSON-safe.
|
|
28
|
+
*
|
|
29
|
+
* Codec-id-keyed static metadata (`traits`, `targetTypes`, `renderOutputType`) lives on the unified `CodecDescriptor` rather than on the codec instance itself (TML-2357).
|
|
44
30
|
*/
|
|
45
|
-
declare function mongoCodec<Id extends string, const TTraits
|
|
31
|
+
declare function mongoCodec<Id extends string, const TTraits extends readonly MongoCodecTrait[] = readonly [], TWire = unknown, TInput = unknown>(config: {
|
|
46
32
|
typeId: Id;
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
decode: (wire: TWire) => TInput | Promise<TInput>;
|
|
51
|
-
renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;
|
|
52
|
-
} & JsonRoundTripConfig<TInput>): MongoCodec<Id, TTraits$1, TWire, TInput>;
|
|
33
|
+
encode: (value: TInput, ctx: CodecCallContext) => TWire | Promise<TWire>;
|
|
34
|
+
decode: (wire: TWire, ctx: CodecCallContext) => TInput | Promise<TInput>;
|
|
35
|
+
} & JsonRoundTripConfig<TInput>): MongoCodec<Id, TTraits, TWire, TInput>;
|
|
53
36
|
/** Extract the JS application type carried by a Mongo codec — used both as `encode` input and as `decode` output. */
|
|
54
37
|
type MongoCodecInput<T> = T extends MongoCodec<string, readonly MongoCodecTrait[], unknown, infer TInput> ? TInput : never;
|
|
55
|
-
type MongoCodecTraits<T> = T extends MongoCodec<string, infer TTraits> ? TTraits[number] & MongoCodecTrait : never;
|
|
56
38
|
//#endregion
|
|
57
39
|
//#region src/codec-registry.d.ts
|
|
58
40
|
interface MongoCodecRegistry {
|
|
@@ -62,7 +44,10 @@ interface MongoCodecRegistry {
|
|
|
62
44
|
[Symbol.iterator](): Iterator<MongoCodec<string>>;
|
|
63
45
|
values(): IterableIterator<MongoCodec<string>>;
|
|
64
46
|
}
|
|
65
|
-
|
|
47
|
+
/**
|
|
48
|
+
* Create a new Mongo codec registry. Inline object literal — no class implementation; the registry is just a private `Map` with the documented surface methods.
|
|
49
|
+
*/
|
|
50
|
+
declare function newMongoCodecRegistry(): MongoCodecRegistry;
|
|
66
51
|
//#endregion
|
|
67
|
-
export { type MongoCodec, type MongoCodecInput, type MongoCodecRegistry, type MongoCodecTrait,
|
|
52
|
+
export { type MongoCodec, type MongoCodecInput, type MongoCodecRegistry, type MongoCodecTrait, mongoCodec, newMongoCodecRegistry };
|
|
68
53
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/codecs.ts","../src/codec-registry.ts"],"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/codecs.ts","../src/codec-registry.ts"],"mappings":";;;;KAOY,eAAA,GAAkB,UAAA;;AAA9B;;;;UAOiB,UAAA,sDAEU,eAAA,cAA6B,eAAA,+CAG9C,KAAA,CAAU,EAAA,EAAI,OAAA,EAAS,KAAA,EAAO,MAAA;;;;KAKnC,mBAAA,YAA+B,MAAA,WAAiB,SAAA;EAE/C,UAAA,IAAc,KAAA,EAAO,MAAA,KAAW,SAAA;EAChC,UAAA,IAAc,IAAA,EAAM,SAAA,KAAc,MAAA;AAAA;EAGlC,UAAA,GAAa,KAAA,EAAO,MAAA,KAAW,SAAA;EAC/B,UAAA,GAAa,IAAA,EAAM,SAAA,KAAc,MAAA;AAAA;;;;;;;;;;iBAYvB,UAAA,mDAEiB,eAAA,oDAAA,CAI/B,MAAA;EACE,MAAA,EAAQ,EAAA;EACR,MAAA,GAAS,KAAA,EAAO,MAAA,EAAQ,GAAA,EAAK,gBAAA,KAAqB,KAAA,GAAQ,OAAA,CAAQ,KAAA;EAClE,MAAA,GAAS,IAAA,EAAM,KAAA,EAAO,GAAA,EAAK,gBAAA,KAAqB,MAAA,GAAS,OAAA,CAAQ,MAAA;AAAA,IAC/D,mBAAA,CAAoB,MAAA,IACvB,UAAA,CAAW,EAAA,EAAI,OAAA,EAAS,KAAA,EAAO,MAAA;AAnCgB;AAAA,KAkEtC,eAAA,MACV,CAAA,SAAU,UAAA,kBAA4B,eAAA,6BAA4C,MAAA;;;UCpFnE,kBAAA;EACf,GAAA,CAAI,EAAA,WAAa,UAAA;EACjB,GAAA,CAAI,EAAA;EACJ,QAAA,CAAS,KAAA,EAAO,UAAA;EAAA,CACf,MAAA,CAAO,QAAP,KAAoB,QAAA,CAAS,UAAA;EAC9B,MAAA,IAAU,gBAAA,CAAiB,UAAA;AAAA;;ADO7B;;iBCDgB,qBAAA,CAAA,GAAyB,kBAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,65 +1,50 @@
|
|
|
1
|
-
import { ifDefined } from "@prisma-next/utils/defined";
|
|
2
|
-
|
|
3
1
|
//#region src/codec-registry.ts
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
};
|
|
23
|
-
function createMongoCodecRegistry() {
|
|
24
|
-
return new MongoCodecRegistryImpl();
|
|
2
|
+
/**
|
|
3
|
+
* Create a new Mongo codec registry. Inline object literal — no class implementation; the registry is just a private `Map` with the documented surface methods.
|
|
4
|
+
*/
|
|
5
|
+
function newMongoCodecRegistry() {
|
|
6
|
+
const byId = /* @__PURE__ */ new Map();
|
|
7
|
+
return {
|
|
8
|
+
get: (id) => byId.get(id),
|
|
9
|
+
has: (id) => byId.has(id),
|
|
10
|
+
register: (codec) => {
|
|
11
|
+
if (byId.has(codec.id)) throw new Error(`Codec with ID '${codec.id}' is already registered`);
|
|
12
|
+
byId.set(codec.id, codec);
|
|
13
|
+
},
|
|
14
|
+
values: () => byId.values(),
|
|
15
|
+
[Symbol.iterator]: function* () {
|
|
16
|
+
yield* byId.values();
|
|
17
|
+
}
|
|
18
|
+
};
|
|
25
19
|
}
|
|
26
|
-
|
|
27
20
|
//#endregion
|
|
28
21
|
//#region src/codecs.ts
|
|
29
22
|
/**
|
|
30
23
|
* Construct a Mongo codec from author functions.
|
|
31
24
|
*
|
|
32
|
-
* Author `encode` and `decode` as sync or async functions; the factory
|
|
33
|
-
*
|
|
34
|
-
*
|
|
25
|
+
* Author `encode` and `decode` as sync or async functions; the factory produces a {@link MongoCodec} whose query-time methods follow the boundary contract documented on the framework {@link BaseCodec}. Authors receive a second `ctx` options argument carrying the per-call context; ignore it if you don't need it.
|
|
26
|
+
*
|
|
27
|
+
* Both `encode` and `decode` are required so `TInput` and `TWire` are always covered by an explicit author function — the factory installs no identity fallback. `encodeJson` and `decodeJson` default to identity **only when `TInput` is assignable to `JsonValue`**; otherwise both are required so the contract artifact stays JSON-safe.
|
|
35
28
|
*
|
|
36
|
-
* `
|
|
37
|
-
* (declaring "the input value already is the wire value", so `TInput` and
|
|
38
|
-
* `TWire` are interchangeable for that codec). `decode` is always
|
|
39
|
-
* required. `encodeJson` and `decodeJson` default to identity **only when
|
|
40
|
-
* `TInput` is assignable to `JsonValue`**; otherwise both are required so
|
|
41
|
-
* the contract artifact stays JSON-safe.
|
|
29
|
+
* Codec-id-keyed static metadata (`traits`, `targetTypes`, `renderOutputType`) lives on the unified `CodecDescriptor` rather than on the codec instance itself (TML-2357).
|
|
42
30
|
*/
|
|
43
31
|
function mongoCodec(config) {
|
|
44
32
|
const identity = (v) => v;
|
|
45
|
-
const userEncode = config.encode
|
|
33
|
+
const userEncode = config.encode;
|
|
46
34
|
const userDecode = config.decode;
|
|
47
35
|
const widenedConfig = config;
|
|
48
36
|
return {
|
|
49
37
|
id: config.typeId,
|
|
50
|
-
|
|
51
|
-
...ifDefined("traits", config.traits ? Object.freeze([...config.traits]) : void 0),
|
|
52
|
-
...ifDefined("renderOutputType", config.renderOutputType),
|
|
53
|
-
encode: (value) => {
|
|
38
|
+
encode: (value, ctx) => {
|
|
54
39
|
try {
|
|
55
|
-
return Promise.resolve(userEncode(value));
|
|
40
|
+
return Promise.resolve(userEncode(value, ctx));
|
|
56
41
|
} catch (error) {
|
|
57
42
|
return Promise.reject(error);
|
|
58
43
|
}
|
|
59
44
|
},
|
|
60
|
-
decode: (wire) => {
|
|
45
|
+
decode: (wire, ctx) => {
|
|
61
46
|
try {
|
|
62
|
-
return Promise.resolve(userDecode(wire));
|
|
47
|
+
return Promise.resolve(userDecode(wire, ctx));
|
|
63
48
|
} catch (error) {
|
|
64
49
|
return Promise.reject(error);
|
|
65
50
|
}
|
|
@@ -68,7 +53,7 @@ function mongoCodec(config) {
|
|
|
68
53
|
decodeJson: widenedConfig.decodeJson ?? identity
|
|
69
54
|
};
|
|
70
55
|
}
|
|
71
|
-
|
|
72
56
|
//#endregion
|
|
73
|
-
export {
|
|
57
|
+
export { mongoCodec, newMongoCodecRegistry };
|
|
58
|
+
|
|
74
59
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"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\n/**\n * Create a new Mongo codec registry. Inline object literal — no class implementation; the registry is just a private `Map` with the documented surface methods.\n */\nexport function newMongoCodecRegistry(): MongoCodecRegistry {\n const byId = new Map<string, MongoCodec<string>>();\n return {\n get: (id) => byId.get(id),\n has: (id) => byId.has(id),\n register: (codec) => {\n if (byId.has(codec.id)) {\n throw new Error(`Codec with ID '${codec.id}' is already registered`);\n }\n byId.set(codec.id, codec);\n },\n values: () => byId.values(),\n [Symbol.iterator]: function* () {\n yield* byId.values();\n },\n };\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';\n\nexport type MongoCodecTrait = CodecTrait;\n\n/**\n * A codec for the Mongo target. Translates between an application value and the BSON-shaped wire form the Mongo driver exchanges, and between an application value and the JSON form stored in contract artifacts.\n *\n * Same shape as the framework codec base — see `Codec` in `@prisma-next/framework-components/codec` for the contract. Codec-id-keyed static metadata (`traits`, `targetTypes`, `renderOutputType`) lives on the unified {@link import('@prisma-next/framework-components/codec').CodecDescriptor}; Mongo's full migration to descriptor-side registration is tracked under TML-2324.\n */\nexport interface MongoCodec<\n Id extends string = string,\n TTraits extends readonly MongoCodecTrait[] = readonly MongoCodecTrait[],\n TWire = unknown,\n TInput = unknown,\n> extends BaseCodec<Id, TTraits, TWire, TInput> {}\n\n/**\n * Conditional bundle for `encodeJson`/`decodeJson`: when `TInput` is structurally assignable to `JsonValue` the identity defaults are sound and both fields are optional; otherwise both fields are required so an author cannot silently produce a non-JSON-safe 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 produces a {@link MongoCodec} whose query-time methods follow the boundary contract documented on the framework {@link BaseCodec}. Authors receive a second `ctx` options argument carrying the per-call context; ignore it if you don't need it.\n *\n * Both `encode` and `decode` are required so `TInput` and `TWire` are always covered by an explicit author function — the factory installs no identity fallback. `encodeJson` and `decodeJson` default to identity **only when `TInput` is assignable to `JsonValue`**; otherwise both are required so the contract artifact stays JSON-safe.\n *\n * Codec-id-keyed static metadata (`traits`, `targetTypes`, `renderOutputType`) lives on the unified `CodecDescriptor` rather than on the codec instance itself (TML-2357).\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 encode: (value: TInput, ctx: CodecCallContext) => TWire | Promise<TWire>;\n decode: (wire: TWire, ctx: CodecCallContext) => TInput | Promise<TInput>;\n } & JsonRoundTripConfig<TInput>,\n): MongoCodec<Id, TTraits, TWire, TInput> {\n const identity = (v: unknown) => v;\n // The runtime allocates one `CodecCallContext` per `runtime.execute()` call (no caller-supplied `signal` produces `{}` instead of `undefined`) and threads it as a non-optional reference to every codec call. The author surface keeps the second parameter optional so single-arg `(value) => …` authors continue to satisfy the signature via 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 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"],"mappings":";;;;AAaA,SAAgB,wBAA4C;CAC1D,MAAM,uBAAO,IAAI,KAAiC;CAClD,OAAO;EACL,MAAM,OAAO,KAAK,IAAI,GAAG;EACzB,MAAM,OAAO,KAAK,IAAI,GAAG;EACzB,WAAW,UAAU;GACnB,IAAI,KAAK,IAAI,MAAM,GAAG,EACpB,MAAM,IAAI,MAAM,kBAAkB,MAAM,GAAG,yBAAyB;GAEtE,KAAK,IAAI,MAAM,IAAI,MAAM;;EAE3B,cAAc,KAAK,QAAQ;EAC3B,CAAC,OAAO,WAAW,aAAa;GAC9B,OAAO,KAAK,QAAQ;;EAEvB;;;;;;;;;;;;;ACeH,SAAgB,WAMd,QAKwC;CACxC,MAAM,YAAY,MAAe;CAEjC,MAAM,aAAa,OAAO;CAC1B,MAAM,aAAa,OAAO;CAC1B,MAAM,gBAAgB;CAItB,OAAO;EACL,IAAI,OAAO;EACX,SAAS,OAAO,QAAQ;GACtB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,OAAO,IAAI,CAAC;YACvC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGhC,SAAS,MAAM,QAAQ;GACrB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,MAAM,IAAI,CAAC;YACtC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGhC,YAAa,cAAc,cAAc;EACzC,YAAa,cAAc,cAAc;EAC1C"}
|
package/package.json
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/mongo-codec",
|
|
3
|
-
"version": "0.5.0
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
4
5
|
"type": "module",
|
|
5
6
|
"sideEffects": false,
|
|
6
7
|
"description": "Codec interface and registry for Prisma Next MongoDB support",
|
|
7
8
|
"dependencies": {
|
|
8
|
-
"@prisma-next/framework-components": "0.5.0
|
|
9
|
-
"@prisma-next/utils": "0.5.0
|
|
10
|
-
"@prisma-next/contract": "0.5.0
|
|
9
|
+
"@prisma-next/framework-components": "0.5.0",
|
|
10
|
+
"@prisma-next/utils": "0.5.0",
|
|
11
|
+
"@prisma-next/contract": "0.5.0"
|
|
11
12
|
},
|
|
12
13
|
"devDependencies": {
|
|
13
|
-
"tsdown": "0.
|
|
14
|
+
"tsdown": "0.22.0",
|
|
14
15
|
"typescript": "5.9.3",
|
|
15
|
-
"vitest": "4.
|
|
16
|
-
"@prisma-next/
|
|
16
|
+
"vitest": "4.1.5",
|
|
17
|
+
"@prisma-next/tsconfig": "0.0.0",
|
|
17
18
|
"@prisma-next/tsdown": "0.0.0",
|
|
18
|
-
"@prisma-next/
|
|
19
|
+
"@prisma-next/test-utils": "0.0.1"
|
|
19
20
|
},
|
|
20
21
|
"files": [
|
|
21
22
|
"dist",
|
package/src/codec-registry.ts
CHANGED
|
@@ -8,33 +8,23 @@ export interface MongoCodecRegistry {
|
|
|
8
8
|
values(): IterableIterator<MongoCodec<string>>;
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
yield* this.#byId.values();
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
values(): IterableIterator<MongoCodec<string>> {
|
|
34
|
-
return this.#byId.values();
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export function createMongoCodecRegistry(): MongoCodecRegistry {
|
|
39
|
-
return new MongoCodecRegistryImpl();
|
|
11
|
+
/**
|
|
12
|
+
* Create a new Mongo codec registry. Inline object literal — no class implementation; the registry is just a private `Map` with the documented surface methods.
|
|
13
|
+
*/
|
|
14
|
+
export function newMongoCodecRegistry(): MongoCodecRegistry {
|
|
15
|
+
const byId = new Map<string, MongoCodec<string>>();
|
|
16
|
+
return {
|
|
17
|
+
get: (id) => byId.get(id),
|
|
18
|
+
has: (id) => byId.has(id),
|
|
19
|
+
register: (codec) => {
|
|
20
|
+
if (byId.has(codec.id)) {
|
|
21
|
+
throw new Error(`Codec with ID '${codec.id}' is already registered`);
|
|
22
|
+
}
|
|
23
|
+
byId.set(codec.id, codec);
|
|
24
|
+
},
|
|
25
|
+
values: () => byId.values(),
|
|
26
|
+
[Symbol.iterator]: function* () {
|
|
27
|
+
yield* byId.values();
|
|
28
|
+
},
|
|
29
|
+
};
|
|
40
30
|
}
|
package/src/codecs.ts
CHANGED
|
@@ -1,32 +1,26 @@
|
|
|
1
1
|
import type { JsonValue } from '@prisma-next/contract/types';
|
|
2
|
-
import type {
|
|
3
|
-
|
|
2
|
+
import type {
|
|
3
|
+
Codec as BaseCodec,
|
|
4
|
+
CodecCallContext,
|
|
5
|
+
CodecTrait,
|
|
6
|
+
} from '@prisma-next/framework-components/codec';
|
|
4
7
|
|
|
5
8
|
export type MongoCodecTrait = CodecTrait;
|
|
6
9
|
|
|
7
10
|
/**
|
|
8
|
-
* A codec for the Mongo target. Translates between an application value
|
|
9
|
-
* and the BSON-shaped wire form the Mongo driver exchanges, and between
|
|
10
|
-
* an application value and the JSON form stored in contract artifacts.
|
|
11
|
+
* A codec for the Mongo target. Translates between an application value and the BSON-shaped wire form the Mongo driver exchanges, and between an application value and the JSON form stored in contract artifacts.
|
|
11
12
|
*
|
|
12
|
-
* Same shape as the framework codec base — see `Codec` in
|
|
13
|
-
* `@prisma-next/framework-components/codec` for the contract. The alias
|
|
14
|
-
* exists so Mongo-specific metadata can be added here in future without
|
|
15
|
-
* touching the framework base.
|
|
13
|
+
* Same shape as the framework codec base — see `Codec` in `@prisma-next/framework-components/codec` for the contract. Codec-id-keyed static metadata (`traits`, `targetTypes`, `renderOutputType`) lives on the unified {@link import('@prisma-next/framework-components/codec').CodecDescriptor}; Mongo's full migration to descriptor-side registration is tracked under TML-2324.
|
|
16
14
|
*/
|
|
17
|
-
export
|
|
15
|
+
export interface MongoCodec<
|
|
18
16
|
Id extends string = string,
|
|
19
17
|
TTraits extends readonly MongoCodecTrait[] = readonly MongoCodecTrait[],
|
|
20
18
|
TWire = unknown,
|
|
21
19
|
TInput = unknown,
|
|
22
|
-
>
|
|
20
|
+
> extends BaseCodec<Id, TTraits, TWire, TInput> {}
|
|
23
21
|
|
|
24
22
|
/**
|
|
25
|
-
* Conditional bundle for `encodeJson`/`decodeJson`: when `TInput` is
|
|
26
|
-
* structurally assignable to `JsonValue` the identity defaults are
|
|
27
|
-
* sound and both fields are optional; otherwise both fields are
|
|
28
|
-
* required so an author cannot silently produce a non-JSON-safe
|
|
29
|
-
* contract artifact.
|
|
23
|
+
* Conditional bundle for `encodeJson`/`decodeJson`: when `TInput` is structurally assignable to `JsonValue` the identity defaults are sound and both fields are optional; otherwise both fields are required so an author cannot silently produce a non-JSON-safe contract artifact.
|
|
30
24
|
*/
|
|
31
25
|
type JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]
|
|
32
26
|
? {
|
|
@@ -41,16 +35,11 @@ type JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]
|
|
|
41
35
|
/**
|
|
42
36
|
* Construct a Mongo codec from author functions.
|
|
43
37
|
*
|
|
44
|
-
* Author `encode` and `decode` as sync or async functions; the factory
|
|
45
|
-
* produces a {@link MongoCodec} whose query-time methods follow the
|
|
46
|
-
* boundary contract documented on the framework {@link BaseCodec}.
|
|
38
|
+
* Author `encode` and `decode` as sync or async functions; the factory produces a {@link MongoCodec} whose query-time methods follow the boundary contract documented on the framework {@link BaseCodec}. Authors receive a second `ctx` options argument carrying the per-call context; ignore it if you don't need it.
|
|
47
39
|
*
|
|
48
|
-
* `encode`
|
|
49
|
-
*
|
|
50
|
-
* `
|
|
51
|
-
* required. `encodeJson` and `decodeJson` default to identity **only when
|
|
52
|
-
* `TInput` is assignable to `JsonValue`**; otherwise both are required so
|
|
53
|
-
* the contract artifact stays JSON-safe.
|
|
40
|
+
* Both `encode` and `decode` are required so `TInput` and `TWire` are always covered by an explicit author function — the factory installs no identity fallback. `encodeJson` and `decodeJson` default to identity **only when `TInput` is assignable to `JsonValue`**; otherwise both are required so the contract artifact stays JSON-safe.
|
|
41
|
+
*
|
|
42
|
+
* Codec-id-keyed static metadata (`traits`, `targetTypes`, `renderOutputType`) lives on the unified `CodecDescriptor` rather than on the codec instance itself (TML-2357).
|
|
54
43
|
*/
|
|
55
44
|
export function mongoCodec<
|
|
56
45
|
Id extends string,
|
|
@@ -60,18 +49,13 @@ export function mongoCodec<
|
|
|
60
49
|
>(
|
|
61
50
|
config: {
|
|
62
51
|
typeId: Id;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
encode?: (value: TInput) => TWire | Promise<TWire>;
|
|
66
|
-
decode: (wire: TWire) => TInput | Promise<TInput>;
|
|
67
|
-
renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;
|
|
52
|
+
encode: (value: TInput, ctx: CodecCallContext) => TWire | Promise<TWire>;
|
|
53
|
+
decode: (wire: TWire, ctx: CodecCallContext) => TInput | Promise<TInput>;
|
|
68
54
|
} & JsonRoundTripConfig<TInput>,
|
|
69
55
|
): MongoCodec<Id, TTraits, TWire, TInput> {
|
|
70
56
|
const identity = (v: unknown) => v;
|
|
71
|
-
// The
|
|
72
|
-
|
|
73
|
-
// it returns the value directly, never a Promise.
|
|
74
|
-
const userEncode = config.encode ?? ((value: TInput) => value as unknown as TWire);
|
|
57
|
+
// The runtime allocates one `CodecCallContext` per `runtime.execute()` call (no caller-supplied `signal` produces `{}` instead of `undefined`) and threads it as a non-optional reference to every codec call. The author surface keeps the second parameter optional so single-arg `(value) => …` authors continue to satisfy the signature via TypeScript's bivariance for trailing parameters.
|
|
58
|
+
const userEncode = config.encode;
|
|
75
59
|
const userDecode = config.decode;
|
|
76
60
|
const widenedConfig = config as {
|
|
77
61
|
encodeJson?: (value: TInput) => JsonValue;
|
|
@@ -79,22 +63,16 @@ export function mongoCodec<
|
|
|
79
63
|
};
|
|
80
64
|
return {
|
|
81
65
|
id: config.typeId,
|
|
82
|
-
|
|
83
|
-
...ifDefined(
|
|
84
|
-
'traits',
|
|
85
|
-
config.traits ? (Object.freeze([...config.traits]) as TTraits) : undefined,
|
|
86
|
-
),
|
|
87
|
-
...ifDefined('renderOutputType', config.renderOutputType),
|
|
88
|
-
encode: (value) => {
|
|
66
|
+
encode: (value, ctx) => {
|
|
89
67
|
try {
|
|
90
|
-
return Promise.resolve(userEncode(value));
|
|
68
|
+
return Promise.resolve(userEncode(value, ctx));
|
|
91
69
|
} catch (error) {
|
|
92
70
|
return Promise.reject(error);
|
|
93
71
|
}
|
|
94
72
|
},
|
|
95
|
-
decode: (wire) => {
|
|
73
|
+
decode: (wire, ctx) => {
|
|
96
74
|
try {
|
|
97
|
-
return Promise.resolve(userDecode(wire));
|
|
75
|
+
return Promise.resolve(userDecode(wire, ctx));
|
|
98
76
|
} catch (error) {
|
|
99
77
|
return Promise.reject(error);
|
|
100
78
|
}
|
|
@@ -107,6 +85,3 @@ export function mongoCodec<
|
|
|
107
85
|
/** Extract the JS application type carried by a Mongo codec — used both as `encode` input and as `decode` output. */
|
|
108
86
|
export type MongoCodecInput<T> =
|
|
109
87
|
T extends MongoCodec<string, readonly MongoCodecTrait[], unknown, infer TInput> ? TInput : never;
|
|
110
|
-
|
|
111
|
-
export type MongoCodecTraits<T> =
|
|
112
|
-
T extends MongoCodec<string, infer TTraits> ? TTraits[number] & MongoCodecTrait : never;
|
package/src/exports/index.ts
CHANGED
|
@@ -1,9 +1,4 @@
|
|
|
1
1
|
export type { MongoCodecRegistry } from '../codec-registry';
|
|
2
|
-
export {
|
|
3
|
-
export type {
|
|
4
|
-
MongoCodec,
|
|
5
|
-
MongoCodecInput,
|
|
6
|
-
MongoCodecTrait,
|
|
7
|
-
MongoCodecTraits,
|
|
8
|
-
} from '../codecs';
|
|
2
|
+
export { newMongoCodecRegistry } from '../codec-registry';
|
|
3
|
+
export type { MongoCodec, MongoCodecInput, MongoCodecTrait } from '../codecs';
|
|
9
4
|
export { mongoCodec } from '../codecs';
|