@prisma-next/sql-runtime 0.5.0-dev.7 → 0.5.0-dev.70

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 (48) hide show
  1. package/README.md +31 -22
  2. package/dist/exports-CXtbKm5q.mjs +1516 -0
  3. package/dist/exports-CXtbKm5q.mjs.map +1 -0
  4. package/dist/{index-yb51L_1h.d.mts → index-C4Dz0JKE.d.mts} +116 -45
  5. package/dist/index-C4Dz0JKE.d.mts.map +1 -0
  6. package/dist/index.d.mts +2 -2
  7. package/dist/index.mjs +2 -3
  8. package/dist/test/utils.d.mts +38 -33
  9. package/dist/test/utils.d.mts.map +1 -1
  10. package/dist/test/utils.mjs +107 -56
  11. package/dist/test/utils.mjs.map +1 -1
  12. package/package.json +18 -19
  13. package/src/codecs/alias-resolver.ts +34 -0
  14. package/src/codecs/decoding.ts +263 -176
  15. package/src/codecs/encoding.ts +151 -38
  16. package/src/codecs/validation.ts +4 -4
  17. package/src/content-hash.ts +44 -0
  18. package/src/exports/index.ts +13 -7
  19. package/src/fingerprint.ts +22 -0
  20. package/src/guardrails/raw.ts +165 -0
  21. package/src/lower-sql-plan.ts +3 -3
  22. package/src/marker.ts +75 -0
  23. package/src/middleware/before-compile-chain.ts +1 -0
  24. package/src/middleware/budgets.ts +36 -120
  25. package/src/middleware/lints.ts +3 -3
  26. package/src/middleware/sql-middleware.ts +6 -5
  27. package/src/runtime-spi.ts +44 -0
  28. package/src/sql-context.ts +315 -105
  29. package/src/sql-family-adapter.ts +3 -2
  30. package/src/sql-marker.ts +89 -51
  31. package/src/sql-runtime.ts +305 -144
  32. package/dist/exports-BQZSVXXt.mjs +0 -981
  33. package/dist/exports-BQZSVXXt.mjs.map +0 -1
  34. package/dist/index-yb51L_1h.d.mts.map +0 -1
  35. package/src/codecs/json-schema-validation.ts +0 -61
  36. package/test/async-iterable-result.test.ts +0 -141
  37. package/test/before-compile-chain.test.ts +0 -223
  38. package/test/budgets.test.ts +0 -431
  39. package/test/context.types.test-d.ts +0 -68
  40. package/test/execution-stack.test.ts +0 -161
  41. package/test/json-schema-validation.test.ts +0 -571
  42. package/test/lints.test.ts +0 -160
  43. package/test/mutation-default-generators.test.ts +0 -254
  44. package/test/parameterized-types.test.ts +0 -529
  45. package/test/sql-context.test.ts +0 -384
  46. package/test/sql-family-adapter.test.ts +0 -103
  47. package/test/sql-runtime.test.ts +0 -792
  48. package/test/utils.ts +0 -297
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-C4Dz0JKE.d.mts","names":[],"sources":["../src/codecs/validation.ts","../src/lower-sql-plan.ts","../src/marker.ts","../src/middleware/sql-middleware.ts","../src/middleware/budgets.ts","../src/middleware/lints.ts","../src/runtime-spi.ts","../src/sql-context.ts","../src/sql-marker.ts","../src/sql-runtime.ts"],"mappings":";;;;;;;;;;;;;iBAKgB,eAAA,CAAgB,QAAA,EAAU,QAAA,CAAS,UAAA,IAAc,GAAA;AAAA,iBA2BjD,6BAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;AAAA,iBA4BL,iCAAA,CACd,QAAA,EAAU,uBAAA,EACV,QAAA,EAAU,QAAA,CAAS,UAAA;;;;;;;;;;;iBCnDL,YAAA,KAAA,CACd,OAAA,EAAS,OAAA,CAAQ,WAAA,EAAa,QAAA,CAAS,UAAA,GAAa,gBAAA,GACpD,QAAA,EAAU,QAAA,CAAS,UAAA,GACnB,SAAA,EAAW,YAAA,CAAa,GAAA,IACvB,gBAAA,CAAiB,GAAA;;;iBCkCJ,sBAAA,CAAuB,GAAA,YAAe,oBAAA;;;UCzCrC,oBAAA,SAA6B,wBAAA;EAAA,SACnC,QAAA,EAAU,QAAA,CAAS,UAAA;AAAA;;;;;UAOb,SAAA;EAAA,SACN,GAAA,EAAK,WAAA;EAAA,SACL,IAAA,EAAM,QAAA;AAAA;AAAA,UAGA,aAAA,SAAsB,iBAAA,CAAkB,gBAAA;EAAA,SAC9C,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AgC,QAAA,CAAS,UAAA,4BAAA,CACvD,OAAA,EAAS,oBAAA,CAAqB,SAAA,EAAW,SAAA,IACxC,OAAA"}
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as SqlRuntimeExtensionInstance, B as SqlMiddleware, C as RuntimeParameterizedCodecDescriptor, D as SqlRuntimeAdapterInstance, E as SqlRuntimeAdapterDescriptor, F as createSqlExecutionStack, G as validateContractCodecMappings, H as lowerSqlPlan, I as LintsOptions, L as lints, M as SqlStaticContributions, N as TypeHelperRegistry, O as SqlRuntimeDriverInstance, P as createExecutionContext, R as BudgetsOptions, S as RuntimeMutationDefaultGenerator, T as SqlExecutionStackWithDriver, U as extractCodecIds, V as SqlMiddlewareContext, W as validateCodecRegistryCompleteness, _ as ensureSchemaStatement, a as CreateRuntimeOptions, b as writeContractMarker, c as RuntimeQueryable, d as RuntimeVerifyOptions, f as TelemetryOutcome, g as SqlStatement, h as withTransaction, i as MiddlewareContext, j as SqlRuntimeTargetDescriptor, k as SqlRuntimeExtensionDescriptor, l as RuntimeTelemetryEvent, m as createRuntime, n as Log, o as Runtime, p as TransactionContext, r as Middleware, s as RuntimeConnection, t as AfterExecuteResult, u as RuntimeTransaction, v as ensureTableStatement, w as SqlExecutionStack, x as ExecutionContext, y as readContractMarker, z as budgets } from "./index-yb51L_1h.mjs";
2
- export { AfterExecuteResult, BudgetsOptions, CreateRuntimeOptions, ExecutionContext, LintsOptions, Log, Middleware, MiddlewareContext, Runtime, RuntimeConnection, RuntimeMutationDefaultGenerator, RuntimeParameterizedCodecDescriptor, RuntimeQueryable, RuntimeTelemetryEvent, RuntimeTransaction, RuntimeVerifyOptions, SqlExecutionStack, SqlExecutionStackWithDriver, SqlMiddleware, SqlMiddlewareContext, SqlRuntimeAdapterDescriptor, SqlRuntimeAdapterInstance, SqlRuntimeDriverInstance, SqlRuntimeExtensionDescriptor, SqlRuntimeExtensionInstance, SqlRuntimeTargetDescriptor, SqlStatement, SqlStaticContributions, TelemetryOutcome, TransactionContext, TypeHelperRegistry, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
1
+ import { A as SqlStaticContributions, B as lints, C as SqlExecutionStackWithDriver, D as SqlRuntimeExtensionDescriptor, E as SqlRuntimeDriverInstance, F as RuntimeFamilyAdapter, G as parseContractMarkerRow, H as budgets, I as RuntimeTelemetryEvent, J as validateCodecRegistryCompleteness, K as lowerSqlPlan, L as RuntimeVerifyOptions, M as createExecutionContext, N as createSqlExecutionStack, O as SqlRuntimeExtensionInstance, P as MarkerReader, R as TelemetryOutcome, S as SqlExecutionStack, T as SqlRuntimeAdapterInstance, U as SqlMiddleware, V as BudgetsOptions, W as SqlMiddlewareContext, Y as validateContractCodecMappings, _ as writeContractMarker, a as Runtime, b as RuntimeMutationDefaultGenerator, c as RuntimeTransaction, d as withTransaction, f as APP_SPACE_ID, g as readContractMarker, h as ensureTableStatement, i as CreateRuntimeOptions, j as TypeHelperRegistry, k as SqlRuntimeTargetDescriptor, l as TransactionContext, m as ensureSchemaStatement, n as Log, o as RuntimeConnection, p as SqlStatement, q as extractCodecIds, r as MarkerStatement, s as RuntimeQueryable, t as AfterExecuteResult, u as createRuntime, v as ExecutionContext, w as SqlRuntimeAdapterDescriptor, x as RuntimeParameterizedCodecDescriptor, y as GeneratorStability, z as LintsOptions } from "./index-C4Dz0JKE.mjs";
2
+ export { APP_SPACE_ID, AfterExecuteResult, BudgetsOptions, CreateRuntimeOptions, ExecutionContext, GeneratorStability, LintsOptions, Log, MarkerReader, MarkerStatement, Runtime, RuntimeConnection, RuntimeFamilyAdapter, RuntimeMutationDefaultGenerator, RuntimeParameterizedCodecDescriptor, RuntimeQueryable, RuntimeTelemetryEvent, RuntimeTransaction, RuntimeVerifyOptions, SqlExecutionStack, SqlExecutionStackWithDriver, SqlMiddleware, SqlMiddlewareContext, SqlRuntimeAdapterDescriptor, SqlRuntimeAdapterInstance, SqlRuntimeDriverInstance, SqlRuntimeExtensionDescriptor, SqlRuntimeExtensionInstance, SqlRuntimeTargetDescriptor, SqlStatement, SqlStaticContributions, TelemetryOutcome, TransactionContext, TypeHelperRegistry, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
package/dist/index.mjs CHANGED
@@ -1,3 +1,2 @@
1
- import { a as readContractMarker, c as createSqlExecutionStack, d as lowerSqlPlan, f as extractCodecIds, i as ensureTableStatement, l as lints, m as validateContractCodecMappings, n as withTransaction, o as writeContractMarker, p as validateCodecRegistryCompleteness, r as ensureSchemaStatement, s as createExecutionContext, t as createRuntime, u as budgets } from "./exports-BQZSVXXt.mjs";
2
-
3
- export { budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
1
+ import { a as ensureTableStatement, c as createExecutionContext, d as budgets, f as parseContractMarkerRow, g as validateContractCodecMappings, h as validateCodecRegistryCompleteness, i as ensureSchemaStatement, l as createSqlExecutionStack, m as extractCodecIds, n as withTransaction, o as readContractMarker, p as lowerSqlPlan, r as APP_SPACE_ID, s as writeContractMarker, t as createRuntime, u as lints } from "./exports-CXtbKm5q.mjs";
2
+ export { APP_SPACE_ID, budgets, createExecutionContext, createRuntime, createSqlExecutionStack, ensureSchemaStatement, ensureTableStatement, extractCodecIds, lints, lowerSqlPlan, parseContractMarkerRow, readContractMarker, validateCodecRegistryCompleteness, validateContractCodecMappings, withTransaction, writeContractMarker };
@@ -1,77 +1,82 @@
1
- import { A as SqlRuntimeExtensionInstance, D as SqlRuntimeAdapterInstance, E as SqlRuntimeAdapterDescriptor, O as SqlRuntimeDriverInstance, g as SqlStatement, j as SqlRuntimeTargetDescriptor, k as SqlRuntimeExtensionDescriptor, m as createRuntime, x as ExecutionContext } from "../index-yb51L_1h.mjs";
2
- import { Adapter, LoweredStatement, SelectAst } from "@prisma-next/sql-relational-core/ast";
3
- import * as _prisma_next_framework_components_execution0 from "@prisma-next/framework-components/execution";
1
+ import { D as SqlRuntimeExtensionDescriptor, E as SqlRuntimeDriverInstance, O as SqlRuntimeExtensionInstance, T as SqlRuntimeAdapterInstance, k as SqlRuntimeTargetDescriptor, p as SqlStatement, u as createRuntime, v as ExecutionContext, w as SqlRuntimeAdapterDescriptor } from "../index-C4Dz0JKE.mjs";
2
+ import { ResultType } from "@prisma-next/framework-components/runtime";
3
+ import { Adapter, Codec, ContractCodecRegistry, LoweredStatement, SelectAst } from "@prisma-next/sql-relational-core/ast";
4
+ import * as _$_prisma_next_framework_components_execution0 from "@prisma-next/framework-components/execution";
4
5
  import { RuntimeDriverDescriptor } from "@prisma-next/framework-components/execution";
5
- import { Contract, ExecutionPlan, ResultType } from "@prisma-next/contract/types";
6
+ import { Contract } from "@prisma-next/contract/types";
7
+ import { CodecDescriptor } from "@prisma-next/framework-components/codec";
6
8
  import { DevDatabase, collectAsync, createDevDatabase, teardownTestDatabase, withClient } from "@prisma-next/test-utils";
7
9
  import { SqlStorage } from "@prisma-next/sql-contract/types";
8
- import { SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
10
+ import { SqlExecutionPlan, SqlQueryPlan } from "@prisma-next/sql-relational-core/plan";
9
11
  import { Client } from "pg";
10
12
 
11
13
  //#region test/utils.d.ts
12
-
13
14
  /**
14
- * Executes a plan and collects all results into an array.
15
- * This helper DRYs up the common pattern of executing plans in tests.
16
- * The return type is inferred from the plan's type parameter.
15
+ * Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.
17
16
  */
18
- declare function executePlanAndCollect<P extends ExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]>;
17
+ declare function executePlanAndCollect<P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]>;
19
18
  /**
20
- * Drains a plan execution, consuming all results without collecting them.
21
- * Useful for testing side effects without memory overhead.
19
+ * Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.
22
20
  */
23
- declare function drainPlanExecution(runtime: ReturnType<typeof createRuntime>, plan: ExecutionPlan | SqlQueryPlan<unknown>): Promise<void>;
21
+ declare function drainPlanExecution(runtime: ReturnType<typeof createRuntime>, plan: SqlExecutionPlan | SqlQueryPlan<unknown>): Promise<void>;
24
22
  /**
25
23
  * Executes a SQL statement on a database client.
26
24
  */
27
25
  declare function executeStatement(client: Client, statement: SqlStatement): Promise<void>;
28
26
  /**
29
- * Sets up database schema and data, then writes the contract marker.
30
- * This helper DRYs up the common pattern of database setup in tests.
27
+ * Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.
31
28
  */
32
29
  declare function setupTestDatabase(client: Client, contract: Contract<SqlStorage>, setupFn: (client: Client) => Promise<void>): Promise<void>;
33
30
  /**
34
- * Writes a contract marker to the database.
35
- * This helper DRYs up the common pattern of writing contract markers in tests.
31
+ * Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.
36
32
  */
37
33
  declare function writeTestContractMarker(client: Client, contract: Contract<SqlStorage>): Promise<void>;
38
34
  /**
39
- * Creates a test adapter descriptor from a raw adapter.
40
- * Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions
41
- * derived from the adapter's codec registry.
35
+ * Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.
36
+ */
37
+ /**
38
+ * Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.
42
39
  */
43
- declare function createTestAdapterDescriptor(adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>): SqlRuntimeAdapterDescriptor<'postgres'>;
40
+ declare function buildTestContractCodecs(codecs: ReadonlyArray<Codec<string>>): ContractCodecRegistry;
41
+ /**
42
+ * Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry
43
+ * `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.
44
+ */
45
+ declare function descriptorsFromCodecs(codecs: ReadonlyArray<Codec<string>>): ReadonlyArray<CodecDescriptor>;
46
+ declare function createTestAdapterDescriptor(adapter: StubAdapter): SqlRuntimeAdapterDescriptor<'postgres'>;
44
47
  /**
45
48
  * Creates a test target descriptor with empty static contributions.
46
49
  */
47
50
  declare function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'>;
48
51
  /**
49
- * Creates an ExecutionContext for testing.
50
- * This helper DRYs up the common pattern of context creation in tests.
52
+ * Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.
51
53
  *
52
- * Accepts a raw adapter and optional extension descriptors, wrapping the
53
- * adapter in a descriptor internally for descriptor-first context creation.
54
+ * Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.
54
55
  */
55
- declare function createTestContext<TContract extends Contract<SqlStorage>>(contract: TContract, adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>, options?: {
56
+ declare function createTestContext<TContract extends Contract<SqlStorage>>(contract: TContract, adapter: StubAdapter, options?: {
56
57
  extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;
57
58
  }): ExecutionContext<TContract>;
58
59
  declare function createTestStackInstance(options?: {
59
60
  extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;
60
61
  driver?: RuntimeDriverDescriptor<'sql', 'postgres', unknown, SqlRuntimeDriverInstance<'postgres'>>;
61
- }): _prisma_next_framework_components_execution0.ExecutionStackInstance<"sql", "postgres", SqlRuntimeAdapterInstance<"postgres">, SqlRuntimeDriverInstance<"postgres">, SqlRuntimeExtensionInstance<"postgres">>;
62
+ }): _$_prisma_next_framework_components_execution0.ExecutionStackInstance<"sql", "postgres", SqlRuntimeAdapterInstance<"postgres">, SqlRuntimeDriverInstance<"postgres">, SqlRuntimeExtensionInstance<"postgres">>;
63
+ /**
64
+ * Stub-adapter type augments the public {@link Adapter} surface with a `__codecs` slot that exposes the test stub's runtime codec set to descriptor-shaping helpers (`createTestAdapterDescriptor`). Production adapters do not declare this slot — runtime codecs flow through the descriptor list from `SqlRuntimeAdapterDescriptor.codecs()` — so the augmentation is intentionally test-only.
65
+ */
66
+ type StubAdapter = Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> & {
67
+ readonly __codecs: ReadonlyArray<Codec<string>>;
68
+ };
62
69
  /**
63
- * Creates a stub adapter for testing.
64
- * This helper DRYs up the common pattern of adapter creation in tests.
70
+ * Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.
65
71
  *
66
- * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1)
67
- * to enable type inference in tests without requiring the postgres adapter package.
72
+ * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.
68
73
  */
69
- declare function createStubAdapter(): Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>;
74
+ declare function createStubAdapter(): StubAdapter;
70
75
  declare function createTestContract(contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {
71
76
  storageHash?: string;
72
77
  profileHash?: string;
73
78
  storage?: Omit<SqlStorage, 'storageHash'>;
74
79
  }): Contract<SqlStorage>;
75
80
  //#endregion
76
- export { type DevDatabase, collectAsync, createDevDatabase, createStubAdapter, createTestAdapterDescriptor, createTestContext, createTestContract, createTestStackInstance, createTestTargetDescriptor, drainPlanExecution, executePlanAndCollect, executeStatement, setupTestDatabase, teardownTestDatabase, withClient, writeTestContractMarker };
81
+ export { type DevDatabase, StubAdapter, buildTestContractCodecs, collectAsync, createDevDatabase, createStubAdapter, createTestAdapterDescriptor, createTestContext, createTestContract, createTestStackInstance, createTestTargetDescriptor, descriptorsFromCodecs, drainPlanExecution, executePlanAndCollect, executeStatement, setupTestDatabase, teardownTestDatabase, withClient, writeTestContractMarker };
77
82
  //# sourceMappingURL=utils.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../../test/utils.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;AA4CA;;;AACY,iBADU,qBACV,CAAA,UAAA,aAAA,CAAc,UAAd,CAAyB,CAAzB,CAAA,CAAA,GAA+B,YAA/B,CAA4C,UAA5C,CAAuD,CAAvD,CAAA,CAAA,CAAA,CAAA,OAAA,EACD,UADC,CAAA,OACiB,aADjB,CAAA,EAAA,IAAA,EACuC,CADvC,CAAA,EAC2C,OAD3C,CACmD,UADnD,CAC8D,CAD9D,CAAA,EAAA,CAAA;;;;;AACD,iBASW,kBAAA,CATX,OAAA,EAUA,UAVA,CAAA,OAUkB,aAVlB,CAAA,EAAA,IAAA,EAWH,aAXG,GAWa,YAXb,CAAA,OAAA,CAAA,CAAA,EAYR,OAZQ,CAAA,IAAA,CAAA;;;;AAA4C,iBAmBjC,gBAAA,CAnBiC,MAAA,EAmBR,MAnBQ,EAAA,SAAA,EAmBW,YAnBX,CAAA,EAmB0B,OAnB1B,CAAA,IAAA,CAAA;;AASvD;;;AAEQ,iBAqBc,iBAAA,CArBd,MAAA,EAsBE,MAtBF,EA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;iBAqBmB,uBAAA,CACpB,MAAA,EAAQ,MAAA,EACR,QAAA,EAAU,QAAA,CAAS,UAAA,IAClB,OAAA;;;;;;;iBAiBa,uBAAA,CACd,MAAA,EAAQ,aAAA,CAAc,KAAA,YACrB,qBAAA;;;;;iBAea,qBAAA,CACd,MAAA,EAAQ,aAAA,CAAc,KAAA,YACrB,aAAA,CAAc,eAAA;AAAA,iBAqBD,2BAAA,CACd,OAAA,EAAS,WAAA,GACR,2BAAA;;;;iBAmBa,0BAAA,CAAA,GAA8B,0BAAA;;;;;;iBAmB9B,iBAAA,mBAAoC,QAAA,CAAS,UAAA,EAAA,CAC3D,QAAA,EAAU,SAAA,EACV,OAAA,EAAS,WAAA,EACT,OAAA;EACE,cAAA,GAAiB,aAAA,CAAc,6BAAA;AAAA,IAEhC,gBAAA,CAAiB,SAAA;AAAA,iBAWJ,uBAAA,CAAwB,OAAA;EACtC,cAAA,GAAiB,aAAA,CAAc,6BAAA;EAC/B,MAAA,GAAS,uBAAA,6BAIP,wBAAA;AAAA,IAEH,8CAAA,CAAA,sBAAA,oBAAA,yBAAA,cAAA,wBAAA,cAAA,2BAAA;;;;KAcW,WAAA,GAAc,OAAA,CAAQ,SAAA,EAAW,QAAA,CAAS,UAAA,GAAa,gBAAA;EAAA,SACxD,QAAA,EAAU,aAAA,CAAc,KAAA;AAAA;AAjLnC;;;;;AAAA,iBAyLgB,iBAAA,CAAA,GAAqB,WAAA;AAAA,iBAkDrB,kBAAA,CACd,QAAA,EAAU,OAAA,CAAQ,IAAA,CAAK,QAAA,CAAS,UAAA;EAC9B,WAAA;EACA,WAAA;EACA,OAAA,GAAU,IAAA,CAAK,UAAA;AAAA,IAEhB,QAAA,CAAS,UAAA"}
@@ -1,11 +1,37 @@
1
- import { c as createSqlExecutionStack, i as ensureTableStatement, o as writeContractMarker, r as ensureSchemaStatement, s as createExecutionContext } from "../exports-BQZSVXXt.mjs";
2
- import { codec, createCodecRegistry } from "@prisma-next/sql-relational-core/ast";
1
+ import { a as ensureTableStatement, c as createExecutionContext, f as parseContractMarkerRow, i as ensureSchemaStatement, l as createSqlExecutionStack, r as APP_SPACE_ID, s as writeContractMarker } from "../exports-CXtbKm5q.mjs";
3
2
  import { instantiateExecutionStack } from "@prisma-next/framework-components/execution";
4
3
  import { coreHash, profileHash } from "@prisma-next/contract/types";
4
+ import { voidParamsSchema } from "@prisma-next/framework-components/codec";
5
5
  import { builtinGeneratorIds } from "@prisma-next/ids";
6
6
  import { generateId } from "@prisma-next/ids/runtime";
7
7
  import { collectAsync, collectAsync as collectAsync$1, createDevDatabase, drainAsyncIterable, teardownTestDatabase, withClient } from "@prisma-next/test-utils";
8
-
8
+ //#region test/test-codec.ts
9
+ function defineTestCodec(config) {
10
+ const identity = (v) => v;
11
+ const userEncode = config.encode;
12
+ const userDecode = config.decode;
13
+ const widenedConfig = config;
14
+ return {
15
+ id: config.typeId,
16
+ encode: (value, ctx) => {
17
+ try {
18
+ return Promise.resolve(userEncode(value, ctx));
19
+ } catch (error) {
20
+ return Promise.reject(error);
21
+ }
22
+ },
23
+ decode: (wire, ctx) => {
24
+ try {
25
+ return Promise.resolve(userDecode(wire, ctx));
26
+ } catch (error) {
27
+ return Promise.reject(error);
28
+ }
29
+ },
30
+ encodeJson: widenedConfig.encodeJson ?? identity,
31
+ decodeJson: widenedConfig.decodeJson ?? identity
32
+ };
33
+ }
34
+ //#endregion
9
35
  //#region test/utils.ts
10
36
  function createTestMutationDefaultGenerators() {
11
37
  return builtinGeneratorIds.map((id) => ({
@@ -13,20 +39,18 @@ function createTestMutationDefaultGenerators() {
13
39
  generate: (params) => generateId(params ? {
14
40
  id,
15
41
  params
16
- } : { id })
42
+ } : { id }),
43
+ stability: "field"
17
44
  }));
18
45
  }
19
46
  /**
20
- * Executes a plan and collects all results into an array.
21
- * This helper DRYs up the common pattern of executing plans in tests.
22
- * The return type is inferred from the plan's type parameter.
47
+ * Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.
23
48
  */
24
49
  async function executePlanAndCollect(runtime, plan) {
25
50
  return collectAsync$1(runtime.execute(plan));
26
51
  }
27
52
  /**
28
- * Drains a plan execution, consuming all results without collecting them.
29
- * Useful for testing side effects without memory overhead.
53
+ * Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.
30
54
  */
31
55
  async function drainPlanExecution(runtime, plan) {
32
56
  return drainAsyncIterable(runtime.execute(plan));
@@ -42,8 +66,7 @@ async function executeStatement(client, statement) {
42
66
  await client.query(statement.sql);
43
67
  }
44
68
  /**
45
- * Sets up database schema and data, then writes the contract marker.
46
- * This helper DRYs up the common pattern of database setup in tests.
69
+ * Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.
47
70
  */
48
71
  async function setupTestDatabase(client, contract, setupFn) {
49
72
  await client.query("drop schema if exists prisma_contract cascade");
@@ -52,6 +75,7 @@ async function setupTestDatabase(client, contract, setupFn) {
52
75
  await executeStatement(client, ensureSchemaStatement);
53
76
  await executeStatement(client, ensureTableStatement);
54
77
  await executeStatement(client, writeContractMarker({
78
+ space: APP_SPACE_ID,
55
79
  storageHash: contract.storage.storageHash,
56
80
  profileHash: contract.profileHash,
57
81
  contractJson: contract,
@@ -59,11 +83,11 @@ async function setupTestDatabase(client, contract, setupFn) {
59
83
  }).insert);
60
84
  }
61
85
  /**
62
- * Writes a contract marker to the database.
63
- * This helper DRYs up the common pattern of writing contract markers in tests.
86
+ * Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.
64
87
  */
65
88
  async function writeTestContractMarker(client, contract) {
66
89
  await executeStatement(client, writeContractMarker({
90
+ space: APP_SPACE_ID,
67
91
  storageHash: contract.storage.storageHash,
68
92
  profileHash: contract.profileHash,
69
93
  contractJson: contract,
@@ -71,20 +95,48 @@ async function writeTestContractMarker(client, contract) {
71
95
  }).insert);
72
96
  }
73
97
  /**
74
- * Creates a test adapter descriptor from a raw adapter.
75
- * Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions
76
- * derived from the adapter's codec registry.
98
+ * Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.
99
+ */
100
+ /**
101
+ * Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.
102
+ */
103
+ function buildTestContractCodecs(codecs) {
104
+ const byId = /* @__PURE__ */ new Map();
105
+ for (const codec of codecs) byId.set(codec.id, codec);
106
+ return {
107
+ forColumn: () => void 0,
108
+ forCodecId: (codecId) => byId.get(codecId)
109
+ };
110
+ }
111
+ /**
112
+ * Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry
113
+ * `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.
77
114
  */
115
+ function descriptorsFromCodecs(codecs) {
116
+ const descriptors = [];
117
+ for (const instance of codecs) {
118
+ const legacy = instance;
119
+ descriptors.push({
120
+ codecId: instance.id,
121
+ traits: legacy.traits ?? [],
122
+ targetTypes: legacy.targetTypes ?? [],
123
+ paramsSchema: voidParamsSchema,
124
+ isParameterized: false,
125
+ factory: () => () => instance,
126
+ ...legacy.meta !== void 0 ? { meta: legacy.meta } : {}
127
+ });
128
+ }
129
+ return descriptors;
130
+ }
78
131
  function createTestAdapterDescriptor(adapter) {
79
- const codecRegistry = adapter.profile.codecs();
132
+ const descriptors = descriptorsFromCodecs(adapter.__codecs);
80
133
  return {
81
134
  kind: "adapter",
82
135
  id: "test-adapter",
83
136
  version: "0.0.1",
84
137
  familyId: "sql",
85
138
  targetId: "postgres",
86
- codecs: () => codecRegistry,
87
- parameterizedCodecs: () => [],
139
+ codecs: () => descriptors,
88
140
  mutationDefaultGenerators: createTestMutationDefaultGenerators,
89
141
  create(_stack) {
90
142
  return Object.assign({
@@ -104,8 +156,7 @@ function createTestTargetDescriptor() {
104
156
  version: "0.0.1",
105
157
  familyId: "sql",
106
158
  targetId: "postgres",
107
- codecs: () => createCodecRegistry(),
108
- parameterizedCodecs: () => [],
159
+ codecs: () => [],
109
160
  create() {
110
161
  return {
111
162
  familyId: "sql",
@@ -115,11 +166,9 @@ function createTestTargetDescriptor() {
115
166
  };
116
167
  }
117
168
  /**
118
- * Creates an ExecutionContext for testing.
119
- * This helper DRYs up the common pattern of context creation in tests.
169
+ * Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.
120
170
  *
121
- * Accepts a raw adapter and optional extension descriptors, wrapping the
122
- * adapter in a descriptor internally for descriptor-first context creation.
171
+ * Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.
123
172
  */
124
173
  function createTestContext(contract, adapter, options) {
125
174
  return createExecutionContext({
@@ -140,46 +189,48 @@ function createTestStackInstance(options) {
140
189
  }));
141
190
  }
142
191
  /**
143
- * Creates a stub adapter for testing.
144
- * This helper DRYs up the common pattern of adapter creation in tests.
192
+ * Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.
145
193
  *
146
- * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1)
147
- * to enable type inference in tests without requiring the postgres adapter package.
194
+ * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.
148
195
  */
149
196
  function createStubAdapter() {
150
- const codecRegistry = createCodecRegistry();
151
- codecRegistry.register(codec({
152
- typeId: "pg/int4@1",
153
- targetTypes: ["int4"],
154
- encode: (value) => value,
155
- decode: (wire) => wire
156
- }));
157
- codecRegistry.register(codec({
158
- typeId: "pg/text@1",
159
- targetTypes: ["text"],
160
- encode: (value) => value,
161
- decode: (wire) => wire
162
- }));
163
- codecRegistry.register(codec({
164
- typeId: "pg/timestamptz@1",
165
- targetTypes: ["timestamptz"],
166
- encode: (value) => value instanceof Date ? value.toISOString() : value,
167
- decode: (wire) => wire instanceof Date ? wire : new Date(wire)
168
- }));
169
197
  return {
198
+ __codecs: [
199
+ defineTestCodec({
200
+ typeId: "pg/int4@1",
201
+ targetTypes: ["int4"],
202
+ encode: (value) => value,
203
+ decode: (wire) => wire
204
+ }),
205
+ defineTestCodec({
206
+ typeId: "pg/text@1",
207
+ targetTypes: ["text"],
208
+ encode: (value) => value,
209
+ decode: (wire) => wire
210
+ }),
211
+ defineTestCodec({
212
+ typeId: "pg/timestamptz@1",
213
+ targetTypes: ["timestamptz"],
214
+ encode: (value) => value,
215
+ decode: (wire) => wire,
216
+ encodeJson: (value) => value.toISOString(),
217
+ decodeJson: (json) => {
218
+ if (typeof json !== "string") throw new Error("expected ISO date string");
219
+ return new Date(json);
220
+ }
221
+ })
222
+ ],
170
223
  profile: {
171
224
  id: "stub-profile",
172
225
  target: "postgres",
173
226
  capabilities: {},
174
- codecs() {
175
- return codecRegistry;
176
- },
177
227
  readMarkerStatement() {
178
228
  return {
179
- sql: "select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta from prisma_contract.marker where id = $1",
180
- params: [1]
229
+ sql: "select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta, invariants from prisma_contract.marker where space = $1",
230
+ params: ["app"]
181
231
  };
182
- }
232
+ },
233
+ parseMarkerRow: parseContractMarkerRow
183
234
  },
184
235
  lower(ast, ctx) {
185
236
  const sqlText = JSON.stringify(ast);
@@ -212,7 +263,7 @@ function createTestContract(contract) {
212
263
  profileHash: profileHash(rest["profileHash"] ?? "sha256:testprofile")
213
264
  };
214
265
  }
215
-
216
266
  //#endregion
217
- export { collectAsync, createDevDatabase, createStubAdapter, createTestAdapterDescriptor, createTestContext, createTestContract, createTestStackInstance, createTestTargetDescriptor, drainPlanExecution, executePlanAndCollect, executeStatement, setupTestDatabase, teardownTestDatabase, withClient, writeTestContractMarker };
267
+ export { buildTestContractCodecs, collectAsync, createDevDatabase, createStubAdapter, createTestAdapterDescriptor, createTestContext, createTestContract, createTestStackInstance, createTestTargetDescriptor, descriptorsFromCodecs, drainPlanExecution, executePlanAndCollect, executeStatement, setupTestDatabase, teardownTestDatabase, withClient, writeTestContractMarker };
268
+
218
269
  //# sourceMappingURL=utils.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":["collectAsync"],"sources":["../../test/utils.ts"],"sourcesContent":["import type { Contract, ExecutionPlan, ResultType } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Adapter, LoweredStatement, SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport { codec, createCodecRegistry } from '@prisma-next/sql-relational-core/ast';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array.\n * This helper DRYs up the common pattern of executing plans in tests.\n * The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends ExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them.\n * Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: ExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker.\n * This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database.\n * This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter.\n * Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions\n * derived from the adapter's codec registry.\n */\nexport function createTestAdapterDescriptor(\n adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const codecRegistry = adapter.profile.codecs();\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => codecRegistry,\n parameterizedCodecs: () => [],\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => createCodecRegistry(),\n parameterizedCodecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing.\n * This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the\n * adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement>,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Creates a stub adapter for testing.\n * This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1)\n * to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> {\n const codecRegistry = createCodecRegistry();\n\n // Register stub codecs for common test types\n // These match the codec IDs used in test contracts (pg/int4@1, pg/text@1, pg/timestamptz@1)\n // but don't require importing from the postgres adapter package\n codecRegistry.register(\n codec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n );\n\n codecRegistry.register(\n codec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n );\n\n codecRegistry.register(\n codec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: string | Date) => (value instanceof Date ? value.toISOString() : value),\n decode: (wire: string | Date) => (wire instanceof Date ? wire : new Date(wire)),\n }),\n );\n\n return {\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n codecs() {\n return codecRegistry;\n },\n readMarkerStatement() {\n return {\n sql: 'select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta from prisma_contract.marker where id = $1',\n params: [1],\n };\n },\n },\n lower(ast: SelectAst, ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n return Object.freeze({ sql: sqlText, params: ctx.params ? [...ctx.params] : [] });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorage, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? { ...rest['storage'], storageHash: storageHashValue }\n : { storageHash: storageHashValue, tables: {} },\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;;AAgCA,SAAS,sCAAsC;AAC7C,QAAO,oBAAoB,KAAK,QAAQ;EACtC;EACA,WAAW,WAAqC,WAAW,SAAS;GAAE;GAAI;GAAQ,GAAG,EAAE,IAAI,CAAC;EAC7F,EAAE;;;;;;;AAQL,eAAsB,sBAEpB,SAA2C,MAAmC;AAE9E,QAAOA,eAAkB,QAAQ,QAAa,KAAK,CAAC;;;;;;AAOtD,eAAsB,mBACpB,SACA,MACe;AACf,QAAO,mBAAmB,QAAQ,QAAQ,KAAK,CAAC;;;;;AAMlD,eAAsB,iBAAiB,QAAgB,WAAwC;AAC7F,KAAI,UAAU,OAAO,SAAS,GAAG;AAC/B,QAAM,OAAO,MAAM,UAAU,KAAK,CAAC,GAAG,UAAU,OAAO,CAAC;AACxD;;AAGF,OAAM,OAAO,MAAM,UAAU,IAAI;;;;;;AAOnC,eAAsB,kBACpB,QACA,UACA,SACe;AACf,OAAM,OAAO,MAAM,gDAAgD;AACnE,OAAM,OAAO,MAAM,qCAAqC;AAExD,OAAM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gB,KAAK,qBAAqB,EAAE;EAC5C,MAAM,KAAK,WAAW,EAAE;EACxB,GAAI,YAAY,EAAE,WAAW,GAAG,EAAE;EAClC,aAAa,YAAY,KAAK,kBAAkB,qBAAqB;EACtE"}
1
+ {"version":3,"file":"utils.mjs","names":["collectAsync"],"sources":["../../test/test-codec.ts","../../test/utils.ts"],"sourcesContent":["/**\n * Test-only helper that constructs a SQL-family `Codec` instance from author-side encode/decode functions. Replaces the legacy public `mkCodec()` factory (deleted under TML-2357); tests that need a stub codec for behavioural assertions instantiate one through this helper rather than going through `descriptor.factory(...)`.\n *\n * The body is identical in spirit to the retired `mkCodec`: promise-lift sync author functions onto the framework-required `Promise<…>` boundary, default `encodeJson`/`decodeJson` to identity when `TInput` is JSON-safe, fail loudly otherwise.\n */\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { CodecTrait } from '@prisma-next/framework-components/codec';\nimport type { Codec, SqlCodecCallContext } from '@prisma-next/sql-relational-core/ast';\n\ntype JsonRoundTripConfig<TInput> = [TInput] extends [JsonValue]\n ? {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n }\n : {\n encodeJson: (value: TInput) => JsonValue;\n decodeJson: (json: JsonValue) => TInput;\n };\n\nexport function defineTestCodec<\n Id extends string,\n const TTraits extends readonly CodecTrait[] = readonly [],\n TWire = unknown,\n TInput = unknown,\n>(\n config: {\n typeId: Id;\n targetTypes?: readonly string[];\n encode: (value: TInput, ctx: SqlCodecCallContext) => TWire | Promise<TWire>;\n decode: (wire: TWire, ctx: SqlCodecCallContext) => TInput | Promise<TInput>;\n traits?: TTraits;\n } & JsonRoundTripConfig<TInput>,\n): Codec<Id, TTraits, TWire, TInput> {\n const identity = (v: unknown) => v;\n const userEncode = config.encode;\n const userDecode = config.decode;\n const widenedConfig = config as {\n encodeJson?: (value: TInput) => JsonValue;\n decodeJson?: (json: JsonValue) => TInput;\n };\n return {\n id: config.typeId,\n encode: (value, ctx) => {\n try {\n return Promise.resolve(userEncode(value, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n decode: (wire, ctx) => {\n try {\n return Promise.resolve(userDecode(wire, ctx));\n } catch (error) {\n return Promise.reject(error);\n }\n },\n encodeJson: (widenedConfig.encodeJson ?? identity) as (value: TInput) => JsonValue,\n decodeJson: (widenedConfig.decodeJson ?? identity) as (json: JsonValue) => TInput,\n } as Codec<Id, TTraits, TWire, TInput>;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { coreHash, profileHash } from '@prisma-next/contract/types';\nimport type {\n CodecDescriptor,\n CodecMeta,\n CodecTrait,\n} from '@prisma-next/framework-components/codec';\nimport { voidParamsSchema } from '@prisma-next/framework-components/codec';\nimport {\n instantiateExecutionStack,\n type RuntimeDriverDescriptor,\n} from '@prisma-next/framework-components/execution';\nimport type { ResultType } from '@prisma-next/framework-components/runtime';\nimport { builtinGeneratorIds } from '@prisma-next/ids';\nimport { generateId } from '@prisma-next/ids/runtime';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type {\n Adapter,\n Codec,\n ContractCodecRegistry,\n LoweredStatement,\n SelectAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport type { SqlExecutionPlan, SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { collectAsync, drainAsyncIterable } from '@prisma-next/test-utils';\nimport type { Client } from 'pg';\nimport type { SqlStatement } from '../src/exports';\nimport {\n APP_SPACE_ID,\n createExecutionContext,\n type createRuntime,\n createSqlExecutionStack,\n ensureSchemaStatement,\n ensureTableStatement,\n parseContractMarkerRow,\n writeContractMarker,\n} from '../src/exports';\nimport type {\n ExecutionContext,\n SqlRuntimeAdapterDescriptor,\n SqlRuntimeAdapterInstance,\n SqlRuntimeDriverInstance,\n SqlRuntimeExtensionDescriptor,\n SqlRuntimeTargetDescriptor,\n} from '../src/sql-context';\nimport { defineTestCodec } from './test-codec';\n\nfunction createTestMutationDefaultGenerators() {\n return builtinGeneratorIds.map((id) => ({\n id,\n generate: (params?: Record<string, unknown>) => generateId(params ? { id, params } : { id }),\n stability: 'field' as const,\n }));\n}\n\n/**\n * Executes a plan and collects all results into an array. This helper DRYs up the common pattern of executing plans in tests. The return type is inferred from the plan's type parameter.\n */\nexport async function executePlanAndCollect<\n P extends SqlExecutionPlan<ResultType<P>> | SqlQueryPlan<ResultType<P>>,\n>(runtime: ReturnType<typeof createRuntime>, plan: P): Promise<ResultType<P>[]> {\n type Row = ResultType<P>;\n return collectAsync<Row>(runtime.execute<Row>(plan));\n}\n\n/**\n * Drains a plan execution, consuming all results without collecting them. Useful for testing side effects without memory overhead.\n */\nexport async function drainPlanExecution(\n runtime: ReturnType<typeof createRuntime>,\n plan: SqlExecutionPlan | SqlQueryPlan<unknown>,\n): Promise<void> {\n return drainAsyncIterable(runtime.execute(plan));\n}\n\n/**\n * Executes a SQL statement on a database client.\n */\nexport async function executeStatement(client: Client, statement: SqlStatement): Promise<void> {\n if (statement.params.length > 0) {\n await client.query(statement.sql, [...statement.params]);\n return;\n }\n\n await client.query(statement.sql);\n}\n\n/**\n * Sets up database schema and data, then writes the contract marker. This helper DRYs up the common pattern of database setup in tests.\n */\nexport async function setupTestDatabase(\n client: Client,\n contract: Contract<SqlStorage>,\n setupFn: (client: Client) => Promise<void>,\n): Promise<void> {\n await client.query('drop schema if exists prisma_contract cascade');\n await client.query('create schema if not exists public');\n\n await setupFn(client);\n\n await executeStatement(client, ensureSchemaStatement);\n await executeStatement(client, ensureTableStatement);\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Writes a contract marker to the database. This helper DRYs up the common pattern of writing contract markers in tests.\n */\nexport async function writeTestContractMarker(\n client: Client,\n contract: Contract<SqlStorage>,\n): Promise<void> {\n const write = writeContractMarker({\n space: APP_SPACE_ID,\n storageHash: contract.storage.storageHash,\n profileHash: contract.profileHash,\n contractJson: contract,\n canonicalVersion: 1,\n });\n await executeStatement(client, write.insert);\n}\n\n/**\n * Creates a test adapter descriptor from a raw adapter. Wraps the adapter in an SqlRuntimeAdapterDescriptor with static contributions derived from the adapter's codec registry.\n */\n/**\n * Build a {@link ContractCodecRegistry} from a codec array for tests that exercise `encodeParam(s)` / `decodeRow` in isolation. The production runtime builds `ContractCodecRegistry` from contract walk + descriptor list and never goes through this helper; tests use it to wire a hand-built codec set into the surface those functions consume in production.\n */\nexport function buildTestContractCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ContractCodecRegistry {\n const byId = new Map<string, Codec<string>>();\n for (const codec of codecs) {\n byId.set(codec.id, codec);\n }\n return {\n forColumn: () => undefined,\n forCodecId: (codecId) => byId.get(codecId),\n };\n}\n\n/**\n * Synthesize `CodecDescriptor`s from a codec array of non-parameterized codec instances. Test-only: the production synthesis bridge was retired under TML-2357. Lets the existing `createTestAdapterDescriptor` pattern keep wrapping a stub `Adapter` (whose `__codecs` slot still exposes the codec set) into the descriptor-list shape that `SqlStaticContributions.codecs:` now expects. The `Codec` instances carry\n * `traits`/`targetTypes`/`meta` via the SQL family extension; the structural narrow reads those fields directly.\n */\nexport function descriptorsFromCodecs(\n codecs: ReadonlyArray<Codec<string>>,\n): ReadonlyArray<CodecDescriptor> {\n const descriptors: CodecDescriptor[] = [];\n for (const instance of codecs) {\n const legacy = instance as {\n readonly traits?: readonly CodecTrait[];\n readonly targetTypes?: readonly string[];\n readonly meta?: CodecMeta;\n };\n descriptors.push({\n codecId: instance.id,\n traits: legacy.traits ?? [],\n targetTypes: legacy.targetTypes ?? [],\n paramsSchema: voidParamsSchema,\n isParameterized: false,\n factory: () => () => instance,\n ...(legacy.meta !== undefined ? { meta: legacy.meta } : {}),\n });\n }\n return descriptors;\n}\n\nexport function createTestAdapterDescriptor(\n adapter: StubAdapter,\n): SqlRuntimeAdapterDescriptor<'postgres'> {\n const descriptors = descriptorsFromCodecs(adapter.__codecs);\n return {\n kind: 'adapter' as const,\n id: 'test-adapter',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => descriptors,\n mutationDefaultGenerators: createTestMutationDefaultGenerators,\n create(_stack): SqlRuntimeAdapterInstance<'postgres'> {\n return Object.assign({ familyId: 'sql' as const, targetId: 'postgres' as const }, adapter);\n },\n };\n}\n\n/**\n * Creates a test target descriptor with empty static contributions.\n */\nexport function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {\n return {\n kind: 'target' as const,\n id: 'postgres',\n version: '0.0.1',\n familyId: 'sql' as const,\n targetId: 'postgres' as const,\n codecs: () => [],\n create() {\n return { familyId: 'sql' as const, targetId: 'postgres' as const };\n },\n };\n}\n\n/**\n * Creates an ExecutionContext for testing. This helper DRYs up the common pattern of context creation in tests.\n *\n * Accepts a raw adapter and optional extension descriptors, wrapping the adapter in a descriptor internally for descriptor-first context creation.\n */\nexport function createTestContext<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n adapter: StubAdapter,\n options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n },\n): ExecutionContext<TContract> {\n return createExecutionContext({\n contract,\n stack: {\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(adapter),\n extensionPacks: options?.extensionPacks ?? [],\n },\n });\n}\n\nexport function createTestStackInstance(options?: {\n extensionPacks?: ReadonlyArray<SqlRuntimeExtensionDescriptor<'postgres'>>;\n driver?: RuntimeDriverDescriptor<\n 'sql',\n 'postgres',\n unknown,\n SqlRuntimeDriverInstance<'postgres'>\n >;\n}) {\n const stack = createSqlExecutionStack({\n target: createTestTargetDescriptor(),\n adapter: createTestAdapterDescriptor(createStubAdapter()),\n driver: options?.driver,\n extensionPacks: options?.extensionPacks ?? [],\n });\n\n return instantiateExecutionStack(stack);\n}\n\n/**\n * Stub-adapter type augments the public {@link Adapter} surface with a `__codecs` slot that exposes the test stub's runtime codec set to descriptor-shaping helpers (`createTestAdapterDescriptor`). Production adapters do not declare this slot — runtime codecs flow through the descriptor list from `SqlRuntimeAdapterDescriptor.codecs()` — so the augmentation is intentionally test-only.\n */\nexport type StubAdapter = Adapter<SelectAst, Contract<SqlStorage>, LoweredStatement> & {\n readonly __codecs: ReadonlyArray<Codec<string>>;\n};\n\n/**\n * Creates a stub adapter for testing. This helper DRYs up the common pattern of adapter creation in tests.\n *\n * The stub adapter includes simple codecs for common test types (pg/int4@1, pg/text@1, pg/timestamptz@1) to enable type inference in tests without requiring the postgres adapter package.\n */\nexport function createStubAdapter(): StubAdapter {\n // Stub codecs for common test types — match the codec IDs used in test contracts (pg/int4@1, pg/text@1, pg/timestamptz@1) without importing from the postgres adapter package.\n const codecs: ReadonlyArray<Codec<string>> = [\n defineTestCodec({\n typeId: 'pg/int4@1',\n targetTypes: ['int4'],\n encode: (value: number) => value,\n decode: (wire: number) => wire,\n }),\n defineTestCodec({\n typeId: 'pg/text@1',\n targetTypes: ['text'],\n encode: (value: string) => value,\n decode: (wire: string) => wire,\n }),\n defineTestCodec({\n typeId: 'pg/timestamptz@1',\n targetTypes: ['timestamptz'],\n encode: (value: Date) => value,\n decode: (wire: Date) => wire,\n // Date is not assignable to JsonValue, so the JSON round-trip pair must be supplied explicitly.\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') throw new Error('expected ISO date string');\n return new Date(json);\n },\n }),\n ];\n\n return {\n __codecs: codecs,\n profile: {\n id: 'stub-profile',\n target: 'postgres',\n capabilities: {},\n readMarkerStatement() {\n return {\n sql: 'select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta, invariants from prisma_contract.marker where space = $1',\n params: ['app'],\n };\n },\n parseMarkerRow: parseContractMarkerRow,\n },\n lower(ast: SelectAst, ctx: { contract: Contract<SqlStorage>; params?: readonly unknown[] }) {\n const sqlText = JSON.stringify(ast);\n return Object.freeze({ sql: sqlText, params: ctx.params ? [...ctx.params] : [] });\n },\n };\n}\n\nexport function createTestContract(\n contract: Partial<Omit<Contract<SqlStorage>, 'profileHash' | 'storage'>> & {\n storageHash?: string;\n profileHash?: string;\n storage?: Omit<SqlStorage, 'storageHash'>;\n },\n): Contract<SqlStorage> {\n const { execution, ...rest } = contract;\n const storageHashValue = coreHash(rest['storageHash'] ?? 'sha256:testcore');\n\n return {\n target: rest['target'] ?? 'postgres',\n targetFamily: rest['targetFamily'] ?? 'sql',\n storage: rest['storage']\n ? { ...rest['storage'], storageHash: storageHashValue }\n : { storageHash: storageHashValue, tables: {} },\n models: rest['models'] ?? {},\n roots: rest['roots'] ?? {},\n capabilities: rest['capabilities'] ?? {},\n extensionPacks: rest['extensionPacks'] ?? {},\n meta: rest['meta'] ?? {},\n ...(execution ? { execution } : {}),\n profileHash: profileHash(rest['profileHash'] ?? 'sha256:testprofile'),\n };\n}\n\n// Re-export generic utilities from test-utils\nexport {\n collectAsync,\n createDevDatabase,\n type DevDatabase,\n teardownTestDatabase,\n withClient,\n} from '@prisma-next/test-utils';\n"],"mappings":";;;;;;;;AAmBA,SAAgB,gBAMd,QAOmC;CACnC,MAAM,YAAY,MAAe;CACjC,MAAM,aAAa,OAAO;CAC1B,MAAM,aAAa,OAAO;CAC1B,MAAM,gBAAgB;CAItB,OAAO;EACL,IAAI,OAAO;EACX,SAAS,OAAO,QAAQ;GACtB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,OAAO,IAAI,CAAC;YACvC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGhC,SAAS,MAAM,QAAQ;GACrB,IAAI;IACF,OAAO,QAAQ,QAAQ,WAAW,MAAM,IAAI,CAAC;YACtC,OAAO;IACd,OAAO,QAAQ,OAAO,MAAM;;;EAGhC,YAAa,cAAc,cAAc;EACzC,YAAa,cAAc,cAAc;EAC1C;;;;ACXH,SAAS,sCAAsC;CAC7C,OAAO,oBAAoB,KAAK,QAAQ;EACtC;EACA,WAAW,WAAqC,WAAW,SAAS;GAAE;GAAI;GAAQ,GAAG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next/sql-runtime",
3
- "version": "0.5.0-dev.7",
3
+ "version": "0.5.0-dev.70",
4
+ "license": "Apache-2.0",
4
5
  "type": "module",
5
6
  "sideEffects": false,
6
7
  "description": "SQL runtime implementation for Prisma Next",
7
8
  "dependencies": {
8
- "arktype": "^2.1.26",
9
- "@prisma-next/contract": "0.5.0-dev.7",
10
- "@prisma-next/utils": "0.5.0-dev.7",
11
- "@prisma-next/framework-components": "0.5.0-dev.7",
12
- "@prisma-next/operations": "0.5.0-dev.7",
13
- "@prisma-next/ids": "0.5.0-dev.7",
14
- "@prisma-next/sql-contract": "0.5.0-dev.7",
15
- "@prisma-next/sql-operations": "0.5.0-dev.7",
16
- "@prisma-next/runtime-executor": "0.5.0-dev.7",
17
- "@prisma-next/sql-relational-core": "0.5.0-dev.7"
9
+ "arktype": "^2.1.29",
10
+ "@prisma-next/contract": "0.5.0-dev.70",
11
+ "@prisma-next/utils": "0.5.0-dev.70",
12
+ "@prisma-next/framework-components": "0.5.0-dev.70",
13
+ "@prisma-next/ids": "0.5.0-dev.70",
14
+ "@prisma-next/operations": "0.5.0-dev.70",
15
+ "@prisma-next/sql-relational-core": "0.5.0-dev.70",
16
+ "@prisma-next/sql-operations": "0.5.0-dev.70",
17
+ "@prisma-next/sql-contract": "0.5.0-dev.70"
18
18
  },
19
19
  "devDependencies": {
20
- "@types/pg": "8.16.0",
21
- "pg": "8.16.3",
22
- "tsdown": "0.18.4",
20
+ "@types/pg": "8.20.0",
21
+ "pg": "8.20.0",
22
+ "tsdown": "0.22.0",
23
23
  "typescript": "5.9.3",
24
- "vitest": "4.0.17",
25
- "@prisma-next/test-utils": "0.0.1",
24
+ "vitest": "4.1.5",
26
25
  "@prisma-next/tsconfig": "0.0.0",
27
- "@prisma-next/tsdown": "0.0.0"
26
+ "@prisma-next/tsdown": "0.0.0",
27
+ "@prisma-next/test-utils": "0.0.1"
28
28
  },
29
29
  "files": [
30
30
  "dist",
31
- "src",
32
- "test"
31
+ "src"
33
32
  ],
34
33
  "exports": {
35
34
  ".": "./dist/index.mjs",
@@ -0,0 +1,34 @@
1
+ import type { AnyFromSource, AnyQueryAst } from '@prisma-next/sql-relational-core/ast';
2
+
3
+ /**
4
+ * Build a map from query-local table aliases to their underlying source table names.
5
+ *
6
+ * Self-joins like `db.sql.post.as('p1').innerJoin(db.sql.post.as('p2'), …)` produce `ColumnRef`s whose `table` is the alias (`p1`, `p2`) — the SQL renderer needs the alias for `SELECT p1.id, …`. Codec dispatch keys `byColumn` by the underlying source table, so aliases must be resolved back to the source name for `forColumn(...)` to hit. Tables that already use their canonical name (no alias) are also entered so a single
7
+ * lookup works for both shapes.
8
+ */
9
+ function buildAliasMap(ast: AnyQueryAst): ReadonlyMap<string, string> {
10
+ const aliases = new Map<string, string>();
11
+ const recordSource = (source: AnyFromSource): void => {
12
+ if (source.kind === 'table-source') {
13
+ const key = source.alias ?? source.name;
14
+ aliases.set(key, source.name);
15
+ } else {
16
+ aliases.set(source.alias, source.alias);
17
+ }
18
+ };
19
+ if (ast.kind === 'select') {
20
+ recordSource(ast.from);
21
+ for (const join of ast.joins ?? []) {
22
+ recordSource(join.source);
23
+ }
24
+ } else {
25
+ recordSource(ast.table);
26
+ }
27
+ return aliases;
28
+ }
29
+
30
+ export function makeAliasResolver(ast: AnyQueryAst | undefined): (alias: string) => string {
31
+ if (!ast) return (alias) => alias;
32
+ const map = buildAliasMap(ast);
33
+ return (alias) => map.get(alias) ?? alias;
34
+ }