@prisma-next/framework-components 0.5.0-dev.6 → 0.5.0-dev.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +63 -3
  2. package/dist/authoring.d.mts +2 -2
  3. package/dist/authoring.mjs +2 -121
  4. package/dist/codec-BUBJeOk4.d.mts +168 -0
  5. package/dist/codec-BUBJeOk4.d.mts.map +1 -0
  6. package/dist/codec.d.mts +49 -2
  7. package/dist/codec.d.mts.map +1 -0
  8. package/dist/codec.mjs +68 -3
  9. package/dist/codec.mjs.map +1 -1
  10. package/dist/components.d.mts +3 -1
  11. package/dist/components.mjs +1 -1
  12. package/dist/control.d.mts +110 -71
  13. package/dist/control.d.mts.map +1 -1
  14. package/dist/control.mjs +47 -45
  15. package/dist/control.mjs.map +1 -1
  16. package/dist/emission-types-DzNgwiFC.d.mts +39 -0
  17. package/dist/emission-types-DzNgwiFC.d.mts.map +1 -0
  18. package/dist/emission.d.mts +2 -2
  19. package/dist/execution.d.mts +7 -5
  20. package/dist/execution.d.mts.map +1 -1
  21. package/dist/execution.mjs +3 -3
  22. package/dist/execution.mjs.map +1 -1
  23. package/dist/{framework-authoring-D1-JZ37B.d.mts → framework-authoring-DJbiXhmf.d.mts} +41 -12
  24. package/dist/framework-authoring-DJbiXhmf.d.mts.map +1 -0
  25. package/dist/framework-authoring-gi_BJlNO.mjs +206 -0
  26. package/dist/framework-authoring-gi_BJlNO.mjs.map +1 -0
  27. package/dist/{framework-components-EJXe-pum.d.mts → framework-components-BVqm1I48.d.mts} +45 -55
  28. package/dist/framework-components-BVqm1I48.d.mts.map +1 -0
  29. package/dist/{framework-components-C8ZhSwXe.mjs → framework-components-BsWST1Rn.mjs} +2 -2
  30. package/dist/framework-components-BsWST1Rn.mjs.map +1 -0
  31. package/dist/psl-ast-BlDveJZ4.d.mts +159 -0
  32. package/dist/psl-ast-BlDveJZ4.d.mts.map +1 -0
  33. package/dist/psl-ast.d.mts +2 -0
  34. package/dist/psl-ast.mjs +1 -0
  35. package/dist/runtime.d.mts +346 -19
  36. package/dist/runtime.d.mts.map +1 -1
  37. package/dist/runtime.mjs +256 -4
  38. package/dist/runtime.mjs.map +1 -1
  39. package/dist/{types-import-spec-C4sc7wbb.d.mts → types-import-spec-CPhrNJIV.d.mts} +2 -2
  40. package/dist/types-import-spec-CPhrNJIV.d.mts.map +1 -0
  41. package/package.json +7 -4
  42. package/src/control/control-capabilities.ts +71 -0
  43. package/src/{control-descriptors.ts → control/control-descriptors.ts} +7 -7
  44. package/src/{control-instances.ts → control/control-instances.ts} +6 -6
  45. package/src/{control-migration-types.ts → control/control-migration-types.ts} +57 -60
  46. package/src/control/control-operation-preview.ts +23 -0
  47. package/src/{control-stack.ts → control/control-stack.ts} +77 -94
  48. package/src/control/emission-types.ts +49 -0
  49. package/src/control/psl-ast.ts +193 -0
  50. package/src/{execution-descriptors.ts → execution/execution-descriptors.ts} +7 -7
  51. package/src/{execution-instances.ts → execution/execution-instances.ts} +1 -1
  52. package/src/{execution-requirements.ts → execution/execution-requirements.ts} +1 -1
  53. package/src/execution/query-plan.ts +53 -0
  54. package/src/execution/race-against-abort.ts +85 -0
  55. package/src/execution/run-with-middleware.ts +132 -0
  56. package/src/execution/runtime-core.ts +133 -0
  57. package/src/execution/runtime-error.ts +83 -0
  58. package/src/execution/runtime-middleware.ts +182 -0
  59. package/src/exports/authoring.ts +5 -2
  60. package/src/exports/codec.ts +27 -2
  61. package/src/exports/components.ts +2 -2
  62. package/src/exports/control.ts +26 -13
  63. package/src/exports/emission.ts +2 -2
  64. package/src/exports/execution.ts +5 -5
  65. package/src/exports/psl-ast.ts +1 -0
  66. package/src/exports/runtime.ts +17 -5
  67. package/src/shared/codec-descriptor.ts +87 -0
  68. package/src/shared/codec-types.ts +79 -0
  69. package/src/shared/codec.ts +80 -0
  70. package/src/shared/column-spec.ts +83 -0
  71. package/src/{framework-authoring.ts → shared/framework-authoring.ts} +202 -23
  72. package/src/{framework-components.ts → shared/framework-components.ts} +22 -48
  73. package/src/{mutation-default-types.ts → shared/mutation-default-types.ts} +22 -2
  74. package/dist/authoring.mjs.map +0 -1
  75. package/dist/codec-types-B58nCJiu.d.mts +0 -40
  76. package/dist/codec-types-B58nCJiu.d.mts.map +0 -1
  77. package/dist/emission-types-BPAALJbF.d.mts +0 -24
  78. package/dist/emission-types-BPAALJbF.d.mts.map +0 -1
  79. package/dist/framework-authoring-D1-JZ37B.d.mts.map +0 -1
  80. package/dist/framework-components-C8ZhSwXe.mjs.map +0 -1
  81. package/dist/framework-components-EJXe-pum.d.mts.map +0 -1
  82. package/dist/types-import-spec-C4sc7wbb.d.mts.map +0 -1
  83. package/src/codec-types.ts +0 -46
  84. package/src/control-capabilities.ts +0 -34
  85. package/src/emission-types.ts +0 -28
  86. package/src/runtime-error.ts +0 -39
  87. package/src/runtime-middleware.ts +0 -83
  88. /package/src/{control-result-types.ts → control/control-result-types.ts} +0 -0
  89. /package/src/{control-schema-view.ts → control/control-schema-view.ts} +0 -0
  90. /package/src/{async-iterable-result.ts → execution/async-iterable-result.ts} +0 -0
  91. /package/src/{execution-stack.ts → execution/execution-stack.ts} +0 -0
  92. /package/src/{types-import-spec.ts → shared/types-import-spec.ts} +0 -0
@@ -0,0 +1,182 @@
1
+ import type { AsyncIterableResult } from './async-iterable-result';
2
+ import type { ExecutionPlan, QueryPlan } from './query-plan';
3
+ import { runtimeError } from './runtime-error';
4
+
5
+ export interface RuntimeLog {
6
+ info(event: unknown): void;
7
+ warn(event: unknown): void;
8
+ error(event: unknown): void;
9
+ debug?(event: unknown): void;
10
+ }
11
+
12
+ export interface RuntimeMiddlewareContext {
13
+ readonly contract: unknown;
14
+ readonly mode: 'strict' | 'permissive';
15
+ readonly now: () => number;
16
+ readonly log: RuntimeLog;
17
+ /**
18
+ * Returns a stable string identifying the (storage, statement, params)
19
+ * tuple of an execution. Two semantically equivalent executions return
20
+ * the same string. Used by middleware that need per-execution identity
21
+ * (caching, request coalescing).
22
+ *
23
+ * The family runtime owns the implementation:
24
+ * - SQL: `meta.storageHash` + `exec.sql` + `canonicalStringify(exec.params)`
25
+ * - Mongo: `meta.storageHash` + `canonicalStringify({ ...exec.command })`
26
+ *
27
+ * The method is `async` because the underlying digest helper
28
+ * (`hashContent`) uses the WebCrypto API, whose `crypto.subtle.digest`
29
+ * primitive is asynchronous by design.
30
+ *
31
+ * The returned string is intended to be consumed directly as a `Map` key
32
+ * — it is not (and should not be) further hashed by callers.
33
+ */
34
+ contentHash(exec: ExecutionPlan): Promise<string>;
35
+ }
36
+
37
+ export interface AfterExecuteResult {
38
+ readonly rowCount: number;
39
+ readonly latencyMs: number;
40
+ readonly completed: boolean;
41
+ /**
42
+ * Indicates where the rows observed during this execution came from.
43
+ *
44
+ * - `'driver'` — the default. Rows came from the underlying driver via
45
+ * `runDriver` / `runWithMiddleware`'s normal path.
46
+ * - `'middleware'` — a `RuntimeMiddleware.intercept` hook short-circuited
47
+ * execution and supplied the rows directly. The driver was not invoked.
48
+ *
49
+ * Observers (telemetry, lints, budgets) that need to distinguish between
50
+ * driver-served and middleware-served executions read this field.
51
+ * Observers that don't care can ignore it.
52
+ */
53
+ readonly source: 'driver' | 'middleware';
54
+ }
55
+
56
+ /**
57
+ * Result of a successful `RuntimeMiddleware.intercept` hook.
58
+ *
59
+ * Carries the rows that the middleware wishes to return in place of
60
+ * invoking the driver. The runtime iterates `rows` in order and yields
61
+ * each row to the consumer; `beforeExecute`, `runDriver`, and `onRow` are
62
+ * all skipped on the hit path. `afterExecute` still fires with
63
+ * `source: 'middleware'`.
64
+ *
65
+ * `rows` accepts both `Iterable` (arrays, sync generators) and
66
+ * `AsyncIterable` (async generators). `for await` natively handles both
67
+ * via `Symbol.asyncIterator` / `Symbol.iterator` fallback, so the
68
+ * orchestrator does not need to branch on the variant. Cached arrays in
69
+ * the cache middleware are the common case; streaming variants support
70
+ * future use cases like mock layers replaying recordings.
71
+ *
72
+ * Row shape is `Record<string, unknown>` — the same untyped shape
73
+ * `onRow` receives. The SQL runtime decodes intercepted rows through its
74
+ * normal codec pass, so interceptors cache and return raw (undecoded)
75
+ * rows.
76
+ */
77
+ export interface InterceptResult {
78
+ readonly rows: AsyncIterable<Record<string, unknown>> | Iterable<Record<string, unknown>>;
79
+ }
80
+
81
+ /**
82
+ * Family-agnostic middleware SPI parameterized over the plan marker.
83
+ *
84
+ * `TPlan` defaults to the framework `QueryPlan` marker so a generic
85
+ * middleware (e.g. cross-family telemetry) can be authored without
86
+ * naming a family. Family-specific middleware (`SqlMiddleware`,
87
+ * `MongoMiddleware`) narrow `TPlan` to their concrete plan type.
88
+ */
89
+ export interface RuntimeMiddleware<TPlan extends QueryPlan = QueryPlan> {
90
+ readonly name: string;
91
+ readonly familyId?: string;
92
+ readonly targetId?: string;
93
+ /**
94
+ * Optional short-circuit hook. Runs inside `runWithMiddleware`, after
95
+ * the orchestrator receives the lowered plan and before any
96
+ * `beforeExecute` hook fires. Middleware run in registration order; the
97
+ * first to return a non-`undefined` `InterceptResult` wins, and
98
+ * subsequent middleware's `intercept` does not fire.
99
+ *
100
+ * On a hit, `beforeExecute`, `runDriver`, and `onRow` are all skipped.
101
+ * `afterExecute` still fires with `source: 'middleware'`.
102
+ *
103
+ * Returning `undefined` (or omitting the hook entirely) signals
104
+ * passthrough — execution proceeds through the normal driver path.
105
+ *
106
+ * Errors thrown inside `intercept` are rethrown by `runWithMiddleware`
107
+ * as the original `Error` — no envelope is guaranteed at this layer.
108
+ * Before rethrowing, `afterExecute` fires with `completed: false` and
109
+ * `source: 'middleware'`. Errors thrown by `afterExecute` during the
110
+ * error path remain swallowed (existing semantics, unchanged).
111
+ *
112
+ * Used by middleware that need to short-circuit execution and supply
113
+ * rows directly: caching, mocks, rate limiting, circuit breaking.
114
+ */
115
+ intercept?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<InterceptResult | undefined>;
116
+ beforeExecute?(plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;
117
+ onRow?(row: Record<string, unknown>, plan: TPlan, ctx: RuntimeMiddlewareContext): Promise<void>;
118
+ afterExecute?(
119
+ plan: TPlan,
120
+ result: AfterExecuteResult,
121
+ ctx: RuntimeMiddlewareContext,
122
+ ): Promise<void>;
123
+ }
124
+
125
+ /**
126
+ * Optional per-`execute` options accepted by every family runtime.
127
+ *
128
+ * `signal` is the per-query cancellation signal. The runtime threads the
129
+ * signal through to every codec call for the query and uses it to short-
130
+ * circuit the row stream with `RUNTIME.ABORTED` when the caller aborts.
131
+ * Omitting the option (or passing `undefined`) preserves today's behavior
132
+ * bit-for-bit.
133
+ */
134
+ export interface RuntimeExecuteOptions {
135
+ readonly signal?: AbortSignal;
136
+ }
137
+
138
+ /**
139
+ * Cross-family SPI for any runtime that can execute plans and be shut down.
140
+ * Each family runtime (SQL, Mongo) satisfies this interface — SQL nominally,
141
+ * Mongo structurally (due to its phantom Row parameter using a unique symbol).
142
+ *
143
+ * The `_row` intersection on `execute` connects the `Row` type parameter to the
144
+ * plan, mirroring how `QueryPlan<Row>` carries a phantom `_row?: Row`.
145
+ */
146
+ export interface RuntimeExecutor<TPlan extends QueryPlan> {
147
+ execute<Row>(
148
+ plan: TPlan & { readonly _row?: Row },
149
+ options?: RuntimeExecuteOptions,
150
+ ): AsyncIterableResult<Row>;
151
+ close(): Promise<void>;
152
+ }
153
+
154
+ export function checkMiddlewareCompatibility(
155
+ middleware: RuntimeMiddleware,
156
+ runtimeFamilyId: string,
157
+ runtimeTargetId: string,
158
+ ): void {
159
+ if (middleware.targetId !== undefined && middleware.familyId === undefined) {
160
+ throw runtimeError(
161
+ 'RUNTIME.MIDDLEWARE_INCOMPATIBLE',
162
+ `Middleware '${middleware.name}' specifies targetId '${middleware.targetId}' without familyId`,
163
+ { middleware: middleware.name, targetId: middleware.targetId },
164
+ );
165
+ }
166
+
167
+ if (middleware.familyId !== undefined && middleware.familyId !== runtimeFamilyId) {
168
+ throw runtimeError(
169
+ 'RUNTIME.MIDDLEWARE_FAMILY_MISMATCH',
170
+ `Middleware '${middleware.name}' requires family '${middleware.familyId}' but the runtime is configured for family '${runtimeFamilyId}'`,
171
+ { middleware: middleware.name, middlewareFamilyId: middleware.familyId, runtimeFamilyId },
172
+ );
173
+ }
174
+
175
+ if (middleware.targetId !== undefined && middleware.targetId !== runtimeTargetId) {
176
+ throw runtimeError(
177
+ 'RUNTIME.MIDDLEWARE_TARGET_MISMATCH',
178
+ `Middleware '${middleware.name}' requires target '${middleware.targetId}' but the runtime is configured for target '${runtimeTargetId}'`,
179
+ { middleware: middleware.name, middlewareTargetId: middleware.targetId, runtimeTargetId },
180
+ );
181
+ }
182
+ }
@@ -10,13 +10,16 @@ export type {
10
10
  AuthoringTemplateValue,
11
11
  AuthoringTypeConstructorDescriptor,
12
12
  AuthoringTypeNamespace,
13
- } from '../framework-authoring';
13
+ } from '../shared/framework-authoring';
14
14
  export {
15
+ assertNoCrossRegistryCollisions,
16
+ hasRegisteredFieldNamespace,
15
17
  instantiateAuthoringFieldPreset,
16
18
  instantiateAuthoringTypeConstructor,
17
19
  isAuthoringArgRef,
18
20
  isAuthoringFieldPresetDescriptor,
19
21
  isAuthoringTypeConstructorDescriptor,
22
+ mergeAuthoringNamespaces,
20
23
  resolveAuthoringTemplateValue,
21
24
  validateAuthoringHelperArguments,
22
- } from '../framework-authoring';
25
+ } from '../shared/framework-authoring';
@@ -1,2 +1,27 @@
1
- export type { Codec, CodecLookup, CodecTrait } from '../codec-types';
2
- export { emptyCodecLookup } from '../codec-types';
1
+ /**
2
+ * Codec model: interfaces (consumer surface) plus abstract `Impl` classes (codec-author surface) plus the column packager.
3
+ *
4
+ * Consumers depend on the interfaces: {@link Codec}, {@link CodecDescriptor}, {@link AnyCodecDescriptor}, {@link ColumnSpec}, {@link ColumnTypeDescriptor}.
5
+ *
6
+ * Codec authors `extend` the abstract bases: {@link CodecImpl} and {@link CodecDescriptorImpl}. They write a per-codec column helper that calls `descriptor.factory(...)` directly and tie the helper to its descriptor with `satisfies ColumnHelperFor<D>` (or `ColumnHelperForStrict<D>`).
7
+ */
8
+
9
+ export type { Codec } from '../shared/codec';
10
+ export { CodecImpl } from '../shared/codec';
11
+ export type { AnyCodecDescriptor, CodecDescriptor } from '../shared/codec-descriptor';
12
+ export { CodecDescriptorImpl } from '../shared/codec-descriptor';
13
+ export type {
14
+ CodecCallContext,
15
+ CodecInstanceContext,
16
+ CodecLookup,
17
+ CodecMeta,
18
+ CodecTrait,
19
+ } from '../shared/codec-types';
20
+ export { emptyCodecLookup, voidParamsSchema } from '../shared/codec-types';
21
+ export type {
22
+ ColumnHelperFor,
23
+ ColumnHelperForStrict,
24
+ ColumnSpec,
25
+ ColumnTypeDescriptor,
26
+ } from '../shared/column-spec';
27
+ export { column } from '../shared/column-spec';
@@ -20,5 +20,5 @@ export type {
20
20
  TargetDescriptor,
21
21
  TargetInstance,
22
22
  TargetPackRef,
23
- } from '../framework-components';
24
- export { checkContractComponentRequirements } from '../framework-components';
23
+ } from '../shared/framework-components';
24
+ export { checkContractComponentRequirements } from '../shared/framework-components';
@@ -1,21 +1,30 @@
1
- export type { MigratableTargetDescriptor, SchemaViewCapable } from '../control-capabilities';
2
- export { hasMigrations, hasSchemaView } from '../control-capabilities';
1
+ export type {
2
+ MigratableTargetDescriptor,
3
+ OperationPreviewCapable,
4
+ PslContractInferCapable,
5
+ SchemaViewCapable,
6
+ } from '../control/control-capabilities';
7
+ export {
8
+ hasMigrations,
9
+ hasOperationPreview,
10
+ hasPslContractInfer,
11
+ hasSchemaView,
12
+ } from '../control/control-capabilities';
3
13
  export type {
4
14
  ControlAdapterDescriptor,
5
15
  ControlDriverDescriptor,
6
16
  ControlExtensionDescriptor,
7
17
  ControlFamilyDescriptor,
8
18
  ControlTargetDescriptor,
9
- } from '../control-descriptors';
19
+ } from '../control/control-descriptors';
10
20
  export type {
11
21
  ControlAdapterInstance,
12
22
  ControlDriverInstance,
13
23
  ControlExtensionInstance,
14
24
  ControlFamilyInstance,
15
25
  ControlTargetInstance,
16
- } from '../control-instances';
26
+ } from '../control/control-instances';
17
27
  export type {
18
- DataTransformOperation,
19
28
  MigrationOperationClass,
20
29
  MigrationOperationPolicy,
21
30
  MigrationPlan,
@@ -35,7 +44,11 @@ export type {
35
44
  OpFactoryCall,
36
45
  SerializedQueryPlan,
37
46
  TargetMigrationsCapability,
38
- } from '../control-migration-types';
47
+ } from '../control/control-migration-types';
48
+ export type {
49
+ OperationPreview,
50
+ OperationPreviewStatement,
51
+ } from '../control/control-operation-preview';
39
52
  export type {
40
53
  BaseSchemaIssue,
41
54
  EmitContractResult,
@@ -47,25 +60,25 @@ export type {
47
60
  SignDatabaseResult,
48
61
  VerifyDatabaseResult,
49
62
  VerifyDatabaseSchemaResult,
50
- } from '../control-result-types';
63
+ } from '../control/control-result-types';
51
64
  export {
52
65
  VERIFY_CODE_HASH_MISMATCH,
53
66
  VERIFY_CODE_MARKER_MISSING,
54
67
  VERIFY_CODE_SCHEMA_FAILURE,
55
68
  VERIFY_CODE_TARGET_MISMATCH,
56
- } from '../control-result-types';
69
+ } from '../control/control-result-types';
57
70
  export type {
58
71
  CoreSchemaView,
59
72
  SchemaNodeKind,
60
73
  SchemaTreeNodeOptions,
61
74
  SchemaTreeVisitor,
62
- } from '../control-schema-view';
63
- export { SchemaTreeNode } from '../control-schema-view';
75
+ } from '../control/control-schema-view';
76
+ export { SchemaTreeNode } from '../control/control-schema-view';
64
77
  export type {
65
78
  AssembledAuthoringContributions,
66
79
  ControlStack,
67
80
  CreateControlStackInput,
68
- } from '../control-stack';
81
+ } from '../control/control-stack';
69
82
  export {
70
83
  assembleAuthoringContributions,
71
84
  assembleControlMutationDefaults,
@@ -77,7 +90,7 @@ export {
77
90
  extractComponentIds,
78
91
  extractOperationTypeImports,
79
92
  extractQueryOperationTypeImports,
80
- } from '../control-stack';
93
+ } from '../control/control-stack';
81
94
  export type {
82
95
  ControlMutationDefaultEntry,
83
96
  ControlMutationDefaultRegistry,
@@ -92,4 +105,4 @@ export type {
92
105
  ParsedDefaultFunctionCall,
93
106
  SourceDiagnostic,
94
107
  SourceSpan,
95
- } from '../mutation-default-types';
108
+ } from '../shared/mutation-default-types';
@@ -2,5 +2,5 @@ export type {
2
2
  EmissionSpi,
3
3
  GenerateContractTypesOptions,
4
4
  ValidationContext,
5
- } from '../emission-types';
6
- export type { TypesImportSpec } from '../types-import-spec';
5
+ } from '../control/emission-types';
6
+ export type { TypesImportSpec } from '../shared/types-import-spec';
@@ -4,14 +4,14 @@ export type {
4
4
  RuntimeExtensionDescriptor,
5
5
  RuntimeFamilyDescriptor,
6
6
  RuntimeTargetDescriptor,
7
- } from '../execution-descriptors';
7
+ } from '../execution/execution-descriptors';
8
8
  export type {
9
9
  RuntimeAdapterInstance,
10
10
  RuntimeDriverInstance,
11
11
  RuntimeExtensionInstance,
12
12
  RuntimeFamilyInstance,
13
13
  RuntimeTargetInstance,
14
- } from '../execution-instances';
15
- export { assertRuntimeContractRequirementsSatisfied } from '../execution-requirements';
16
- export type { ExecutionStack, ExecutionStackInstance } from '../execution-stack';
17
- export { createExecutionStack, instantiateExecutionStack } from '../execution-stack';
14
+ } from '../execution/execution-instances';
15
+ export { assertRuntimeContractRequirementsSatisfied } from '../execution/execution-requirements';
16
+ export type { ExecutionStack, ExecutionStackInstance } from '../execution/execution-stack';
17
+ export { createExecutionStack, instantiateExecutionStack } from '../execution/execution-stack';
@@ -0,0 +1 @@
1
+ export * from '../control/psl-ast';
@@ -1,11 +1,23 @@
1
- export { AsyncIterableResult } from '../async-iterable-result';
2
- export type { RuntimeErrorEnvelope } from '../runtime-error';
3
- export { runtimeError } from '../runtime-error';
1
+ export { AsyncIterableResult } from '../execution/async-iterable-result';
2
+ export type { ExecutionPlan, QueryPlan, ResultType } from '../execution/query-plan';
3
+ export { checkAborted, raceAgainstAbort } from '../execution/race-against-abort';
4
+ export { runWithMiddleware } from '../execution/run-with-middleware';
5
+ export type { RuntimeCoreOptions } from '../execution/runtime-core';
6
+ export { RuntimeCore } from '../execution/runtime-core';
7
+ export type { RuntimeAbortedPhase, RuntimeErrorEnvelope } from '../execution/runtime-error';
8
+ export {
9
+ isRuntimeError,
10
+ RUNTIME_ABORTED,
11
+ runtimeAborted,
12
+ runtimeError,
13
+ } from '../execution/runtime-error';
4
14
  export type {
5
15
  AfterExecuteResult,
16
+ InterceptResult,
17
+ RuntimeExecuteOptions,
6
18
  RuntimeExecutor,
7
19
  RuntimeLog,
8
20
  RuntimeMiddleware,
9
21
  RuntimeMiddlewareContext,
10
- } from '../runtime-middleware';
11
- export { checkMiddlewareCompatibility } from '../runtime-middleware';
22
+ } from '../execution/runtime-middleware';
23
+ export { checkMiddlewareCompatibility } from '../execution/runtime-middleware';
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Codec descriptor interface (consumer surface) and abstract `CodecDescriptorImpl` base (codec-author surface).
3
+ *
4
+ * Consumers depend on the {@link CodecDescriptor} interface — it is the codec-id-keyed source of truth for static metadata (`traits`, `targetTypes`, `meta`) and registration concerns (`paramsSchema`; optional `renderOutputType`). The runtime `Codec` instance returned by `factory(params)(ctx)` carries only the conversion behavior.
5
+ *
6
+ * Codec authors `extend` the {@link CodecDescriptorImpl} abstract class to declare their codec id, traits, target types, params schema, the `factory(params)` that materializes a typed `Codec<...>`, and (optionally) a `renderOutputType(params)` for the emit path.
7
+ *
8
+ * The factory's method-level generic is the load-bearing piece for literal preservation: per-codec column helpers invoke `descriptor.factory(...)` *directly*, and the direct call binds the generic at its call site. Type extraction (`ReturnType<D['factory']>`, structural matching) widens method generics to their constraint — that's why the column-helper surface is per-codec, not polymorphic.
9
+ */
10
+
11
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
12
+ import type { Codec } from './codec';
13
+ import {
14
+ type CodecInstanceContext,
15
+ type CodecMeta,
16
+ type CodecTrait,
17
+ voidParamsSchema,
18
+ } from './codec-types';
19
+
20
+ /**
21
+ * Unified codec descriptor. Every codec in the framework registers through this shape — non-parameterized codecs use `P = void` and a constant factory that returns the same shared codec instance for every column; parameterized codecs use a non-empty `P` and a curried higher-order factory that returns a per-instance codec.
22
+ *
23
+ * The descriptor is the codec-id-keyed source of truth for static metadata (`traits`, `targetTypes`, `meta`) and registration concerns (`paramsSchema` for JSON-boundary validation; optional `renderOutputType` for the `contract.d.ts` emit path). The runtime `Codec` instance returned by `factory(params)(ctx)` carries only the conversion behavior.
24
+ *
25
+ * Whether a codec id "is parameterized" stops being a registration-time distinction — it's a property of `P` on the descriptor. The descriptor map indexes every descriptor by `codecId`; both `descriptorFor(codecId)` and `forColumn(table, column)` resolve through the same map without branching on parameterization.
26
+ *
27
+ * @template P - The shape of the params accepted by the factory (`void` for non-parameterized codecs; a record like `{ length: number }` for parameterized codecs).
28
+ *
29
+ * Codec-registry-unification project § Decision.
30
+ */
31
+ export interface CodecDescriptor<P = void> {
32
+ /** The codec ID this descriptor applies to (e.g. `pg/vector@1`, `pg/text@1`). */
33
+ readonly codecId: string;
34
+ /** Semantic traits for operator gating (e.g. equality, order, numeric). */
35
+ readonly traits: readonly CodecTrait[];
36
+ /** Database-native type names this codec handles (e.g. `['timestamptz']`). */
37
+ readonly targetTypes: readonly string[];
38
+ /** Optional family-specific metadata (e.g. SQL-side `db.sql.postgres.nativeType`). */
39
+ readonly meta?: CodecMeta;
40
+ /** Standard Schema validator for the factory's params. Validates JSON-sourced params at the contract boundary (PSL → IR; `contract.json` → runtime). For non-parameterized codecs (`P = void`), the schema validates `void`/`undefined` — the framework supplies no params at the call boundary. */
41
+ readonly paramsSchema: StandardSchemaV1<P>;
42
+ /** Whether this descriptor is parameterized — i.e. its `paramsSchema` is something other than the singleton `voidParamsSchema`. Consumers that need to gate column-aware dispatch (e.g. the `validateParamRefRefs` AST-builder pass) read this directly rather than threading a free-floating `(codecId) => boolean` callback. */
43
+ readonly isParameterized: boolean;
44
+ /** Emit-path string renderer for `contract.d.ts`. Returns the TypeScript output type expression for given params (e.g. `Vector<1536>`). Optional; absent renderers cause the emitter to fall back to the codec's base output type. Non-parameterized codecs typically omit it. */
45
+ readonly renderOutputType?: (params: P) => string | undefined;
46
+ /** The curried higher-order codec. For non-parameterized codecs, the factory is constant — every call returns the same shared codec instance. For parameterized codecs, the factory is called once per `storage.types` instance (or once per inline-`typeParams` column), with `ctx` carrying the column set the resulting codec serves. */
47
+ readonly factory: (params: P) => (ctx: CodecInstanceContext) => Codec;
48
+ }
49
+
50
+ /**
51
+ * Variance-erased {@link CodecDescriptor} alias. `CodecDescriptor<P>` is invariant in `P` (the `factory` and `renderOutputType` slots use `P` contravariantly), so `CodecDescriptor<P>` does not extend `CodecDescriptor<unknown>` for specific `P`. Heterogeneous descriptor collections — e.g. `SqlStaticContributions.codecs:` returning a list that mixes parameterized and non-parameterized descriptors — type against this alias and narrow per codec id at the consumer.
52
+ *
53
+ * Codec-registry-unification spec § Decision: every codec resolves through one descriptor map; reads are non-branching.
54
+ */
55
+ // biome-ignore lint/suspicious/noExplicitAny: variance erasure for heterogeneous descriptor collections
56
+ export type AnyCodecDescriptor = CodecDescriptor<any>;
57
+
58
+ /**
59
+ * Abstract base class for concrete codec descriptors.
60
+ *
61
+ * Codec authors extend this class with their typed `TParams` and declare `codecId`, `traits`, `targetTypes`, `paramsSchema`, the curried `factory(params)`, and (optionally) `renderOutputType`.
62
+ *
63
+ * Implements the {@link CodecDescriptor} interface so a concrete subclass instance is directly usable wherever the framework expects a `CodecDescriptor<P>`.
64
+ */
65
+ export abstract class CodecDescriptorImpl<TParams = void> implements CodecDescriptor<TParams> {
66
+ abstract readonly codecId: string;
67
+ abstract readonly traits: readonly CodecTrait[];
68
+ abstract readonly targetTypes: readonly string[];
69
+ readonly meta?: CodecMeta;
70
+
71
+ abstract readonly paramsSchema: StandardSchemaV1<TParams>;
72
+
73
+ /** Boolean derived from `paramsSchema`: `true` whenever the schema is not the singleton `voidParamsSchema`. The framework registry's `validateParamRefRefs` pass reads this through `descriptorFor(codecId).isParameterized` to gate column-ref enforcement. */
74
+ get isParameterized(): boolean {
75
+ return this.paramsSchema !== voidParamsSchema;
76
+ }
77
+
78
+ /** Optional emit-path string renderer for `contract.d.ts`. Returns the TypeScript output type expression for the given params (e.g. `Vector<1536>`). Non-parameterized codecs typically omit it. */
79
+ renderOutputType?(params: TParams): string | undefined;
80
+
81
+ /**
82
+ * Materialize a curried codec factory for the given params. Concrete subclasses override with a typed return type (e.g. `factory<N>(params: { length: N }): (ctx) => VectorCodec<N>`); per-codec helpers read the typed return at the *direct* call site, which is what preserves method-level generics. Type extraction (e.g. `ReturnType<D['factory']>`) widens method generics to their constraint — that's why the column-helper surface is per-codec, not polymorphic.
83
+ */
84
+ abstract factory(
85
+ params: TParams,
86
+ ): (ctx: CodecInstanceContext) => Codec<string, readonly CodecTrait[], unknown, unknown>;
87
+ }
@@ -0,0 +1,79 @@
1
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import type { Codec } from './codec';
3
+
4
+ export type CodecTrait = 'equality' | 'order' | 'boolean' | 'numeric' | 'textual';
5
+
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
+ export interface CodecCallContext {
18
+ readonly signal?: AbortSignal;
19
+ }
20
+
21
+ /**
22
+ * Codec-id-keyed read surface threaded into emit and authoring paths.
23
+ *
24
+ * - `get(id)` returns the runtime {@link Codec} instance for the codec id (used by `validateContract` for `decodeJson` of literal column defaults).
25
+ * - `targetTypesFor(id)` exposes the codec-id-keyed `targetTypes` metadata the runtime instance no longer carries (TML-2357). Returns the same array `CodecDescriptor.targetTypes` would; for Mongo (whose registration doesn't yet resolve through the unified descriptor map — TML-2324) the family-side assembly populates this directly from the contributor's codec metadata.
26
+ * - `metaFor(id)` exposes the codec-id-keyed `meta` (e.g. SQL-side `db.sql.postgres.nativeType`) the runtime instance no longer carries.
27
+ * - `renderOutputTypeFor(id, params)` exposes the codec-id-keyed `renderOutputType` renderer the runtime instance no longer carries. Returns `undefined` when the codec doesn't render a custom type or when the codec id is unknown.
28
+ */
29
+ export interface CodecLookup {
30
+ get(id: string): Codec | undefined;
31
+ targetTypesFor(id: string): readonly string[] | undefined;
32
+ metaFor(id: string): CodecMeta | undefined;
33
+ renderOutputTypeFor(id: string, params: Record<string, unknown>): string | undefined;
34
+ }
35
+
36
+ export const emptyCodecLookup: CodecLookup = {
37
+ get: () => undefined,
38
+ targetTypesFor: () => undefined,
39
+ metaFor: () => undefined,
40
+ renderOutputTypeFor: () => undefined,
41
+ };
42
+
43
+ /**
44
+ * Family-agnostic per-instance context supplied by the framework when applying a higher-order codec factory. Allows stateful codecs (e.g. column-scoped encryption) to derive per-instance state from the materialization site.
45
+ *
46
+ * - `name` — the family-agnostic instance identity. For SQL, the runtime populates this as the `storage.types` instance name (e.g. `Embedding1536`) for typeRef-shaped columns, the synthesized anonymous instance name (`<anon:Document.embedding>`) for inline-`typeParams` columns, or a shared sentinel (`<shared:pg/text@1>`) for non-parameterized codec ids. Other families pick the analogous identity for their materialization sites.
47
+ *
48
+ * Family-specific extensions (e.g. {@link import('@prisma-next/sql-relational-core/ast').SqlCodecInstanceContext} in the SQL layer) augment this base with domain-shaped column-set metadata. Codec authors target the base when they don't read family-specific metadata; they target the family extension when they do.
49
+ */
50
+ export interface CodecInstanceContext {
51
+ readonly name: string;
52
+ }
53
+
54
+ /**
55
+ * Family-agnostic codec metadata. Family-specific extensions augment the base `db.<family>.<target>` block with native-type information; the base shape is an empty object so non-relational codecs can carry no metadata.
56
+ */
57
+ export interface CodecMeta {
58
+ readonly db?: Record<string, unknown>;
59
+ }
60
+
61
+ /**
62
+ * Standard Schema validator for `void` params. Accepts only `undefined` (or absent input); rejects any other value so a contract that tries to thread `typeParams` through a non-parameterized codec id fails fast at the JSON boundary instead of silently coercing the value away. Used by the framework-supplied non-parameterized descriptor synthesizer.
63
+ */
64
+ export const voidParamsSchema: StandardSchemaV1<void> = {
65
+ '~standard': {
66
+ version: 1,
67
+ vendor: 'prisma-next',
68
+ validate: (input) =>
69
+ input === undefined
70
+ ? { value: undefined }
71
+ : {
72
+ issues: [
73
+ {
74
+ message: 'unexpected typeParams for non-parameterized codec (void params expected)',
75
+ },
76
+ ],
77
+ },
78
+ },
79
+ };
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Codec interface (consumer surface) and abstract `CodecImpl` base (codec-author surface).
3
+ *
4
+ * Consumers depend on the {@link Codec} interface — it describes the runtime instance returned by a descriptor's curried factory and is what the framework threads through emit, validate, and execute paths.
5
+ *
6
+ * Codec authors `extend` the {@link CodecImpl} abstract class to declare a typed runtime codec instance. The class carries a variance-erased descriptor reference (`CodecDescriptor<any>`); `id` proxies through the descriptor so one source of truth governs both metadata reads and aliasing semantics (alias subclasses inherit the descriptor's id automatically).
7
+ *
8
+ * Class generic shape: `Id`, `TTraits`, `TWire`, `TInput`. Method generics on the codec subclass's own surface (e.g. arktype-json's schema generic, pgvector's dimension generic) flow through the subclass's constructor and propagate via the descriptor's typed `factory(params)` return at *direct* call sites.
9
+ */
10
+
11
+ import type { JsonValue } from '@prisma-next/contract/types';
12
+ import type { CodecDescriptor } from './codec-descriptor';
13
+ import type { CodecCallContext, CodecTrait } from './codec-types';
14
+
15
+ /**
16
+ * A codec is the contract between an application value and its on-wire and on-contract-disk representations.
17
+ *
18
+ * The author's mental model is two JS-side types — `TInput` (the application JS type) and `TWire` (the database driver wire format) — plus `JsonValue` for build-time contract artifacts. The codec translates `TInput` to `TWire` on writes and back on reads, and to/from `JsonValue` during contract emission and loading.
19
+ *
20
+ * Three representations participate:
21
+ * - **Input** (`TInput`): the JS type at the application boundary.
22
+ * - **Wire** (`TWire`): the format exchanged with the database driver.
23
+ * - **JSON** (`JsonValue`): a JSON-safe form used in contract artifacts.
24
+ *
25
+ * The runtime instance carries only its `id` (the descriptor's `codecId`, set by the factory) and the four conversion methods. Static metadata (`traits`, `targetTypes`, `meta`) and the build-time `renderOutputType` renderer live on the {@link CodecDescriptor} keyed by `codecId` — the read-surface single source of truth. Consumers that need them resolve through `descriptorFor(codecId)`.
26
+ *
27
+ * Codec methods split into two groups:
28
+ *
29
+ * - **Query-time** methods (`encode`, `decode`) run per row/parameter at the IO boundary; they are required and Promise-returning. The per-family codec factory accepts sync or async author functions and lifts sync ones to Promise-shaped methods automatically.
30
+ * - **Build-time** methods (`encodeJson`, `decodeJson`) run when the contract is serialized or loaded. They stay synchronous so contract validation and client construction are synchronous.
31
+ *
32
+ * Target-family codec interfaces extend this base; family-specific concerns (e.g. the SQL `column?` per-call context) layer on through the `CodecCallContext` extension pattern.
33
+ */
34
+ export interface Codec<
35
+ Id extends string = string,
36
+ TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
37
+ TWire = unknown,
38
+ TInput = unknown,
39
+ > {
40
+ /** Unique codec identifier in `namespace/name@version` format (e.g. `pg/timestamptz@1`). The factory sets this to the descriptor's `codecId`; consumers use it as a back-reference for descriptor lookups and for decode-error diagnostics. */
41
+ readonly id: Id;
42
+ /** Phantom carrier for the `TTraits` generic; type-only, undefined at runtime. Runtime traits live on {@link CodecDescriptor.traits}. Implemented as a string-key phantom (`__codecTraits`) rather than `unique symbol` so bundlers that split `.d.ts` chunks do not strand symbol identity on chunk-private paths (the same `TS2742` family that the public re-export of `CodecTypes` works around). */
43
+ readonly __codecTraits?: TTraits;
44
+ /** Converts a JS value to the wire format expected by the database driver. Always Promise-returning at the boundary. The {@link CodecCallContext} is supplied by the runtime on every call (allocated once per `runtime.execute()`); family layers may narrow the ctx to extend it (e.g. SQL adds `column`). Author-side single-arg `(value) => …` functions remain legal via TypeScript's bivariance for trailing parameters. */
45
+ encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
46
+ /** Converts a wire value from the database driver into the JS application type. Always Promise-returning at the boundary. The {@link CodecCallContext} is supplied by the runtime on every call (allocated once per `runtime.execute()`); family layers may narrow the ctx to extend it (e.g. SQL adds `column`). Author-side single-arg `(wire) => …` functions remain legal via TypeScript's bivariance for trailing parameters. */
47
+ decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
48
+ /** Converts a JS value to a JSON-safe representation for contract serialization. Synchronous; called during contract emission. */
49
+ encodeJson(value: TInput): JsonValue;
50
+ /** Converts a JSON representation back to the JS input type. Synchronous; called during contract loading via `validateContract`. */
51
+ decodeJson(json: JsonValue): TInput;
52
+ }
53
+
54
+ /**
55
+ * Abstract base class for concrete codec implementations.
56
+ *
57
+ * Codec authors extend this class with their typed `Id`, `TTraits`, `TWire`, `TInput` and override `encode`/`decode` (and optionally `encodeJson`/`decodeJson`). The runtime instance carries only its `id` (proxied through the descriptor so alias subclasses inherit the descriptor's id automatically) and the conversion methods — static metadata lives on the {@link CodecDescriptor}.
58
+ */
59
+ export abstract class CodecImpl<
60
+ Id extends string = string,
61
+ TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
62
+ TWire = unknown,
63
+ TInput = unknown,
64
+ > implements Codec<Id, TTraits, TWire, TInput>
65
+ {
66
+ /**
67
+ * Variance-erased descriptor reference. Concrete codec subclasses receive the typed descriptor in their own constructors and forward it via `super(descriptor)`; the variance erasure lives at this base because the abstract surface can't carry the concrete `TParams`.
68
+ */
69
+ // biome-ignore lint/suspicious/noExplicitAny: variance-erased descriptor reference; subclasses retain typed access via their own state
70
+ constructor(public readonly descriptor: CodecDescriptor<any>) {}
71
+
72
+ get id(): Id {
73
+ return this.descriptor.codecId as Id;
74
+ }
75
+
76
+ abstract encode(value: TInput, ctx: CodecCallContext): Promise<TWire>;
77
+ abstract decode(wire: TWire, ctx: CodecCallContext): Promise<TInput>;
78
+ abstract encodeJson(value: TInput): JsonValue;
79
+ abstract decodeJson(json: JsonValue): TInput;
80
+ }