@prisma-next/framework-components 0.5.0-dev.60 → 0.5.0-dev.61
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 +11 -12
- package/dist/codec-BUBJeOk4.d.mts +168 -0
- package/dist/codec-BUBJeOk4.d.mts.map +1 -0
- package/dist/codec.d.mts +49 -2
- package/dist/codec.d.mts.map +1 -0
- package/dist/codec.mjs +54 -25
- package/dist/codec.mjs.map +1 -1
- package/dist/components.d.mts +2 -2
- package/dist/control.d.mts +3 -3
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +27 -10
- package/dist/control.mjs.map +1 -1
- package/dist/execution.d.mts +2 -2
- package/dist/{framework-components-BvzjH6Pt.d.mts → framework-components-BVqm1I48.d.mts} +23 -49
- package/dist/framework-components-BVqm1I48.d.mts.map +1 -0
- package/dist/framework-components-BsWST1Rn.mjs.map +1 -1
- package/dist/psl-ast-BlDveJZ4.d.mts.map +1 -1
- package/dist/runtime.d.mts +1 -1
- package/dist/runtime.d.mts.map +1 -1
- package/package.json +6 -6
- package/src/control/control-stack.ts +52 -13
- package/src/exports/codec.ts +20 -7
- package/src/shared/codec-descriptor.ts +87 -0
- package/src/shared/codec-types.ts +22 -204
- package/src/shared/codec.ts +80 -0
- package/src/shared/column-spec.ts +83 -0
- package/src/shared/framework-components.ts +22 -48
- package/dist/codec-types-MWvfFmu1.d.mts +0 -207
- package/dist/codec-types-MWvfFmu1.d.mts.map +0 -1
- package/dist/framework-components-BvzjH6Pt.d.mts.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Codec } from '../shared/codec';
|
|
2
|
+
import type { CodecLookup, CodecMeta } from '../shared/codec-types';
|
|
2
3
|
import type {
|
|
3
4
|
AuthoringContributions,
|
|
4
5
|
AuthoringFieldNamespace,
|
|
@@ -270,27 +271,65 @@ export function assembleControlMutationDefaults(
|
|
|
270
271
|
}
|
|
271
272
|
|
|
272
273
|
export function extractCodecLookup(
|
|
273
|
-
descriptors: ReadonlyArray<Pick<ComponentMetadata & { id
|
|
274
|
+
descriptors: ReadonlyArray<Pick<ComponentMetadata & { id: string }, 'types' | 'id'>>,
|
|
274
275
|
): CodecLookup {
|
|
275
|
-
const byId = new Map<string,
|
|
276
|
+
const byId = new Map<string, Codec>();
|
|
277
|
+
const targetTypesById = new Map<string, readonly string[]>();
|
|
278
|
+
const metaById = new Map<string, CodecMeta>();
|
|
279
|
+
const renderersById = new Map<string, (params: Record<string, unknown>) => string | undefined>();
|
|
276
280
|
const owners = new Map<string, string>();
|
|
277
281
|
for (const descriptor of descriptors) {
|
|
278
|
-
const
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
for (const
|
|
282
|
+
const codecTypes = descriptor.types?.codecTypes;
|
|
283
|
+
const descriptorId = descriptor.id;
|
|
284
|
+
// Descriptor-side metadata is the single source of truth for `targetTypes` / `meta` / `renderOutputType`. Every contributor ships a `codecDescriptors` list on `types.codecTypes`.
|
|
285
|
+
for (const codecDescriptor of codecTypes?.codecDescriptors ?? []) {
|
|
282
286
|
assertUniqueCodecOwner({
|
|
283
|
-
codecId:
|
|
287
|
+
codecId: codecDescriptor.codecId,
|
|
284
288
|
owners,
|
|
285
289
|
descriptorId,
|
|
286
|
-
entityLabel: 'codec
|
|
287
|
-
entityOwnershipLabel: 'codec
|
|
290
|
+
entityLabel: 'codec descriptor',
|
|
291
|
+
entityOwnershipLabel: 'codec descriptor provider',
|
|
288
292
|
});
|
|
289
|
-
owners.set(
|
|
290
|
-
|
|
293
|
+
owners.set(codecDescriptor.codecId, descriptorId);
|
|
294
|
+
if (Array.isArray(codecDescriptor.targetTypes)) {
|
|
295
|
+
targetTypesById.set(codecDescriptor.codecId, codecDescriptor.targetTypes);
|
|
296
|
+
}
|
|
297
|
+
if (codecDescriptor.meta !== undefined) {
|
|
298
|
+
metaById.set(codecDescriptor.codecId, codecDescriptor.meta);
|
|
299
|
+
}
|
|
300
|
+
if (typeof codecDescriptor.renderOutputType === 'function') {
|
|
301
|
+
renderersById.set(codecDescriptor.codecId, codecDescriptor.renderOutputType);
|
|
302
|
+
}
|
|
303
|
+
// Materialize a representative `Codec` instance for `byId.get()` so consumers reading the lookup's instance side (e.g. SQL renderer's cast-policy lookup, or the contract emitter's literal-default `encodeJson` resolver) keep finding the codec.
|
|
304
|
+
//
|
|
305
|
+
// Two cohorts:
|
|
306
|
+
// - Non-parameterized descriptors: factory must succeed; any throw is a real bug and we let it propagate (no silent try/catch).
|
|
307
|
+
// - Parameterized descriptors: try with empty params. Many parameterized codecs treat params as advisory (e.g. `pg/timestamptz@1` whose precision is rendered into the `nativeType` only and never read by the runtime codec), so an empty-params construction yields a usable representative for id-keyed lookups (e.g. emit-time literal-default encoding). Codecs whose factory genuinely requires params (e.g. `pg/vector@1` threading `length` into the runtime codec) will throw; for those, per-column instances are materialized at runtime by `buildContractCodecRegistry` and the id-keyed lookup miss is correct (the column-aware path resolves them).
|
|
308
|
+
if (!byId.has(codecDescriptor.codecId)) {
|
|
309
|
+
if (codecDescriptor.isParameterized) {
|
|
310
|
+
try {
|
|
311
|
+
const representative = codecDescriptor.factory({} as never)({
|
|
312
|
+
name: `<lookup:${codecDescriptor.codecId}>`,
|
|
313
|
+
} as Parameters<ReturnType<typeof codecDescriptor.factory>>[0]);
|
|
314
|
+
byId.set(codecDescriptor.codecId, representative);
|
|
315
|
+
} catch {
|
|
316
|
+
// Factory requires concrete params; skip representative materialization. Per-column instances are built at runtime; id-keyed lookup miss is the correct outcome here.
|
|
317
|
+
}
|
|
318
|
+
} else {
|
|
319
|
+
const representative = codecDescriptor.factory(undefined as never)({
|
|
320
|
+
name: `<lookup:${codecDescriptor.codecId}>`,
|
|
321
|
+
} as Parameters<ReturnType<typeof codecDescriptor.factory>>[0]);
|
|
322
|
+
byId.set(codecDescriptor.codecId, representative);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
291
325
|
}
|
|
292
326
|
}
|
|
293
|
-
return {
|
|
327
|
+
return {
|
|
328
|
+
get: (id) => byId.get(id),
|
|
329
|
+
targetTypesFor: (id) => targetTypesById.get(id),
|
|
330
|
+
metaFor: (id) => metaById.get(id),
|
|
331
|
+
renderOutputTypeFor: (id, params) => renderersById.get(id)?.(params),
|
|
332
|
+
};
|
|
294
333
|
}
|
|
295
334
|
|
|
296
335
|
export function validateScalarTypeCodecIds(
|
package/src/exports/codec.ts
CHANGED
|
@@ -1,14 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codec model: interfaces (consumer surface) plus abstract `Impl` classes (codec-author surface) plus the column packager.
|
|
3
|
+
*
|
|
4
|
+
* Consumers depend on the interfaces: {@link Codec}, {@link CodecDescriptor}, {@link AnyCodecDescriptor}, {@link ColumnSpec}, {@link ColumnTypeDescriptor}.
|
|
5
|
+
*
|
|
6
|
+
* Codec authors `extend` the abstract bases: {@link CodecImpl} and {@link CodecDescriptorImpl}. They write a per-codec column helper that calls `descriptor.factory(...)` directly and tie the helper to its descriptor with `satisfies ColumnHelperFor<D>` (or `ColumnHelperForStrict<D>`).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type { Codec } from '../shared/codec';
|
|
10
|
+
export { CodecImpl } from '../shared/codec';
|
|
11
|
+
export type { AnyCodecDescriptor, CodecDescriptor } from '../shared/codec-descriptor';
|
|
12
|
+
export { CodecDescriptorImpl } from '../shared/codec-descriptor';
|
|
1
13
|
export type {
|
|
2
|
-
Codec,
|
|
3
14
|
CodecCallContext,
|
|
4
|
-
CodecDescriptor,
|
|
5
15
|
CodecInstanceContext,
|
|
6
16
|
CodecLookup,
|
|
7
17
|
CodecMeta,
|
|
8
18
|
CodecTrait,
|
|
9
19
|
} from '../shared/codec-types';
|
|
10
|
-
export {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
20
|
+
export { emptyCodecLookup, voidParamsSchema } from '../shared/codec-types';
|
|
21
|
+
export type {
|
|
22
|
+
ColumnHelperFor,
|
|
23
|
+
ColumnHelperForStrict,
|
|
24
|
+
ColumnSpec,
|
|
25
|
+
ColumnTypeDescriptor,
|
|
26
|
+
} from '../shared/column-spec';
|
|
27
|
+
export { column } from '../shared/column-spec';
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codec descriptor interface (consumer surface) and abstract `CodecDescriptorImpl` base (codec-author surface).
|
|
3
|
+
*
|
|
4
|
+
* Consumers depend on the {@link CodecDescriptor} interface — it is the codec-id-keyed source of truth for static metadata (`traits`, `targetTypes`, `meta`) and registration concerns (`paramsSchema`; optional `renderOutputType`). The runtime `Codec` instance returned by `factory(params)(ctx)` carries only the conversion behavior.
|
|
5
|
+
*
|
|
6
|
+
* Codec authors `extend` the {@link CodecDescriptorImpl} abstract class to declare their codec id, traits, target types, params schema, the `factory(params)` that materializes a typed `Codec<...>`, and (optionally) a `renderOutputType(params)` for the emit path.
|
|
7
|
+
*
|
|
8
|
+
* The factory's method-level generic is the load-bearing piece for literal preservation: per-codec column helpers invoke `descriptor.factory(...)` *directly*, and the direct call binds the generic at its call site. Type extraction (`ReturnType<D['factory']>`, structural matching) widens method generics to their constraint — that's why the column-helper surface is per-codec, not polymorphic.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
12
|
+
import type { Codec } from './codec';
|
|
13
|
+
import {
|
|
14
|
+
type CodecInstanceContext,
|
|
15
|
+
type CodecMeta,
|
|
16
|
+
type CodecTrait,
|
|
17
|
+
voidParamsSchema,
|
|
18
|
+
} from './codec-types';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Unified codec descriptor. Every codec in the framework registers through this shape — non-parameterized codecs use `P = void` and a constant factory that returns the same shared codec instance for every column; parameterized codecs use a non-empty `P` and a curried higher-order factory that returns a per-instance codec.
|
|
22
|
+
*
|
|
23
|
+
* The descriptor is the codec-id-keyed source of truth for static metadata (`traits`, `targetTypes`, `meta`) and registration concerns (`paramsSchema` for JSON-boundary validation; optional `renderOutputType` for the `contract.d.ts` emit path). The runtime `Codec` instance returned by `factory(params)(ctx)` carries only the conversion behavior.
|
|
24
|
+
*
|
|
25
|
+
* Whether a codec id "is parameterized" stops being a registration-time distinction — it's a property of `P` on the descriptor. The descriptor map indexes every descriptor by `codecId`; both `descriptorFor(codecId)` and `forColumn(table, column)` resolve through the same map without branching on parameterization.
|
|
26
|
+
*
|
|
27
|
+
* @template P - The shape of the params accepted by the factory (`void` for non-parameterized codecs; a record like `{ length: number }` for parameterized codecs).
|
|
28
|
+
*
|
|
29
|
+
* Codec-registry-unification project § Decision.
|
|
30
|
+
*/
|
|
31
|
+
export interface CodecDescriptor<P = void> {
|
|
32
|
+
/** The codec ID this descriptor applies to (e.g. `pg/vector@1`, `pg/text@1`). */
|
|
33
|
+
readonly codecId: string;
|
|
34
|
+
/** Semantic traits for operator gating (e.g. equality, order, numeric). */
|
|
35
|
+
readonly traits: readonly CodecTrait[];
|
|
36
|
+
/** Database-native type names this codec handles (e.g. `['timestamptz']`). */
|
|
37
|
+
readonly targetTypes: readonly string[];
|
|
38
|
+
/** Optional family-specific metadata (e.g. SQL-side `db.sql.postgres.nativeType`). */
|
|
39
|
+
readonly meta?: CodecMeta;
|
|
40
|
+
/** Standard Schema validator for the factory's params. Validates JSON-sourced params at the contract boundary (PSL → IR; `contract.json` → runtime). For non-parameterized codecs (`P = void`), the schema validates `void`/`undefined` — the framework supplies no params at the call boundary. */
|
|
41
|
+
readonly paramsSchema: StandardSchemaV1<P>;
|
|
42
|
+
/** Whether this descriptor is parameterized — i.e. its `paramsSchema` is something other than the singleton `voidParamsSchema`. Consumers that need to gate column-aware dispatch (e.g. the `validateParamRefRefs` AST-builder pass) read this directly rather than threading a free-floating `(codecId) => boolean` callback. */
|
|
43
|
+
readonly isParameterized: boolean;
|
|
44
|
+
/** Emit-path string renderer for `contract.d.ts`. Returns the TypeScript output type expression for given params (e.g. `Vector<1536>`). Optional; absent renderers cause the emitter to fall back to the codec's base output type. Non-parameterized codecs typically omit it. */
|
|
45
|
+
readonly renderOutputType?: (params: P) => string | undefined;
|
|
46
|
+
/** The curried higher-order codec. For non-parameterized codecs, the factory is constant — every call returns the same shared codec instance. For parameterized codecs, the factory is called once per `storage.types` instance (or once per inline-`typeParams` column), with `ctx` carrying the column set the resulting codec serves. */
|
|
47
|
+
readonly factory: (params: P) => (ctx: CodecInstanceContext) => Codec;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Variance-erased {@link CodecDescriptor} alias. `CodecDescriptor<P>` is invariant in `P` (the `factory` and `renderOutputType` slots use `P` contravariantly), so `CodecDescriptor<P>` does not extend `CodecDescriptor<unknown>` for specific `P`. Heterogeneous descriptor collections — e.g. `SqlStaticContributions.codecs:` returning a list that mixes parameterized and non-parameterized descriptors — type against this alias and narrow per codec id at the consumer.
|
|
52
|
+
*
|
|
53
|
+
* Codec-registry-unification spec § Decision: every codec resolves through one descriptor map; reads are non-branching.
|
|
54
|
+
*/
|
|
55
|
+
// biome-ignore lint/suspicious/noExplicitAny: variance erasure for heterogeneous descriptor collections
|
|
56
|
+
export type AnyCodecDescriptor = CodecDescriptor<any>;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Abstract base class for concrete codec descriptors.
|
|
60
|
+
*
|
|
61
|
+
* Codec authors extend this class with their typed `TParams` and declare `codecId`, `traits`, `targetTypes`, `paramsSchema`, the curried `factory(params)`, and (optionally) `renderOutputType`.
|
|
62
|
+
*
|
|
63
|
+
* Implements the {@link CodecDescriptor} interface so a concrete subclass instance is directly usable wherever the framework expects a `CodecDescriptor<P>`.
|
|
64
|
+
*/
|
|
65
|
+
export abstract class CodecDescriptorImpl<TParams = void> implements CodecDescriptor<TParams> {
|
|
66
|
+
abstract readonly codecId: string;
|
|
67
|
+
abstract readonly traits: readonly CodecTrait[];
|
|
68
|
+
abstract readonly targetTypes: readonly string[];
|
|
69
|
+
readonly meta?: CodecMeta;
|
|
70
|
+
|
|
71
|
+
abstract readonly paramsSchema: StandardSchemaV1<TParams>;
|
|
72
|
+
|
|
73
|
+
/** Boolean derived from `paramsSchema`: `true` whenever the schema is not the singleton `voidParamsSchema`. The framework registry's `validateParamRefRefs` pass reads this through `descriptorFor(codecId).isParameterized` to gate column-ref enforcement. */
|
|
74
|
+
get isParameterized(): boolean {
|
|
75
|
+
return this.paramsSchema !== voidParamsSchema;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Optional emit-path string renderer for `contract.d.ts`. Returns the TypeScript output type expression for the given params (e.g. `Vector<1536>`). Non-parameterized codecs typically omit it. */
|
|
79
|
+
renderOutputType?(params: TParams): string | undefined;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Materialize a curried codec factory for the given params. Concrete subclasses override with a typed return type (e.g. `factory<N>(params: { length: N }): (ctx) => VectorCodec<N>`); per-codec helpers read the typed return at the *direct* call site, which is what preserves method-level generics. Type extraction (e.g. `ReturnType<D['factory']>`) widens method generics to their constraint — that's why the column-helper surface is per-codec, not polymorphic.
|
|
83
|
+
*/
|
|
84
|
+
abstract factory(
|
|
85
|
+
params: TParams,
|
|
86
|
+
): (ctx: CodecInstanceContext) => Codec<string, readonly CodecTrait[], unknown, unknown>;
|
|
87
|
+
}
|
|
@@ -1,212 +1,65 @@
|
|
|
1
|
-
import type { JsonValue } from '@prisma-next/contract/types';
|
|
2
1
|
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
2
|
+
import type { Codec } from './codec';
|
|
3
3
|
|
|
4
|
-
export type CodecTrait =
|
|
5
|
-
| 'equality'
|
|
6
|
-
| 'order'
|
|
7
|
-
| 'boolean'
|
|
8
|
-
| 'numeric'
|
|
9
|
-
| 'textual'
|
|
10
|
-
/**
|
|
11
|
-
* The codec carries a per-instance `validate(value: unknown) =>
|
|
12
|
-
* JsonSchemaValidationResult` function on the resolved codec object that
|
|
13
|
-
* the framework's `JsonSchemaValidatorRegistry` consults at runtime. The
|
|
14
|
-
* trait gates the `extractValidator` cast from structurally-typed
|
|
15
|
-
* `unknown` to a typed validator view.
|
|
16
|
-
*
|
|
17
|
-
* Retirement target. The unified `CodecDescriptor` model moves
|
|
18
|
-
* validation into the resolved codec's `decode` body; the parallel
|
|
19
|
-
* `JsonSchemaValidatorRegistry` (and this trait alongside it) retires
|
|
20
|
-
* under TML-2357 (T3.5.12). Per-library JSON extensions like
|
|
21
|
-
* `@prisma-next/extension-arktype-json` already follow the new pattern.
|
|
22
|
-
*/
|
|
23
|
-
| 'json-validator';
|
|
4
|
+
export type CodecTrait = 'equality' | 'order' | 'boolean' | 'numeric' | 'textual';
|
|
24
5
|
|
|
25
6
|
/**
|
|
26
|
-
* Per-call context the runtime threads to every `codec.encode` /
|
|
27
|
-
* `codec.decode` invocation for a single `runtime.execute()` call.
|
|
7
|
+
* Per-call context the runtime threads to every `codec.encode` / `codec.decode` invocation for a single `runtime.execute()` call.
|
|
28
8
|
*
|
|
29
9
|
* The framework-level shape is family-agnostic and carries one field:
|
|
30
10
|
*
|
|
31
|
-
* - `signal?: AbortSignal` — per-query cancellation. The runtime returns
|
|
32
|
-
* a `RUNTIME.ABORTED` envelope when the signal aborts; codec authors
|
|
33
|
-
* who forward `signal` to their underlying SDK get true cancellation
|
|
34
|
-
* of in-flight network calls.
|
|
11
|
+
* - `signal?: AbortSignal` — per-query cancellation. The runtime returns a `RUNTIME.ABORTED` envelope when the signal aborts; codec authors who forward `signal` to their underlying SDK get true cancellation of in-flight network calls.
|
|
35
12
|
*
|
|
36
|
-
* Family layers extend this base with their own shape-of-call metadata:
|
|
37
|
-
* the SQL family adds `column?: SqlColumnRef` via `SqlCodecCallContext`
|
|
38
|
-
* (see `@prisma-next/sql-relational-core`). Mongo currently uses this
|
|
39
|
-
* framework type unchanged. Column metadata is intentionally **not** on
|
|
40
|
-
* the framework type — it is a SQL-family concept rooted in SQL's
|
|
41
|
-
* `(table, column)` addressing model and would not generalise to other
|
|
42
|
-
* families.
|
|
13
|
+
* Family layers extend this base with their own shape-of-call metadata: the SQL family adds `column?: SqlColumnRef` via `SqlCodecCallContext` (see `@prisma-next/sql-relational-core`). Mongo currently uses this framework type unchanged. Column metadata is intentionally **not** on the framework type — it is a SQL-family concept rooted in SQL's `(table, column)` addressing model and would not generalise to other families.
|
|
43
14
|
*
|
|
44
|
-
* The interface is named explicitly (not inlined) so future framework
|
|
45
|
-
* fields and family extensions can land additively without breaking
|
|
46
|
-
* codec author signatures.
|
|
15
|
+
* The interface is named explicitly (not inlined) so future framework fields and family extensions can land additively without breaking codec author signatures.
|
|
47
16
|
*/
|
|
48
17
|
export interface CodecCallContext {
|
|
49
18
|
readonly signal?: AbortSignal;
|
|
50
19
|
}
|
|
51
20
|
|
|
52
21
|
/**
|
|
53
|
-
*
|
|
54
|
-
* on-contract-disk representations.
|
|
22
|
+
* Codec-id-keyed read surface threaded into emit and authoring paths.
|
|
55
23
|
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
* `
|
|
60
|
-
* during contract emission and loading.
|
|
61
|
-
*
|
|
62
|
-
* Three representations participate:
|
|
63
|
-
* - **Input** (`TInput`): the JS type at the application boundary.
|
|
64
|
-
* - **Wire** (`TWire`): the format exchanged with the database driver.
|
|
65
|
-
* - **JSON** (`JsonValue`): a JSON-safe form used in contract artifacts.
|
|
66
|
-
*
|
|
67
|
-
* Codec methods split into two groups:
|
|
68
|
-
*
|
|
69
|
-
* - **Query-time** methods (`encode`, `decode`) run per row/parameter at the
|
|
70
|
-
* IO boundary; they are required and Promise-returning. The per-family
|
|
71
|
-
* codec factory accepts sync or async author functions and lifts sync
|
|
72
|
-
* ones to Promise-shaped methods automatically.
|
|
73
|
-
* - **Build-time** methods (`encodeJson`, `decodeJson`, `renderOutputType`)
|
|
74
|
-
* run when the contract is serialized, loaded, or when client types are
|
|
75
|
-
* emitted. They stay synchronous so contract validation and client
|
|
76
|
-
* construction are synchronous.
|
|
77
|
-
*
|
|
78
|
-
* Target-family codec interfaces extend this base with target-shaped
|
|
79
|
-
* metadata.
|
|
24
|
+
* - `get(id)` returns the runtime {@link Codec} instance for the codec id (used by `validateContract` for `decodeJson` of literal column defaults).
|
|
25
|
+
* - `targetTypesFor(id)` exposes the codec-id-keyed `targetTypes` metadata the runtime instance no longer carries (TML-2357). Returns the same array `CodecDescriptor.targetTypes` would; for Mongo (whose registration doesn't yet resolve through the unified descriptor map — TML-2324) the family-side assembly populates this directly from the contributor's codec metadata.
|
|
26
|
+
* - `metaFor(id)` exposes the codec-id-keyed `meta` (e.g. SQL-side `db.sql.postgres.nativeType`) the runtime instance no longer carries.
|
|
27
|
+
* - `renderOutputTypeFor(id, params)` exposes the codec-id-keyed `renderOutputType` renderer the runtime instance no longer carries. Returns `undefined` when the codec doesn't render a custom type or when the codec id is unknown.
|
|
80
28
|
*/
|
|
81
|
-
export interface Codec<
|
|
82
|
-
Id extends string = string,
|
|
83
|
-
TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
|
|
84
|
-
TWire = unknown,
|
|
85
|
-
TInput = unknown,
|
|
86
|
-
> {
|
|
87
|
-
/** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). */
|
|
88
|
-
readonly id: Id;
|
|
89
|
-
/** Database-native type names this codec handles (e.g. `['timestamptz']`). */
|
|
90
|
-
readonly targetTypes: readonly string[];
|
|
91
|
-
/** Semantic traits for operator gating (e.g. equality, order, numeric). */
|
|
92
|
-
readonly traits?: TTraits;
|
|
93
|
-
/** Converts a JS value to the wire format expected by the database driver. Always Promise-returning at the boundary. The {@link CodecCallContext} is supplied by the runtime on every call (allocated once per `runtime.execute()`); family layers may narrow the ctx to extend it (e.g. SQL adds `column`). Author-side single-arg `(value) => …` functions remain legal via TypeScript's bivariance for trailing parameters. */
|
|
94
|
-
encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
|
|
95
|
-
/** Converts a wire value from the database driver into the JS application type. Always Promise-returning at the boundary. The {@link CodecCallContext} is supplied by the runtime on every call (allocated once per `runtime.execute()`); family layers may narrow the ctx to extend it (e.g. SQL adds `column`). Author-side single-arg `(wire) => …` functions remain legal via TypeScript's bivariance for trailing parameters. */
|
|
96
|
-
decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
|
|
97
|
-
/** Converts a JS value to a JSON-safe representation for contract serialization. Synchronous; called during contract emission. */
|
|
98
|
-
encodeJson(value: TInput): JsonValue;
|
|
99
|
-
/** Converts a JSON representation back to the JS input type. Synchronous; called during contract loading via `validateContract`. */
|
|
100
|
-
decodeJson(json: JsonValue): TInput;
|
|
101
|
-
/** Produces the TypeScript output type expression for a field given its `typeParams`. Synchronous; used during contract.d.ts emission. */
|
|
102
|
-
renderOutputType?(typeParams: Record<string, unknown>): string | undefined;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
29
|
export interface CodecLookup {
|
|
106
30
|
get(id: string): Codec | undefined;
|
|
31
|
+
targetTypesFor(id: string): readonly string[] | undefined;
|
|
32
|
+
metaFor(id: string): CodecMeta | undefined;
|
|
33
|
+
renderOutputTypeFor(id: string, params: Record<string, unknown>): string | undefined;
|
|
107
34
|
}
|
|
108
35
|
|
|
109
36
|
export const emptyCodecLookup: CodecLookup = {
|
|
110
37
|
get: () => undefined,
|
|
38
|
+
targetTypesFor: () => undefined,
|
|
39
|
+
metaFor: () => undefined,
|
|
40
|
+
renderOutputTypeFor: () => undefined,
|
|
111
41
|
};
|
|
112
42
|
|
|
113
43
|
/**
|
|
114
|
-
* Family-agnostic per-instance context supplied by the framework when
|
|
115
|
-
* applying a higher-order codec factory. Allows stateful codecs (e.g.
|
|
116
|
-
* column-scoped encryption) to derive per-instance state from the
|
|
117
|
-
* materialization site.
|
|
44
|
+
* Family-agnostic per-instance context supplied by the framework when applying a higher-order codec factory. Allows stateful codecs (e.g. column-scoped encryption) to derive per-instance state from the materialization site.
|
|
118
45
|
*
|
|
119
|
-
* - `name` — the family-agnostic instance identity. For SQL, the runtime
|
|
120
|
-
* populates this as the `storage.types` instance name (e.g.
|
|
121
|
-
* `Embedding1536`) for typeRef-shaped columns, the synthesized
|
|
122
|
-
* anonymous instance name (`<anon:Document.embedding>`) for inline-
|
|
123
|
-
* `typeParams` columns, or a shared sentinel (`<shared:pg/text@1>`)
|
|
124
|
-
* for non-parameterized codec ids. Other families pick the analogous
|
|
125
|
-
* identity for their materialization sites.
|
|
46
|
+
* - `name` — the family-agnostic instance identity. For SQL, the runtime populates this as the `storage.types` instance name (e.g. `Embedding1536`) for typeRef-shaped columns, the synthesized anonymous instance name (`<anon:Document.embedding>`) for inline-`typeParams` columns, or a shared sentinel (`<shared:pg/text@1>`) for non-parameterized codec ids. Other families pick the analogous identity for their materialization sites.
|
|
126
47
|
*
|
|
127
|
-
* Family-specific extensions (e.g. {@link import('@prisma-next/sql-relational-core/ast').SqlCodecInstanceContext}
|
|
128
|
-
* in the SQL layer) augment this base with domain-shaped column-set
|
|
129
|
-
* metadata. Codec authors target the base when they don't read family-
|
|
130
|
-
* specific metadata; they target the family extension when they do.
|
|
48
|
+
* Family-specific extensions (e.g. {@link import('@prisma-next/sql-relational-core/ast').SqlCodecInstanceContext} in the SQL layer) augment this base with domain-shaped column-set metadata. Codec authors target the base when they don't read family-specific metadata; they target the family extension when they do.
|
|
131
49
|
*/
|
|
132
50
|
export interface CodecInstanceContext {
|
|
133
51
|
readonly name: string;
|
|
134
52
|
}
|
|
135
53
|
|
|
136
54
|
/**
|
|
137
|
-
* Family-agnostic codec metadata. Family-specific extensions augment the
|
|
138
|
-
* base `db.<family>.<target>` block with native-type information; the base
|
|
139
|
-
* shape is an empty object so non-relational codecs can carry no metadata.
|
|
55
|
+
* Family-agnostic codec metadata. Family-specific extensions augment the base `db.<family>.<target>` block with native-type information; the base shape is an empty object so non-relational codecs can carry no metadata.
|
|
140
56
|
*/
|
|
141
57
|
export interface CodecMeta {
|
|
142
58
|
readonly db?: Record<string, unknown>;
|
|
143
59
|
}
|
|
144
60
|
|
|
145
61
|
/**
|
|
146
|
-
*
|
|
147
|
-
* this shape — non-parameterized codecs use `P = void` and a constant
|
|
148
|
-
* factory that returns the same shared codec instance for every column;
|
|
149
|
-
* parameterized codecs use a non-empty `P` and a curried higher-order
|
|
150
|
-
* factory that returns a per-instance codec.
|
|
151
|
-
*
|
|
152
|
-
* The descriptor is the codec-id-keyed source of truth for static metadata
|
|
153
|
-
* (`traits`, `targetTypes`, `meta`) and registration concerns
|
|
154
|
-
* (`paramsSchema` for JSON-boundary validation; optional `renderOutputType`
|
|
155
|
-
* for the `contract.d.ts` emit path). The runtime `Codec` instance returned
|
|
156
|
-
* by `factory(params)(ctx)` carries only the conversion behavior.
|
|
157
|
-
*
|
|
158
|
-
* Whether a codec id "is parameterized" stops being a registration-time
|
|
159
|
-
* distinction — it's a property of `P` on the descriptor. The descriptor
|
|
160
|
-
* map indexes every descriptor by `codecId`; both `descriptorFor(codecId)`
|
|
161
|
-
* and `forColumn(table, column)` resolve through the same map without
|
|
162
|
-
* branching on parameterization.
|
|
163
|
-
*
|
|
164
|
-
* @template P - The shape of the params accepted by the factory (`void` for
|
|
165
|
-
* non-parameterized codecs; a record like `{ length: number }` for
|
|
166
|
-
* parameterized codecs).
|
|
167
|
-
*
|
|
168
|
-
* Codec-registry-unification project § Decision.
|
|
169
|
-
*/
|
|
170
|
-
export interface CodecDescriptor<P = void> {
|
|
171
|
-
/** The codec ID this descriptor applies to (e.g. `pg/vector@1`, `pg/text@1`). */
|
|
172
|
-
readonly codecId: string;
|
|
173
|
-
/** Semantic traits for operator gating (e.g. equality, order, numeric). */
|
|
174
|
-
readonly traits: readonly CodecTrait[];
|
|
175
|
-
/** Database-native type names this codec handles (e.g. `['timestamptz']`). */
|
|
176
|
-
readonly targetTypes: readonly string[];
|
|
177
|
-
/** Optional family-specific metadata (e.g. SQL-side `db.sql.postgres.nativeType`). */
|
|
178
|
-
readonly meta?: CodecMeta;
|
|
179
|
-
/**
|
|
180
|
-
* Standard Schema validator for the factory's params. Validates JSON-
|
|
181
|
-
* sourced params at the contract boundary (PSL → IR; `contract.json` →
|
|
182
|
-
* runtime). For non-parameterized codecs (`P = void`), the schema
|
|
183
|
-
* validates `void`/`undefined` — the framework supplies no params at the
|
|
184
|
-
* call boundary.
|
|
185
|
-
*/
|
|
186
|
-
readonly paramsSchema: StandardSchemaV1<P>;
|
|
187
|
-
/**
|
|
188
|
-
* Emit-path string renderer for `contract.d.ts`. Returns the TypeScript
|
|
189
|
-
* output type expression for given params (e.g. `Vector<1536>`).
|
|
190
|
-
* Optional; absent renderers cause the emitter to fall back to the
|
|
191
|
-
* codec's base output type. Non-parameterized codecs typically omit it.
|
|
192
|
-
*/
|
|
193
|
-
readonly renderOutputType?: (params: P) => string | undefined;
|
|
194
|
-
/**
|
|
195
|
-
* The curried higher-order codec. For non-parameterized codecs, the
|
|
196
|
-
* factory is constant — every call returns the same shared codec
|
|
197
|
-
* instance. For parameterized codecs, the factory is called once per
|
|
198
|
-
* `storage.types` instance (or once per inline-`typeParams` column),
|
|
199
|
-
* with `ctx` carrying the column set the resulting codec serves.
|
|
200
|
-
*/
|
|
201
|
-
readonly factory: (params: P) => (ctx: CodecInstanceContext) => Codec;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/**
|
|
205
|
-
* Standard Schema validator for `void` params. Accepts only `undefined`
|
|
206
|
-
* (or absent input); rejects any other value so a contract that tries to
|
|
207
|
-
* thread `typeParams` through a non-parameterized codec id fails fast at
|
|
208
|
-
* the JSON boundary instead of silently coercing the value away. Used by
|
|
209
|
-
* the framework-supplied non-parameterized descriptor synthesizer.
|
|
62
|
+
* Standard Schema validator for `void` params. Accepts only `undefined` (or absent input); rejects any other value so a contract that tries to thread `typeParams` through a non-parameterized codec id fails fast at the JSON boundary instead of silently coercing the value away. Used by the framework-supplied non-parameterized descriptor synthesizer.
|
|
210
63
|
*/
|
|
211
64
|
export const voidParamsSchema: StandardSchemaV1<void> = {
|
|
212
65
|
'~standard': {
|
|
@@ -224,38 +77,3 @@ export const voidParamsSchema: StandardSchemaV1<void> = {
|
|
|
224
77
|
},
|
|
225
78
|
},
|
|
226
79
|
};
|
|
227
|
-
|
|
228
|
-
/**
|
|
229
|
-
* Synthesize a `CodecDescriptor<void>` for a non-parameterized codec
|
|
230
|
-
* runtime instance. The factory is constant — every call returns the same
|
|
231
|
-
* shared codec instance — so columns sharing this codec id share one
|
|
232
|
-
* resolved codec.
|
|
233
|
-
*
|
|
234
|
-
* Codec-registry-unification spec § Decision (Case T — non-parameterized
|
|
235
|
-
* text codec). This is the bridge while non-parameterized codec
|
|
236
|
-
* contributors still register through the legacy `codecs:` slot; once they
|
|
237
|
-
* migrate to ship descriptors directly (TML-2357 T3.5.3), this synthesis
|
|
238
|
-
* steps aside.
|
|
239
|
-
*/
|
|
240
|
-
export function synthesizeNonParameterizedDescriptor(codec: Codec): CodecDescriptor<void> {
|
|
241
|
-
// The descriptor's `factory: (params: void) => (ctx: CodecInstanceContext)
|
|
242
|
-
// => Codec` is a constant for non-parameterized codecs — `params` is
|
|
243
|
-
// never read and the returned ctx-applier always yields the same shared
|
|
244
|
-
// codec. We rely on the descriptor's typed `factory` slot to infer the
|
|
245
|
-
// signatures rather than naming `void` locally (biome's
|
|
246
|
-
// `noConfusingVoidType` flags `void` outside return positions).
|
|
247
|
-
const sharedFactory = () => () => codec;
|
|
248
|
-
// Family-extended codecs (SQL `Codec`) carry an optional `meta` field
|
|
249
|
-
// that the base interface doesn't declare. Read it through a structural
|
|
250
|
-
// narrow so the synthesizer forwards it to the descriptor without losing
|
|
251
|
-
// type safety on the base shape.
|
|
252
|
-
const codecMeta = (codec as { readonly meta?: CodecMeta }).meta;
|
|
253
|
-
return {
|
|
254
|
-
codecId: codec.id,
|
|
255
|
-
traits: codec.traits ?? [],
|
|
256
|
-
targetTypes: codec.targetTypes,
|
|
257
|
-
paramsSchema: voidParamsSchema,
|
|
258
|
-
factory: sharedFactory,
|
|
259
|
-
...(codecMeta !== undefined ? { meta: codecMeta } : {}),
|
|
260
|
-
};
|
|
261
|
-
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codec interface (consumer surface) and abstract `CodecImpl` base (codec-author surface).
|
|
3
|
+
*
|
|
4
|
+
* Consumers depend on the {@link Codec} interface — it describes the runtime instance returned by a descriptor's curried factory and is what the framework threads through emit, validate, and execute paths.
|
|
5
|
+
*
|
|
6
|
+
* Codec authors `extend` the {@link CodecImpl} abstract class to declare a typed runtime codec instance. The class carries a variance-erased descriptor reference (`CodecDescriptor<any>`); `id` proxies through the descriptor so one source of truth governs both metadata reads and aliasing semantics (alias subclasses inherit the descriptor's id automatically).
|
|
7
|
+
*
|
|
8
|
+
* Class generic shape: `Id`, `TTraits`, `TWire`, `TInput`. Method generics on the codec subclass's own surface (e.g. arktype-json's schema generic, pgvector's dimension generic) flow through the subclass's constructor and propagate via the descriptor's typed `factory(params)` return at *direct* call sites.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { JsonValue } from '@prisma-next/contract/types';
|
|
12
|
+
import type { CodecDescriptor } from './codec-descriptor';
|
|
13
|
+
import type { CodecCallContext, CodecTrait } from './codec-types';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A codec is the contract between an application value and its on-wire and on-contract-disk representations.
|
|
17
|
+
*
|
|
18
|
+
* The author's mental model is two JS-side types — `TInput` (the application JS type) and `TWire` (the database driver wire format) — plus `JsonValue` for build-time contract artifacts. The codec translates `TInput` to `TWire` on writes and back on reads, and to/from `JsonValue` during contract emission and loading.
|
|
19
|
+
*
|
|
20
|
+
* Three representations participate:
|
|
21
|
+
* - **Input** (`TInput`): the JS type at the application boundary.
|
|
22
|
+
* - **Wire** (`TWire`): the format exchanged with the database driver.
|
|
23
|
+
* - **JSON** (`JsonValue`): a JSON-safe form used in contract artifacts.
|
|
24
|
+
*
|
|
25
|
+
* The runtime instance carries only its `id` (the descriptor's `codecId`, set by the factory) and the four conversion methods. Static metadata (`traits`, `targetTypes`, `meta`) and the build-time `renderOutputType` renderer live on the {@link CodecDescriptor} keyed by `codecId` — the read-surface single source of truth. Consumers that need them resolve through `descriptorFor(codecId)`.
|
|
26
|
+
*
|
|
27
|
+
* Codec methods split into two groups:
|
|
28
|
+
*
|
|
29
|
+
* - **Query-time** methods (`encode`, `decode`) run per row/parameter at the IO boundary; they are required and Promise-returning. The per-family codec factory accepts sync or async author functions and lifts sync ones to Promise-shaped methods automatically.
|
|
30
|
+
* - **Build-time** methods (`encodeJson`, `decodeJson`) run when the contract is serialized or loaded. They stay synchronous so contract validation and client construction are synchronous.
|
|
31
|
+
*
|
|
32
|
+
* Target-family codec interfaces extend this base; family-specific concerns (e.g. the SQL `column?` per-call context) layer on through the `CodecCallContext` extension pattern.
|
|
33
|
+
*/
|
|
34
|
+
export interface Codec<
|
|
35
|
+
Id extends string = string,
|
|
36
|
+
TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
|
|
37
|
+
TWire = unknown,
|
|
38
|
+
TInput = unknown,
|
|
39
|
+
> {
|
|
40
|
+
/** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). The factory sets this to the descriptor's `codecId`; consumers use it as a back-reference for descriptor lookups and for decode-error diagnostics. */
|
|
41
|
+
readonly id: Id;
|
|
42
|
+
/** Phantom carrier for the `TTraits` generic; type-only, undefined at runtime. Runtime traits live on {@link CodecDescriptor.traits}. Implemented as a string-key phantom (`__codecTraits`) rather than `unique symbol` so bundlers that split `.d.ts` chunks do not strand symbol identity on chunk-private paths (the same `TS2742` family that the public re-export of `CodecTypes` works around). */
|
|
43
|
+
readonly __codecTraits?: TTraits;
|
|
44
|
+
/** Converts a JS value to the wire format expected by the database driver. Always Promise-returning at the boundary. The {@link CodecCallContext} is supplied by the runtime on every call (allocated once per `runtime.execute()`); family layers may narrow the ctx to extend it (e.g. SQL adds `column`). Author-side single-arg `(value) => …` functions remain legal via TypeScript's bivariance for trailing parameters. */
|
|
45
|
+
encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
|
|
46
|
+
/** Converts a wire value from the database driver into the JS application type. Always Promise-returning at the boundary. The {@link CodecCallContext} is supplied by the runtime on every call (allocated once per `runtime.execute()`); family layers may narrow the ctx to extend it (e.g. SQL adds `column`). Author-side single-arg `(wire) => …` functions remain legal via TypeScript's bivariance for trailing parameters. */
|
|
47
|
+
decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
|
|
48
|
+
/** Converts a JS value to a JSON-safe representation for contract serialization. Synchronous; called during contract emission. */
|
|
49
|
+
encodeJson(value: TInput): JsonValue;
|
|
50
|
+
/** Converts a JSON representation back to the JS input type. Synchronous; called during contract loading via `validateContract`. */
|
|
51
|
+
decodeJson(json: JsonValue): TInput;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Abstract base class for concrete codec implementations.
|
|
56
|
+
*
|
|
57
|
+
* Codec authors extend this class with their typed `Id`, `TTraits`, `TWire`, `TInput` and override `encode`/`decode` (and optionally `encodeJson`/`decodeJson`). The runtime instance carries only its `id` (proxied through the descriptor so alias subclasses inherit the descriptor's id automatically) and the conversion methods — static metadata lives on the {@link CodecDescriptor}.
|
|
58
|
+
*/
|
|
59
|
+
export abstract class CodecImpl<
|
|
60
|
+
Id extends string = string,
|
|
61
|
+
TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
|
|
62
|
+
TWire = unknown,
|
|
63
|
+
TInput = unknown,
|
|
64
|
+
> implements Codec<Id, TTraits, TWire, TInput>
|
|
65
|
+
{
|
|
66
|
+
/**
|
|
67
|
+
* Variance-erased descriptor reference. Concrete codec subclasses receive the typed descriptor in their own constructors and forward it via `super(descriptor)`; the variance erasure lives at this base because the abstract surface can't carry the concrete `TParams`.
|
|
68
|
+
*/
|
|
69
|
+
// biome-ignore lint/suspicious/noExplicitAny: variance-erased descriptor reference; subclasses retain typed access via their own state
|
|
70
|
+
constructor(public readonly descriptor: CodecDescriptor<any>) {}
|
|
71
|
+
|
|
72
|
+
get id(): Id {
|
|
73
|
+
return this.descriptor.codecId as Id;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
abstract encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
|
|
77
|
+
abstract decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
|
|
78
|
+
abstract encodeJson(value: TInput): JsonValue;
|
|
79
|
+
abstract decodeJson(json: JsonValue): TInput;
|
|
80
|
+
}
|