@prisma-next/framework-components 0.5.0-dev.8 → 0.5.0-dev.81

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.
Files changed (94) hide show
  1. package/README.md +53 -4
  2. package/dist/authoring.d.mts +2 -2
  3. package/dist/authoring.mjs +2 -122
  4. package/dist/codec-m_-FAyQn.d.mts +168 -0
  5. package/dist/codec-m_-FAyQn.d.mts.map +1 -0
  6. package/dist/codec.d.mts +48 -2
  7. package/dist/codec.d.mts.map +1 -0
  8. package/dist/codec.mjs +67 -4
  9. package/dist/codec.mjs.map +1 -1
  10. package/dist/components.d.mts +1 -1
  11. package/dist/components.mjs +2 -3
  12. package/dist/control.d.mts +420 -74
  13. package/dist/control.d.mts.map +1 -1
  14. package/dist/control.mjs +83 -49
  15. package/dist/control.mjs.map +1 -1
  16. package/dist/emission-types-BKa4bR9m.d.mts +39 -0
  17. package/dist/emission-types-BKa4bR9m.d.mts.map +1 -0
  18. package/dist/emission.d.mts +2 -2
  19. package/dist/emission.mjs +1 -1
  20. package/dist/execution.d.mts +5 -5
  21. package/dist/execution.d.mts.map +1 -1
  22. package/dist/execution.mjs +4 -6
  23. package/dist/execution.mjs.map +1 -1
  24. package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-DGIQbNPt.d.mts} +43 -12
  25. package/dist/framework-authoring-DGIQbNPt.d.mts.map +1 -0
  26. package/dist/framework-authoring-DxXcjyJX.mjs +209 -0
  27. package/dist/framework-authoring-DxXcjyJX.mjs.map +1 -0
  28. package/dist/{framework-components-DFZMi2h7.d.mts → framework-components-BGo7HsbL.d.mts} +45 -55
  29. package/dist/framework-components-BGo7HsbL.d.mts.map +1 -0
  30. package/dist/{framework-components-C8ZhSwXe.mjs → framework-components-FdqmlGUj.mjs} +3 -3
  31. package/dist/framework-components-FdqmlGUj.mjs.map +1 -0
  32. package/dist/psl-ast-Ckn_G-jv.d.mts +159 -0
  33. package/dist/psl-ast-Ckn_G-jv.d.mts.map +1 -0
  34. package/dist/psl-ast.d.mts +2 -0
  35. package/dist/psl-ast.mjs +1 -0
  36. package/dist/runtime.d.mts +395 -19
  37. package/dist/runtime.d.mts.map +1 -1
  38. package/dist/runtime.mjs +256 -7
  39. package/dist/runtime.mjs.map +1 -1
  40. package/dist/{types-import-spec-C4sc7wbb.d.mts → types-import-spec-BxI5cSQy.d.mts} +2 -2
  41. package/dist/types-import-spec-BxI5cSQy.d.mts.map +1 -0
  42. package/package.json +10 -6
  43. package/src/control/control-capabilities.ts +96 -0
  44. package/src/{control-descriptors.ts → control/control-descriptors.ts} +7 -7
  45. package/src/{control-instances.ts → control/control-instances.ts} +52 -6
  46. package/src/{control-migration-types.ts → control/control-migration-types.ts} +251 -63
  47. package/src/control/control-operation-preview.ts +23 -0
  48. package/src/control/control-spaces.ts +82 -0
  49. package/src/{control-stack.ts → control/control-stack.ts} +77 -94
  50. package/src/control/emission-types.ts +49 -0
  51. package/src/control/psl-ast.ts +193 -0
  52. package/src/{execution-descriptors.ts → execution/execution-descriptors.ts} +7 -7
  53. package/src/{execution-instances.ts → execution/execution-instances.ts} +1 -1
  54. package/src/{execution-requirements.ts → execution/execution-requirements.ts} +1 -1
  55. package/src/execution/query-plan.ts +53 -0
  56. package/src/execution/race-against-abort.ts +89 -0
  57. package/src/execution/run-with-middleware.ts +153 -0
  58. package/src/execution/runtime-core.ts +133 -0
  59. package/src/execution/runtime-error.ts +94 -0
  60. package/src/execution/runtime-middleware.ts +235 -0
  61. package/src/exports/authoring.ts +5 -2
  62. package/src/exports/codec.ts +27 -2
  63. package/src/exports/components.ts +2 -2
  64. package/src/exports/control.ts +41 -13
  65. package/src/exports/emission.ts +2 -2
  66. package/src/exports/execution.ts +5 -5
  67. package/src/exports/psl-ast.ts +1 -0
  68. package/src/exports/runtime.ts +18 -5
  69. package/src/shared/codec-descriptor.ts +87 -0
  70. package/src/shared/codec-types.ts +79 -0
  71. package/src/shared/codec.ts +80 -0
  72. package/src/shared/column-spec.ts +83 -0
  73. package/src/{framework-authoring.ts → shared/framework-authoring.ts} +210 -23
  74. package/src/{framework-components.ts → shared/framework-components.ts} +22 -48
  75. package/src/{mutation-default-types.ts → shared/mutation-default-types.ts} +22 -2
  76. package/dist/authoring.mjs.map +0 -1
  77. package/dist/codec-types-DQ1Agjom.d.mts +0 -58
  78. package/dist/codec-types-DQ1Agjom.d.mts.map +0 -1
  79. package/dist/emission-types-BPAALJbF.d.mts +0 -24
  80. package/dist/emission-types-BPAALJbF.d.mts.map +0 -1
  81. package/dist/framework-authoring-D1-JZ37B.d.mts.map +0 -1
  82. package/dist/framework-components-C8ZhSwXe.mjs.map +0 -1
  83. package/dist/framework-components-DFZMi2h7.d.mts.map +0 -1
  84. package/dist/types-import-spec-C4sc7wbb.d.mts.map +0 -1
  85. package/src/codec-types.ts +0 -64
  86. package/src/control-capabilities.ts +0 -34
  87. package/src/emission-types.ts +0 -28
  88. package/src/runtime-error.ts +0 -55
  89. package/src/runtime-middleware.ts +0 -83
  90. /package/src/{control-result-types.ts → control/control-result-types.ts} +0 -0
  91. /package/src/{control-schema-view.ts → control/control-schema-view.ts} +0 -0
  92. /package/src/{async-iterable-result.ts → execution/async-iterable-result.ts} +0 -0
  93. /package/src/{execution-stack.ts → execution/execution-stack.ts} +0 -0
  94. /package/src/{types-import-spec.ts → shared/types-import-spec.ts} +0 -0
package/README.md CHANGED
@@ -1,8 +1,6 @@
1
1
  # @prisma-next/framework-components
2
2
 
3
- > **Internal package.** This package is an implementation detail of [`prisma-next`](https://www.npmjs.com/package/prisma-next)
4
- > and is published only to support its runtime. Its API is unstable and may change
5
- > without notice. Do not depend on this package directly; install `prisma-next` instead.
3
+ > **Internal package.** This package is an implementation detail of [`prisma-next`](https://www.npmjs.com/package/prisma-next) and is published only to support its runtime. Its API is unstable and may change without notice. Do not depend on this package directly; install `prisma-next` instead.
6
4
 
7
5
  Framework component types, authoring logic, control stack assembly, and emission SPI for Prisma Next.
8
6
 
@@ -14,6 +12,7 @@ Framework component types, authoring logic, control stack assembly, and emission
14
12
  - **Control stack** (`./control`): Assembly functions that combine component descriptors into a unified `ControlStack` with derived state (codec imports, renderers, authoring contributions)
15
13
  - **Emission SPI** (`./emission`): Types for the emission pipeline — `TargetFamilyHook`, `ValidationContext`, `GenerateContractTypesOptions`, `TypeRenderEntry`, `TypeRenderer`, `ParameterizedCodecDescriptor`, and related types
16
14
  - **Execution types** (`./execution`): Execution-plane stack and instance interfaces
15
+ - **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).
17
16
 
18
17
  ## Subpath exports
19
18
 
@@ -23,17 +22,67 @@ import { AuthoringContributions, instantiateAuthoringTypeConstructor } from '@pr
23
22
  import type { Codec } from '@prisma-next/framework-components/codec';
24
23
  import { createControlStack, ControlStack } from '@prisma-next/framework-components/control';
25
24
  import type { EmissionSpi } from '@prisma-next/framework-components/emission';
25
+ import { RuntimeCore, runWithMiddleware, type RuntimeMiddleware } from '@prisma-next/framework-components/runtime';
26
26
  ```
27
27
 
28
28
  ## `Codec` interface
29
29
 
30
30
  The base `Codec` interface lands on the seam between **query-time** methods (per-row, IO-relevant) and **build-time** methods (per-contract-load):
31
31
 
32
- - 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.
32
+ - Query-time: `encode(value): Promise<TWire>` and `decode(wire): Promise<TInput>` are required and **Promise-returning at the public boundary**. Codec authors extend `CodecImpl` (per [ADR 208 Higher-order codecs for parameterized types](../../../../../docs/architecture%20docs/adrs/ADR%20208%20-%20Higher-order%20codecs%20for%20parameterized%20types.md)); a logically synchronous body still has to return a `Promise`-compatible value (mark the method `async`, or return `Promise.resolve(...)` explicitly). The runtime always awaits the result.
33
33
  - Build-time: `encodeJson`, `decodeJson`, and the optional `renderOutputType` are **synchronous** so `validateContract` and client construction stay synchronous.
34
34
 
35
35
  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.
36
36
 
37
+ ### Codec call context (`ctx`)
38
+
39
+ 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:
40
+
41
+ ```ts
42
+ export interface CodecCallContext {
43
+ readonly signal?: AbortSignal;
44
+ }
45
+ ```
46
+
47
+ The internal `Codec` interface declares the parameter as required:
48
+
49
+ ```ts
50
+ encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
51
+ decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
52
+ ```
53
+
54
+ Codec authors who write `(value) => …` continue to compile via TypeScript's bivariance for trailing parameters; nothing at the author surface changes.
55
+
56
+ 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:
57
+
58
+ ```ts
59
+ // Sketch — codec authors extend `CodecImpl`; class methods receive `(value, ctx)`.
60
+ async encode(v: string, ctx: CodecCallContext): Promise<EncryptedWire> {
61
+ return kms.encrypt({ plaintext: v }, { signal: ctx.signal });
62
+ }
63
+ ```
64
+
65
+ 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`.
66
+
67
+ 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.
68
+
69
+ ## Higher-order codecs (`CodecDescriptor`, `CodecInstanceContext`)
70
+
71
+ Codec metadata, parameterized-codec registration, and runtime materialization live on a unified `CodecDescriptor<P>` — the only registration shape framework consumers see:
72
+
73
+ ```ts
74
+ import type { CodecDescriptor, CodecInstanceContext } from '@prisma-next/framework-components/codec';
75
+ import { voidParamsSchema } from '@prisma-next/framework-components/codec';
76
+ ```
77
+
78
+ - `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` (with the framework-supplied `voidParamsSchema`) and a constant factory; parameterized codecs use a non-empty `P` (e.g. `{ length: number }` for pgvector).
79
+ - `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.
80
+ - Contributors expose their descriptors through `ComponentMetadata.types.codecTypes.codecDescriptors` and the unified `codecs: () => ReadonlyArray<CodecDescriptor>` slot. `extractCodecLookup` reads `targetTypes` / `meta` / `renderOutputType` directly off the descriptors — there is no parameterized vs. non-parameterized split and no synthesis bridge.
81
+
82
+ `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.
83
+
84
+ 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.
85
+
37
86
  ## Why SPI types live here (dependency inversion)
38
87
 
39
88
  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).
@@ -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-D1-JZ37B.mjs";
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 };
1
+ import { _ as isAuthoringFieldPresetDescriptor, a as AuthoringFieldNamespace, b as resolveAuthoringTemplateValue, c as AuthoringStorageTypeTemplate, d as AuthoringTypeNamespace, f as assertNoCrossRegistryCollisions, g as isAuthoringArgRef, h as instantiateAuthoringTypeConstructor, i as AuthoringContributions, l as AuthoringTemplateValue, m as instantiateAuthoringFieldPreset, n as AuthoringArgumentDescriptor, o as AuthoringFieldPresetDescriptor, p as hasRegisteredFieldNamespace, r as AuthoringColumnDefaultTemplate, s as AuthoringFieldPresetOutput, t as AuthoringArgRef, u as AuthoringTypeConstructorDescriptor, v as isAuthoringTypeConstructorDescriptor, x as validateAuthoringHelperArguments, y as mergeAuthoringNamespaces } from "./framework-authoring-DGIQbNPt.mjs";
2
+ export { type AuthoringArgRef, type AuthoringArgumentDescriptor, type AuthoringColumnDefaultTemplate, type AuthoringContributions, type AuthoringFieldNamespace, type AuthoringFieldPresetDescriptor, type AuthoringFieldPresetOutput, type AuthoringStorageTypeTemplate, type AuthoringTemplateValue, type AuthoringTypeConstructorDescriptor, type AuthoringTypeNamespace, assertNoCrossRegistryCollisions, hasRegisteredFieldNamespace, instantiateAuthoringFieldPreset, instantiateAuthoringTypeConstructor, isAuthoringArgRef, isAuthoringFieldPresetDescriptor, isAuthoringTypeConstructorDescriptor, mergeAuthoringNamespaces, resolveAuthoringTemplateValue, validateAuthoringHelperArguments };
@@ -1,122 +1,2 @@
1
- import { ifDefined } from "@prisma-next/utils/defined";
2
-
3
- //#region src/framework-authoring.ts
4
- function isAuthoringArgRef(value) {
5
- if (typeof value !== "object" || value === null || value.kind !== "arg") return false;
6
- const { index, path } = value;
7
- if (typeof index !== "number" || !Number.isInteger(index) || index < 0) return false;
8
- if (path !== void 0 && (!Array.isArray(path) || path.some((s) => typeof s !== "string"))) return false;
9
- return true;
10
- }
11
- function isAuthoringTemplateRecord(value) {
12
- return typeof value === "object" && value !== null && !Array.isArray(value);
13
- }
14
- function isAuthoringTypeConstructorDescriptor(value) {
15
- return typeof value === "object" && value !== null && value.kind === "typeConstructor" && typeof value.output === "object" && value.output !== null;
16
- }
17
- function isAuthoringFieldPresetDescriptor(value) {
18
- return typeof value === "object" && value !== null && value.kind === "fieldPreset" && typeof value.output === "object" && value.output !== null;
19
- }
20
- function resolveAuthoringTemplateValue(template, args) {
21
- if (isAuthoringArgRef(template)) {
22
- let value = args[template.index];
23
- for (const segment of template.path ?? []) {
24
- if (!isAuthoringTemplateRecord(value) || !Object.hasOwn(value, segment)) {
25
- value = void 0;
26
- break;
27
- }
28
- value = value[segment];
29
- }
30
- if (value === void 0 && template.default !== void 0) return resolveAuthoringTemplateValue(template.default, args);
31
- return value;
32
- }
33
- if (Array.isArray(template)) return template.map((value) => resolveAuthoringTemplateValue(value, args));
34
- if (typeof template === "object" && template !== null) {
35
- const resolved = {};
36
- for (const [key, value] of Object.entries(template)) {
37
- const resolvedValue = resolveAuthoringTemplateValue(value, args);
38
- if (resolvedValue !== void 0) resolved[key] = resolvedValue;
39
- }
40
- return resolved;
41
- }
42
- return template;
43
- }
44
- function validateAuthoringArgument(descriptor, value, path) {
45
- if (value === void 0) {
46
- if (descriptor.optional) return;
47
- throw new Error(`Missing required authoring helper argument at ${path}`);
48
- }
49
- if (descriptor.kind === "string") {
50
- if (typeof value !== "string") throw new Error(`Authoring helper argument at ${path} must be a string`);
51
- return;
52
- }
53
- if (descriptor.kind === "stringArray") {
54
- if (!Array.isArray(value)) throw new Error(`Authoring helper argument at ${path} must be an array of strings`);
55
- for (const entry of value) if (typeof entry !== "string") throw new Error(`Authoring helper argument at ${path} must be an array of strings`);
56
- return;
57
- }
58
- if (descriptor.kind === "object") {
59
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`Authoring helper argument at ${path} must be an object`);
60
- const input = value;
61
- const expectedKeys = new Set(Object.keys(descriptor.properties));
62
- for (const key of Object.keys(input)) if (!expectedKeys.has(key)) throw new Error(`Authoring helper argument at ${path} contains unknown property "${key}"`);
63
- for (const [key, propertyDescriptor] of Object.entries(descriptor.properties)) validateAuthoringArgument(propertyDescriptor, input[key], `${path}.${key}`);
64
- return;
65
- }
66
- if (typeof value !== "number" || Number.isNaN(value)) throw new Error(`Authoring helper argument at ${path} must be a number`);
67
- if (descriptor.integer && !Number.isInteger(value)) throw new Error(`Authoring helper argument at ${path} must be an integer`);
68
- if (descriptor.minimum !== void 0 && value < descriptor.minimum) throw new Error(`Authoring helper argument at ${path} must be >= ${descriptor.minimum}, received ${value}`);
69
- if (descriptor.maximum !== void 0 && value > descriptor.maximum) throw new Error(`Authoring helper argument at ${path} must be <= ${descriptor.maximum}, received ${value}`);
70
- }
71
- function validateAuthoringHelperArguments(helperPath, descriptors, args) {
72
- const expected = descriptors ?? [];
73
- const minimumArgs = expected.reduce((count, descriptor, index) => descriptor.optional ? count : index + 1, 0);
74
- if (args.length < minimumArgs || args.length > expected.length) throw new Error(`${helperPath} expects ${minimumArgs === expected.length ? expected.length : `${minimumArgs}-${expected.length}`} argument(s), received ${args.length}`);
75
- expected.forEach((descriptor, index) => {
76
- validateAuthoringArgument(descriptor, args[index], `${helperPath}[${index}]`);
77
- });
78
- }
79
- function resolveAuthoringStorageTypeTemplate(template, args) {
80
- const nativeType = resolveAuthoringTemplateValue(template.nativeType, args);
81
- if (typeof nativeType !== "string") throw new Error(`Resolved authoring nativeType must be a string for codec "${template.codecId}", received ${String(nativeType)}`);
82
- const typeParams = template.typeParams === void 0 ? void 0 : resolveAuthoringTemplateValue(template.typeParams, args);
83
- if (typeParams !== void 0 && !isAuthoringTemplateRecord(typeParams)) throw new Error(`Resolved authoring typeParams must be an object for codec "${template.codecId}", received ${String(typeParams)}`);
84
- return {
85
- codecId: template.codecId,
86
- nativeType,
87
- ...typeParams === void 0 ? {} : { typeParams }
88
- };
89
- }
90
- function resolveAuthoringColumnDefaultTemplate(template, args) {
91
- if (template.kind === "literal") {
92
- const value = resolveAuthoringTemplateValue(template.value, args);
93
- if (value === void 0) throw new Error("Resolved authoring literal default must not be undefined");
94
- return {
95
- kind: "literal",
96
- value
97
- };
98
- }
99
- const expression = resolveAuthoringTemplateValue(template.expression, args);
100
- if (expression === void 0 || typeof expression === "object" && expression !== null) throw new Error(`Resolved authoring function default expression must resolve to a primitive, received ${String(expression)}`);
101
- return {
102
- kind: "function",
103
- expression: String(expression)
104
- };
105
- }
106
- function instantiateAuthoringTypeConstructor(descriptor, args) {
107
- return resolveAuthoringStorageTypeTemplate(descriptor.output, args);
108
- }
109
- function instantiateAuthoringFieldPreset(descriptor, args) {
110
- return {
111
- descriptor: resolveAuthoringStorageTypeTemplate(descriptor.output, args),
112
- nullable: descriptor.output.nullable ?? false,
113
- ...ifDefined("default", descriptor.output.default !== void 0 ? resolveAuthoringColumnDefaultTemplate(descriptor.output.default, args) : void 0),
114
- ...ifDefined("executionDefault", descriptor.output.executionDefault !== void 0 ? resolveAuthoringTemplateValue(descriptor.output.executionDefault, args) : void 0),
115
- id: descriptor.output.id ?? false,
116
- unique: descriptor.output.unique ?? false
117
- };
118
- }
119
-
120
- //#endregion
121
- export { instantiateAuthoringFieldPreset, instantiateAuthoringTypeConstructor, isAuthoringArgRef, isAuthoringFieldPresetDescriptor, isAuthoringTypeConstructorDescriptor, resolveAuthoringTemplateValue, validateAuthoringHelperArguments };
122
- //# sourceMappingURL=authoring.mjs.map
1
+ import { a as isAuthoringArgRef, c as mergeAuthoringNamespaces, i as instantiateAuthoringTypeConstructor, l as resolveAuthoringTemplateValue, n as hasRegisteredFieldNamespace, o as isAuthoringFieldPresetDescriptor, r as instantiateAuthoringFieldPreset, s as isAuthoringTypeConstructorDescriptor, t as assertNoCrossRegistryCollisions, u as validateAuthoringHelperArguments } from "./framework-authoring-DxXcjyJX.mjs";
2
+ export { assertNoCrossRegistryCollisions, hasRegisteredFieldNamespace, instantiateAuthoringFieldPreset, instantiateAuthoringTypeConstructor, isAuthoringArgRef, isAuthoringFieldPresetDescriptor, isAuthoringTypeConstructorDescriptor, mergeAuthoringNamespaces, resolveAuthoringTemplateValue, validateAuthoringHelperArguments };
@@ -0,0 +1,168 @@
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
+ * Per-call context the runtime threads to every `codec.encode` / `codec.decode` invocation for a single `runtime.execute()` call.
8
+ *
9
+ * The framework-level shape is family-agnostic and carries one field:
10
+ *
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.
12
+ *
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.
14
+ *
15
+ * The interface is named explicitly (not inlined) so future framework fields and family extensions can land additively without breaking codec author signatures.
16
+ */
17
+ interface CodecCallContext {
18
+ readonly signal?: AbortSignal;
19
+ }
20
+ /**
21
+ * Codec-id-keyed read surface threaded into emit and authoring paths.
22
+ *
23
+ * - `get(id)` returns the runtime {@link Codec} instance for the codec id (used by `validateContract` for `decodeJson` of literal column defaults).
24
+ * - `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.
25
+ * - `metaFor(id)` exposes the codec-id-keyed `meta` (e.g. SQL-side `db.sql.postgres.nativeType`) the runtime instance no longer carries.
26
+ * - `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.
27
+ */
28
+ interface CodecLookup {
29
+ get(id: string): Codec | undefined;
30
+ targetTypesFor(id: string): readonly string[] | undefined;
31
+ metaFor(id: string): CodecMeta | undefined;
32
+ renderOutputTypeFor(id: string, params: Record<string, unknown>): string | undefined;
33
+ }
34
+ declare const emptyCodecLookup: CodecLookup;
35
+ /**
36
+ * 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.
37
+ *
38
+ * - `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.
39
+ *
40
+ * 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.
41
+ */
42
+ interface CodecInstanceContext {
43
+ readonly name: string;
44
+ }
45
+ /**
46
+ * 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.
47
+ */
48
+ interface CodecMeta {
49
+ readonly db?: Record<string, unknown>;
50
+ }
51
+ /**
52
+ * 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.
53
+ */
54
+ declare const voidParamsSchema: StandardSchemaV1<void>;
55
+ //#endregion
56
+ //#region src/shared/codec-descriptor.d.ts
57
+ /**
58
+ * 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.
59
+ *
60
+ * 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.
61
+ *
62
+ * 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.
63
+ *
64
+ * @template P - The shape of the params accepted by the factory (`void` for non-parameterized codecs; a record like `{ length: number }` for parameterized codecs).
65
+ *
66
+ * Codec-registry-unification project § Decision.
67
+ */
68
+ interface CodecDescriptor<P = void> {
69
+ /** The codec ID this descriptor applies to (e.g. `pg/vector@1`, `pg/text@1`). */
70
+ readonly codecId: string;
71
+ /** Semantic traits for operator gating (e.g. equality, order, numeric). */
72
+ readonly traits: readonly CodecTrait[];
73
+ /** Database-native type names this codec handles (e.g. `['timestamptz']`). */
74
+ readonly targetTypes: readonly string[];
75
+ /** Optional family-specific metadata (e.g. SQL-side `db.sql.postgres.nativeType`). */
76
+ readonly meta?: CodecMeta;
77
+ /** 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. */
78
+ readonly paramsSchema: StandardSchemaV1<P>;
79
+ /** 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. */
80
+ readonly isParameterized: boolean;
81
+ /** 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. */
82
+ readonly renderOutputType?: (params: P) => string | undefined;
83
+ /** 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. */
84
+ readonly factory: (params: P) => (ctx: CodecInstanceContext) => Codec;
85
+ }
86
+ /**
87
+ * 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.
88
+ *
89
+ * Codec-registry-unification spec § Decision: every codec resolves through one descriptor map; reads are non-branching.
90
+ */
91
+ type AnyCodecDescriptor = CodecDescriptor<any>;
92
+ /**
93
+ * Abstract base class for concrete codec descriptors.
94
+ *
95
+ * Codec authors extend this class with their typed `TParams` and declare `codecId`, `traits`, `targetTypes`, `paramsSchema`, the curried `factory(params)`, and (optionally) `renderOutputType`.
96
+ *
97
+ * Implements the {@link CodecDescriptor} interface so a concrete subclass instance is directly usable wherever the framework expects a `CodecDescriptor<P>`.
98
+ */
99
+ declare abstract class CodecDescriptorImpl<TParams = void> implements CodecDescriptor<TParams> {
100
+ abstract readonly codecId: string;
101
+ abstract readonly traits: readonly CodecTrait[];
102
+ abstract readonly targetTypes: readonly string[];
103
+ readonly meta?: CodecMeta;
104
+ abstract readonly paramsSchema: StandardSchemaV1<TParams>;
105
+ /** 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. */
106
+ get isParameterized(): boolean;
107
+ /** 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. */
108
+ renderOutputType?(params: TParams): string | undefined;
109
+ /**
110
+ * 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.
111
+ */
112
+ abstract factory(params: TParams): (ctx: CodecInstanceContext) => Codec<string, readonly CodecTrait[], unknown, unknown>;
113
+ }
114
+ //#endregion
115
+ //#region src/shared/codec.d.ts
116
+ /**
117
+ * A codec is the contract between an application value and its on-wire and on-contract-disk representations.
118
+ *
119
+ * 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.
120
+ *
121
+ * Three representations participate:
122
+ * - **Input** (`TInput`): the JS type at the application boundary.
123
+ * - **Wire** (`TWire`): the format exchanged with the database driver.
124
+ * - **JSON** (`JsonValue`): a JSON-safe form used in contract artifacts.
125
+ *
126
+ * 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)`.
127
+ *
128
+ * Codec methods split into two groups:
129
+ *
130
+ * - **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.
131
+ * - **Build-time** methods (`encodeJson`, `decodeJson`) run when the contract is serialized or loaded. They stay synchronous so contract validation and client construction are synchronous.
132
+ *
133
+ * 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.
134
+ */
135
+ interface Codec<Id extends string = string, TTraits extends readonly CodecTrait[] = readonly CodecTrait[], TWire = unknown, TInput = unknown> {
136
+ /** 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. */
137
+ readonly id: Id;
138
+ /** 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). */
139
+ readonly __codecTraits?: TTraits;
140
+ /** 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. */
141
+ encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
142
+ /** 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. */
143
+ decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
144
+ /** Converts a JS value to a JSON-safe representation for contract serialization. Synchronous; called during contract emission. */
145
+ encodeJson(value: TInput): JsonValue;
146
+ /** Converts a JSON representation back to the JS input type. Synchronous; called during contract loading via `validateContract`. */
147
+ decodeJson(json: JsonValue): TInput;
148
+ }
149
+ /**
150
+ * Abstract base class for concrete codec implementations.
151
+ *
152
+ * 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}.
153
+ */
154
+ declare abstract class CodecImpl<Id extends string = string, TTraits extends readonly CodecTrait[] = readonly CodecTrait[], TWire = unknown, TInput = unknown> implements Codec<Id, TTraits, TWire, TInput> {
155
+ readonly descriptor: CodecDescriptor<any>;
156
+ /**
157
+ * 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`.
158
+ */
159
+ constructor(descriptor: CodecDescriptor<any>);
160
+ get id(): Id;
161
+ abstract encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
162
+ abstract decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
163
+ abstract encodeJson(value: TInput): JsonValue;
164
+ abstract decodeJson(json: JsonValue): TInput;
165
+ }
166
+ //#endregion
167
+ export { CodecDescriptorImpl as a, CodecLookup as c, emptyCodecLookup as d, voidParamsSchema as f, CodecDescriptor as i, CodecMeta as l, CodecImpl as n, CodecCallContext as o, AnyCodecDescriptor as r, CodecInstanceContext as s, Codec as t, CodecTrait as u };
168
+ //# sourceMappingURL=codec-m_-FAyQn.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codec-m_-FAyQn.d.mts","names":[],"sources":["../src/shared/codec-types.ts","../src/shared/codec-descriptor.ts","../src/shared/codec.ts"],"mappings":";;;;KAGY,UAAA;;AAAZ;;;;;AAaA;;;;;UAAiB,gBAAA;EAAA,SACN,MAAA,GAAS,WAAA;AAAA;;;;;;;;;UAWH,WAAA;EACf,GAAA,CAAI,EAAA,WAAa,KAAA;EACjB,cAAA,CAAe,EAAA;EACf,OAAA,CAAQ,EAAA,WAAa,SAAA;EACrB,mBAAA,CAAoB,EAAA,UAAY,MAAA,EAAQ,MAAA;AAAA;AAAA,cAG7B,gBAAA,EAAkB,WAAA;;;;;AAA/B;;;UAciB,oBAAA;EAAA,SACN,IAAA;AAAA;;;;UAMM,SAAA;EAAA,SACN,EAAA,GAAK,MAAA;AAAA;;;;cAMH,gBAAA,EAAkB,gBAAA;;;;;AAnC/B;;;;;;;;;UCEiB,eAAA;EDDE;EAAA,SCGR,OAAA;EDFM;EAAA,SCIN,MAAA,WAAiB,UAAA;EDHlB;EAAA,SCKC,WAAA;EDJT;EAAA,SCMS,IAAA,GAAO,SAAA;EDNwB;EAAA,SCQ/B,YAAA,EAAc,gBAAA,CAAiB,CAAA;EDRuB;EAAA,SCUtD,eAAA;EDPE;EAAA,SCSF,gBAAA,IAAoB,MAAA,EAAQ,CAAA;;WAE5B,OAAA,GAAU,MAAA,EAAQ,CAAA,MAAO,GAAA,EAAK,oBAAA,KAAyB,KAAA;AAAA;ADGlE;;;;;AAAA,KCMY,kBAAA,GAAqB,eAAA;;;;;ADQjC;;;uBCCsB,mBAAA,4BAA+C,eAAA,CAAgB,OAAA;EAAA,kBACjE,OAAA;EAAA,kBACA,MAAA,WAAiB,UAAA;EAAA,kBACjB,WAAA;EAAA,SACT,IAAA,GAAO,SAAA;EAAA,kBAEE,YAAA,EAAc,gBAAA,CAAiB,OAAA;EAxCnB;EAAA,IA2C1B,eAAA,CAAA;EAvCsB;EA4C1B,gBAAA,CAAA,CAAkB,MAAA,EAAQ,OAAA;EAtCc;;;EAAA,SA2C/B,OAAA,CACP,MAAA,EAAQ,OAAA,IACN,GAAA,EAAK,oBAAA,KAAyB,KAAA,kBAAuB,UAAA;AAAA;;;;;ADzD3D;;;;;;;;;;;;;;;;;UEKiB,KAAA,sDAEU,UAAA,cAAwB,UAAA;EFHT;EAAA,SEQ/B,EAAA,EAAI,EAAA;EFRkD;EAAA,SEUtD,aAAA,GAAgB,OAAA;EFPd;EESX,MAAA,CAAO,KAAA,EAAO,MAAA,EAAQ,GAAA,EAAK,gBAAA,GAAmB,OAAA,CAAQ,KAAA;;EAEtD,MAAA,CAAO,IAAA,EAAM,KAAA,EAAO,GAAA,EAAK,gBAAA,GAAmB,OAAA,CAAQ,MAAA;EFNrD;EEQC,UAAA,CAAW,KAAA,EAAO,MAAA,GAAS,SAAA;EFCQ;EECnC,UAAA,CAAW,IAAA,EAAM,SAAA,GAAY,MAAA;AAAA;;AFM/B;;;;uBEEsB,SAAA,sDAEK,UAAA,cAAwB,UAAA,kDAGtC,KAAA,CAAM,EAAA,EAAI,OAAA,EAAS,KAAA,EAAO,MAAA;EAAA,SAMT,UAAA,EAAY,eAAA;EFSzC;;;cET6B,UAAA,EAAY,eAAA;EAAA,IAEpC,EAAA,CAAA,GAAM,EAAA;EAAA,SAID,MAAA,CAAO,KAAA,EAAO,MAAA,EAAQ,GAAA,EAAK,gBAAA,GAAmB,OAAA,CAAQ,KAAA;EAAA,SACtD,MAAA,CAAO,IAAA,EAAM,KAAA,EAAO,GAAA,EAAK,gBAAA,GAAmB,OAAA,CAAQ,MAAA;EAAA,SACpD,UAAA,CAAW,KAAA,EAAO,MAAA,GAAS,SAAA;EAAA,SAC3B,UAAA,CAAW,IAAA,EAAM,SAAA,GAAY,MAAA;AAAA"}
package/dist/codec.d.mts CHANGED
@@ -1,2 +1,48 @@
1
- import { i as emptyCodecLookup, n as CodecLookup, r as CodecTrait, t as Codec } from "./codec-types-DQ1Agjom.mjs";
2
- export { type Codec, type CodecLookup, type CodecTrait, emptyCodecLookup };
1
+ import { a as CodecDescriptorImpl, c as CodecLookup, d as emptyCodecLookup, f as voidParamsSchema, i as CodecDescriptor, l as CodecMeta, n as CodecImpl, o as CodecCallContext, r as AnyCodecDescriptor, s as CodecInstanceContext, t as Codec, u as CodecTrait } from "./codec-m_-FAyQn.mjs";
2
+
3
+ //#region src/shared/column-spec.d.ts
4
+ /**
5
+ * Authored column-type descriptor — the data shape an authoring site (PSL or TypeScript builders) attaches to a column to identify its codec and its native database type.
6
+ *
7
+ * Lives at the framework-components layer alongside the codec types so codec-author packages (e.g. column-spec / `column()` packagers) can extend it directly without crossing layer boundaries.
8
+ *
9
+ * @template TCodecId Narrowed codec id literal for sites that thread a specific codec id through the type system.
10
+ */
11
+ type ColumnTypeDescriptor<TCodecId extends string = string> = {
12
+ readonly codecId: TCodecId;
13
+ readonly nativeType: string;
14
+ readonly typeParams?: Record<string, unknown> | undefined;
15
+ readonly typeRef?: string;
16
+ };
17
+ /**
18
+ * Column spec carrying the codec factory closure alongside the {@link ColumnTypeDescriptor} fields. Codec authors return a `ColumnSpec` from per-codec column helpers; the runtime materializes the codec instance by calling `codecFactory(ctx)` once it knows the column's `CodecInstanceContext`.
19
+ *
20
+ * Extends {@link ColumnTypeDescriptor} so `ColumnSpec` instances flow directly into contract-authoring sites that consume the descriptor shape — no structural mirroring required.
21
+ */
22
+ interface ColumnSpec<R, P extends Record<string, unknown> | undefined> extends ColumnTypeDescriptor {
23
+ readonly codecFactory: (ctx: CodecInstanceContext) => R;
24
+ readonly typeParams: P;
25
+ }
26
+ /**
27
+ * Trivial column packager. Per-codec helpers call this directly with the result of `descriptor.factory(params)` — direct method invocation binds the descriptor's method-level generic at the call site and the literal flows through `R`.
28
+ *
29
+ * `nativeType` is the column's database-native type spelling — the value the postgres adapter's migration planner, the SQL renderer's cast policy, and the contract's `meta.db.<family>.<target>.nativeType` slot read. Per-codec helpers pass the literal native-type string for their codec (e.g. `'text'`, `'int4'`, `'character varying'`); for codecs whose native-type spelling depends on parameters (none today; reserved for future shapes), the helper computes the rendered string before calling `column`. The framework does not derive the value from `codecId` — that mapping is target-specific and lives at the helper.
30
+ */
31
+ declare function column<R, P extends Record<string, unknown> | undefined>(codecFactory: (ctx: CodecInstanceContext) => R, codecId: string, typeParams: P, nativeType: string): ColumnSpec<R, P>;
32
+ /**
33
+ * Coarse `satisfies` shape — checks the helper's typeParams record matches the descriptor's factory params. Catches "wrong typeParams shape" wiring mistakes; does NOT catch "wrong descriptor's factory" mistakes (the codec slot is left as `unknown`).
34
+ *
35
+ * Use when the codec's `ReturnType<factory>` is unstable (e.g. heavily overloaded factories where extraction widens too much).
36
+ */
37
+ type ColumnHelperFor<D extends CodecDescriptor<any>> = (...args: any[]) => ColumnSpec<unknown, ColumnHelperParams<D>>;
38
+ /**
39
+ * Strict `satisfies` shape — also checks the helper's codec is at least the *base* codec instance type the descriptor's factory returns. `ReturnType<ReturnType<D['factory']>>` widens method generics to their constraint, so this only sanity-checks the wiring at the base type level. Literal preservation comes from the direct `descriptor.factory(...)` call inside the helper, not from `satisfies`.
40
+ */
41
+ type ColumnHelperForStrict<D extends CodecDescriptor<any>> = (...args: any[]) => ColumnSpec<ReturnType<ReturnType<D['factory']>>, ColumnHelperParams<D>>;
42
+ /**
43
+ * Coerce a descriptor's `factory` first parameter into the typeParams shape `ColumnSpec` accepts. Non-parameterized descriptors (factory with no params, or `params: void`) collapse to `undefined`; parameterized descriptors keep the params record shape.
44
+ */
45
+ type ColumnHelperParams<D extends CodecDescriptor<any>> = Parameters<D['factory']>[0] extends Record<string, unknown> ? Parameters<D['factory']>[0] : undefined;
46
+ //#endregion
47
+ export { type AnyCodecDescriptor, type Codec, type CodecCallContext, type CodecDescriptor, CodecDescriptorImpl, CodecImpl, type CodecInstanceContext, type CodecLookup, type CodecMeta, type CodecTrait, type ColumnHelperFor, type ColumnHelperForStrict, type ColumnSpec, type ColumnTypeDescriptor, column, emptyCodecLookup, voidParamsSchema };
48
+ //# sourceMappingURL=codec.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codec.d.mts","names":[],"sources":["../src/shared/column-spec.ts"],"mappings":";;;;;;;;;;KAkBY,oBAAA;EAAA,SACD,OAAA,EAAS,QAAA;EAAA,SACT,UAAA;EAAA,SACA,UAAA,GAAa,MAAA;EAAA,SACb,OAAA;AAAA;;;;;;UAQM,UAAA,cAAwB,MAAA,uCAC/B,oBAAA;EAAA,SACC,YAAA,GAAe,GAAA,EAAK,oBAAA,KAAyB,CAAA;EAAA,SAC7C,UAAA,EAAY,CAAA;AAAA;;;;;;iBAQP,MAAA,cAAoB,MAAA,8BAAA,CAClC,YAAA,GAAe,GAAA,EAAK,oBAAA,KAAyB,CAAA,EAC7C,OAAA,UACA,UAAA,EAAY,CAAA,EACZ,UAAA,WACC,UAAA,CAAW,CAAA,EAAG,CAAA;;AALjB;;;;KAoBY,eAAA,WAA0B,eAAA,aAEjC,IAAA,YACA,UAAA,UAAoB,kBAAA,CAAmB,CAAA;;;;KAMhC,qBAAA,WAAgC,eAAA,aAEvC,IAAA,YACA,UAAA,CAAW,UAAA,CAAW,UAAA,CAAW,CAAA,eAAgB,kBAAA,CAAmB,CAAA;;;;KAMpE,kBAAA,WAA6B,eAAA,SAChC,UAAA,CAAW,CAAA,wBAAyB,MAAA,oBAChC,UAAA,CAAW,CAAA"}
package/dist/codec.mjs CHANGED
@@ -1,6 +1,69 @@
1
- //#region src/codec-types.ts
2
- const emptyCodecLookup = { get: () => void 0 };
3
-
1
+ //#region src/shared/codec.ts
2
+ /**
3
+ * Abstract base class for concrete codec implementations.
4
+ *
5
+ * 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}.
6
+ */
7
+ var CodecImpl = class {
8
+ descriptor;
9
+ /**
10
+ * 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`.
11
+ */
12
+ constructor(descriptor) {
13
+ this.descriptor = descriptor;
14
+ }
15
+ get id() {
16
+ return this.descriptor.codecId;
17
+ }
18
+ };
19
+ //#endregion
20
+ //#region src/shared/codec-types.ts
21
+ const emptyCodecLookup = {
22
+ get: () => void 0,
23
+ targetTypesFor: () => void 0,
24
+ metaFor: () => void 0,
25
+ renderOutputTypeFor: () => void 0
26
+ };
27
+ /**
28
+ * 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.
29
+ */
30
+ const voidParamsSchema = { "~standard": {
31
+ version: 1,
32
+ vendor: "prisma-next",
33
+ validate: (input) => input === void 0 ? { value: void 0 } : { issues: [{ message: "unexpected typeParams for non-parameterized codec (void params expected)" }] }
34
+ } };
35
+ //#endregion
36
+ //#region src/shared/codec-descriptor.ts
37
+ /**
38
+ * Abstract base class for concrete codec descriptors.
39
+ *
40
+ * Codec authors extend this class with their typed `TParams` and declare `codecId`, `traits`, `targetTypes`, `paramsSchema`, the curried `factory(params)`, and (optionally) `renderOutputType`.
41
+ *
42
+ * Implements the {@link CodecDescriptor} interface so a concrete subclass instance is directly usable wherever the framework expects a `CodecDescriptor<P>`.
43
+ */
44
+ var CodecDescriptorImpl = class {
45
+ meta;
46
+ /** 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. */
47
+ get isParameterized() {
48
+ return this.paramsSchema !== voidParamsSchema;
49
+ }
50
+ };
4
51
  //#endregion
5
- export { emptyCodecLookup };
52
+ //#region src/shared/column-spec.ts
53
+ /**
54
+ * Trivial column packager. Per-codec helpers call this directly with the result of `descriptor.factory(params)` — direct method invocation binds the descriptor's method-level generic at the call site and the literal flows through `R`.
55
+ *
56
+ * `nativeType` is the column's database-native type spelling — the value the postgres adapter's migration planner, the SQL renderer's cast policy, and the contract's `meta.db.<family>.<target>.nativeType` slot read. Per-codec helpers pass the literal native-type string for their codec (e.g. `'text'`, `'int4'`, `'character varying'`); for codecs whose native-type spelling depends on parameters (none today; reserved for future shapes), the helper computes the rendered string before calling `column`. The framework does not derive the value from `codecId` — that mapping is target-specific and lives at the helper.
57
+ */
58
+ function column(codecFactory, codecId, typeParams, nativeType) {
59
+ return {
60
+ codecFactory,
61
+ codecId,
62
+ typeParams,
63
+ nativeType
64
+ };
65
+ }
66
+ //#endregion
67
+ export { CodecDescriptorImpl, CodecImpl, column, emptyCodecLookup, voidParamsSchema };
68
+
6
69
  //# sourceMappingURL=codec.mjs.map
@@ -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 * 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. */\n encode(value: TInput): Promise<TWire>;\n /** Converts a wire value from the database driver into the JS application type. Always Promise-returning at the boundary. */\n decode(wire: TWire): 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"],"mappings":";AA6DA,MAAaA,mBAAgC,EAC3C,WAAW,QACZ"}
1
+ {"version":3,"file":"codec.mjs","names":[],"sources":["../src/shared/codec.ts","../src/shared/codec-types.ts","../src/shared/codec-descriptor.ts","../src/shared/column-spec.ts"],"sourcesContent":["/**\n * Codec interface (consumer surface) and abstract `CodecImpl` base (codec-author surface).\n *\n * 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.\n *\n * 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).\n *\n * 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.\n */\n\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecDescriptor } from './codec-descriptor';\nimport type { CodecCallContext, CodecTrait } from './codec-types';\n\n/**\n * A codec is the contract between an application value and its on-wire and on-contract-disk representations.\n *\n * 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.\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 * 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)`.\n *\n * Codec methods split into two groups:\n *\n * - **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.\n * - **Build-time** methods (`encodeJson`, `decodeJson`) run when the contract is serialized or loaded. They stay synchronous so contract validation and client construction are synchronous.\n *\n * 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.\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`). The factory sets this to the descriptor's `codecId`; consumers use it as a back-reference for descriptor lookups and for decode-error diagnostics. */\n readonly id: Id;\n /** 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). */\n readonly __codecTraits?: 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}\n\n/**\n * Abstract base class for concrete codec implementations.\n *\n * 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}.\n */\nexport abstract class CodecImpl<\n Id extends string = string,\n TTraits extends readonly CodecTrait[] = readonly CodecTrait[],\n TWire = unknown,\n TInput = unknown,\n> implements Codec<Id, TTraits, TWire, TInput>\n{\n /**\n * 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`.\n */\n // biome-ignore lint/suspicious/noExplicitAny: variance-erased descriptor reference; subclasses retain typed access via their own state\n constructor(public readonly descriptor: CodecDescriptor<any>) {}\n\n get id(): Id {\n return this.descriptor.codecId as Id;\n }\n\n abstract encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;\n abstract decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;\n abstract encodeJson(value: TInput): JsonValue;\n abstract decodeJson(json: JsonValue): TInput;\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Codec } from './codec';\n\nexport type CodecTrait = 'equality' | 'order' | 'boolean' | 'numeric' | 'textual';\n\n/**\n * Per-call context the runtime threads to every `codec.encode` / `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 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.\n *\n * 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.\n *\n * The interface is named explicitly (not inlined) so future framework fields and family extensions can land additively without breaking codec author signatures.\n */\nexport interface CodecCallContext {\n readonly signal?: AbortSignal;\n}\n\n/**\n * Codec-id-keyed read surface threaded into emit and authoring paths.\n *\n * - `get(id)` returns the runtime {@link Codec} instance for the codec id (used by `validateContract` for `decodeJson` of literal column defaults).\n * - `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.\n * - `metaFor(id)` exposes the codec-id-keyed `meta` (e.g. SQL-side `db.sql.postgres.nativeType`) the runtime instance no longer carries.\n * - `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.\n */\nexport interface CodecLookup {\n get(id: string): Codec | undefined;\n targetTypesFor(id: string): readonly string[] | undefined;\n metaFor(id: string): CodecMeta | undefined;\n renderOutputTypeFor(id: string, params: Record<string, unknown>): string | undefined;\n}\n\nexport const emptyCodecLookup: CodecLookup = {\n get: () => undefined,\n targetTypesFor: () => undefined,\n metaFor: () => undefined,\n renderOutputTypeFor: () => undefined,\n};\n\n/**\n * 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.\n *\n * - `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.\n *\n * 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.\n */\nexport interface CodecInstanceContext {\n readonly name: string;\n}\n\n/**\n * 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.\n */\nexport interface CodecMeta {\n readonly db?: Record<string, unknown>;\n}\n\n/**\n * 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.\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 * Codec descriptor interface (consumer surface) and abstract `CodecDescriptorImpl` base (codec-author surface).\n *\n * 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.\n *\n * 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.\n *\n * 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.\n */\n\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Codec } from './codec';\nimport {\n type CodecInstanceContext,\n type CodecMeta,\n type CodecTrait,\n voidParamsSchema,\n} from './codec-types';\n\n/**\n * 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.\n *\n * 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.\n *\n * 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.\n *\n * @template P - The shape of the params accepted by the factory (`void` for non-parameterized codecs; a record like `{ length: number }` for 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 /** 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. */\n readonly paramsSchema: StandardSchemaV1<P>;\n /** 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. */\n readonly isParameterized: boolean;\n /** 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. */\n readonly renderOutputType?: (params: P) => string | undefined;\n /** 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. */\n readonly factory: (params: P) => (ctx: CodecInstanceContext) => Codec;\n}\n\n/**\n * 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.\n *\n * Codec-registry-unification spec § Decision: every codec resolves through one descriptor map; reads are non-branching.\n */\n// biome-ignore lint/suspicious/noExplicitAny: variance erasure for heterogeneous descriptor collections\nexport type AnyCodecDescriptor = CodecDescriptor<any>;\n\n/**\n * Abstract base class for concrete codec descriptors.\n *\n * Codec authors extend this class with their typed `TParams` and declare `codecId`, `traits`, `targetTypes`, `paramsSchema`, the curried `factory(params)`, and (optionally) `renderOutputType`.\n *\n * Implements the {@link CodecDescriptor} interface so a concrete subclass instance is directly usable wherever the framework expects a `CodecDescriptor<P>`.\n */\nexport abstract class CodecDescriptorImpl<TParams = void> implements CodecDescriptor<TParams> {\n abstract readonly codecId: string;\n abstract readonly traits: readonly CodecTrait[];\n abstract readonly targetTypes: readonly string[];\n readonly meta?: CodecMeta;\n\n abstract readonly paramsSchema: StandardSchemaV1<TParams>;\n\n /** 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. */\n get isParameterized(): boolean {\n return this.paramsSchema !== voidParamsSchema;\n }\n\n /** 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. */\n renderOutputType?(params: TParams): string | undefined;\n\n /**\n * 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.\n */\n abstract factory(\n params: TParams,\n ): (ctx: CodecInstanceContext) => Codec<string, readonly CodecTrait[], unknown, unknown>;\n}\n","/**\n * `column()` packager + `ColumnSpec<R, P>` shape + `ColumnHelperFor<D>` variants for tying per-codec column helpers to their descriptor.\n *\n * `ColumnSpec<R, P>` extends {@link ColumnTypeDescriptor} so it remains a drop-in for contract authoring sites that consume `ColumnTypeDescriptor` shapes — both types live at the framework-components layer so the `extends` clause is real (no structural mirror).\n *\n * `column()` is a trivial, non-polymorphic packager. Generic over `R` (the codec instance type returned by the descriptor's curried factory) and `P` (the typeParams record). The framework does NOT try to infer `R` and `P` from a descriptor — that path is the variance trap. Per-codec helpers absorb the descriptor relationship instead and tie themselves to their descriptor via `satisfies ColumnHelperFor<D>` or `satisfies ColumnHelperForStrict<D>`.\n */\n\nimport type { CodecDescriptor } from './codec-descriptor';\nimport type { CodecInstanceContext } from './codec-types';\n\n/**\n * Authored column-type descriptor — the data shape an authoring site (PSL or TypeScript builders) attaches to a column to identify its codec and its native database type.\n *\n * Lives at the framework-components layer alongside the codec types so codec-author packages (e.g. column-spec / `column()` packagers) can extend it directly without crossing layer boundaries.\n *\n * @template TCodecId Narrowed codec id literal for sites that thread a specific codec id through the type system.\n */\nexport type ColumnTypeDescriptor<TCodecId extends string = string> = {\n readonly codecId: TCodecId;\n readonly nativeType: string;\n readonly typeParams?: Record<string, unknown> | undefined;\n readonly typeRef?: string;\n};\n\n/**\n * Column spec carrying the codec factory closure alongside the {@link ColumnTypeDescriptor} fields. Codec authors return a `ColumnSpec` from per-codec column helpers; the runtime materializes the codec instance by calling `codecFactory(ctx)` once it knows the column's `CodecInstanceContext`.\n *\n * Extends {@link ColumnTypeDescriptor} so `ColumnSpec` instances flow directly into contract-authoring sites that consume the descriptor shape — no structural mirroring required.\n */\nexport interface ColumnSpec<R, P extends Record<string, unknown> | undefined>\n extends ColumnTypeDescriptor {\n readonly codecFactory: (ctx: CodecInstanceContext) => R;\n readonly typeParams: P;\n}\n\n/**\n * Trivial column packager. Per-codec helpers call this directly with the result of `descriptor.factory(params)` — direct method invocation binds the descriptor's method-level generic at the call site and the literal flows through `R`.\n *\n * `nativeType` is the column's database-native type spelling — the value the postgres adapter's migration planner, the SQL renderer's cast policy, and the contract's `meta.db.<family>.<target>.nativeType` slot read. Per-codec helpers pass the literal native-type string for their codec (e.g. `'text'`, `'int4'`, `'character varying'`); for codecs whose native-type spelling depends on parameters (none today; reserved for future shapes), the helper computes the rendered string before calling `column`. The framework does not derive the value from `codecId` — that mapping is target-specific and lives at the helper.\n */\nexport function column<R, P extends Record<string, unknown> | undefined>(\n codecFactory: (ctx: CodecInstanceContext) => R,\n codecId: string,\n typeParams: P,\n nativeType: string,\n): ColumnSpec<R, P> {\n return {\n codecFactory,\n codecId,\n typeParams,\n nativeType,\n };\n}\n\n/**\n * Coarse `satisfies` shape — checks the helper's typeParams record matches the descriptor's factory params. Catches \"wrong typeParams shape\" wiring mistakes; does NOT catch \"wrong descriptor's factory\" mistakes (the codec slot is left as `unknown`).\n *\n * Use when the codec's `ReturnType<factory>` is unstable (e.g. heavily overloaded factories where extraction widens too much).\n */\n// biome-ignore lint/suspicious/noExplicitAny: variance erasure — `CodecDescriptor<P>` is invariant in P, so concrete subclasses do not extend `CodecDescriptor<unknown>`; matches the existing `AnyCodecDescriptor` pattern\nexport type ColumnHelperFor<D extends CodecDescriptor<any>> = (\n // biome-ignore lint/suspicious/noExplicitAny: helper signature is the verification subject; satisfies clauses can't narrow this without circular inference\n ...args: any[]\n) => ColumnSpec<unknown, ColumnHelperParams<D>>;\n\n/**\n * Strict `satisfies` shape — also checks the helper's codec is at least the *base* codec instance type the descriptor's factory returns. `ReturnType<ReturnType<D['factory']>>` widens method generics to their constraint, so this only sanity-checks the wiring at the base type level. Literal preservation comes from the direct `descriptor.factory(...)` call inside the helper, not from `satisfies`.\n */\n// biome-ignore lint/suspicious/noExplicitAny: variance erasure — `CodecDescriptor<P>` is invariant in P, so concrete subclasses do not extend `CodecDescriptor<unknown>`; matches the existing `AnyCodecDescriptor` pattern\nexport type ColumnHelperForStrict<D extends CodecDescriptor<any>> = (\n // biome-ignore lint/suspicious/noExplicitAny: helper signature is the verification subject; satisfies clauses can't narrow this without circular inference\n ...args: any[]\n) => ColumnSpec<ReturnType<ReturnType<D['factory']>>, ColumnHelperParams<D>>;\n\n/**\n * Coerce a descriptor's `factory` first parameter into the typeParams shape `ColumnSpec` accepts. Non-parameterized descriptors (factory with no params, or `params: void`) collapse to `undefined`; parameterized descriptors keep the params record shape.\n */\n// biome-ignore lint/suspicious/noExplicitAny: variance erasure — see above\ntype ColumnHelperParams<D extends CodecDescriptor<any>> =\n Parameters<D['factory']>[0] extends Record<string, unknown>\n ? Parameters<D['factory']>[0]\n : undefined;\n"],"mappings":";;;;;;AA0DA,IAAsB,YAAtB,MAMA;CAK8B;;;;CAA5B,YAAY,YAAkD;EAAlC,KAAA,aAAA;;CAE5B,IAAI,KAAS;EACX,OAAO,KAAK,WAAW;;;;;ACrC3B,MAAa,mBAAgC;CAC3C,WAAW,KAAA;CACX,sBAAsB,KAAA;CACtB,eAAe,KAAA;CACf,2BAA2B,KAAA;CAC5B;;;;AAuBD,MAAa,mBAA2C,EACtD,aAAa;CACX,SAAS;CACT,QAAQ;CACR,WAAW,UACT,UAAU,KAAA,IACN,EAAE,OAAO,KAAA,GAAW,GACpB,EACE,QAAQ,CACN,EACE,SAAS,4EACV,CACF,EACF;CACR,EACF;;;;;;;;;;ACdD,IAAsB,sBAAtB,MAA8F;CAI5F;;CAKA,IAAI,kBAA2B;EAC7B,OAAO,KAAK,iBAAiB;;;;;;;;;;ACjCjC,SAAgB,OACd,cACA,SACA,YACA,YACkB;CAClB,OAAO;EACL;EACA;EACA;EACA;EACD"}