@prisma-next/framework-components 0.5.0-dev.4 → 0.5.0-dev.41
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 +61 -0
- package/dist/authoring.d.mts +1 -1
- package/dist/authoring.mjs +1 -1
- package/dist/authoring.mjs.map +1 -1
- package/dist/codec-types-CB0jWeHU.d.mts +207 -0
- package/dist/codec-types-CB0jWeHU.d.mts.map +1 -0
- package/dist/codec.d.mts +2 -2
- package/dist/codec.mjs +38 -2
- package/dist/codec.mjs.map +1 -1
- package/dist/components.d.mts +1 -1
- package/dist/components.mjs +1 -1
- package/dist/control.d.mts +101 -35
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +11 -5
- package/dist/control.mjs.map +1 -1
- package/dist/emission-types-D6t3_a0x.d.mts +39 -0
- package/dist/emission-types-D6t3_a0x.d.mts.map +1 -0
- package/dist/emission.d.mts +2 -2
- package/dist/execution.d.mts +5 -5
- package/dist/execution.d.mts.map +1 -1
- package/dist/execution.mjs +3 -3
- package/dist/execution.mjs.map +1 -1
- package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-BdrFDx4x.d.mts} +2 -2
- package/dist/framework-authoring-BdrFDx4x.d.mts.map +1 -0
- package/dist/{framework-components-EJXe-pum.d.mts → framework-components-AHI6V96G.d.mts} +6 -6
- package/dist/framework-components-AHI6V96G.d.mts.map +1 -0
- package/dist/{framework-components-C8ZhSwXe.mjs → framework-components-BsWST1Rn.mjs} +2 -2
- package/dist/framework-components-BsWST1Rn.mjs.map +1 -0
- package/dist/psl-ast-9X5rwo98.d.mts +159 -0
- package/dist/psl-ast-9X5rwo98.d.mts.map +1 -0
- package/dist/psl-ast.d.mts +2 -0
- package/dist/psl-ast.mjs +1 -0
- package/dist/runtime.d.mts +251 -19
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +215 -4
- package/dist/runtime.mjs.map +1 -1
- package/dist/{types-import-spec-C4sc7wbb.d.mts → types-import-spec-D-O6GotH.d.mts} +2 -2
- package/dist/types-import-spec-D-O6GotH.d.mts.map +1 -0
- package/package.json +8 -6
- package/src/control/control-capabilities.ts +71 -0
- package/src/{control-descriptors.ts → control/control-descriptors.ts} +7 -7
- package/src/{control-instances.ts → control/control-instances.ts} +6 -6
- package/src/{control-migration-types.ts → control/control-migration-types.ts} +48 -23
- package/src/control/control-operation-preview.ts +23 -0
- package/src/{control-stack.ts → control/control-stack.ts} +13 -13
- package/src/control/emission-types.ts +49 -0
- package/src/control/psl-ast.ts +193 -0
- package/src/{execution-descriptors.ts → execution/execution-descriptors.ts} +7 -7
- package/src/{execution-instances.ts → execution/execution-instances.ts} +1 -1
- package/src/{execution-requirements.ts → execution/execution-requirements.ts} +1 -1
- package/src/execution/query-plan.ts +53 -0
- package/src/execution/race-against-abort.ts +85 -0
- package/src/execution/run-with-middleware.ts +77 -0
- package/src/execution/runtime-core.ts +133 -0
- package/src/execution/runtime-error.ts +83 -0
- package/src/{runtime-middleware.ts → execution/runtime-middleware.ts} +32 -12
- package/src/exports/authoring.ts +2 -2
- package/src/exports/codec.ts +14 -2
- package/src/exports/components.ts +2 -2
- package/src/exports/control.ts +26 -12
- package/src/exports/emission.ts +2 -2
- package/src/exports/execution.ts +5 -5
- package/src/exports/psl-ast.ts +1 -0
- package/src/exports/runtime.ts +16 -5
- package/src/shared/codec-types.ts +261 -0
- package/dist/codec-types-B58nCJiu.d.mts +0 -40
- package/dist/codec-types-B58nCJiu.d.mts.map +0 -1
- package/dist/emission-types-BPAALJbF.d.mts +0 -24
- package/dist/emission-types-BPAALJbF.d.mts.map +0 -1
- package/dist/framework-authoring-D1-JZ37B.d.mts.map +0 -1
- package/dist/framework-components-C8ZhSwXe.mjs.map +0 -1
- package/dist/framework-components-EJXe-pum.d.mts.map +0 -1
- package/dist/types-import-spec-C4sc7wbb.d.mts.map +0 -1
- package/src/codec-types.ts +0 -46
- package/src/control-capabilities.ts +0 -34
- package/src/emission-types.ts +0 -28
- package/src/runtime-error.ts +0 -39
- /package/src/{control-result-types.ts → control/control-result-types.ts} +0 -0
- /package/src/{control-schema-view.ts → control/control-schema-view.ts} +0 -0
- /package/src/{async-iterable-result.ts → execution/async-iterable-result.ts} +0 -0
- /package/src/{execution-stack.ts → execution/execution-stack.ts} +0 -0
- /package/src/{framework-authoring.ts → shared/framework-authoring.ts} +0 -0
- /package/src/{framework-components.ts → shared/framework-components.ts} +0 -0
- /package/src/{mutation-default-types.ts → shared/mutation-default-types.ts} +0 -0
- /package/src/{types-import-spec.ts → shared/types-import-spec.ts} +0 -0
package/README.md
CHANGED
|
@@ -10,19 +10,80 @@ Framework component types, authoring logic, control stack assembly, and emission
|
|
|
10
10
|
|
|
11
11
|
- **Component types** (`./components`): Base descriptor and instance interfaces for framework components (family, target, adapter, driver, extension), pack refs, and type renderer system
|
|
12
12
|
- **Authoring types** (`./authoring`): Declarative authoring contribution types, template resolution, and validation for type constructors and field presets
|
|
13
|
+
- **Codec base interface** (`./codec`): The cross-family `Codec` base type that SQL `Codec` and Mongo `MongoCodec` extend
|
|
13
14
|
- **Control stack** (`./control`): Assembly functions that combine component descriptors into a unified `ControlStack` with derived state (codec imports, renderers, authoring contributions)
|
|
14
15
|
- **Emission SPI** (`./emission`): Types for the emission pipeline — `TargetFamilyHook`, `ValidationContext`, `GenerateContractTypesOptions`, `TypeRenderEntry`, `TypeRenderer`, `ParameterizedCodecDescriptor`, and related types
|
|
15
16
|
- **Execution types** (`./execution`): Execution-plane stack and instance interfaces
|
|
17
|
+
- **Runtime SPI** (`./runtime`): Abstract `RuntimeCore<TPlan, TExec, TMiddleware>` base class, `RuntimeMiddleware` interface, and the canonical `runWithMiddleware` orchestrator helper. Family runtimes (`@prisma-next/sql-runtime`, `@prisma-next/mongo-runtime`) extend `RuntimeCore` directly per [ADR 204](../../../../../docs/architecture%20docs/adrs/ADR%20204%20-%20Single-tier%20runtime.md).
|
|
16
18
|
|
|
17
19
|
## Subpath exports
|
|
18
20
|
|
|
19
21
|
```typescript
|
|
20
22
|
import { ComponentMetadata, FamilyDescriptor, normalizeRenderer } from '@prisma-next/framework-components/components';
|
|
21
23
|
import { AuthoringContributions, instantiateAuthoringTypeConstructor } from '@prisma-next/framework-components/authoring';
|
|
24
|
+
import type { Codec } from '@prisma-next/framework-components/codec';
|
|
22
25
|
import { createControlStack, ControlStack } from '@prisma-next/framework-components/control';
|
|
23
26
|
import type { EmissionSpi } from '@prisma-next/framework-components/emission';
|
|
27
|
+
import { RuntimeCore, runWithMiddleware, type RuntimeMiddleware } from '@prisma-next/framework-components/runtime';
|
|
24
28
|
```
|
|
25
29
|
|
|
30
|
+
## `Codec` interface
|
|
31
|
+
|
|
32
|
+
The base `Codec` interface lands on the seam between **query-time** methods (per-row, IO-relevant) and **build-time** methods (per-contract-load):
|
|
33
|
+
|
|
34
|
+
- Query-time: `encode(value): Promise<TWire>` and `decode(wire): Promise<TInput>` are required and **Promise-returning at the public boundary**, regardless of whether the codec body is synchronous or asynchronous. Family factories (`codec()` for SQL, `mongoCodec()` for Mongo) accept either sync or async author functions and lift sync ones to Promise-shaped methods, so authors write whichever shape is natural per method without annotations.
|
|
35
|
+
- Build-time: `encodeJson`, `decodeJson`, and the optional `renderOutputType` are **synchronous** so `validateContract` and client construction stay synchronous.
|
|
36
|
+
|
|
37
|
+
There is no `runtime` / `kind` / equivalent async marker on the interface and no `TRuntime` generic. The runtime always awaits the query-time methods. See [ADR 204 — Single-Path Async Codec Runtime](../../../../../docs/architecture%20docs/adrs/ADR%20204%20-%20Single-Path%20Async%20Codec%20Runtime.md) for the full design.
|
|
38
|
+
|
|
39
|
+
### Codec call context (`ctx`)
|
|
40
|
+
|
|
41
|
+
Codecs receive a second `ctx` options argument; you may ignore it. The runtime allocates one `CodecCallContext` per `execute()` 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`. The framework `CodecCallContext` is signal-only:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
export interface CodecCallContext {
|
|
45
|
+
readonly signal?: AbortSignal;
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The internal `Codec` interface declares the parameter as required:
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
|
|
53
|
+
decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Codec authors who write `(value) => …` continue to compile via TypeScript's bivariance for trailing parameters; nothing at the author surface changes.
|
|
57
|
+
|
|
58
|
+
Family layers extend the context where they have a per-call concept that doesn't generalise. SQL declares `SqlCodecCallContext extends CodecCallContext { column?: SqlColumnRef }` (see `@prisma-next/sql-relational-core`); Mongo continues to use the framework type directly. Codec authors that take a `(value, ctx)` author signature can forward `ctx.signal` to network SDKs:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
// Sketch — actual factory lives in a family package (codec() / mongoCodec()).
|
|
62
|
+
encode: async (v: string, ctx) =>
|
|
63
|
+
kms.encrypt({ plaintext: v }, { signal: ctx?.signal });
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Aborts surface to the caller as `RUNTIME.ABORTED` with `details.phase ∈ { 'encode', 'decode', 'stream' }`. Codec bodies that ignore the signal complete in the background (cooperative cancellation). The `runtimeAborted(phase, cause?)` envelope helper and the `raceAgainstAbort(work, signal, phase)` race helper are exported from `@prisma-next/framework-components/runtime`.
|
|
67
|
+
|
|
68
|
+
See [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 full design.
|
|
69
|
+
|
|
70
|
+
## Higher-order codecs (`CodecDescriptor`, `CodecInstanceContext`, `synthesizeNonParameterizedDescriptor`)
|
|
71
|
+
|
|
72
|
+
Codec metadata, parameterized-codec registration, and runtime materialization live on a unified `CodecDescriptor<P>`:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import type { CodecDescriptor, CodecInstanceContext } from '@prisma-next/framework-components/codec';
|
|
76
|
+
import { synthesizeNonParameterizedDescriptor, voidParamsSchema } from '@prisma-next/framework-components/codec';
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
- `CodecDescriptor<P = void>` carries `codecId`, `traits`, `targetTypes`, `meta`, `paramsSchema: StandardSchemaV1<P>`, optional `renderOutputType`, and a curried `factory: (P) => (CodecInstanceContext) => Codec`. Non-parameterized codecs use `P = void` and a constant factory; parameterized codecs use a non-empty `P` (e.g. `{ length: number }` for pgvector).
|
|
80
|
+
- `CodecInstanceContext` (family-agnostic, `{ name }` only) is supplied by the runtime when materializing a per-instance codec. Pack authors close over it inside the factory; they never construct it. This is the **per-materialization** context, sibling to the **per-call** `CodecCallContext` documented above. Family-specific extensions augment it — the SQL family ships `SqlCodecInstanceContext extends CodecInstanceContext` in `@prisma-next/sql-relational-core/ast`, adding `usedAt: ReadonlyArray<{ table; column }>` for SQL-domain codecs that need column-set metadata.
|
|
81
|
+
- `synthesizeNonParameterizedDescriptor(codec)` wraps an existing `Codec` (with its async `encode`/`decode` per ADR 204) into a `CodecDescriptor<void>` whose constant factory returns the same shared codec instance for every column. The synthesis bridge keeps non-parameterized codec contributors on the legacy `codecs:` slot while the unified descriptor map remains the single read source for codec-id-keyed metadata.
|
|
82
|
+
|
|
83
|
+
`paramsSchema` is typed as Standard Schema (`StandardSchemaV1<P>`), not arktype-specific. arktype `Type`s satisfy the shape via their `~standard` getter, so existing arktype-typed descriptors satisfy the new shape transparently while `framework-components` itself takes no dependency on arktype.
|
|
84
|
+
|
|
85
|
+
See [ADR 208 — Higher-order codecs for parameterized types](../../../../../docs/architecture%20docs/adrs/ADR%20208%20-%20Higher-order%20codecs%20for%20parameterized%20types.md) for the full design.
|
|
86
|
+
|
|
26
87
|
## Why SPI types live here (dependency inversion)
|
|
27
88
|
|
|
28
89
|
This package sits in the **core** layer — below the tooling layer where family-specific emitters and control implementations live. SPI interfaces like `EmissionSpi` define the contract between framework orchestration code (control-plane emission, CLI) and family-specific implementations (SQL emitter, Mongo emitter).
|
package/dist/authoring.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as resolveAuthoringTemplateValue, a as AuthoringFieldNamespace, c as AuthoringStorageTypeTemplate, d as AuthoringTypeNamespace, f as instantiateAuthoringFieldPreset, g as isAuthoringTypeConstructorDescriptor, h as isAuthoringFieldPresetDescriptor, i as AuthoringContributions, l as AuthoringTemplateValue, m as isAuthoringArgRef, n as AuthoringArgumentDescriptor, o as AuthoringFieldPresetDescriptor, p as instantiateAuthoringTypeConstructor, r as AuthoringColumnDefaultTemplate, s as AuthoringFieldPresetOutput, t as AuthoringArgRef, u as AuthoringTypeConstructorDescriptor, v as validateAuthoringHelperArguments } from "./framework-authoring-
|
|
1
|
+
import { _ as resolveAuthoringTemplateValue, a as AuthoringFieldNamespace, c as AuthoringStorageTypeTemplate, d as AuthoringTypeNamespace, f as instantiateAuthoringFieldPreset, g as isAuthoringTypeConstructorDescriptor, h as isAuthoringFieldPresetDescriptor, i as AuthoringContributions, l as AuthoringTemplateValue, m as isAuthoringArgRef, n as AuthoringArgumentDescriptor, o as AuthoringFieldPresetDescriptor, p as instantiateAuthoringTypeConstructor, r as AuthoringColumnDefaultTemplate, s as AuthoringFieldPresetOutput, t as AuthoringArgRef, u as AuthoringTypeConstructorDescriptor, v as validateAuthoringHelperArguments } from "./framework-authoring-BdrFDx4x.mjs";
|
|
2
2
|
export { type AuthoringArgRef, type AuthoringArgumentDescriptor, type AuthoringColumnDefaultTemplate, type AuthoringContributions, type AuthoringFieldNamespace, type AuthoringFieldPresetDescriptor, type AuthoringFieldPresetOutput, type AuthoringStorageTypeTemplate, type AuthoringTemplateValue, type AuthoringTypeConstructorDescriptor, type AuthoringTypeNamespace, instantiateAuthoringFieldPreset, instantiateAuthoringTypeConstructor, isAuthoringArgRef, isAuthoringFieldPresetDescriptor, isAuthoringTypeConstructorDescriptor, resolveAuthoringTemplateValue, validateAuthoringHelperArguments };
|
package/dist/authoring.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
2
2
|
|
|
3
|
-
//#region src/framework-authoring.ts
|
|
3
|
+
//#region src/shared/framework-authoring.ts
|
|
4
4
|
function isAuthoringArgRef(value) {
|
|
5
5
|
if (typeof value !== "object" || value === null || value.kind !== "arg") return false;
|
|
6
6
|
const { index, path } = value;
|
package/dist/authoring.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authoring.mjs","names":["resolved: Record<string, unknown>"],"sources":["../src/framework-authoring.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\n\nexport type AuthoringArgRef = {\n readonly kind: 'arg';\n readonly index: number;\n readonly path?: readonly string[];\n readonly default?: AuthoringTemplateValue;\n};\n\nexport type AuthoringTemplateValue =\n | string\n | number\n | boolean\n | null\n | AuthoringArgRef\n | readonly AuthoringTemplateValue[]\n | { readonly [key: string]: AuthoringTemplateValue };\n\ninterface AuthoringArgumentDescriptorCommon {\n readonly name?: string;\n readonly optional?: boolean;\n}\n\nexport type AuthoringArgumentDescriptor = AuthoringArgumentDescriptorCommon &\n (\n | { readonly kind: 'string' }\n | {\n readonly kind: 'number';\n readonly integer?: boolean;\n readonly minimum?: number;\n readonly maximum?: number;\n }\n | { readonly kind: 'stringArray' }\n | {\n readonly kind: 'object';\n readonly properties: Record<string, AuthoringArgumentDescriptor>;\n }\n );\n\nexport interface AuthoringStorageTypeTemplate {\n readonly codecId: string;\n readonly nativeType: AuthoringTemplateValue;\n readonly typeParams?: Record<string, AuthoringTemplateValue>;\n}\n\nexport interface AuthoringTypeConstructorDescriptor {\n readonly kind: 'typeConstructor';\n readonly args?: readonly AuthoringArgumentDescriptor[];\n readonly output: AuthoringStorageTypeTemplate;\n}\n\nexport interface AuthoringColumnDefaultTemplateLiteral {\n readonly kind: 'literal';\n readonly value: AuthoringTemplateValue;\n}\n\nexport interface AuthoringColumnDefaultTemplateFunction {\n readonly kind: 'function';\n readonly expression: AuthoringTemplateValue;\n}\n\nexport type AuthoringColumnDefaultTemplate =\n | AuthoringColumnDefaultTemplateLiteral\n | AuthoringColumnDefaultTemplateFunction;\n\nexport interface AuthoringFieldPresetOutput extends AuthoringStorageTypeTemplate {\n readonly nullable?: boolean;\n readonly default?: AuthoringColumnDefaultTemplate;\n readonly executionDefault?: AuthoringTemplateValue;\n readonly id?: boolean;\n readonly unique?: boolean;\n}\n\nexport interface AuthoringFieldPresetDescriptor {\n readonly kind: 'fieldPreset';\n readonly args?: readonly AuthoringArgumentDescriptor[];\n readonly output: AuthoringFieldPresetOutput;\n}\n\nexport type AuthoringTypeNamespace = {\n readonly [name: string]: AuthoringTypeConstructorDescriptor | AuthoringTypeNamespace;\n};\n\nexport type AuthoringFieldNamespace = {\n readonly [name: string]: AuthoringFieldPresetDescriptor | AuthoringFieldNamespace;\n};\n\nexport interface AuthoringContributions {\n readonly type?: AuthoringTypeNamespace;\n readonly field?: AuthoringFieldNamespace;\n}\n\nexport function isAuthoringArgRef(value: unknown): value is AuthoringArgRef {\n if (typeof value !== 'object' || value === null || (value as { kind?: unknown }).kind !== 'arg') {\n return false;\n }\n const { index, path } = value as { index?: unknown; path?: unknown };\n if (typeof index !== 'number' || !Number.isInteger(index) || index < 0) {\n return false;\n }\n if (path !== undefined && (!Array.isArray(path) || path.some((s) => typeof s !== 'string'))) {\n return false;\n }\n return true;\n}\n\nfunction isAuthoringTemplateRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function isAuthoringTypeConstructorDescriptor(\n value: unknown,\n): value is AuthoringTypeConstructorDescriptor {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === 'typeConstructor' &&\n typeof (value as { output?: unknown }).output === 'object' &&\n (value as { output?: unknown }).output !== null\n );\n}\n\nexport function isAuthoringFieldPresetDescriptor(\n value: unknown,\n): value is AuthoringFieldPresetDescriptor {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === 'fieldPreset' &&\n typeof (value as { output?: unknown }).output === 'object' &&\n (value as { output?: unknown }).output !== null\n );\n}\n\nexport function resolveAuthoringTemplateValue(\n template: AuthoringTemplateValue,\n args: readonly unknown[],\n): unknown {\n if (isAuthoringArgRef(template)) {\n let value = args[template.index];\n\n for (const segment of template.path ?? []) {\n if (!isAuthoringTemplateRecord(value) || !Object.hasOwn(value, segment)) {\n value = undefined;\n break;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n\n if (value === undefined && template.default !== undefined) {\n return resolveAuthoringTemplateValue(template.default, args);\n }\n\n return value;\n }\n if (Array.isArray(template)) {\n return template.map((value) => resolveAuthoringTemplateValue(value, args));\n }\n if (typeof template === 'object' && template !== null) {\n const resolved: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(template)) {\n const resolvedValue = resolveAuthoringTemplateValue(value, args);\n if (resolvedValue !== undefined) {\n resolved[key] = resolvedValue;\n }\n }\n return resolved;\n }\n return template;\n}\n\nfunction validateAuthoringArgument(\n descriptor: AuthoringArgumentDescriptor,\n value: unknown,\n path: string,\n): void {\n if (value === undefined) {\n if (descriptor.optional) {\n return;\n }\n throw new Error(`Missing required authoring helper argument at ${path}`);\n }\n\n if (descriptor.kind === 'string') {\n if (typeof value !== 'string') {\n throw new Error(`Authoring helper argument at ${path} must be a string`);\n }\n return;\n }\n\n if (descriptor.kind === 'stringArray') {\n if (!Array.isArray(value)) {\n throw new Error(`Authoring helper argument at ${path} must be an array of strings`);\n }\n for (const entry of value) {\n if (typeof entry !== 'string') {\n throw new Error(`Authoring helper argument at ${path} must be an array of strings`);\n }\n }\n return;\n }\n\n if (descriptor.kind === 'object') {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Authoring helper argument at ${path} must be an object`);\n }\n\n const input = value as Record<string, unknown>;\n const expectedKeys = new Set(Object.keys(descriptor.properties));\n\n for (const key of Object.keys(input)) {\n if (!expectedKeys.has(key)) {\n throw new Error(`Authoring helper argument at ${path} contains unknown property \"${key}\"`);\n }\n }\n\n for (const [key, propertyDescriptor] of Object.entries(descriptor.properties)) {\n validateAuthoringArgument(propertyDescriptor, input[key], `${path}.${key}`);\n }\n\n return;\n }\n\n if (typeof value !== 'number' || Number.isNaN(value)) {\n throw new Error(`Authoring helper argument at ${path} must be a number`);\n }\n\n if (descriptor.integer && !Number.isInteger(value)) {\n throw new Error(`Authoring helper argument at ${path} must be an integer`);\n }\n if (descriptor.minimum !== undefined && value < descriptor.minimum) {\n throw new Error(\n `Authoring helper argument at ${path} must be >= ${descriptor.minimum}, received ${value}`,\n );\n }\n if (descriptor.maximum !== undefined && value > descriptor.maximum) {\n throw new Error(\n `Authoring helper argument at ${path} must be <= ${descriptor.maximum}, received ${value}`,\n );\n }\n}\n\nexport function validateAuthoringHelperArguments(\n helperPath: string,\n descriptors: readonly AuthoringArgumentDescriptor[] | undefined,\n args: readonly unknown[],\n): void {\n const expected = descriptors ?? [];\n const minimumArgs = expected.reduce(\n (count, descriptor, index) => (descriptor.optional ? count : index + 1),\n 0,\n );\n if (args.length < minimumArgs || args.length > expected.length) {\n throw new Error(\n `${helperPath} expects ${minimumArgs === expected.length ? expected.length : `${minimumArgs}-${expected.length}`} argument(s), received ${args.length}`,\n );\n }\n\n expected.forEach((descriptor, index) => {\n validateAuthoringArgument(descriptor, args[index], `${helperPath}[${index}]`);\n });\n}\n\nfunction resolveAuthoringStorageTypeTemplate(\n template: AuthoringStorageTypeTemplate,\n args: readonly unknown[],\n): {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown>;\n} {\n const nativeType = resolveAuthoringTemplateValue(template.nativeType, args);\n if (typeof nativeType !== 'string') {\n throw new Error(\n `Resolved authoring nativeType must be a string for codec \"${template.codecId}\", received ${String(nativeType)}`,\n );\n }\n const typeParams =\n template.typeParams === undefined\n ? undefined\n : resolveAuthoringTemplateValue(template.typeParams, args);\n if (typeParams !== undefined && !isAuthoringTemplateRecord(typeParams)) {\n throw new Error(\n `Resolved authoring typeParams must be an object for codec \"${template.codecId}\", received ${String(typeParams)}`,\n );\n }\n\n return {\n codecId: template.codecId,\n nativeType,\n ...(typeParams === undefined ? {} : { typeParams }),\n };\n}\n\nfunction resolveAuthoringColumnDefaultTemplate(\n template: AuthoringColumnDefaultTemplate,\n args: readonly unknown[],\n):\n | {\n readonly kind: 'literal';\n readonly value: unknown;\n }\n | {\n readonly kind: 'function';\n readonly expression: string;\n } {\n if (template.kind === 'literal') {\n const value = resolveAuthoringTemplateValue(template.value, args);\n if (value === undefined) {\n throw new Error('Resolved authoring literal default must not be undefined');\n }\n return {\n kind: 'literal',\n value,\n };\n }\n\n const expression = resolveAuthoringTemplateValue(template.expression, args);\n if (expression === undefined || (typeof expression === 'object' && expression !== null)) {\n throw new Error(\n `Resolved authoring function default expression must resolve to a primitive, received ${String(expression)}`,\n );\n }\n return {\n kind: 'function',\n expression: String(expression),\n };\n}\n\nexport function instantiateAuthoringTypeConstructor(\n descriptor: AuthoringTypeConstructorDescriptor,\n args: readonly unknown[],\n): {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown>;\n} {\n return resolveAuthoringStorageTypeTemplate(descriptor.output, args);\n}\n\nexport function instantiateAuthoringFieldPreset(\n descriptor: AuthoringFieldPresetDescriptor,\n args: readonly unknown[],\n): {\n readonly descriptor: {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown>;\n };\n readonly nullable: boolean;\n readonly default?:\n | {\n readonly kind: 'literal';\n readonly value: unknown;\n }\n | {\n readonly kind: 'function';\n readonly expression: string;\n };\n readonly executionDefault?: unknown;\n readonly id: boolean;\n readonly unique: boolean;\n} {\n return {\n descriptor: resolveAuthoringStorageTypeTemplate(descriptor.output, args),\n nullable: descriptor.output.nullable ?? false,\n ...ifDefined(\n 'default',\n descriptor.output.default !== undefined\n ? resolveAuthoringColumnDefaultTemplate(descriptor.output.default, args)\n : undefined,\n ),\n ...ifDefined(\n 'executionDefault',\n descriptor.output.executionDefault !== undefined\n ? resolveAuthoringTemplateValue(descriptor.output.executionDefault, args)\n : undefined,\n ),\n id: descriptor.output.id ?? false,\n unique: descriptor.output.unique ?? false,\n };\n}\n"],"mappings":";;;AA4FA,SAAgB,kBAAkB,OAA0C;AAC1E,KAAI,OAAO,UAAU,YAAY,UAAU,QAAS,MAA6B,SAAS,MACxF,QAAO;CAET,MAAM,EAAE,OAAO,SAAS;AACxB,KAAI,OAAO,UAAU,YAAY,CAAC,OAAO,UAAU,MAAM,IAAI,QAAQ,EACnE,QAAO;AAET,KAAI,SAAS,WAAc,CAAC,MAAM,QAAQ,KAAK,IAAI,KAAK,MAAM,MAAM,OAAO,MAAM,SAAS,EACxF,QAAO;AAET,QAAO;;AAGT,SAAS,0BAA0B,OAAkD;AACnF,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;AAG7E,SAAgB,qCACd,OAC6C;AAC7C,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA6B,SAAS,qBACvC,OAAQ,MAA+B,WAAW,YACjD,MAA+B,WAAW;;AAI/C,SAAgB,iCACd,OACyC;AACzC,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA6B,SAAS,iBACvC,OAAQ,MAA+B,WAAW,YACjD,MAA+B,WAAW;;AAI/C,SAAgB,8BACd,UACA,MACS;AACT,KAAI,kBAAkB,SAAS,EAAE;EAC/B,IAAI,QAAQ,KAAK,SAAS;AAE1B,OAAK,MAAM,WAAW,SAAS,QAAQ,EAAE,EAAE;AACzC,OAAI,CAAC,0BAA0B,MAAM,IAAI,CAAC,OAAO,OAAO,OAAO,QAAQ,EAAE;AACvE,YAAQ;AACR;;AAEF,WAAS,MAAkC;;AAG7C,MAAI,UAAU,UAA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M,IAAI,MACR,8DAA8D,SAAS,QAAQ,cAAc,OAAO,WAAW,GAChH;AAGH,QAAO;EACL,SAAS,SAAS;EAClB;EACA,GAAI,eAAe,SAAY,EAAE,GAAG,EAAE,YAAY;EACnD;;AAGH,SAAS,sCACP,UACA,MASI;AACJ,KAAI,SAAS,SAAS,WAAW;EAC/B,MAAM,QAAQ,8BAA8B,SAAS,OAAO,KAAK;AACjE,MAAI,UAAU,OACZ,OAAM,IAAI,MAAM,2DAA2D;AAE7E,SAAO;GACL,MAAM;GACN;GACD;;CAGH,MAAM,aAAa,8BAA8B,SAAS,YAAY,KAAK;AAC3E,KAAI,eAAe,UAAc,OAAO,eAAe,YAAY,eAAe,KAChF,OAAM,IAAI,MACR,wFAAwF,OAAO,WAAW,GAC3G;AAEH,QAAO;EACL,MAAM;EACN,YAAY,OAAO,WAAW;EAC/B;;AAGH,SAAgB,oCACd,YACA,MAKA;AACA,QAAO,oCAAoC,WAAW,QAAQ,KAAK;;AAGrE,SAAgB,gCACd,YACA,MAoBA;AACA,QAAO;EACL,YAAY,oCAAoC,WAAW,QAAQ,KAAK;EACxE,UAAU,WAAW,OAAO,YAAY;EACxC,GAAG,UACD,WACA,WAAW,OAAO,YAAY,SAC1B,sCAAsC,WAAW,OAAO,SAAS,KAAK,GACtE,OACL;EACD,GAAG,UACD,oBACA,WAAW,OAAO,qBAAqB,SACnC,8BAA8B,WAAW,OAAO,kBAAkB,KAAK,GACvE,OACL;EACD,IAAI,WAAW,OAAO,MAAM;EAC5B,QAAQ,WAAW,OAAO,UAAU;EACrC"}
|
|
1
|
+
{"version":3,"file":"authoring.mjs","names":["resolved: Record<string, unknown>"],"sources":["../src/shared/framework-authoring.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\n\nexport type AuthoringArgRef = {\n readonly kind: 'arg';\n readonly index: number;\n readonly path?: readonly string[];\n readonly default?: AuthoringTemplateValue;\n};\n\nexport type AuthoringTemplateValue =\n | string\n | number\n | boolean\n | null\n | AuthoringArgRef\n | readonly AuthoringTemplateValue[]\n | { readonly [key: string]: AuthoringTemplateValue };\n\ninterface AuthoringArgumentDescriptorCommon {\n readonly name?: string;\n readonly optional?: boolean;\n}\n\nexport type AuthoringArgumentDescriptor = AuthoringArgumentDescriptorCommon &\n (\n | { readonly kind: 'string' }\n | {\n readonly kind: 'number';\n readonly integer?: boolean;\n readonly minimum?: number;\n readonly maximum?: number;\n }\n | { readonly kind: 'stringArray' }\n | {\n readonly kind: 'object';\n readonly properties: Record<string, AuthoringArgumentDescriptor>;\n }\n );\n\nexport interface AuthoringStorageTypeTemplate {\n readonly codecId: string;\n readonly nativeType: AuthoringTemplateValue;\n readonly typeParams?: Record<string, AuthoringTemplateValue>;\n}\n\nexport interface AuthoringTypeConstructorDescriptor {\n readonly kind: 'typeConstructor';\n readonly args?: readonly AuthoringArgumentDescriptor[];\n readonly output: AuthoringStorageTypeTemplate;\n}\n\nexport interface AuthoringColumnDefaultTemplateLiteral {\n readonly kind: 'literal';\n readonly value: AuthoringTemplateValue;\n}\n\nexport interface AuthoringColumnDefaultTemplateFunction {\n readonly kind: 'function';\n readonly expression: AuthoringTemplateValue;\n}\n\nexport type AuthoringColumnDefaultTemplate =\n | AuthoringColumnDefaultTemplateLiteral\n | AuthoringColumnDefaultTemplateFunction;\n\nexport interface AuthoringFieldPresetOutput extends AuthoringStorageTypeTemplate {\n readonly nullable?: boolean;\n readonly default?: AuthoringColumnDefaultTemplate;\n readonly executionDefault?: AuthoringTemplateValue;\n readonly id?: boolean;\n readonly unique?: boolean;\n}\n\nexport interface AuthoringFieldPresetDescriptor {\n readonly kind: 'fieldPreset';\n readonly args?: readonly AuthoringArgumentDescriptor[];\n readonly output: AuthoringFieldPresetOutput;\n}\n\nexport type AuthoringTypeNamespace = {\n readonly [name: string]: AuthoringTypeConstructorDescriptor | AuthoringTypeNamespace;\n};\n\nexport type AuthoringFieldNamespace = {\n readonly [name: string]: AuthoringFieldPresetDescriptor | AuthoringFieldNamespace;\n};\n\nexport interface AuthoringContributions {\n readonly type?: AuthoringTypeNamespace;\n readonly field?: AuthoringFieldNamespace;\n}\n\nexport function isAuthoringArgRef(value: unknown): value is AuthoringArgRef {\n if (typeof value !== 'object' || value === null || (value as { kind?: unknown }).kind !== 'arg') {\n return false;\n }\n const { index, path } = value as { index?: unknown; path?: unknown };\n if (typeof index !== 'number' || !Number.isInteger(index) || index < 0) {\n return false;\n }\n if (path !== undefined && (!Array.isArray(path) || path.some((s) => typeof s !== 'string'))) {\n return false;\n }\n return true;\n}\n\nfunction isAuthoringTemplateRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function isAuthoringTypeConstructorDescriptor(\n value: unknown,\n): value is AuthoringTypeConstructorDescriptor {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === 'typeConstructor' &&\n typeof (value as { output?: unknown }).output === 'object' &&\n (value as { output?: unknown }).output !== null\n );\n}\n\nexport function isAuthoringFieldPresetDescriptor(\n value: unknown,\n): value is AuthoringFieldPresetDescriptor {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === 'fieldPreset' &&\n typeof (value as { output?: unknown }).output === 'object' &&\n (value as { output?: unknown }).output !== null\n );\n}\n\nexport function resolveAuthoringTemplateValue(\n template: AuthoringTemplateValue,\n args: readonly unknown[],\n): unknown {\n if (isAuthoringArgRef(template)) {\n let value = args[template.index];\n\n for (const segment of template.path ?? []) {\n if (!isAuthoringTemplateRecord(value) || !Object.hasOwn(value, segment)) {\n value = undefined;\n break;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n\n if (value === undefined && template.default !== undefined) {\n return resolveAuthoringTemplateValue(template.default, args);\n }\n\n return value;\n }\n if (Array.isArray(template)) {\n return template.map((value) => resolveAuthoringTemplateValue(value, args));\n }\n if (typeof template === 'object' && template !== null) {\n const resolved: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(template)) {\n const resolvedValue = resolveAuthoringTemplateValue(value, args);\n if (resolvedValue !== undefined) {\n resolved[key] = resolvedValue;\n }\n }\n return resolved;\n }\n return template;\n}\n\nfunction validateAuthoringArgument(\n descriptor: AuthoringArgumentDescriptor,\n value: unknown,\n path: string,\n): void {\n if (value === undefined) {\n if (descriptor.optional) {\n return;\n }\n throw new Error(`Missing required authoring helper argument at ${path}`);\n }\n\n if (descriptor.kind === 'string') {\n if (typeof value !== 'string') {\n throw new Error(`Authoring helper argument at ${path} must be a string`);\n }\n return;\n }\n\n if (descriptor.kind === 'stringArray') {\n if (!Array.isArray(value)) {\n throw new Error(`Authoring helper argument at ${path} must be an array of strings`);\n }\n for (const entry of value) {\n if (typeof entry !== 'string') {\n throw new Error(`Authoring helper argument at ${path} must be an array of strings`);\n }\n }\n return;\n }\n\n if (descriptor.kind === 'object') {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`Authoring helper argument at ${path} must be an object`);\n }\n\n const input = value as Record<string, unknown>;\n const expectedKeys = new Set(Object.keys(descriptor.properties));\n\n for (const key of Object.keys(input)) {\n if (!expectedKeys.has(key)) {\n throw new Error(`Authoring helper argument at ${path} contains unknown property \"${key}\"`);\n }\n }\n\n for (const [key, propertyDescriptor] of Object.entries(descriptor.properties)) {\n validateAuthoringArgument(propertyDescriptor, input[key], `${path}.${key}`);\n }\n\n return;\n }\n\n if (typeof value !== 'number' || Number.isNaN(value)) {\n throw new Error(`Authoring helper argument at ${path} must be a number`);\n }\n\n if (descriptor.integer && !Number.isInteger(value)) {\n throw new Error(`Authoring helper argument at ${path} must be an integer`);\n }\n if (descriptor.minimum !== undefined && value < descriptor.minimum) {\n throw new Error(\n `Authoring helper argument at ${path} must be >= ${descriptor.minimum}, received ${value}`,\n );\n }\n if (descriptor.maximum !== undefined && value > descriptor.maximum) {\n throw new Error(\n `Authoring helper argument at ${path} must be <= ${descriptor.maximum}, received ${value}`,\n );\n }\n}\n\nexport function validateAuthoringHelperArguments(\n helperPath: string,\n descriptors: readonly AuthoringArgumentDescriptor[] | undefined,\n args: readonly unknown[],\n): void {\n const expected = descriptors ?? [];\n const minimumArgs = expected.reduce(\n (count, descriptor, index) => (descriptor.optional ? count : index + 1),\n 0,\n );\n if (args.length < minimumArgs || args.length > expected.length) {\n throw new Error(\n `${helperPath} expects ${minimumArgs === expected.length ? expected.length : `${minimumArgs}-${expected.length}`} argument(s), received ${args.length}`,\n );\n }\n\n expected.forEach((descriptor, index) => {\n validateAuthoringArgument(descriptor, args[index], `${helperPath}[${index}]`);\n });\n}\n\nfunction resolveAuthoringStorageTypeTemplate(\n template: AuthoringStorageTypeTemplate,\n args: readonly unknown[],\n): {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown>;\n} {\n const nativeType = resolveAuthoringTemplateValue(template.nativeType, args);\n if (typeof nativeType !== 'string') {\n throw new Error(\n `Resolved authoring nativeType must be a string for codec \"${template.codecId}\", received ${String(nativeType)}`,\n );\n }\n const typeParams =\n template.typeParams === undefined\n ? undefined\n : resolveAuthoringTemplateValue(template.typeParams, args);\n if (typeParams !== undefined && !isAuthoringTemplateRecord(typeParams)) {\n throw new Error(\n `Resolved authoring typeParams must be an object for codec \"${template.codecId}\", received ${String(typeParams)}`,\n );\n }\n\n return {\n codecId: template.codecId,\n nativeType,\n ...(typeParams === undefined ? {} : { typeParams }),\n };\n}\n\nfunction resolveAuthoringColumnDefaultTemplate(\n template: AuthoringColumnDefaultTemplate,\n args: readonly unknown[],\n):\n | {\n readonly kind: 'literal';\n readonly value: unknown;\n }\n | {\n readonly kind: 'function';\n readonly expression: string;\n } {\n if (template.kind === 'literal') {\n const value = resolveAuthoringTemplateValue(template.value, args);\n if (value === undefined) {\n throw new Error('Resolved authoring literal default must not be undefined');\n }\n return {\n kind: 'literal',\n value,\n };\n }\n\n const expression = resolveAuthoringTemplateValue(template.expression, args);\n if (expression === undefined || (typeof expression === 'object' && expression !== null)) {\n throw new Error(\n `Resolved authoring function default expression must resolve to a primitive, received ${String(expression)}`,\n );\n }\n return {\n kind: 'function',\n expression: String(expression),\n };\n}\n\nexport function instantiateAuthoringTypeConstructor(\n descriptor: AuthoringTypeConstructorDescriptor,\n args: readonly unknown[],\n): {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown>;\n} {\n return resolveAuthoringStorageTypeTemplate(descriptor.output, args);\n}\n\nexport function instantiateAuthoringFieldPreset(\n descriptor: AuthoringFieldPresetDescriptor,\n args: readonly unknown[],\n): {\n readonly descriptor: {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown>;\n };\n readonly nullable: boolean;\n readonly default?:\n | {\n readonly kind: 'literal';\n readonly value: unknown;\n }\n | {\n readonly kind: 'function';\n readonly expression: string;\n };\n readonly executionDefault?: unknown;\n readonly id: boolean;\n readonly unique: boolean;\n} {\n return {\n descriptor: resolveAuthoringStorageTypeTemplate(descriptor.output, args),\n nullable: descriptor.output.nullable ?? false,\n ...ifDefined(\n 'default',\n descriptor.output.default !== undefined\n ? resolveAuthoringColumnDefaultTemplate(descriptor.output.default, args)\n : undefined,\n ),\n ...ifDefined(\n 'executionDefault',\n descriptor.output.executionDefault !== undefined\n ? resolveAuthoringTemplateValue(descriptor.output.executionDefault, args)\n : undefined,\n ),\n id: descriptor.output.id ?? false,\n unique: descriptor.output.unique ?? false,\n };\n}\n"],"mappings":";;;AA4FA,SAAgB,kBAAkB,OAA0C;AAC1E,KAAI,OAAO,UAAU,YAAY,UAAU,QAAS,MAA6B,SAAS,MACxF,QAAO;CAET,MAAM,EAAE,OAAO,SAAS;AACxB,KAAI,OAAO,UAAU,YAAY,CAAC,OAAO,UAAU,MAAM,IAAI,QAAQ,EACnE,QAAO;AAET,KAAI,SAAS,WAAc,CAAC,MAAM,QAAQ,KAAK,IAAI,KAAK,MAAM,MAAM,OAAO,MAAM,SAAS,EACxF,QAAO;AAET,QAAO;;AAGT,SAAS,0BAA0B,OAAkD;AACnF,QAAO,OAAO,UAAU,YA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;EACL,YAAY,oCAAoC,WAAW,QAAQ,KAAK;EACxE,UAAU,WAAW,OAAO,YAAY;EACxC,GAAG,UACD,WACA,WAAW,OAAO,YAAY,SAC1B,sCAAsC,WAAW,OAAO,SAAS,KAAK,GACtE,OACL;EACD,GAAG,UACD,oBACA,WAAW,OAAO,qBAAqB,SACnC,8BAA8B,WAAW,OAAO,kBAAkB,KAAK,GACvE,OACL;EACD,IAAI,WAAW,OAAO,MAAM;EAC5B,QAAQ,WAAW,OAAO,UAAU;EACrC"}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { JsonValue } from "@prisma-next/contract/types";
|
|
2
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
+
|
|
4
|
+
//#region src/shared/codec-types.d.ts
|
|
5
|
+
type CodecTrait = 'equality' | 'order' | 'boolean' | 'numeric' | 'textual'
|
|
6
|
+
/**
|
|
7
|
+
* The codec carries a per-instance `validate(value: unknown) =>
|
|
8
|
+
* JsonSchemaValidationResult` function on the resolved codec object that
|
|
9
|
+
* the framework's `JsonSchemaValidatorRegistry` consults at runtime. The
|
|
10
|
+
* trait gates the `extractValidator` cast from structurally-typed
|
|
11
|
+
* `unknown` to a typed validator view.
|
|
12
|
+
*
|
|
13
|
+
* Retirement target. The unified `CodecDescriptor` model moves
|
|
14
|
+
* validation into the resolved codec's `decode` body; the parallel
|
|
15
|
+
* `JsonSchemaValidatorRegistry` (and this trait alongside it) retires
|
|
16
|
+
* under TML-2357 (T3.5.12). Per-library JSON extensions like
|
|
17
|
+
* `@prisma-next/extension-arktype-json` already follow the new pattern.
|
|
18
|
+
*/ | 'json-validator';
|
|
19
|
+
/**
|
|
20
|
+
* Per-call context the runtime threads to every `codec.encode` /
|
|
21
|
+
* `codec.decode` invocation for a single `runtime.execute()` call.
|
|
22
|
+
*
|
|
23
|
+
* The framework-level shape is family-agnostic and carries one field:
|
|
24
|
+
*
|
|
25
|
+
* - `signal?: AbortSignal` — per-query cancellation. The runtime returns
|
|
26
|
+
* a `RUNTIME.ABORTED` envelope when the signal aborts; codec authors
|
|
27
|
+
* who forward `signal` to their underlying SDK get true cancellation
|
|
28
|
+
* of in-flight network calls.
|
|
29
|
+
*
|
|
30
|
+
* Family layers extend this base with their own shape-of-call metadata:
|
|
31
|
+
* the SQL family adds `column?: SqlColumnRef` via `SqlCodecCallContext`
|
|
32
|
+
* (see `@prisma-next/sql-relational-core`). Mongo currently uses this
|
|
33
|
+
* framework type unchanged. Column metadata is intentionally **not** on
|
|
34
|
+
* the framework type — it is a SQL-family concept rooted in SQL's
|
|
35
|
+
* `(table, column)` addressing model and would not generalise to other
|
|
36
|
+
* families.
|
|
37
|
+
*
|
|
38
|
+
* The interface is named explicitly (not inlined) so future framework
|
|
39
|
+
* fields and family extensions can land additively without breaking
|
|
40
|
+
* codec author signatures.
|
|
41
|
+
*/
|
|
42
|
+
interface CodecCallContext {
|
|
43
|
+
readonly signal?: AbortSignal;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* A codec is the contract between an application value and its on-wire and
|
|
47
|
+
* on-contract-disk representations.
|
|
48
|
+
*
|
|
49
|
+
* The author's mental model is two JS-side types — `TInput` (the
|
|
50
|
+
* application JS type) and `TWire` (the database driver wire format) —
|
|
51
|
+
* plus `JsonValue` for build-time contract artifacts. The codec translates
|
|
52
|
+
* `TInput` to `TWire` on writes and back on reads, and to/from `JsonValue`
|
|
53
|
+
* during contract emission and loading.
|
|
54
|
+
*
|
|
55
|
+
* Three representations participate:
|
|
56
|
+
* - **Input** (`TInput`): the JS type at the application boundary.
|
|
57
|
+
* - **Wire** (`TWire`): the format exchanged with the database driver.
|
|
58
|
+
* - **JSON** (`JsonValue`): a JSON-safe form used in contract artifacts.
|
|
59
|
+
*
|
|
60
|
+
* Codec methods split into two groups:
|
|
61
|
+
*
|
|
62
|
+
* - **Query-time** methods (`encode`, `decode`) run per row/parameter at the
|
|
63
|
+
* IO boundary; they are required and Promise-returning. The per-family
|
|
64
|
+
* codec factory accepts sync or async author functions and lifts sync
|
|
65
|
+
* ones to Promise-shaped methods automatically.
|
|
66
|
+
* - **Build-time** methods (`encodeJson`, `decodeJson`, `renderOutputType`)
|
|
67
|
+
* run when the contract is serialized, loaded, or when client types are
|
|
68
|
+
* emitted. They stay synchronous so contract validation and client
|
|
69
|
+
* construction are synchronous.
|
|
70
|
+
*
|
|
71
|
+
* Target-family codec interfaces extend this base with target-shaped
|
|
72
|
+
* metadata.
|
|
73
|
+
*/
|
|
74
|
+
interface Codec<Id extends string = string, TTraits extends readonly CodecTrait[] = readonly CodecTrait[], TWire = unknown, TInput = unknown> {
|
|
75
|
+
/** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). */
|
|
76
|
+
readonly id: Id;
|
|
77
|
+
/** Database-native type names this codec handles (e.g. `['timestamptz']`). */
|
|
78
|
+
readonly targetTypes: readonly string[];
|
|
79
|
+
/** Semantic traits for operator gating (e.g. equality, order, numeric). */
|
|
80
|
+
readonly traits?: TTraits;
|
|
81
|
+
/** 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. */
|
|
82
|
+
encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
|
|
83
|
+
/** 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. */
|
|
84
|
+
decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
|
|
85
|
+
/** Converts a JS value to a JSON-safe representation for contract serialization. Synchronous; called during contract emission. */
|
|
86
|
+
encodeJson(value: TInput): JsonValue;
|
|
87
|
+
/** Converts a JSON representation back to the JS input type. Synchronous; called during contract loading via `validateContract`. */
|
|
88
|
+
decodeJson(json: JsonValue): TInput;
|
|
89
|
+
/** Produces the TypeScript output type expression for a field given its `typeParams`. Synchronous; used during contract.d.ts emission. */
|
|
90
|
+
renderOutputType?(typeParams: Record<string, unknown>): string | undefined;
|
|
91
|
+
}
|
|
92
|
+
interface CodecLookup {
|
|
93
|
+
get(id: string): Codec | undefined;
|
|
94
|
+
}
|
|
95
|
+
declare const emptyCodecLookup: CodecLookup;
|
|
96
|
+
/**
|
|
97
|
+
* Family-agnostic per-instance context supplied by the framework when
|
|
98
|
+
* applying a higher-order codec factory. Allows stateful codecs (e.g.
|
|
99
|
+
* column-scoped encryption) to derive per-instance state from the
|
|
100
|
+
* materialization site.
|
|
101
|
+
*
|
|
102
|
+
* - `name` — the family-agnostic instance identity. For SQL, the runtime
|
|
103
|
+
* populates this as the `storage.types` instance name (e.g.
|
|
104
|
+
* `Embedding1536`) for typeRef-shaped columns, the synthesized
|
|
105
|
+
* anonymous instance name (`<anon:Document.embedding>`) for inline-
|
|
106
|
+
* `typeParams` columns, or a shared sentinel (`<shared:pg/text@1>`)
|
|
107
|
+
* for non-parameterized codec ids. Other families pick the analogous
|
|
108
|
+
* identity for their materialization sites.
|
|
109
|
+
*
|
|
110
|
+
* Family-specific extensions (e.g. {@link import('@prisma-next/sql-relational-core/ast').SqlCodecInstanceContext}
|
|
111
|
+
* in the SQL layer) augment this base with domain-shaped column-set
|
|
112
|
+
* metadata. Codec authors target the base when they don't read family-
|
|
113
|
+
* specific metadata; they target the family extension when they do.
|
|
114
|
+
*/
|
|
115
|
+
interface CodecInstanceContext {
|
|
116
|
+
readonly name: string;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Family-agnostic codec metadata. Family-specific extensions augment the
|
|
120
|
+
* base `db.<family>.<target>` block with native-type information; the base
|
|
121
|
+
* shape is an empty object so non-relational codecs can carry no metadata.
|
|
122
|
+
*/
|
|
123
|
+
interface CodecMeta {
|
|
124
|
+
readonly db?: Record<string, unknown>;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Unified codec descriptor. Every codec in the framework registers through
|
|
128
|
+
* this shape — non-parameterized codecs use `P = void` and a constant
|
|
129
|
+
* factory that returns the same shared codec instance for every column;
|
|
130
|
+
* parameterized codecs use a non-empty `P` and a curried higher-order
|
|
131
|
+
* factory that returns a per-instance codec.
|
|
132
|
+
*
|
|
133
|
+
* The descriptor is the codec-id-keyed source of truth for static metadata
|
|
134
|
+
* (`traits`, `targetTypes`, `meta`) and registration concerns
|
|
135
|
+
* (`paramsSchema` for JSON-boundary validation; optional `renderOutputType`
|
|
136
|
+
* for the `contract.d.ts` emit path). The runtime `Codec` instance returned
|
|
137
|
+
* by `factory(params)(ctx)` carries only the conversion behavior.
|
|
138
|
+
*
|
|
139
|
+
* Whether a codec id "is parameterized" stops being a registration-time
|
|
140
|
+
* distinction — it's a property of `P` on the descriptor. The descriptor
|
|
141
|
+
* map indexes every descriptor by `codecId`; both `descriptorFor(codecId)`
|
|
142
|
+
* and `forColumn(table, column)` resolve through the same map without
|
|
143
|
+
* branching on parameterization.
|
|
144
|
+
*
|
|
145
|
+
* @template P - The shape of the params accepted by the factory (`void` for
|
|
146
|
+
* non-parameterized codecs; a record like `{ length: number }` for
|
|
147
|
+
* parameterized codecs).
|
|
148
|
+
*
|
|
149
|
+
* Codec-registry-unification project § Decision.
|
|
150
|
+
*/
|
|
151
|
+
interface CodecDescriptor<P = void> {
|
|
152
|
+
/** The codec ID this descriptor applies to (e.g. `pg/vector@1`, `pg/text@1`). */
|
|
153
|
+
readonly codecId: string;
|
|
154
|
+
/** Semantic traits for operator gating (e.g. equality, order, numeric). */
|
|
155
|
+
readonly traits: readonly CodecTrait[];
|
|
156
|
+
/** Database-native type names this codec handles (e.g. `['timestamptz']`). */
|
|
157
|
+
readonly targetTypes: readonly string[];
|
|
158
|
+
/** Optional family-specific metadata (e.g. SQL-side `db.sql.postgres.nativeType`). */
|
|
159
|
+
readonly meta?: CodecMeta;
|
|
160
|
+
/**
|
|
161
|
+
* Standard Schema validator for the factory's params. Validates JSON-
|
|
162
|
+
* sourced params at the contract boundary (PSL → IR; `contract.json` →
|
|
163
|
+
* runtime). For non-parameterized codecs (`P = void`), the schema
|
|
164
|
+
* validates `void`/`undefined` — the framework supplies no params at the
|
|
165
|
+
* call boundary.
|
|
166
|
+
*/
|
|
167
|
+
readonly paramsSchema: StandardSchemaV1<P>;
|
|
168
|
+
/**
|
|
169
|
+
* Emit-path string renderer for `contract.d.ts`. Returns the TypeScript
|
|
170
|
+
* output type expression for given params (e.g. `Vector<1536>`).
|
|
171
|
+
* Optional; absent renderers cause the emitter to fall back to the
|
|
172
|
+
* codec's base output type. Non-parameterized codecs typically omit it.
|
|
173
|
+
*/
|
|
174
|
+
readonly renderOutputType?: (params: P) => string | undefined;
|
|
175
|
+
/**
|
|
176
|
+
* The curried higher-order codec. For non-parameterized codecs, the
|
|
177
|
+
* factory is constant — every call returns the same shared codec
|
|
178
|
+
* instance. For parameterized codecs, the factory is called once per
|
|
179
|
+
* `storage.types` instance (or once per inline-`typeParams` column),
|
|
180
|
+
* with `ctx` carrying the column set the resulting codec serves.
|
|
181
|
+
*/
|
|
182
|
+
readonly factory: (params: P) => (ctx: CodecInstanceContext) => Codec;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Standard Schema validator for `void` params. Accepts only `undefined`
|
|
186
|
+
* (or absent input); rejects any other value so a contract that tries to
|
|
187
|
+
* thread `typeParams` through a non-parameterized codec id fails fast at
|
|
188
|
+
* the JSON boundary instead of silently coercing the value away. Used by
|
|
189
|
+
* the framework-supplied non-parameterized descriptor synthesizer.
|
|
190
|
+
*/
|
|
191
|
+
declare const voidParamsSchema: StandardSchemaV1<void>;
|
|
192
|
+
/**
|
|
193
|
+
* Synthesize a `CodecDescriptor<void>` for a non-parameterized codec
|
|
194
|
+
* runtime instance. The factory is constant — every call returns the same
|
|
195
|
+
* shared codec instance — so columns sharing this codec id share one
|
|
196
|
+
* resolved codec.
|
|
197
|
+
*
|
|
198
|
+
* Codec-registry-unification spec § Decision (Case T — non-parameterized
|
|
199
|
+
* text codec). This is the bridge while non-parameterized codec
|
|
200
|
+
* contributors still register through the legacy `codecs:` slot; once they
|
|
201
|
+
* migrate to ship descriptors directly (TML-2357 T3.5.3), this synthesis
|
|
202
|
+
* steps aside.
|
|
203
|
+
*/
|
|
204
|
+
declare function synthesizeNonParameterizedDescriptor(codec: Codec): CodecDescriptor<void>;
|
|
205
|
+
//#endregion
|
|
206
|
+
export { CodecLookup as a, emptyCodecLookup as c, CodecInstanceContext as i, synthesizeNonParameterizedDescriptor as l, CodecCallContext as n, CodecMeta as o, CodecDescriptor as r, CodecTrait as s, Codec as t, voidParamsSchema as u };
|
|
207
|
+
//# sourceMappingURL=codec-types-CB0jWeHU.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codec-types-CB0jWeHU.d.mts","names":[],"sources":["../src/shared/codec-types.ts"],"sourcesContent":[],"mappings":";;;;KAGY,UAAA;;AAAZ;AA4CA;AAiCA;;;;;;;;;MAe2B,gBAAA;;;;;;;;;AAS3B;AAIA;AAuBA;AASA;AA6BA;;;;;;;;;;AAyCA;AA6BgB,UAhMC,gBAAA,CAgMD;oBA/LI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAgCH,2DAEU,wBAAwB;;eAKpC;;;;oBAIK;;gBAEJ,aAAa,mBAAmB,QAAQ;;eAEzC,YAAY,mBAAmB,QAAQ;;oBAElC,SAAS;;mBAEV,YAAY;;gCAEC;;UAGf,WAAA;mBACE;;cAGN,kBAAkB;;;;;;;;;;;;;;;;;;;;UAuBd,oBAAA;;;;;;;;UASA,SAAA;gBACD;;;;;;;;;;;;;;;;;;;;;;;;;;;UA4BC;;;;4BAIW;;;;kBAIV;;;;;;;;yBAQO,iBAAiB;;;;;;;uCAOH;;;;;;;;6BAQV,YAAY,yBAAyB;;;;;;;;;cAUrD,kBAAkB;;;;;;;;;;;;;iBA6Bf,oCAAA,QAA4C,QAAQ"}
|
package/dist/codec.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { type Codec, type CodecLookup, type CodecTrait, emptyCodecLookup };
|
|
1
|
+
import { a as CodecLookup, c as emptyCodecLookup, i as CodecInstanceContext, l as synthesizeNonParameterizedDescriptor, n as CodecCallContext, o as CodecMeta, r as CodecDescriptor, s as CodecTrait, t as Codec, u as voidParamsSchema } from "./codec-types-CB0jWeHU.mjs";
|
|
2
|
+
export { type Codec, type CodecCallContext, type CodecDescriptor, type CodecInstanceContext, type CodecLookup, type CodecMeta, type CodecTrait, emptyCodecLookup, synthesizeNonParameterizedDescriptor, voidParamsSchema };
|
package/dist/codec.mjs
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
|
-
//#region src/codec-types.ts
|
|
1
|
+
//#region src/shared/codec-types.ts
|
|
2
2
|
const emptyCodecLookup = { get: () => void 0 };
|
|
3
|
+
/**
|
|
4
|
+
* Standard Schema validator for `void` params. Accepts only `undefined`
|
|
5
|
+
* (or absent input); rejects any other value so a contract that tries to
|
|
6
|
+
* thread `typeParams` through a non-parameterized codec id fails fast at
|
|
7
|
+
* the JSON boundary instead of silently coercing the value away. Used by
|
|
8
|
+
* the framework-supplied non-parameterized descriptor synthesizer.
|
|
9
|
+
*/
|
|
10
|
+
const voidParamsSchema = { "~standard": {
|
|
11
|
+
version: 1,
|
|
12
|
+
vendor: "prisma-next",
|
|
13
|
+
validate: (input) => input === void 0 ? { value: void 0 } : { issues: [{ message: "unexpected typeParams for non-parameterized codec (void params expected)" }] }
|
|
14
|
+
} };
|
|
15
|
+
/**
|
|
16
|
+
* Synthesize a `CodecDescriptor<void>` for a non-parameterized codec
|
|
17
|
+
* runtime instance. The factory is constant — every call returns the same
|
|
18
|
+
* shared codec instance — so columns sharing this codec id share one
|
|
19
|
+
* resolved codec.
|
|
20
|
+
*
|
|
21
|
+
* Codec-registry-unification spec § Decision (Case T — non-parameterized
|
|
22
|
+
* text codec). This is the bridge while non-parameterized codec
|
|
23
|
+
* contributors still register through the legacy `codecs:` slot; once they
|
|
24
|
+
* migrate to ship descriptors directly (TML-2357 T3.5.3), this synthesis
|
|
25
|
+
* steps aside.
|
|
26
|
+
*/
|
|
27
|
+
function synthesizeNonParameterizedDescriptor(codec) {
|
|
28
|
+
const sharedFactory = () => () => codec;
|
|
29
|
+
const codecMeta = codec.meta;
|
|
30
|
+
return {
|
|
31
|
+
codecId: codec.id,
|
|
32
|
+
traits: codec.traits ?? [],
|
|
33
|
+
targetTypes: codec.targetTypes,
|
|
34
|
+
paramsSchema: voidParamsSchema,
|
|
35
|
+
factory: sharedFactory,
|
|
36
|
+
...codecMeta !== void 0 ? { meta: codecMeta } : {}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
3
39
|
|
|
4
40
|
//#endregion
|
|
5
|
-
export { emptyCodecLookup };
|
|
41
|
+
export { emptyCodecLookup, synthesizeNonParameterizedDescriptor, voidParamsSchema };
|
|
6
42
|
//# sourceMappingURL=codec.mjs.map
|
package/dist/codec.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec.mjs","names":["emptyCodecLookup: CodecLookup"],"sources":["../src/codec-types.ts"],"sourcesContent":["import type { JsonValue } from '@prisma-next/contract/types';\n\nexport type CodecTrait = 'equality' | 'order' | 'boolean' | 'numeric' | 'textual';\n\n/**\n * Base codec interface for all target families.\n *\n * A codec maps between three representations of a value:\n * - **JS** (`TJs`): the JavaScript type used in application code\n * - **Wire** (`TWire`): the format sent to/from the database driver\n * - **JSON** (`JsonValue`): the JSON-safe form stored in contract artifacts\n *\n * Family-specific codec interfaces (SQL `Codec`, Mongo `MongoCodec`) extend\n * this base to add family-specific metadata.\n */\nexport interface Codec<\n Id extends string = string,\n TTraits extends readonly CodecTrait[] = readonly CodecTrait[],\n TWire = unknown,\n TJs = unknown,\n> {\n /** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). */\n readonly id: Id;\n /** Database-native type names this codec handles (e.g. `['timestamptz']`). */\n readonly targetTypes: readonly string[];\n /** Semantic traits for operator gating (e.g. equality, order, numeric). */\n readonly traits?: TTraits;\n /** Converts a JS value to the wire format expected by the database driver. Optional when the driver accepts the JS type directly. */\n encode?(value: TJs): TWire;\n /** Converts a wire value from the database driver into the JS type. */\n decode(wire: TWire): TJs;\n /** Converts a JS value to a JSON-safe representation for contract serialization. Called during contract emission. */\n encodeJson(value: TJs): JsonValue;\n /** Converts a JSON representation back to the JS type. Called during contract loading via `validateContract`. */\n decodeJson(json: JsonValue): TJs;\n /** Produces the TypeScript output type expression for a field given its `typeParams`. Used during contract.d.ts emission. */\n renderOutputType?(typeParams: Record<string, unknown>): string | undefined;\n}\n\nexport interface CodecLookup {\n get(id: string): Codec | undefined;\n}\n\nexport const emptyCodecLookup: CodecLookup = {\n get: () => undefined,\n};\n"],"mappings":";AA2CA,MAAaA,mBAAgC,EAC3C,WAAW,QACZ"}
|
|
1
|
+
{"version":3,"file":"codec.mjs","names":["emptyCodecLookup: CodecLookup","voidParamsSchema: StandardSchemaV1<void>"],"sources":["../src/shared/codec-types.ts"],"sourcesContent":["import type { JsonValue } from '@prisma-next/contract/types';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport type CodecTrait =\n | 'equality'\n | 'order'\n | 'boolean'\n | 'numeric'\n | 'textual'\n /**\n * The codec carries a per-instance `validate(value: unknown) =>\n * JsonSchemaValidationResult` function on the resolved codec object that\n * the framework's `JsonSchemaValidatorRegistry` consults at runtime. The\n * trait gates the `extractValidator` cast from structurally-typed\n * `unknown` to a typed validator view.\n *\n * Retirement target. The unified `CodecDescriptor` model moves\n * validation into the resolved codec's `decode` body; the parallel\n * `JsonSchemaValidatorRegistry` (and this trait alongside it) retires\n * under TML-2357 (T3.5.12). Per-library JSON extensions like\n * `@prisma-next/extension-arktype-json` already follow the new pattern.\n */\n | 'json-validator';\n\n/**\n * Per-call context the runtime threads to every `codec.encode` /\n * `codec.decode` invocation for a single `runtime.execute()` call.\n *\n * The framework-level shape is family-agnostic and carries one field:\n *\n * - `signal?: AbortSignal` — per-query cancellation. The runtime returns\n * a `RUNTIME.ABORTED` envelope when the signal aborts; codec authors\n * who forward `signal` to their underlying SDK get true cancellation\n * of in-flight network calls.\n *\n * Family layers extend this base with their own shape-of-call metadata:\n * the SQL family adds `column?: SqlColumnRef` via `SqlCodecCallContext`\n * (see `@prisma-next/sql-relational-core`). Mongo currently uses this\n * framework type unchanged. Column metadata is intentionally **not** on\n * the framework type — it is a SQL-family concept rooted in SQL's\n * `(table, column)` addressing model and would not generalise to other\n * families.\n *\n * The interface is named explicitly (not inlined) so future framework\n * fields and family extensions can land additively without breaking\n * codec author signatures.\n */\nexport interface CodecCallContext {\n readonly signal?: AbortSignal;\n}\n\n/**\n * A codec is the contract between an application value and its on-wire and\n * on-contract-disk representations.\n *\n * The author's mental model is two JS-side types — `TInput` (the\n * application JS type) and `TWire` (the database driver wire format) —\n * plus `JsonValue` for build-time contract artifacts. The codec translates\n * `TInput` to `TWire` on writes and back on reads, and to/from `JsonValue`\n * during contract emission and loading.\n *\n * Three representations participate:\n * - **Input** (`TInput`): the JS type at the application boundary.\n * - **Wire** (`TWire`): the format exchanged with the database driver.\n * - **JSON** (`JsonValue`): a JSON-safe form used in contract artifacts.\n *\n * Codec methods split into two groups:\n *\n * - **Query-time** methods (`encode`, `decode`) run per row/parameter at the\n * IO boundary; they are required and Promise-returning. The per-family\n * codec factory accepts sync or async author functions and lifts sync\n * ones to Promise-shaped methods automatically.\n * - **Build-time** methods (`encodeJson`, `decodeJson`, `renderOutputType`)\n * run when the contract is serialized, loaded, or when client types are\n * emitted. They stay synchronous so contract validation and client\n * construction are synchronous.\n *\n * Target-family codec interfaces extend this base with target-shaped\n * metadata.\n */\nexport interface Codec<\n Id extends string = string,\n TTraits extends readonly CodecTrait[] = readonly CodecTrait[],\n TWire = unknown,\n TInput = unknown,\n> {\n /** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). */\n readonly id: Id;\n /** Database-native type names this codec handles (e.g. `['timestamptz']`). */\n readonly targetTypes: readonly string[];\n /** Semantic traits for operator gating (e.g. equality, order, numeric). */\n readonly traits?: TTraits;\n /** 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. */\n encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;\n /** 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. */\n decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;\n /** Converts a JS value to a JSON-safe representation for contract serialization. Synchronous; called during contract emission. */\n encodeJson(value: TInput): JsonValue;\n /** Converts a JSON representation back to the JS input type. Synchronous; called during contract loading via `validateContract`. */\n decodeJson(json: JsonValue): TInput;\n /** Produces the TypeScript output type expression for a field given its `typeParams`. Synchronous; used during contract.d.ts emission. */\n renderOutputType?(typeParams: Record<string, unknown>): string | undefined;\n}\n\nexport interface CodecLookup {\n get(id: string): Codec | undefined;\n}\n\nexport const emptyCodecLookup: CodecLookup = {\n get: () => undefined,\n};\n\n/**\n * Family-agnostic per-instance context supplied by the framework when\n * applying a higher-order codec factory. Allows stateful codecs (e.g.\n * column-scoped encryption) to derive per-instance state from the\n * materialization site.\n *\n * - `name` — the family-agnostic instance identity. For SQL, the runtime\n * populates this as the `storage.types` instance name (e.g.\n * `Embedding1536`) for typeRef-shaped columns, the synthesized\n * anonymous instance name (`<anon:Document.embedding>`) for inline-\n * `typeParams` columns, or a shared sentinel (`<shared:pg/text@1>`)\n * for non-parameterized codec ids. Other families pick the analogous\n * identity for their materialization sites.\n *\n * Family-specific extensions (e.g. {@link import('@prisma-next/sql-relational-core/ast').SqlCodecInstanceContext}\n * in the SQL layer) augment this base with domain-shaped column-set\n * metadata. Codec authors target the base when they don't read family-\n * specific metadata; they target the family extension when they do.\n */\nexport interface CodecInstanceContext {\n readonly name: string;\n}\n\n/**\n * Family-agnostic codec metadata. Family-specific extensions augment the\n * base `db.<family>.<target>` block with native-type information; the base\n * shape is an empty object so non-relational codecs can carry no metadata.\n */\nexport interface CodecMeta {\n readonly db?: Record<string, unknown>;\n}\n\n/**\n * Unified codec descriptor. Every codec in the framework registers through\n * this shape — non-parameterized codecs use `P = void` and a constant\n * factory that returns the same shared codec instance for every column;\n * parameterized codecs use a non-empty `P` and a curried higher-order\n * factory that returns a per-instance codec.\n *\n * The descriptor is the codec-id-keyed source of truth for static metadata\n * (`traits`, `targetTypes`, `meta`) and registration concerns\n * (`paramsSchema` for JSON-boundary validation; optional `renderOutputType`\n * for the `contract.d.ts` emit path). The runtime `Codec` instance returned\n * by `factory(params)(ctx)` carries only the conversion behavior.\n *\n * Whether a codec id \"is parameterized\" stops being a registration-time\n * distinction — it's a property of `P` on the descriptor. The descriptor\n * map indexes every descriptor by `codecId`; both `descriptorFor(codecId)`\n * and `forColumn(table, column)` resolve through the same map without\n * branching on parameterization.\n *\n * @template P - The shape of the params accepted by the factory (`void` for\n * non-parameterized codecs; a record like `{ length: number }` for\n * parameterized codecs).\n *\n * Codec-registry-unification project § Decision.\n */\nexport interface CodecDescriptor<P = void> {\n /** The codec ID this descriptor applies to (e.g. `pg/vector@1`, `pg/text@1`). */\n readonly codecId: string;\n /** Semantic traits for operator gating (e.g. equality, order, numeric). */\n readonly traits: readonly CodecTrait[];\n /** Database-native type names this codec handles (e.g. `['timestamptz']`). */\n readonly targetTypes: readonly string[];\n /** Optional family-specific metadata (e.g. SQL-side `db.sql.postgres.nativeType`). */\n readonly meta?: CodecMeta;\n /**\n * Standard Schema validator for the factory's params. Validates JSON-\n * sourced params at the contract boundary (PSL → IR; `contract.json` →\n * runtime). For non-parameterized codecs (`P = void`), the schema\n * validates `void`/`undefined` — the framework supplies no params at the\n * call boundary.\n */\n readonly paramsSchema: StandardSchemaV1<P>;\n /**\n * Emit-path string renderer for `contract.d.ts`. Returns the TypeScript\n * output type expression for given params (e.g. `Vector<1536>`).\n * Optional; absent renderers cause the emitter to fall back to the\n * codec's base output type. Non-parameterized codecs typically omit it.\n */\n readonly renderOutputType?: (params: P) => string | undefined;\n /**\n * The curried higher-order codec. For non-parameterized codecs, the\n * factory is constant — every call returns the same shared codec\n * instance. For parameterized codecs, the factory is called once per\n * `storage.types` instance (or once per inline-`typeParams` column),\n * with `ctx` carrying the column set the resulting codec serves.\n */\n readonly factory: (params: P) => (ctx: CodecInstanceContext) => Codec;\n}\n\n/**\n * Standard Schema validator for `void` params. Accepts only `undefined`\n * (or absent input); rejects any other value so a contract that tries to\n * thread `typeParams` through a non-parameterized codec id fails fast at\n * the JSON boundary instead of silently coercing the value away. Used by\n * the framework-supplied non-parameterized descriptor synthesizer.\n */\nexport const voidParamsSchema: StandardSchemaV1<void> = {\n '~standard': {\n version: 1,\n vendor: 'prisma-next',\n validate: (input) =>\n input === undefined\n ? { value: undefined }\n : {\n issues: [\n {\n message: 'unexpected typeParams for non-parameterized codec (void params expected)',\n },\n ],\n },\n },\n};\n\n/**\n * Synthesize a `CodecDescriptor<void>` for a non-parameterized codec\n * runtime instance. The factory is constant — every call returns the same\n * shared codec instance — so columns sharing this codec id share one\n * resolved codec.\n *\n * Codec-registry-unification spec § Decision (Case T — non-parameterized\n * text codec). This is the bridge while non-parameterized codec\n * contributors still register through the legacy `codecs:` slot; once they\n * migrate to ship descriptors directly (TML-2357 T3.5.3), this synthesis\n * steps aside.\n */\nexport function synthesizeNonParameterizedDescriptor(codec: Codec): CodecDescriptor<void> {\n // The descriptor's `factory: (params: void) => (ctx: CodecInstanceContext)\n // => Codec` is a constant for non-parameterized codecs — `params` is\n // never read and the returned ctx-applier always yields the same shared\n // codec. We rely on the descriptor's typed `factory` slot to infer the\n // signatures rather than naming `void` locally (biome's\n // `noConfusingVoidType` flags `void` outside return positions).\n const sharedFactory = () => () => codec;\n // Family-extended codecs (SQL `Codec`) carry an optional `meta` field\n // that the base interface doesn't declare. Read it through a structural\n // narrow so the synthesizer forwards it to the descriptor without losing\n // type safety on the base shape.\n const codecMeta = (codec as { readonly meta?: CodecMeta }).meta;\n return {\n codecId: codec.id,\n traits: codec.traits ?? [],\n targetTypes: codec.targetTypes,\n paramsSchema: voidParamsSchema,\n factory: sharedFactory,\n ...(codecMeta !== undefined ? { meta: codecMeta } : {}),\n };\n}\n"],"mappings":";AA4GA,MAAaA,mBAAgC,EAC3C,WAAW,QACZ;;;;;;;;AAoGD,MAAaC,mBAA2C,EACtD,aAAa;CACX,SAAS;CACT,QAAQ;CACR,WAAW,UACT,UAAU,SACN,EAAE,OAAO,QAAW,GACpB,EACE,QAAQ,CACN,EACE,SAAS,4EACV,CACF,EACF;CACR,EACF;;;;;;;;;;;;;AAcD,SAAgB,qCAAqC,OAAqC;CAOxF,MAAM,4BAA4B;CAKlC,MAAM,YAAa,MAAwC;AAC3D,QAAO;EACL,SAAS,MAAM;EACf,QAAQ,MAAM,UAAU,EAAE;EAC1B,aAAa,MAAM;EACnB,cAAc;EACd,SAAS;EACT,GAAI,cAAc,SAAY,EAAE,MAAM,WAAW,GAAG,EAAE;EACvD"}
|
package/dist/components.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { S as checkContractComponentRequirements, _ as PackRefBase, a as ComponentMetadata, b as TargetInstance, c as DriverDescriptor, d as ExtensionDescriptor, f as ExtensionInstance, g as FamilyPackRef, h as FamilyInstance, i as ComponentDescriptor, l as DriverInstance, m as FamilyDescriptor, n as AdapterInstance, o as ContractComponentRequirementsCheckInput, p as ExtensionPackRef, r as AdapterPackRef, s as ContractComponentRequirementsCheckResult, t as AdapterDescriptor, u as DriverPackRef, v as TargetBoundComponentDescriptor, x as TargetPackRef, y as TargetDescriptor } from "./framework-components-
|
|
1
|
+
import { S as checkContractComponentRequirements, _ as PackRefBase, a as ComponentMetadata, b as TargetInstance, c as DriverDescriptor, d as ExtensionDescriptor, f as ExtensionInstance, g as FamilyPackRef, h as FamilyInstance, i as ComponentDescriptor, l as DriverInstance, m as FamilyDescriptor, n as AdapterInstance, o as ContractComponentRequirementsCheckInput, p as ExtensionPackRef, r as AdapterPackRef, s as ContractComponentRequirementsCheckResult, t as AdapterDescriptor, u as DriverPackRef, v as TargetBoundComponentDescriptor, x as TargetPackRef, y as TargetDescriptor } from "./framework-components-AHI6V96G.mjs";
|
|
2
2
|
export { type AdapterDescriptor, type AdapterInstance, type AdapterPackRef, type ComponentDescriptor, type ComponentMetadata, type ContractComponentRequirementsCheckInput, type ContractComponentRequirementsCheckResult, type DriverDescriptor, type DriverInstance, type DriverPackRef, type ExtensionDescriptor, type ExtensionInstance, type ExtensionPackRef, type FamilyDescriptor, type FamilyInstance, type FamilyPackRef, type PackRefBase, type TargetBoundComponentDescriptor, type TargetDescriptor, type TargetInstance, type TargetPackRef, checkContractComponentRequirements };
|
package/dist/components.mjs
CHANGED