@prisma-next/adapter-postgres 0.1.0-dev.29 → 0.1.0-dev.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,9 +10,7 @@ PostgreSQL adapter for Prisma Next.
10
10
 
11
11
  ## Overview
12
12
 
13
- The PostgreSQL adapter implements the adapter SPI for PostgreSQL databases. It provides SQL lowering, capability discovery, codec definitions, and error mapping for PostgreSQL-specific behavior.
14
-
15
- This package is an extension pack that extends Prisma Next with PostgreSQL-specific capabilities. It includes a manifest declaring its capabilities and codec types, and provides the adapter implementation that lowers SQL ASTs to PostgreSQL dialect SQL.
13
+ The PostgreSQL adapter implements the adapter SPI for PostgreSQL databases. It provides SQL lowering, capability discovery, codec definitions, and error mapping for PostgreSQL-specific behavior. It also exports both control-plane and runtime-plane adapter descriptors for config wiring.
16
14
 
17
15
  ## Purpose
18
16
 
@@ -30,7 +28,7 @@ Provide PostgreSQL-specific adapter implementation, codecs, and capabilities. En
30
28
  - Wire format to JavaScript type decoding
31
29
  - JavaScript type to wire format encoding
32
30
  - **Codec Types**: Export TypeScript types for PostgreSQL codecs
33
- - **Extension Pack**: Provide manifest declaring capabilities and codec types
31
+ - **Descriptors**: Provide adapter descriptors declaring capabilities and codec type imports
34
32
 
35
33
  **Non-goals:**
36
34
  - Transport/pooling management (drivers)
@@ -42,8 +40,8 @@ Provide PostgreSQL-specific adapter implementation, codecs, and capabilities. En
42
40
  This package spans multiple planes:
43
41
 
44
42
  - **Shared plane** (`src/core/**`): Core adapter implementation, codecs, and types that can be imported by both migration and runtime planes
45
- - **Migration plane** (`src/exports/cli.ts`): CLI entry point that exports `AdapterDescriptor` for config files
46
- - **Runtime plane** (`src/exports/runtime.ts`): Runtime entry point for DB-connected commands (future)
43
+ - **Migration plane** (`src/exports/control.ts`): Control-plane entry point that exports the adapter descriptor for config files
44
+ - **Runtime plane** (`src/exports/runtime.ts`): Runtime-plane entry point that exports the runtime adapter descriptor
47
45
 
48
46
  ```mermaid
49
47
  flowchart TD
@@ -64,8 +62,9 @@ flowchart TD
64
62
  PG[(PostgreSQL)]
65
63
  end
66
64
 
67
- subgraph "Extension Pack"
68
- MANIFEST[Manifest]
65
+ subgraph "Descriptors"
66
+ CONTROL[Control Descriptor]
67
+ RUNTIME_DESC[Runtime Descriptor]
69
68
  CODECTYPES[Codec Types]
70
69
  end
71
70
 
@@ -76,7 +75,8 @@ flowchart TD
76
75
  ADAPTER --> CAPS
77
76
  ADAPTER --> DRIVER
78
77
  DRIVER --> PG
79
- MANIFEST --> RT
78
+ CONTROL --> RT
79
+ RUNTIME_DESC --> RT
80
80
  CODECTYPES --> RT
81
81
  CODECS --> CODECTYPES
82
82
  ```
@@ -105,14 +105,12 @@ flowchart TD
105
105
 
106
106
  ### Exports (`src/exports/`)
107
107
 
108
- **CLI Entry Point (`cli.ts`)**
109
- - Exports `AdapterDescriptor` for CLI config
110
- - Loads adapter manifest from `packs/manifest.json`
108
+ **Control Entry Point (`control.ts`)**
109
+ - Exports the control-plane adapter descriptor for CLI config
111
110
  - Used by `prisma-next.config.ts` to declare the adapter
112
111
 
113
112
  **Runtime Entry Point (`runtime.ts`)**
114
- - Placeholder for future DB-connected commands
115
- - Will export runtime factory functions
113
+ - Exports the runtime-plane adapter descriptor
116
114
 
117
115
  **Adapter Export (`adapter.ts`)**
118
116
  - Re-exports `createPostgresAdapter` from core
@@ -124,12 +122,6 @@ flowchart TD
124
122
  **Types Export (`types.ts`)**
125
123
  - Re-exports PostgreSQL-specific types
126
124
 
127
- ### Manifest (`packs/manifest.json`)
128
-
129
- - Extension pack manifest
130
- - Declares capabilities and codec types import
131
- - Provides canonical scalar map for type canonicalization
132
-
133
125
  ## Dependencies
134
126
 
135
127
  - **`@prisma-next/sql-contract`**: SQL contract types
@@ -138,18 +130,18 @@ flowchart TD
138
130
 
139
131
  ## Related Subsystems
140
132
 
141
- - **[Adapters & Targets](../../docs/architecture%20docs/subsystems/5.%20Adapters%20&%20Targets.md)**: Detailed adapter specification
142
- - **[Ecosystem Extensions & Packs](../../docs/architecture%20docs/subsystems/6.%20Ecosystem%20Extensions%20&%20Packs.md)**: Extension pack model
133
+ - **[Adapters & Targets](../../../../docs/architecture%20docs/subsystems/5.%20Adapters%20&%20Targets.md)**: Detailed adapter specification
134
+ - **[Ecosystem Extensions & Packs](../../../../docs/architecture%20docs/subsystems/6.%20Ecosystem%20Extensions%20&%20Packs.md)**: Extension pack model
143
135
 
144
136
  ## Related ADRs
145
137
 
146
- - [ADR 005 - Thin Core Fat Targets](../../docs/architecture%20docs/adrs/ADR%20005%20-%20Thin%20Core%20Fat%20Targets.md)
147
- - [ADR 016 - Adapter SPI for Lowering](../../docs/architecture%20docs/adrs/ADR%20016%20-%20Adapter%20SPI%20for%20Lowering.md)
148
- - [ADR 030 - Result decoding & codecs registry](../../docs/architecture%20docs/adrs/ADR%20030%20-%20Result%20decoding%20&%20codecs%20registry.md)
149
- - [ADR 065 - Adapter capability schema & negotiation v1](../../docs/architecture%20docs/adrs/ADR%20065%20-%20Adapter%20capability%20schema%20&%20negotiation%20v1.md)
150
- - [ADR 068 - Error mapping to RuntimeError](../../docs/architecture%20docs/adrs/ADR%20068%20-%20Error%20mapping%20to%20RuntimeError.md)
151
- - [ADR 112 - Target Extension Packs](../../docs/architecture%20docs/adrs/ADR%20112%20-%20Target%20Extension%20Packs.md)
152
- - [ADR 114 - Extension codecs & branded types](../../docs/architecture%20docs/adrs/ADR%20114%20-%20Extension%20codecs%20&%20branded%20types.md)
138
+ - [ADR 005 - Thin Core Fat Targets](../../../../docs/architecture%20docs/adrs/ADR%20005%20-%20Thin%20Core%20Fat%20Targets.md)
139
+ - [ADR 016 - Adapter SPI for Lowering](../../../../docs/architecture%20docs/adrs/ADR%20016%20-%20Adapter%20SPI%20for%20Lowering.md)
140
+ - [ADR 030 - Result decoding & codecs registry](../../../../docs/architecture%20docs/adrs/ADR%20030%20-%20Result%20decoding%20&%20codecs%20registry.md)
141
+ - [ADR 065 - Adapter capability schema & negotiation v1](../../../../docs/architecture%20docs/adrs/ADR%20065%20-%20Adapter%20capability%20schema%20&%20negotiation%20v1.md)
142
+ - [ADR 068 - Error mapping to RuntimeError](../../../../docs/architecture%20docs/adrs/ADR%20068%20-%20Error%20mapping%20to%20RuntimeError.md)
143
+ - [ADR 112 - Target Extension Packs](../../../../docs/architecture%20docs/adrs/ADR%20112%20-%20Target%20Extension%20Packs.md)
144
+ - [ADR 114 - Extension codecs & branded types](../../../../docs/architecture%20docs/adrs/ADR%20114%20-%20Extension%20codecs%20&%20branded%20types.md)
153
145
 
154
146
  ## Usage
155
147
 
@@ -191,12 +183,12 @@ The adapter declares the following PostgreSQL capabilities:
191
183
 
192
184
  **Important**: Capabilities must be declared in **both** places:
193
185
 
194
- 1. **`packs/manifest.json`**: Capabilities are read by the CLI during emission and included in the contract
195
- 2. **`src/core/adapter.ts`**: The `defaultCapabilities` constant is used at runtime via `adapter.profile.capabilities`
186
+ 1. **Adapter descriptor** (`src/exports/control.ts` and `src/exports/runtime.ts`): Capabilities are read during emission and included in the contract
187
+ 2. **Runtime adapter code** (`src/core/adapter.ts`): The `defaultCapabilities` constant is used at runtime via `adapter.profile.capabilities`
196
188
 
197
- The capabilities in the manifest must match the capabilities in code. If they don't match, the contract won't include the capabilities, causing runtime capability checks to fail.
189
+ The capabilities on the descriptor must match the capabilities in code. If they don't match, emitted contracts and runtime capability checks will diverge.
198
190
 
199
- See `.cursor/rules/adapter-capability-declaration.mdc` for detailed guidelines.
191
+ See `docs/reference/capabilities.md` and `docs/architecture docs/subsystems/5. Adapters & Targets.md` for details.
200
192
 
201
193
  ## includeMany Support
202
194
 
@@ -254,6 +246,6 @@ DELETE FROM "user" WHERE "user"."id" = $1 RETURNING "user"."id", "user"."email"
254
246
  - `./adapter`: Adapter implementation (`createPostgresAdapter`)
255
247
  - `./codec-types`: PostgreSQL codec types (`CodecTypes`, `dataTypes`)
256
248
  - `./types`: PostgreSQL-specific types
257
- - `./cli`: CLI entry point (`AdapterDescriptor`)
258
- - `./runtime`: Runtime entry point (placeholder for future)
249
+ - `./control`: Control-plane entry point (adapter descriptor)
250
+ - `./runtime`: Runtime-plane entry point (runtime adapter descriptor)
259
251
 
@@ -3,6 +3,8 @@ import { PostgresAdapterOptions, PostgresContract, PostgresLoweredStatement } fr
3
3
  import '@prisma-next/sql-contract/types';
4
4
 
5
5
  declare class PostgresAdapterImpl implements Adapter<QueryAst, PostgresContract, PostgresLoweredStatement> {
6
+ readonly familyId: "sql";
7
+ readonly targetId: "postgres";
6
8
  readonly profile: AdapterProfile<'postgres'>;
7
9
  private readonly codecRegistry;
8
10
  constructor(options?: PostgresAdapterOptions);
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createPostgresAdapter
3
- } from "./chunk-XSQYIK5E.js";
3
+ } from "./chunk-ZHJOVBWT.js";
4
4
  import "./chunk-CPAKRHXM.js";
5
5
  export {
6
6
  createPostgresAdapter
@@ -0,0 +1,47 @@
1
+ // src/core/descriptor-meta.ts
2
+ var postgresAdapterDescriptorMeta = {
3
+ kind: "adapter",
4
+ familyId: "sql",
5
+ targetId: "postgres",
6
+ id: "postgres",
7
+ version: "0.0.1",
8
+ capabilities: {
9
+ postgres: {
10
+ orderBy: true,
11
+ limit: true,
12
+ lateral: true,
13
+ jsonAgg: true,
14
+ returning: true
15
+ }
16
+ },
17
+ types: {
18
+ codecTypes: {
19
+ import: {
20
+ package: "@prisma-next/adapter-postgres/codec-types",
21
+ named: "CodecTypes",
22
+ alias: "PgTypes"
23
+ }
24
+ },
25
+ storage: [
26
+ { typeId: "pg/text@1", familyId: "sql", targetId: "postgres", nativeType: "text" },
27
+ { typeId: "pg/int4@1", familyId: "sql", targetId: "postgres", nativeType: "int4" },
28
+ { typeId: "pg/int2@1", familyId: "sql", targetId: "postgres", nativeType: "int2" },
29
+ { typeId: "pg/int8@1", familyId: "sql", targetId: "postgres", nativeType: "int8" },
30
+ { typeId: "pg/float4@1", familyId: "sql", targetId: "postgres", nativeType: "float4" },
31
+ { typeId: "pg/float8@1", familyId: "sql", targetId: "postgres", nativeType: "float8" },
32
+ { typeId: "pg/timestamp@1", familyId: "sql", targetId: "postgres", nativeType: "timestamp" },
33
+ {
34
+ typeId: "pg/timestamptz@1",
35
+ familyId: "sql",
36
+ targetId: "postgres",
37
+ nativeType: "timestamptz"
38
+ },
39
+ { typeId: "pg/bool@1", familyId: "sql", targetId: "postgres", nativeType: "bool" }
40
+ ]
41
+ }
42
+ };
43
+
44
+ export {
45
+ postgresAdapterDescriptorMeta
46
+ };
47
+ //# sourceMappingURL=chunk-B5SU5BVC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/descriptor-meta.ts"],"sourcesContent":["export const postgresAdapterDescriptorMeta = {\n kind: 'adapter',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n version: '0.0.1',\n capabilities: {\n postgres: {\n orderBy: true,\n limit: true,\n lateral: true,\n jsonAgg: true,\n returning: true,\n },\n },\n types: {\n codecTypes: {\n import: {\n package: '@prisma-next/adapter-postgres/codec-types',\n named: 'CodecTypes',\n alias: 'PgTypes',\n },\n },\n storage: [\n { typeId: 'pg/text@1', familyId: 'sql', targetId: 'postgres', nativeType: 'text' },\n { typeId: 'pg/int4@1', familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: 'pg/int2@1', familyId: 'sql', targetId: 'postgres', nativeType: 'int2' },\n { typeId: 'pg/int8@1', familyId: 'sql', targetId: 'postgres', nativeType: 'int8' },\n { typeId: 'pg/float4@1', familyId: 'sql', targetId: 'postgres', nativeType: 'float4' },\n { typeId: 'pg/float8@1', familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n { typeId: 'pg/timestamp@1', familyId: 'sql', targetId: 'postgres', nativeType: 'timestamp' },\n {\n typeId: 'pg/timestamptz@1',\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamptz',\n },\n { typeId: 'pg/bool@1', familyId: 'sql', targetId: 'postgres', nativeType: 'bool' },\n ],\n },\n} as const;\n"],"mappings":";AAAO,IAAM,gCAAgC;AAAA,EAC3C,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,cAAc;AAAA,IACZ,UAAU;AAAA,MACR,SAAS;AAAA,MACT,OAAO;AAAA,MACP,SAAS;AAAA,MACT,SAAS;AAAA,MACT,WAAW;AAAA,IACb;AAAA,EACF;AAAA,EACA,OAAO;AAAA,IACL,YAAY;AAAA,MACV,QAAQ;AAAA,QACN,SAAS;AAAA,QACT,OAAO;AAAA,QACP,OAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA,SAAS;AAAA,MACP,EAAE,QAAQ,aAAa,UAAU,OAAO,UAAU,YAAY,YAAY,OAAO;AAAA,MACjF,EAAE,QAAQ,aAAa,UAAU,OAAO,UAAU,YAAY,YAAY,OAAO;AAAA,MACjF,EAAE,QAAQ,aAAa,UAAU,OAAO,UAAU,YAAY,YAAY,OAAO;AAAA,MACjF,EAAE,QAAQ,aAAa,UAAU,OAAO,UAAU,YAAY,YAAY,OAAO;AAAA,MACjF,EAAE,QAAQ,eAAe,UAAU,OAAO,UAAU,YAAY,YAAY,SAAS;AAAA,MACrF,EAAE,QAAQ,eAAe,UAAU,OAAO,UAAU,YAAY,YAAY,SAAS;AAAA,MACrF,EAAE,QAAQ,kBAAkB,UAAU,OAAO,UAAU,YAAY,YAAY,YAAY;AAAA,MAC3F;AAAA,QACE,QAAQ;AAAA,QACR,UAAU;AAAA,QACV,UAAU;AAAA,QACV,YAAY;AAAA,MACd;AAAA,MACA,EAAE,QAAQ,aAAa,UAAU,OAAO,UAAU,YAAY,YAAY,OAAO;AAAA,IACnF;AAAA,EACF;AACF;","names":[]}
@@ -15,6 +15,10 @@ var defaultCapabilities = Object.freeze({
15
15
  }
16
16
  });
17
17
  var PostgresAdapterImpl = class {
18
+ // These fields make the adapter instance structurally compatible with
19
+ // RuntimeAdapterInstance<'sql', 'postgres'> without introducing a runtime-plane dependency.
20
+ familyId = "sql";
21
+ targetId = "postgres";
18
22
  profile;
19
23
  codecRegistry = (() => {
20
24
  const registry = createCodecRegistry();
@@ -294,4 +298,4 @@ function createPostgresAdapter(options) {
294
298
  export {
295
299
  createPostgresAdapter
296
300
  };
297
- //# sourceMappingURL=chunk-XSQYIK5E.js.map
301
+ //# sourceMappingURL=chunk-ZHJOVBWT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/adapter.ts"],"sourcesContent":["import type {\n Adapter,\n AdapterProfile,\n BinaryExpr,\n ColumnRef,\n DeleteAst,\n ExistsExpr,\n IncludeRef,\n InsertAst,\n JoinAst,\n LiteralExpr,\n LowererContext,\n OperationExpr,\n ParamRef,\n QueryAst,\n SelectAst,\n UpdateAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport { createCodecRegistry, isOperationExpr } from '@prisma-next/sql-relational-core/ast';\nimport { codecDefinitions } from './codecs';\nimport type { PostgresAdapterOptions, PostgresContract, PostgresLoweredStatement } from './types';\n\nconst VECTOR_CODEC_ID = 'pg/vector@1' as const;\n\nconst defaultCapabilities = Object.freeze({\n postgres: {\n orderBy: true,\n limit: true,\n lateral: true,\n jsonAgg: true,\n returning: true,\n },\n});\n\nclass PostgresAdapterImpl implements Adapter<QueryAst, PostgresContract, PostgresLoweredStatement> {\n // These fields make the adapter instance structurally compatible with\n // RuntimeAdapterInstance<'sql', 'postgres'> without introducing a runtime-plane dependency.\n readonly familyId = 'sql' as const;\n readonly targetId = 'postgres' as const;\n\n readonly profile: AdapterProfile<'postgres'>;\n private readonly codecRegistry = (() => {\n const registry = createCodecRegistry();\n for (const definition of Object.values(codecDefinitions)) {\n registry.register(definition.codec);\n }\n return registry;\n })();\n\n constructor(options?: PostgresAdapterOptions) {\n this.profile = Object.freeze({\n id: options?.profileId ?? 'postgres/default@1',\n target: 'postgres',\n capabilities: defaultCapabilities,\n codecs: () => this.codecRegistry,\n });\n }\n\n lower(ast: QueryAst, context: LowererContext<PostgresContract>) {\n let sql: string;\n const params = context.params ? [...context.params] : [];\n\n if (ast.kind === 'select') {\n sql = renderSelect(ast, context.contract);\n } else if (ast.kind === 'insert') {\n sql = renderInsert(ast, context.contract);\n } else if (ast.kind === 'update') {\n sql = renderUpdate(ast, context.contract);\n } else if (ast.kind === 'delete') {\n sql = renderDelete(ast, context.contract);\n } else {\n throw new Error(`Unsupported AST kind: ${(ast as { kind: string }).kind}`);\n }\n\n return Object.freeze({\n profileId: this.profile.id,\n body: Object.freeze({ sql, params }),\n });\n }\n}\n\nfunction renderSelect(ast: SelectAst, contract?: PostgresContract): string {\n const selectClause = `SELECT ${renderProjection(ast, contract)}`;\n const fromClause = `FROM ${quoteIdentifier(ast.from.name)}`;\n\n const joinsClause = ast.joins?.length\n ? ast.joins.map((join) => renderJoin(join, contract)).join(' ')\n : '';\n const includesClause = ast.includes?.length\n ? ast.includes.map((include) => renderInclude(include, contract)).join(' ')\n : '';\n\n const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract)}` : '';\n const orderClause = ast.orderBy?.length\n ? ` ORDER BY ${ast.orderBy\n .map((order) => {\n const expr = renderExpr(order.expr as ColumnRef | OperationExpr, contract);\n return `${expr} ${order.dir.toUpperCase()}`;\n })\n .join(', ')}`\n : '';\n const limitClause = typeof ast.limit === 'number' ? ` LIMIT ${ast.limit}` : '';\n\n const clauses = [joinsClause, includesClause].filter(Boolean).join(' ');\n return `${selectClause} ${fromClause}${clauses ? ` ${clauses}` : ''}${whereClause}${orderClause}${limitClause}`.trim();\n}\n\nfunction renderProjection(ast: SelectAst, contract?: PostgresContract): string {\n return ast.project\n .map((item) => {\n const expr = item.expr as ColumnRef | IncludeRef | OperationExpr | LiteralExpr;\n if (expr.kind === 'includeRef') {\n // For include references, select the column from the LATERAL join alias\n // The LATERAL subquery returns a single column (the JSON array) with the alias\n // The table is aliased as {alias}_lateral, and the column inside is aliased as the include alias\n // We select it using table_alias.column_alias\n const tableAlias = `${expr.alias}_lateral`;\n return `${quoteIdentifier(tableAlias)}.${quoteIdentifier(expr.alias)} AS ${quoteIdentifier(item.alias)}`;\n }\n if (expr.kind === 'operation') {\n const operation = renderOperation(expr, contract);\n const alias = quoteIdentifier(item.alias);\n return `${operation} AS ${alias}`;\n }\n if (expr.kind === 'literal') {\n const literal = renderLiteral(expr);\n const alias = quoteIdentifier(item.alias);\n return `${literal} AS ${alias}`;\n }\n const column = renderColumn(expr as ColumnRef);\n const alias = quoteIdentifier(item.alias);\n return `${column} AS ${alias}`;\n })\n .join(', ');\n}\n\nfunction renderWhere(expr: BinaryExpr | ExistsExpr, contract?: PostgresContract): string {\n if (expr.kind === 'exists') {\n const notKeyword = expr.not ? 'NOT ' : '';\n const subquery = renderSelect(expr.subquery, contract);\n return `${notKeyword}EXISTS (${subquery})`;\n }\n return renderBinary(expr, contract);\n}\n\nfunction renderBinary(expr: BinaryExpr, contract?: PostgresContract): string {\n const leftExpr = expr.left as ColumnRef | OperationExpr;\n const left = renderExpr(leftExpr, contract);\n // Handle both ParamRef and ColumnRef on the right side\n // (ColumnRef can appear in EXISTS subqueries for correlation)\n const rightExpr = expr.right as ParamRef | ColumnRef;\n const right =\n rightExpr.kind === 'col'\n ? renderColumn(rightExpr)\n : renderParam(rightExpr as ParamRef, contract);\n // Only wrap in parentheses if it's an operation expression\n const leftRendered = isOperationExpr(leftExpr) ? `(${left})` : left;\n\n // Map operators to SQL symbols\n const operatorMap: Record<BinaryExpr['op'], string> = {\n eq: '=',\n neq: '!=',\n gt: '>',\n lt: '<',\n gte: '>=',\n lte: '<=',\n };\n\n return `${leftRendered} ${operatorMap[expr.op]} ${right}`;\n}\n\nfunction renderColumn(ref: ColumnRef): string {\n return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;\n}\n\nfunction renderExpr(expr: ColumnRef | OperationExpr, contract?: PostgresContract): string {\n if (isOperationExpr(expr)) {\n return renderOperation(expr, contract);\n }\n return renderColumn(expr);\n}\n\nfunction renderParam(\n ref: ParamRef,\n contract?: PostgresContract,\n tableName?: string,\n columnName?: string,\n): string {\n // Cast vector parameters to vector type for PostgreSQL\n if (contract && tableName && columnName) {\n const tableMeta = contract.storage.tables[tableName];\n const columnMeta = tableMeta?.columns[columnName];\n if (columnMeta?.codecId === VECTOR_CODEC_ID) {\n return `$${ref.index}::vector`;\n }\n }\n return `$${ref.index}`;\n}\n\nfunction renderLiteral(expr: LiteralExpr): string {\n if (typeof expr.value === 'string') {\n return `'${expr.value.replace(/'/g, \"''\")}'`;\n }\n if (typeof expr.value === 'number' || typeof expr.value === 'boolean') {\n return String(expr.value);\n }\n if (expr.value === null) {\n return 'NULL';\n }\n if (Array.isArray(expr.value)) {\n return `ARRAY[${expr.value.map((v: unknown) => renderLiteral({ kind: 'literal', value: v })).join(', ')}]`;\n }\n return JSON.stringify(expr.value);\n}\n\nfunction renderOperation(expr: OperationExpr, contract?: PostgresContract): string {\n const self = renderExpr(expr.self, contract);\n // For vector operations, cast param arguments to vector type\n const isVectorOperation = expr.forTypeId === VECTOR_CODEC_ID;\n const args = expr.args.map((arg: ColumnRef | ParamRef | LiteralExpr | OperationExpr) => {\n if (arg.kind === 'col') {\n return renderColumn(arg);\n }\n if (arg.kind === 'param') {\n // Cast vector operation parameters to vector type\n return isVectorOperation ? `$${arg.index}::vector` : renderParam(arg, contract);\n }\n if (arg.kind === 'literal') {\n return renderLiteral(arg);\n }\n if (arg.kind === 'operation') {\n return renderOperation(arg, contract);\n }\n const _exhaustive: never = arg;\n throw new Error(`Unsupported argument kind: ${(_exhaustive as { kind: string }).kind}`);\n });\n\n let result = expr.lowering.template;\n result = result.replace(/\\$\\{self\\}/g, self);\n for (let i = 0; i < args.length; i++) {\n result = result.replace(new RegExp(`\\\\$\\\\{arg${i}\\\\}`, 'g'), args[i] ?? '');\n }\n\n if (expr.lowering.strategy === 'function') {\n return result;\n }\n\n return result;\n}\n\nfunction renderJoin(join: JoinAst, _contract?: PostgresContract): string {\n const joinType = join.joinType.toUpperCase();\n const table = quoteIdentifier(join.table.name);\n const onClause = renderJoinOn(join.on);\n return `${joinType} JOIN ${table} ON ${onClause}`;\n}\n\nfunction renderJoinOn(on: JoinAst['on']): string {\n if (on.kind === 'eqCol') {\n const left = renderColumn(on.left);\n const right = renderColumn(on.right);\n return `${left} = ${right}`;\n }\n throw new Error(`Unsupported join ON expression kind: ${on.kind}`);\n}\n\nfunction renderInclude(\n include: NonNullable<SelectAst['includes']>[number],\n contract?: PostgresContract,\n): string {\n const alias = include.alias;\n\n // Build the lateral subquery\n const childProjection = include.child.project\n .map((item: { alias: string; expr: ColumnRef | OperationExpr }) => {\n const expr = renderExpr(item.expr, contract);\n return `'${item.alias}', ${expr}`;\n })\n .join(', ');\n\n const jsonBuildObject = `json_build_object(${childProjection})`;\n\n // Build the ON condition from the include's ON clause - this goes in the WHERE clause\n const onCondition = renderJoinOn(include.child.on);\n\n // Build WHERE clause: combine ON condition with any additional WHERE clauses\n let whereClause = ` WHERE ${onCondition}`;\n if (include.child.where) {\n whereClause += ` AND ${renderWhere(include.child.where, contract)}`;\n }\n\n // Add ORDER BY if present - it goes inside json_agg() call\n const childOrderBy = include.child.orderBy?.length\n ? ` ORDER BY ${include.child.orderBy\n .map(\n (order: { expr: ColumnRef | OperationExpr; dir: string }) =>\n `${renderExpr(order.expr, contract)} ${order.dir.toUpperCase()}`,\n )\n .join(', ')}`\n : '';\n\n // Add LIMIT if present\n const childLimit = typeof include.child.limit === 'number' ? ` LIMIT ${include.child.limit}` : '';\n\n // Build the lateral subquery\n // When ORDER BY is present without LIMIT, it goes inside json_agg() call: json_agg(expr ORDER BY ...)\n // When LIMIT is present (with or without ORDER BY), we need to wrap in a subquery\n const childTable = quoteIdentifier(include.child.table.name);\n let subquery: string;\n if (typeof include.child.limit === 'number') {\n // With LIMIT, we need to wrap in a subquery\n // Select individual columns in inner query, then aggregate\n // Create a map of column references to their aliases for ORDER BY\n // Only ColumnRef can be mapped (OperationExpr doesn't have table/column properties)\n const columnAliasMap = new Map<string, string>();\n for (const item of include.child.project) {\n if (item.expr.kind === 'col') {\n const columnKey = `${item.expr.table}.${item.expr.column}`;\n columnAliasMap.set(columnKey, item.alias);\n }\n }\n\n const innerColumns = include.child.project\n .map((item: { alias: string; expr: ColumnRef | OperationExpr }) => {\n const expr = renderExpr(item.expr, contract);\n return `${expr} AS ${quoteIdentifier(item.alias)}`;\n })\n .join(', ');\n\n // For ORDER BY, use column aliases if the column is in the SELECT list\n const childOrderByWithAliases = include.child.orderBy?.length\n ? ` ORDER BY ${include.child.orderBy\n .map((order: { expr: ColumnRef | OperationExpr; dir: string }) => {\n if (order.expr.kind === 'col') {\n const columnKey = `${order.expr.table}.${order.expr.column}`;\n const alias = columnAliasMap.get(columnKey);\n if (alias) {\n return `${quoteIdentifier(alias)} ${order.dir.toUpperCase()}`;\n }\n }\n return `${renderExpr(order.expr, contract)} ${order.dir.toUpperCase()}`;\n })\n .join(', ')}`\n : '';\n\n const innerSelect = `SELECT ${innerColumns} FROM ${childTable}${whereClause}${childOrderByWithAliases}${childLimit}`;\n subquery = `(SELECT json_agg(row_to_json(sub.*)) AS ${quoteIdentifier(alias)} FROM (${innerSelect}) sub)`;\n } else if (childOrderBy) {\n // With ORDER BY but no LIMIT, ORDER BY goes inside json_agg()\n subquery = `(SELECT json_agg(${jsonBuildObject}${childOrderBy}) AS ${quoteIdentifier(alias)} FROM ${childTable}${whereClause})`;\n } else {\n // No ORDER BY or LIMIT\n subquery = `(SELECT json_agg(${jsonBuildObject}) AS ${quoteIdentifier(alias)} FROM ${childTable}${whereClause})`;\n }\n\n // Return the LATERAL join with ON true (the condition is in the WHERE clause)\n // The subquery returns a single column (the JSON array) with the alias\n // We use a different alias for the table to avoid ambiguity when selecting the column\n const tableAlias = `${alias}_lateral`;\n return `LEFT JOIN LATERAL ${subquery} AS ${quoteIdentifier(tableAlias)} ON true`;\n}\n\nfunction quoteIdentifier(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction renderInsert(ast: InsertAst, contract: PostgresContract): string {\n const table = quoteIdentifier(ast.table.name);\n const columns = Object.keys(ast.values).map((col) => quoteIdentifier(col));\n const tableMeta = contract.storage.tables[ast.table.name];\n const values = Object.entries(ast.values).map(([colName, val]) => {\n if (val.kind === 'param') {\n const columnMeta = tableMeta?.columns[colName];\n const isVector = columnMeta?.codecId === VECTOR_CODEC_ID;\n return isVector ? `$${val.index}::vector` : `$${val.index}`;\n }\n if (val.kind === 'col') {\n return `${quoteIdentifier(val.table)}.${quoteIdentifier(val.column)}`;\n }\n throw new Error(`Unsupported value kind in INSERT: ${(val as { kind: string }).kind}`);\n });\n\n const insertClause = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${values.join(', ')})`;\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `${insertClause}${returningClause}`;\n}\n\nfunction renderUpdate(ast: UpdateAst, contract: PostgresContract): string {\n const table = quoteIdentifier(ast.table.name);\n const tableMeta = contract.storage.tables[ast.table.name];\n const setClauses = Object.entries(ast.set).map(([col, val]) => {\n const column = quoteIdentifier(col);\n let value: string;\n if (val.kind === 'param') {\n const columnMeta = tableMeta?.columns[col];\n const isVector = columnMeta?.codecId === VECTOR_CODEC_ID;\n value = isVector ? `$${val.index}::vector` : `$${val.index}`;\n } else if (val.kind === 'col') {\n value = `${quoteIdentifier(val.table)}.${quoteIdentifier(val.column)}`;\n } else {\n throw new Error(`Unsupported value kind in UPDATE: ${(val as { kind: string }).kind}`);\n }\n return `${column} = ${value}`;\n });\n\n const whereClause = ` WHERE ${renderBinary(ast.where, contract)}`;\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `UPDATE ${table} SET ${setClauses.join(', ')}${whereClause}${returningClause}`;\n}\n\nfunction renderDelete(ast: DeleteAst, contract?: PostgresContract): string {\n const table = quoteIdentifier(ast.table.name);\n const whereClause = ` WHERE ${renderBinary(ast.where, contract)}`;\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `DELETE FROM ${table}${whereClause}${returningClause}`;\n}\n\nexport function createPostgresAdapter(options?: PostgresAdapterOptions) {\n return Object.freeze(new PostgresAdapterImpl(options));\n}\n"],"mappings":";;;;;AAkBA,SAAS,qBAAqB,uBAAuB;AAIrD,IAAM,kBAAkB;AAExB,IAAM,sBAAsB,OAAO,OAAO;AAAA,EACxC,UAAU;AAAA,IACR,SAAS;AAAA,IACT,OAAO;AAAA,IACP,SAAS;AAAA,IACT,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AACF,CAAC;AAED,IAAM,sBAAN,MAAmG;AAAA;AAAA;AAAA,EAGxF,WAAW;AAAA,EACX,WAAW;AAAA,EAEX;AAAA,EACQ,iBAAiB,MAAM;AACtC,UAAM,WAAW,oBAAoB;AACrC,eAAW,cAAc,OAAO,OAAO,gBAAgB,GAAG;AACxD,eAAS,SAAS,WAAW,KAAK;AAAA,IACpC;AACA,WAAO;AAAA,EACT,GAAG;AAAA,EAEH,YAAY,SAAkC;AAC5C,SAAK,UAAU,OAAO,OAAO;AAAA,MAC3B,IAAI,SAAS,aAAa;AAAA,MAC1B,QAAQ;AAAA,MACR,cAAc;AAAA,MACd,QAAQ,MAAM,KAAK;AAAA,IACrB,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,KAAe,SAA2C;AAC9D,QAAI;AACJ,UAAM,SAAS,QAAQ,SAAS,CAAC,GAAG,QAAQ,MAAM,IAAI,CAAC;AAEvD,QAAI,IAAI,SAAS,UAAU;AACzB,YAAM,aAAa,KAAK,QAAQ,QAAQ;AAAA,IAC1C,WAAW,IAAI,SAAS,UAAU;AAChC,YAAM,aAAa,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import { readFileSync } from "fs";
3
- import { dirname, join } from "path";
4
- import { fileURLToPath } from "url";
5
- import { type } from "arktype";
1
+ import {
2
+ postgresAdapterDescriptorMeta
3
+ } from "./chunk-B5SU5BVC.js";
6
4
 
7
5
  // src/core/control-adapter.ts
8
6
  var PostgresControlAdapter = class {
@@ -268,51 +266,8 @@ var PostgresControlAdapter = class {
268
266
  };
269
267
 
270
268
  // src/exports/control.ts
271
- var __filename = fileURLToPath(import.meta.url);
272
- var __dirname = dirname(__filename);
273
- var TypesImportSpecSchema = type({
274
- package: "string",
275
- named: "string",
276
- alias: "string"
277
- });
278
- var StorageTypeMetadataSchema = type({
279
- typeId: "string",
280
- familyId: "string",
281
- targetId: "string",
282
- "nativeType?": "string"
283
- });
284
- var ExtensionPackManifestSchema = type({
285
- id: "string",
286
- version: "string",
287
- "targets?": type({ "[string]": type({ "minVersion?": "string" }) }),
288
- "capabilities?": "Record<string, unknown>",
289
- "types?": type({
290
- "codecTypes?": type({
291
- import: TypesImportSpecSchema
292
- }),
293
- "operationTypes?": type({
294
- import: TypesImportSpecSchema
295
- }),
296
- "storage?": StorageTypeMetadataSchema.array()
297
- }),
298
- "operations?": "unknown[]"
299
- });
300
- function loadAdapterManifest() {
301
- const manifestPath = join(__dirname, "../../packs/manifest.json");
302
- const manifestJson = JSON.parse(readFileSync(manifestPath, "utf-8"));
303
- const result = ExtensionPackManifestSchema(manifestJson);
304
- if (result instanceof type.errors) {
305
- const messages = result.map((p) => p.message).join("; ");
306
- throw new Error(`Invalid adapter manifest structure at ${manifestPath}: ${messages}`);
307
- }
308
- return result;
309
- }
310
269
  var postgresAdapterDescriptor = {
311
- kind: "adapter",
312
- familyId: "sql",
313
- targetId: "postgres",
314
- id: "postgres",
315
- manifest: loadAdapterManifest(),
270
+ ...postgresAdapterDescriptorMeta,
316
271
  create() {
317
272
  return new PostgresControlAdapter();
318
273
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/exports/control.ts","../../src/core/control-adapter.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ExtensionPackManifest } from '@prisma-next/contract/pack-manifest-types';\nimport type { ControlAdapterDescriptor } from '@prisma-next/core-control-plane/types';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport { type } from 'arktype';\nimport { PostgresControlAdapter } from '../core/control-adapter';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst TypesImportSpecSchema = type({\n package: 'string',\n named: 'string',\n alias: 'string',\n});\n\nconst StorageTypeMetadataSchema = type({\n typeId: 'string',\n familyId: 'string',\n targetId: 'string',\n 'nativeType?': 'string',\n});\n\nconst ExtensionPackManifestSchema = type({\n id: 'string',\n version: 'string',\n 'targets?': type({ '[string]': type({ 'minVersion?': 'string' }) }),\n 'capabilities?': 'Record<string, unknown>',\n 'types?': type({\n 'codecTypes?': type({\n import: TypesImportSpecSchema,\n }),\n 'operationTypes?': type({\n import: TypesImportSpecSchema,\n }),\n 'storage?': StorageTypeMetadataSchema.array(),\n }),\n 'operations?': 'unknown[]',\n});\n\n/**\n * Loads the adapter manifest from packs/manifest.json.\n */\nfunction loadAdapterManifest(): ExtensionPackManifest {\n const manifestPath = join(__dirname, '../../packs/manifest.json');\n const manifestJson = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n\n const result = ExtensionPackManifestSchema(manifestJson);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Invalid adapter manifest structure at ${manifestPath}: ${messages}`);\n }\n\n return result as ExtensionPackManifest;\n}\n\n/**\n * Postgres adapter descriptor for CLI config.\n */\nconst postgresAdapterDescriptor: ControlAdapterDescriptor<\n 'sql',\n 'postgres',\n SqlControlAdapter<'postgres'>\n> = {\n kind: 'adapter',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n manifest: loadAdapterManifest(),\n create(): SqlControlAdapter<'postgres'> {\n return new PostgresControlAdapter();\n },\n};\n\nexport default postgresAdapterDescriptor;\n","import type { ControlDriverInstance } from '@prisma-next/core-control-plane/types';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type {\n PrimaryKey,\n SqlColumnIR,\n SqlForeignKeyIR,\n SqlIndexIR,\n SqlSchemaIR,\n SqlTableIR,\n SqlUniqueIR,\n} from '@prisma-next/sql-schema-ir/types';\n\n/**\n * Postgres control plane adapter for control-plane operations like introspection.\n * Provides target-specific implementations for control-plane domain actions.\n */\nexport class PostgresControlAdapter implements SqlControlAdapter<'postgres'> {\n readonly familyId = 'sql' as const;\n readonly targetId = 'postgres' as const;\n /**\n * @deprecated Use targetId instead\n */\n readonly target = 'postgres' as const;\n\n /**\n * Introspects a Postgres database schema and returns a raw SqlSchemaIR.\n *\n * This is a pure schema discovery operation that queries the Postgres catalog\n * and returns the schema structure without type mapping or contract enrichment.\n * Type mapping and enrichment are handled separately by enrichment helpers.\n *\n * @param driver - ControlDriverInstance<'sql', 'postgres'> instance for executing queries\n * @param contractIR - Optional contract IR for contract-guided introspection (filtering, optimization)\n * @param schema - Schema name to introspect (defaults to 'public')\n * @returns Promise resolving to SqlSchemaIR representing the live database schema\n */\n async introspect(\n driver: ControlDriverInstance<'sql', 'postgres'>,\n _contractIR?: unknown,\n schema = 'public',\n ): Promise<SqlSchemaIR> {\n // Query tables\n const tablesResult = await driver.query<{\n table_name: string;\n }>(\n `SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1\n AND table_type = 'BASE TABLE'\n ORDER BY table_name`,\n [schema],\n );\n\n const tables: Record<string, SqlTableIR> = {};\n\n for (const tableRow of tablesResult.rows) {\n const tableName = tableRow.table_name;\n\n // Query columns for this table\n const columnsResult = await driver.query<{\n column_name: string;\n data_type: string;\n udt_name: string;\n is_nullable: string;\n character_maximum_length: number | null;\n numeric_precision: number | null;\n numeric_scale: number | null;\n }>(\n `SELECT\n column_name,\n data_type,\n udt_name,\n is_nullable,\n character_maximum_length,\n numeric_precision,\n numeric_scale\n FROM information_schema.columns\n WHERE table_schema = $1\n AND table_name = $2\n ORDER BY ordinal_position`,\n [schema, tableName],\n );\n\n const columns: Record<string, SqlColumnIR> = {};\n for (const colRow of columnsResult.rows) {\n // Build native type string from catalog data\n let nativeType = colRow.udt_name;\n if (colRow.data_type === 'character varying' || colRow.data_type === 'character') {\n if (colRow.character_maximum_length) {\n nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;\n } else {\n nativeType = colRow.data_type;\n }\n } else if (colRow.data_type === 'numeric' || colRow.data_type === 'decimal') {\n if (colRow.numeric_precision && colRow.numeric_scale !== null) {\n nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;\n } else if (colRow.numeric_precision) {\n nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;\n } else {\n nativeType = colRow.data_type;\n }\n } else {\n nativeType = colRow.udt_name || colRow.data_type;\n }\n\n columns[colRow.column_name] = {\n name: colRow.column_name,\n nativeType,\n nullable: colRow.is_nullable === 'YES',\n };\n }\n\n // Query primary key\n const pkResult = await driver.query<{\n constraint_name: string;\n column_name: string;\n ordinal_position: number;\n }>(\n `SELECT\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_type = 'PRIMARY KEY'\n ORDER BY kcu.ordinal_position`,\n [schema, tableName],\n );\n\n const primaryKeyColumns = pkResult.rows\n .sort((a, b) => a.ordinal_position - b.ordinal_position)\n .map((row) => row.column_name);\n const primaryKey: PrimaryKey | undefined =\n primaryKeyColumns.length > 0\n ? {\n columns: primaryKeyColumns,\n ...(pkResult.rows[0]?.constraint_name\n ? { name: pkResult.rows[0].constraint_name }\n : {}),\n }\n : undefined;\n\n // Query foreign keys\n const fkResult = await driver.query<{\n constraint_name: string;\n column_name: string;\n ordinal_position: number;\n referenced_table_schema: string;\n referenced_table_name: string;\n referenced_column_name: string;\n }>(\n `SELECT\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position,\n ccu.table_schema AS referenced_table_schema,\n ccu.table_name AS referenced_table_name,\n ccu.column_name AS referenced_column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n JOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.constraint_name, kcu.ordinal_position`,\n [schema, tableName],\n );\n\n const foreignKeysMap = new Map<\n string,\n {\n columns: string[];\n referencedTable: string;\n referencedColumns: string[];\n name: string;\n }\n >();\n for (const fkRow of fkResult.rows) {\n const existing = foreignKeysMap.get(fkRow.constraint_name);\n if (existing) {\n // Multi-column FK - add column\n existing.columns.push(fkRow.column_name);\n existing.referencedColumns.push(fkRow.referenced_column_name);\n } else {\n foreignKeysMap.set(fkRow.constraint_name, {\n columns: [fkRow.column_name],\n referencedTable: fkRow.referenced_table_name,\n referencedColumns: [fkRow.referenced_column_name],\n name: fkRow.constraint_name,\n });\n }\n }\n const foreignKeys: readonly SqlForeignKeyIR[] = Array.from(foreignKeysMap.values()).map(\n (fk) => ({\n columns: Object.freeze([...fk.columns]) as readonly string[],\n referencedTable: fk.referencedTable,\n referencedColumns: Object.freeze([...fk.referencedColumns]) as readonly string[],\n name: fk.name,\n }),\n );\n\n // Query unique constraints (excluding PK)\n const uniqueResult = await driver.query<{\n constraint_name: string;\n column_name: string;\n ordinal_position: number;\n }>(\n `SELECT\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_type = 'UNIQUE'\n AND tc.constraint_name NOT IN (\n SELECT constraint_name\n FROM information_schema.table_constraints\n WHERE table_schema = $1\n AND table_name = $2\n AND constraint_type = 'PRIMARY KEY'\n )\n ORDER BY tc.constraint_name, kcu.ordinal_position`,\n [schema, tableName],\n );\n\n const uniquesMap = new Map<\n string,\n {\n columns: string[];\n name: string;\n }\n >();\n for (const uniqueRow of uniqueResult.rows) {\n const existing = uniquesMap.get(uniqueRow.constraint_name);\n if (existing) {\n existing.columns.push(uniqueRow.column_name);\n } else {\n uniquesMap.set(uniqueRow.constraint_name, {\n columns: [uniqueRow.column_name],\n name: uniqueRow.constraint_name,\n });\n }\n }\n const uniques: readonly SqlUniqueIR[] = Array.from(uniquesMap.values()).map((uq) => ({\n columns: Object.freeze([...uq.columns]) as readonly string[],\n name: uq.name,\n }));\n\n // Query indexes (excluding PK and unique constraints)\n const indexResult = await driver.query<{\n indexname: string;\n indisunique: boolean;\n attname: string;\n attnum: number;\n }>(\n `SELECT\n i.indexname,\n ix.indisunique,\n a.attname,\n a.attnum\n FROM pg_indexes i\n JOIN pg_class ic ON ic.relname = i.indexname\n JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1\n JOIN pg_index ix ON ix.indexrelid = ic.oid\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND a.attnum > 0\n WHERE i.schemaname = $1\n AND i.tablename = $2\n AND NOT EXISTS (\n SELECT 1\n FROM information_schema.table_constraints tc\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_name = i.indexname\n )\n ORDER BY i.indexname, a.attnum`,\n [schema, tableName],\n );\n\n const indexesMap = new Map<\n string,\n {\n columns: string[];\n name: string;\n unique: boolean;\n }\n >();\n for (const idxRow of indexResult.rows) {\n // Skip rows where attname is null (system columns or invalid attnum)\n if (!idxRow.attname) {\n continue;\n }\n const existing = indexesMap.get(idxRow.indexname);\n if (existing) {\n existing.columns.push(idxRow.attname);\n } else {\n indexesMap.set(idxRow.indexname, {\n columns: [idxRow.attname],\n name: idxRow.indexname,\n unique: idxRow.indisunique,\n });\n }\n }\n const indexes: readonly SqlIndexIR[] = Array.from(indexesMap.values()).map((idx) => ({\n columns: Object.freeze([...idx.columns]) as readonly string[],\n name: idx.name,\n unique: idx.unique,\n }));\n\n tables[tableName] = {\n name: tableName,\n columns,\n ...(primaryKey ? { primaryKey } : {}),\n foreignKeys,\n uniques,\n indexes,\n };\n }\n\n // Query extensions\n const extensionsResult = await driver.query<{\n extname: string;\n }>(\n `SELECT extname\n FROM pg_extension\n ORDER BY extname`,\n [],\n );\n\n const extensions = extensionsResult.rows.map((row) => row.extname);\n\n // Build annotations with Postgres-specific metadata\n const annotations = {\n pg: {\n schema,\n version: await this.getPostgresVersion(driver),\n },\n };\n\n return {\n tables,\n extensions,\n annotations,\n };\n }\n\n /**\n * Gets the Postgres version from the database.\n */\n private async getPostgresVersion(\n driver: ControlDriverInstance<'sql', 'postgres'>,\n ): Promise<string> {\n const result = await driver.query<{ version: string }>('SELECT version() AS version', []);\n const versionString = result.rows[0]?.version ?? '';\n // Extract version number from \"PostgreSQL 15.1 ...\" format\n const match = versionString.match(/PostgreSQL (\\d+\\.\\d+)/);\n return match?.[1] ?? 'unknown';\n }\n}\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAI9B,SAAS,YAAY;;;ACUd,IAAM,yBAAN,MAAsE;AAAA,EAClE,WAAW;AAAA,EACX,WAAW;AAAA;AAAA;AAAA;AAAA,EAIX,SAAS;AAAA;AAAA;AAAA;AAAA;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AA4B,KAAK;AAAA,EACrC,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,UAAU;AAAA,EACV,eAAe;AACjB,CAAC;AAED,IAAM,8BAA8B,KAAK;AAAA,EACvC,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,YAAY,KAAK,EAAE,YAAY,KAAK,EAAE,eAAe,SAAS,CAAC,EAAE,CAAC;AAAA,EAClE,iBAAiB;AAAA,EACjB,UAAU,KAAK;AAAA,IACb,eAAe,KAAK;AAAA,MAClB,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,mBAAmB,KAAK;AAAA,MACtB,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,YAAY,0BAA0B,MAAM;AAAA,EAC9C,CAAC;AAAA,EACD,eAAe;AACjB,CAAC;AAKD,SAAS,sBAA6C;AACpD,QAAM,eAAe,KAAK,WAAW,2BAA2B;AAChE,QAAM,eAAe,KAAK,MAAM,aAAa,cAAc,OAAO,CAAC;AAEnE,QAAM,SAAS,4BAA4B,YAAY;AACvD,MAAI,kBAAkB,KAAK,QAAQ;AACjC,UAAM,WAAW,OAAO,IAAI,CAAC,MAA2B,EAAE,OAAO,EAAE,KAAK,IAAI;AAC5E,UAAM,IAAI,MAAM,yCAAyC,YAAY,KAAK,QAAQ,EAAE;AAAA,EACtF;AAEA,SAAO;AACT;AAKA,IAAM,4BAIF;AAAA,EACF,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,IAAI;AAAA,EACJ,UAAU,oBAAoB;AAAA,EAC9B,SAAwC;AACtC,WAAO,IAAI,uBAAuB;AAAA,EACpC;AACF;AAEA,IAAO,kBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../src/core/control-adapter.ts","../../src/exports/control.ts"],"sourcesContent":["import type { ControlDriverInstance } from '@prisma-next/core-control-plane/types';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport type {\n PrimaryKey,\n SqlColumnIR,\n SqlForeignKeyIR,\n SqlIndexIR,\n SqlSchemaIR,\n SqlTableIR,\n SqlUniqueIR,\n} from '@prisma-next/sql-schema-ir/types';\n\n/**\n * Postgres control plane adapter for control-plane operations like introspection.\n * Provides target-specific implementations for control-plane domain actions.\n */\nexport class PostgresControlAdapter implements SqlControlAdapter<'postgres'> {\n readonly familyId = 'sql' as const;\n readonly targetId = 'postgres' as const;\n /**\n * @deprecated Use targetId instead\n */\n readonly target = 'postgres' as const;\n\n /**\n * Introspects a Postgres database schema and returns a raw SqlSchemaIR.\n *\n * This is a pure schema discovery operation that queries the Postgres catalog\n * and returns the schema structure without type mapping or contract enrichment.\n * Type mapping and enrichment are handled separately by enrichment helpers.\n *\n * @param driver - ControlDriverInstance<'sql', 'postgres'> instance for executing queries\n * @param contractIR - Optional contract IR for contract-guided introspection (filtering, optimization)\n * @param schema - Schema name to introspect (defaults to 'public')\n * @returns Promise resolving to SqlSchemaIR representing the live database schema\n */\n async introspect(\n driver: ControlDriverInstance<'sql', 'postgres'>,\n _contractIR?: unknown,\n schema = 'public',\n ): Promise<SqlSchemaIR> {\n // Query tables\n const tablesResult = await driver.query<{\n table_name: string;\n }>(\n `SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1\n AND table_type = 'BASE TABLE'\n ORDER BY table_name`,\n [schema],\n );\n\n const tables: Record<string, SqlTableIR> = {};\n\n for (const tableRow of tablesResult.rows) {\n const tableName = tableRow.table_name;\n\n // Query columns for this table\n const columnsResult = await driver.query<{\n column_name: string;\n data_type: string;\n udt_name: string;\n is_nullable: string;\n character_maximum_length: number | null;\n numeric_precision: number | null;\n numeric_scale: number | null;\n }>(\n `SELECT\n column_name,\n data_type,\n udt_name,\n is_nullable,\n character_maximum_length,\n numeric_precision,\n numeric_scale\n FROM information_schema.columns\n WHERE table_schema = $1\n AND table_name = $2\n ORDER BY ordinal_position`,\n [schema, tableName],\n );\n\n const columns: Record<string, SqlColumnIR> = {};\n for (const colRow of columnsResult.rows) {\n // Build native type string from catalog data\n let nativeType = colRow.udt_name;\n if (colRow.data_type === 'character varying' || colRow.data_type === 'character') {\n if (colRow.character_maximum_length) {\n nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;\n } else {\n nativeType = colRow.data_type;\n }\n } else if (colRow.data_type === 'numeric' || colRow.data_type === 'decimal') {\n if (colRow.numeric_precision && colRow.numeric_scale !== null) {\n nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;\n } else if (colRow.numeric_precision) {\n nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;\n } else {\n nativeType = colRow.data_type;\n }\n } else {\n nativeType = colRow.udt_name || colRow.data_type;\n }\n\n columns[colRow.column_name] = {\n name: colRow.column_name,\n nativeType,\n nullable: colRow.is_nullable === 'YES',\n };\n }\n\n // Query primary key\n const pkResult = await driver.query<{\n constraint_name: string;\n column_name: string;\n ordinal_position: number;\n }>(\n `SELECT\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_type = 'PRIMARY KEY'\n ORDER BY kcu.ordinal_position`,\n [schema, tableName],\n );\n\n const primaryKeyColumns = pkResult.rows\n .sort((a, b) => a.ordinal_position - b.ordinal_position)\n .map((row) => row.column_name);\n const primaryKey: PrimaryKey | undefined =\n primaryKeyColumns.length > 0\n ? {\n columns: primaryKeyColumns,\n ...(pkResult.rows[0]?.constraint_name\n ? { name: pkResult.rows[0].constraint_name }\n : {}),\n }\n : undefined;\n\n // Query foreign keys\n const fkResult = await driver.query<{\n constraint_name: string;\n column_name: string;\n ordinal_position: number;\n referenced_table_schema: string;\n referenced_table_name: string;\n referenced_column_name: string;\n }>(\n `SELECT\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position,\n ccu.table_schema AS referenced_table_schema,\n ccu.table_name AS referenced_table_name,\n ccu.column_name AS referenced_column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n JOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.constraint_name, kcu.ordinal_position`,\n [schema, tableName],\n );\n\n const foreignKeysMap = new Map<\n string,\n {\n columns: string[];\n referencedTable: string;\n referencedColumns: string[];\n name: string;\n }\n >();\n for (const fkRow of fkResult.rows) {\n const existing = foreignKeysMap.get(fkRow.constraint_name);\n if (existing) {\n // Multi-column FK - add column\n existing.columns.push(fkRow.column_name);\n existing.referencedColumns.push(fkRow.referenced_column_name);\n } else {\n foreignKeysMap.set(fkRow.constraint_name, {\n columns: [fkRow.column_name],\n referencedTable: fkRow.referenced_table_name,\n referencedColumns: [fkRow.referenced_column_name],\n name: fkRow.constraint_name,\n });\n }\n }\n const foreignKeys: readonly SqlForeignKeyIR[] = Array.from(foreignKeysMap.values()).map(\n (fk) => ({\n columns: Object.freeze([...fk.columns]) as readonly string[],\n referencedTable: fk.referencedTable,\n referencedColumns: Object.freeze([...fk.referencedColumns]) as readonly string[],\n name: fk.name,\n }),\n );\n\n // Query unique constraints (excluding PK)\n const uniqueResult = await driver.query<{\n constraint_name: string;\n column_name: string;\n ordinal_position: number;\n }>(\n `SELECT\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_type = 'UNIQUE'\n AND tc.constraint_name NOT IN (\n SELECT constraint_name\n FROM information_schema.table_constraints\n WHERE table_schema = $1\n AND table_name = $2\n AND constraint_type = 'PRIMARY KEY'\n )\n ORDER BY tc.constraint_name, kcu.ordinal_position`,\n [schema, tableName],\n );\n\n const uniquesMap = new Map<\n string,\n {\n columns: string[];\n name: string;\n }\n >();\n for (const uniqueRow of uniqueResult.rows) {\n const existing = uniquesMap.get(uniqueRow.constraint_name);\n if (existing) {\n existing.columns.push(uniqueRow.column_name);\n } else {\n uniquesMap.set(uniqueRow.constraint_name, {\n columns: [uniqueRow.column_name],\n name: uniqueRow.constraint_name,\n });\n }\n }\n const uniques: readonly SqlUniqueIR[] = Array.from(uniquesMap.values()).map((uq) => ({\n columns: Object.freeze([...uq.columns]) as readonly string[],\n name: uq.name,\n }));\n\n // Query indexes (excluding PK and unique constraints)\n const indexResult = await driver.query<{\n indexname: string;\n indisunique: boolean;\n attname: string;\n attnum: number;\n }>(\n `SELECT\n i.indexname,\n ix.indisunique,\n a.attname,\n a.attnum\n FROM pg_indexes i\n JOIN pg_class ic ON ic.relname = i.indexname\n JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1\n JOIN pg_index ix ON ix.indexrelid = ic.oid\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND a.attnum > 0\n WHERE i.schemaname = $1\n AND i.tablename = $2\n AND NOT EXISTS (\n SELECT 1\n FROM information_schema.table_constraints tc\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_name = i.indexname\n )\n ORDER BY i.indexname, a.attnum`,\n [schema, tableName],\n );\n\n const indexesMap = new Map<\n string,\n {\n columns: string[];\n name: string;\n unique: boolean;\n }\n >();\n for (const idxRow of indexResult.rows) {\n // Skip rows where attname is null (system columns or invalid attnum)\n if (!idxRow.attname) {\n continue;\n }\n const existing = indexesMap.get(idxRow.indexname);\n if (existing) {\n existing.columns.push(idxRow.attname);\n } else {\n indexesMap.set(idxRow.indexname, {\n columns: [idxRow.attname],\n name: idxRow.indexname,\n unique: idxRow.indisunique,\n });\n }\n }\n const indexes: readonly SqlIndexIR[] = Array.from(indexesMap.values()).map((idx) => ({\n columns: Object.freeze([...idx.columns]) as readonly string[],\n name: idx.name,\n unique: idx.unique,\n }));\n\n tables[tableName] = {\n name: tableName,\n columns,\n ...(primaryKey ? { primaryKey } : {}),\n foreignKeys,\n uniques,\n indexes,\n };\n }\n\n // Query extensions\n const extensionsResult = await driver.query<{\n extname: string;\n }>(\n `SELECT extname\n FROM pg_extension\n ORDER BY extname`,\n [],\n );\n\n const extensions = extensionsResult.rows.map((row) => row.extname);\n\n // Build annotations with Postgres-specific metadata\n const annotations = {\n pg: {\n schema,\n version: await this.getPostgresVersion(driver),\n },\n };\n\n return {\n tables,\n extensions,\n annotations,\n };\n }\n\n /**\n * Gets the Postgres version from the database.\n */\n private async getPostgresVersion(\n driver: ControlDriverInstance<'sql', 'postgres'>,\n ): Promise<string> {\n const result = await driver.query<{ version: string }>('SELECT version() AS version', []);\n const versionString = result.rows[0]?.version ?? '';\n // Extract version number from \"PostgreSQL 15.1 ...\" format\n const match = versionString.match(/PostgreSQL (\\d+\\.\\d+)/);\n return match?.[1] ?? 'unknown';\n }\n}\n","import type { ControlAdapterDescriptor } from '@prisma-next/core-control-plane/types';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport { PostgresControlAdapter } from '../core/control-adapter';\nimport { postgresAdapterDescriptorMeta } from '../core/descriptor-meta';\n\n/**\n * Postgres adapter descriptor for CLI config.\n */\nconst postgresAdapterDescriptor: ControlAdapterDescriptor<\n 'sql',\n 'postgres',\n SqlControlAdapter<'postgres'>\n> = {\n ...postgresAdapterDescriptorMeta,\n create(): SqlControlAdapter<'postgres'> {\n return new PostgresControlAdapter();\n },\n};\n\nexport default postgresAdapterDescriptor;\n"],"mappings":";;;;;AAgBO,IAAM,yBAAN,MAAsE;AA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B;AAAA,EACpC;AACF;AAEA,IAAO,kBAAQ;","names":[]}
@@ -1,58 +1,14 @@
1
1
  import {
2
2
  createPostgresAdapter
3
- } from "./chunk-XSQYIK5E.js";
3
+ } from "./chunk-ZHJOVBWT.js";
4
4
  import "./chunk-CPAKRHXM.js";
5
+ import {
6
+ postgresAdapterDescriptorMeta
7
+ } from "./chunk-B5SU5BVC.js";
5
8
 
6
9
  // src/exports/runtime.ts
7
- import { readFileSync } from "fs";
8
- import { dirname, join } from "path";
9
- import { fileURLToPath } from "url";
10
- import { type } from "arktype";
11
- var __filename = fileURLToPath(import.meta.url);
12
- var __dirname = dirname(__filename);
13
- var TypesImportSpecSchema = type({
14
- package: "string",
15
- named: "string",
16
- alias: "string"
17
- });
18
- var StorageTypeMetadataSchema = type({
19
- typeId: "string",
20
- familyId: "string",
21
- targetId: "string",
22
- "nativeType?": "string"
23
- });
24
- var ExtensionPackManifestSchema = type({
25
- id: "string",
26
- version: "string",
27
- "targets?": type({ "[string]": type({ "minVersion?": "string" }) }),
28
- "capabilities?": "Record<string, unknown>",
29
- "types?": type({
30
- "codecTypes?": type({
31
- import: TypesImportSpecSchema
32
- }),
33
- "operationTypes?": type({
34
- import: TypesImportSpecSchema
35
- }),
36
- "storage?": StorageTypeMetadataSchema.array()
37
- }),
38
- "operations?": "unknown[]"
39
- });
40
- function loadAdapterManifest() {
41
- const manifestPath = join(__dirname, "../../packs/manifest.json");
42
- const manifestJson = JSON.parse(readFileSync(manifestPath, "utf-8"));
43
- const result = ExtensionPackManifestSchema(manifestJson);
44
- if (result instanceof type.errors) {
45
- const messages = result.map((p) => p.message).join("; ");
46
- throw new Error(`Invalid adapter manifest structure at ${manifestPath}: ${messages}`);
47
- }
48
- return result;
49
- }
50
10
  var postgresRuntimeAdapterDescriptor = {
51
- kind: "adapter",
52
- familyId: "sql",
53
- targetId: "postgres",
54
- id: "postgres",
55
- manifest: loadAdapterManifest(),
11
+ ...postgresAdapterDescriptorMeta,
56
12
  create() {
57
13
  return createPostgresAdapter();
58
14
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/exports/runtime.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ExtensionPackManifest } from '@prisma-next/contract/pack-manifest-types';\nimport type {\n RuntimeAdapterDescriptor,\n RuntimeAdapterInstance,\n} from '@prisma-next/core-execution-plane/types';\nimport type { Adapter, QueryAst } from '@prisma-next/sql-relational-core/ast';\nimport { type } from 'arktype';\nimport { createPostgresAdapter } from '../core/adapter';\nimport type { PostgresContract, PostgresLoweredStatement } from '../core/types';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst TypesImportSpecSchema = type({\n package: 'string',\n named: 'string',\n alias: 'string',\n});\n\nconst StorageTypeMetadataSchema = type({\n typeId: 'string',\n familyId: 'string',\n targetId: 'string',\n 'nativeType?': 'string',\n});\n\nconst ExtensionPackManifestSchema = type({\n id: 'string',\n version: 'string',\n 'targets?': type({ '[string]': type({ 'minVersion?': 'string' }) }),\n 'capabilities?': 'Record<string, unknown>',\n 'types?': type({\n 'codecTypes?': type({\n import: TypesImportSpecSchema,\n }),\n 'operationTypes?': type({\n import: TypesImportSpecSchema,\n }),\n 'storage?': StorageTypeMetadataSchema.array(),\n }),\n 'operations?': 'unknown[]',\n});\n\n/**\n * Loads the adapter manifest from packs/manifest.json.\n */\nfunction loadAdapterManifest(): ExtensionPackManifest {\n const manifestPath = join(__dirname, '../../packs/manifest.json');\n const manifestJson = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n\n const result = ExtensionPackManifestSchema(manifestJson);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Invalid adapter manifest structure at ${manifestPath}: ${messages}`);\n }\n\n return result as ExtensionPackManifest;\n}\n\n/**\n * SQL runtime adapter interface for Postgres.\n * Extends RuntimeAdapterInstance with SQL-specific adapter methods.\n */\nexport interface SqlRuntimeAdapter\n extends RuntimeAdapterInstance<'sql', 'postgres'>,\n Adapter<QueryAst, PostgresContract, PostgresLoweredStatement> {}\n\n/**\n * Postgres adapter descriptor for runtime plane.\n */\nconst postgresRuntimeAdapterDescriptor: RuntimeAdapterDescriptor<\n 'sql',\n 'postgres',\n SqlRuntimeAdapter\n> = {\n kind: 'adapter',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n manifest: loadAdapterManifest(),\n create(): SqlRuntimeAdapter {\n return createPostgresAdapter() as unknown as SqlRuntimeAdapter;\n },\n};\n\nexport default postgresRuntimeAdapterDescriptor;\n"],"mappings":";;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAO9B,SAAS,YAAY;AAIrB,IAAM,aAAa,cAAc,YAAY,GAAG;AAChD,IAAM,YAAY,QAAQ,UAAU;AAEpC,IAAM,wBAAwB,KAAK;AAAA,EACjC,SAAS;AAAA,EACT,OAAO;AAAA,EACP,OAAO;AACT,CAAC;AAED,IAAM,4BAA4B,KAAK;AAAA,EACrC,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,UAAU;AAAA,EACV,eAAe;AACjB,CAAC;AAED,IAAM,8BAA8B,KAAK;AAAA,EACvC,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,YAAY,KAAK,EAAE,YAAY,KAAK,EAAE,eAAe,SAAS,CAAC,EAAE,CAAC;AAAA,EAClE,iBAAiB;AAAA,EACjB,UAAU,KAAK;AAAA,IACb,eAAe,KAAK;AAAA,MAClB,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,mBAAmB,KAAK;AAAA,MACtB,QAAQ;AAAA,IACV,CAAC;AAAA,IACD,YAAY,0BAA0B,MAAM;AAAA,EAC9C,CAAC;AAAA,EACD,eAAe;AACjB,CAAC;AAKD,SAAS,sBAA6C;AACpD,QAAM,eAAe,KAAK,WAAW,2BAA2B;AAChE,QAAM,eAAe,KAAK,MAAM,aAAa,cAAc,OAAO,CAAC;AAEnE,QAAM,SAAS,4BAA4B,YAAY;AACvD,MAAI,kBAAkB,KAAK,QAAQ;AACjC,UAAM,WAAW,OAAO,IAAI,CAAC,MAA2B,EAAE,OAAO,EAAE,KAAK,IAAI;AAC5E,UAAM,IAAI,MAAM,yCAAyC,YAAY,KAAK,QAAQ,EAAE;AAAA,EACtF;AAEA,SAAO;AACT;AAaA,IAAM,mCAIF;AAAA,EACF,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,IAAI;AAAA,EACJ,UAAU,oBAAoB;AAAA,EAC9B,SAA4B;AAC1B,WAAO,sBAAsB;AAAA,EAC/B;AACF;AAEA,IAAO,kBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../src/exports/runtime.ts"],"sourcesContent":["import type {\n RuntimeAdapterDescriptor,\n RuntimeAdapterInstance,\n} from '@prisma-next/core-execution-plane/types';\nimport type { Adapter, QueryAst } from '@prisma-next/sql-relational-core/ast';\nimport { createPostgresAdapter } from '../core/adapter';\nimport { postgresAdapterDescriptorMeta } from '../core/descriptor-meta';\nimport type { PostgresContract, PostgresLoweredStatement } from '../core/types';\n\n/**\n * SQL runtime adapter interface for Postgres.\n * Extends RuntimeAdapterInstance with SQL-specific adapter methods.\n */\nexport interface SqlRuntimeAdapter\n extends RuntimeAdapterInstance<'sql', 'postgres'>,\n Adapter<QueryAst, PostgresContract, PostgresLoweredStatement> {}\n\n/**\n * Postgres adapter descriptor for runtime plane.\n */\nconst postgresRuntimeAdapterDescriptor: RuntimeAdapterDescriptor<\n 'sql',\n 'postgres',\n SqlRuntimeAdapter\n> = {\n ...postgresAdapterDescriptorMeta,\n create(): SqlRuntimeAdapter {\n return createPostgresAdapter();\n },\n};\n\nexport default postgresRuntimeAdapterDescriptor;\n"],"mappings":";;;;;;;;;AAoBA,IAAM,mCAIF;AAAA,EACF,GAAG;AAAA,EACH,SAA4B;AAC1B,WAAO,sBAAsB;AAAA,EAC/B;AACF;AAEA,IAAO,kBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma-next/adapter-postgres",
3
- "version": "0.1.0-dev.29",
3
+ "version": "0.1.0-dev.30",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "files": [
@@ -8,17 +8,17 @@
8
8
  ],
9
9
  "dependencies": {
10
10
  "arktype": "^2.0.0",
11
- "@prisma-next/cli": "0.1.0-dev.29",
12
- "@prisma-next/contract": "0.1.0-dev.29",
13
- "@prisma-next/contract-authoring": "0.1.0-dev.29",
14
- "@prisma-next/core-control-plane": "0.1.0-dev.29",
15
- "@prisma-next/core-execution-plane": "0.1.0-dev.29",
16
- "@prisma-next/family-sql": "0.1.0-dev.29",
17
- "@prisma-next/sql-contract-ts": "0.1.0-dev.29",
18
- "@prisma-next/sql-contract": "0.1.0-dev.29",
19
- "@prisma-next/sql-operations": "0.1.0-dev.29",
20
- "@prisma-next/sql-relational-core": "0.1.0-dev.29",
21
- "@prisma-next/sql-schema-ir": "0.1.0-dev.29"
11
+ "@prisma-next/cli": "0.1.0-dev.30",
12
+ "@prisma-next/contract": "0.1.0-dev.30",
13
+ "@prisma-next/contract-authoring": "0.1.0-dev.30",
14
+ "@prisma-next/core-control-plane": "0.1.0-dev.30",
15
+ "@prisma-next/core-execution-plane": "0.1.0-dev.30",
16
+ "@prisma-next/family-sql": "0.1.0-dev.30",
17
+ "@prisma-next/sql-contract-ts": "0.1.0-dev.30",
18
+ "@prisma-next/sql-contract": "0.1.0-dev.30",
19
+ "@prisma-next/sql-operations": "0.1.0-dev.30",
20
+ "@prisma-next/sql-relational-core": "0.1.0-dev.30",
21
+ "@prisma-next/sql-schema-ir": "0.1.0-dev.30"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@vitest/coverage-v8": "^4.0.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/core/adapter.ts"],"sourcesContent":["import type {\n Adapter,\n AdapterProfile,\n BinaryExpr,\n ColumnRef,\n DeleteAst,\n ExistsExpr,\n IncludeRef,\n InsertAst,\n JoinAst,\n LiteralExpr,\n LowererContext,\n OperationExpr,\n ParamRef,\n QueryAst,\n SelectAst,\n UpdateAst,\n} from '@prisma-next/sql-relational-core/ast';\nimport { createCodecRegistry, isOperationExpr } from '@prisma-next/sql-relational-core/ast';\nimport { codecDefinitions } from './codecs';\nimport type { PostgresAdapterOptions, PostgresContract, PostgresLoweredStatement } from './types';\n\nconst VECTOR_CODEC_ID = 'pg/vector@1' as const;\n\nconst defaultCapabilities = Object.freeze({\n postgres: {\n orderBy: true,\n limit: true,\n lateral: true,\n jsonAgg: true,\n returning: true,\n },\n});\n\nclass PostgresAdapterImpl implements Adapter<QueryAst, PostgresContract, PostgresLoweredStatement> {\n readonly profile: AdapterProfile<'postgres'>;\n private readonly codecRegistry = (() => {\n const registry = createCodecRegistry();\n for (const definition of Object.values(codecDefinitions)) {\n registry.register(definition.codec);\n }\n return registry;\n })();\n\n constructor(options?: PostgresAdapterOptions) {\n this.profile = Object.freeze({\n id: options?.profileId ?? 'postgres/default@1',\n target: 'postgres',\n capabilities: defaultCapabilities,\n codecs: () => this.codecRegistry,\n });\n }\n\n lower(ast: QueryAst, context: LowererContext<PostgresContract>) {\n let sql: string;\n const params = context.params ? [...context.params] : [];\n\n if (ast.kind === 'select') {\n sql = renderSelect(ast, context.contract);\n } else if (ast.kind === 'insert') {\n sql = renderInsert(ast, context.contract);\n } else if (ast.kind === 'update') {\n sql = renderUpdate(ast, context.contract);\n } else if (ast.kind === 'delete') {\n sql = renderDelete(ast, context.contract);\n } else {\n throw new Error(`Unsupported AST kind: ${(ast as { kind: string }).kind}`);\n }\n\n return Object.freeze({\n profileId: this.profile.id,\n body: Object.freeze({ sql, params }),\n });\n }\n}\n\nfunction renderSelect(ast: SelectAst, contract?: PostgresContract): string {\n const selectClause = `SELECT ${renderProjection(ast, contract)}`;\n const fromClause = `FROM ${quoteIdentifier(ast.from.name)}`;\n\n const joinsClause = ast.joins?.length\n ? ast.joins.map((join) => renderJoin(join, contract)).join(' ')\n : '';\n const includesClause = ast.includes?.length\n ? ast.includes.map((include) => renderInclude(include, contract)).join(' ')\n : '';\n\n const whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract)}` : '';\n const orderClause = ast.orderBy?.length\n ? ` ORDER BY ${ast.orderBy\n .map((order) => {\n const expr = renderExpr(order.expr as ColumnRef | OperationExpr, contract);\n return `${expr} ${order.dir.toUpperCase()}`;\n })\n .join(', ')}`\n : '';\n const limitClause = typeof ast.limit === 'number' ? ` LIMIT ${ast.limit}` : '';\n\n const clauses = [joinsClause, includesClause].filter(Boolean).join(' ');\n return `${selectClause} ${fromClause}${clauses ? ` ${clauses}` : ''}${whereClause}${orderClause}${limitClause}`.trim();\n}\n\nfunction renderProjection(ast: SelectAst, contract?: PostgresContract): string {\n return ast.project\n .map((item) => {\n const expr = item.expr as ColumnRef | IncludeRef | OperationExpr | LiteralExpr;\n if (expr.kind === 'includeRef') {\n // For include references, select the column from the LATERAL join alias\n // The LATERAL subquery returns a single column (the JSON array) with the alias\n // The table is aliased as {alias}_lateral, and the column inside is aliased as the include alias\n // We select it using table_alias.column_alias\n const tableAlias = `${expr.alias}_lateral`;\n return `${quoteIdentifier(tableAlias)}.${quoteIdentifier(expr.alias)} AS ${quoteIdentifier(item.alias)}`;\n }\n if (expr.kind === 'operation') {\n const operation = renderOperation(expr, contract);\n const alias = quoteIdentifier(item.alias);\n return `${operation} AS ${alias}`;\n }\n if (expr.kind === 'literal') {\n const literal = renderLiteral(expr);\n const alias = quoteIdentifier(item.alias);\n return `${literal} AS ${alias}`;\n }\n const column = renderColumn(expr as ColumnRef);\n const alias = quoteIdentifier(item.alias);\n return `${column} AS ${alias}`;\n })\n .join(', ');\n}\n\nfunction renderWhere(expr: BinaryExpr | ExistsExpr, contract?: PostgresContract): string {\n if (expr.kind === 'exists') {\n const notKeyword = expr.not ? 'NOT ' : '';\n const subquery = renderSelect(expr.subquery, contract);\n return `${notKeyword}EXISTS (${subquery})`;\n }\n return renderBinary(expr, contract);\n}\n\nfunction renderBinary(expr: BinaryExpr, contract?: PostgresContract): string {\n const leftExpr = expr.left as ColumnRef | OperationExpr;\n const left = renderExpr(leftExpr, contract);\n // Handle both ParamRef and ColumnRef on the right side\n // (ColumnRef can appear in EXISTS subqueries for correlation)\n const rightExpr = expr.right as ParamRef | ColumnRef;\n const right =\n rightExpr.kind === 'col'\n ? renderColumn(rightExpr)\n : renderParam(rightExpr as ParamRef, contract);\n // Only wrap in parentheses if it's an operation expression\n const leftRendered = isOperationExpr(leftExpr) ? `(${left})` : left;\n\n // Map operators to SQL symbols\n const operatorMap: Record<BinaryExpr['op'], string> = {\n eq: '=',\n neq: '!=',\n gt: '>',\n lt: '<',\n gte: '>=',\n lte: '<=',\n };\n\n return `${leftRendered} ${operatorMap[expr.op]} ${right}`;\n}\n\nfunction renderColumn(ref: ColumnRef): string {\n return `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;\n}\n\nfunction renderExpr(expr: ColumnRef | OperationExpr, contract?: PostgresContract): string {\n if (isOperationExpr(expr)) {\n return renderOperation(expr, contract);\n }\n return renderColumn(expr);\n}\n\nfunction renderParam(\n ref: ParamRef,\n contract?: PostgresContract,\n tableName?: string,\n columnName?: string,\n): string {\n // Cast vector parameters to vector type for PostgreSQL\n if (contract && tableName && columnName) {\n const tableMeta = contract.storage.tables[tableName];\n const columnMeta = tableMeta?.columns[columnName];\n if (columnMeta?.codecId === VECTOR_CODEC_ID) {\n return `$${ref.index}::vector`;\n }\n }\n return `$${ref.index}`;\n}\n\nfunction renderLiteral(expr: LiteralExpr): string {\n if (typeof expr.value === 'string') {\n return `'${expr.value.replace(/'/g, \"''\")}'`;\n }\n if (typeof expr.value === 'number' || typeof expr.value === 'boolean') {\n return String(expr.value);\n }\n if (expr.value === null) {\n return 'NULL';\n }\n if (Array.isArray(expr.value)) {\n return `ARRAY[${expr.value.map((v: unknown) => renderLiteral({ kind: 'literal', value: v })).join(', ')}]`;\n }\n return JSON.stringify(expr.value);\n}\n\nfunction renderOperation(expr: OperationExpr, contract?: PostgresContract): string {\n const self = renderExpr(expr.self, contract);\n // For vector operations, cast param arguments to vector type\n const isVectorOperation = expr.forTypeId === VECTOR_CODEC_ID;\n const args = expr.args.map((arg: ColumnRef | ParamRef | LiteralExpr | OperationExpr) => {\n if (arg.kind === 'col') {\n return renderColumn(arg);\n }\n if (arg.kind === 'param') {\n // Cast vector operation parameters to vector type\n return isVectorOperation ? `$${arg.index}::vector` : renderParam(arg, contract);\n }\n if (arg.kind === 'literal') {\n return renderLiteral(arg);\n }\n if (arg.kind === 'operation') {\n return renderOperation(arg, contract);\n }\n const _exhaustive: never = arg;\n throw new Error(`Unsupported argument kind: ${(_exhaustive as { kind: string }).kind}`);\n });\n\n let result = expr.lowering.template;\n result = result.replace(/\\$\\{self\\}/g, self);\n for (let i = 0; i < args.length; i++) {\n result = result.replace(new RegExp(`\\\\$\\\\{arg${i}\\\\}`, 'g'), args[i] ?? '');\n }\n\n if (expr.lowering.strategy === 'function') {\n return result;\n }\n\n return result;\n}\n\nfunction renderJoin(join: JoinAst, _contract?: PostgresContract): string {\n const joinType = join.joinType.toUpperCase();\n const table = quoteIdentifier(join.table.name);\n const onClause = renderJoinOn(join.on);\n return `${joinType} JOIN ${table} ON ${onClause}`;\n}\n\nfunction renderJoinOn(on: JoinAst['on']): string {\n if (on.kind === 'eqCol') {\n const left = renderColumn(on.left);\n const right = renderColumn(on.right);\n return `${left} = ${right}`;\n }\n throw new Error(`Unsupported join ON expression kind: ${on.kind}`);\n}\n\nfunction renderInclude(\n include: NonNullable<SelectAst['includes']>[number],\n contract?: PostgresContract,\n): string {\n const alias = include.alias;\n\n // Build the lateral subquery\n const childProjection = include.child.project\n .map((item: { alias: string; expr: ColumnRef | OperationExpr }) => {\n const expr = renderExpr(item.expr, contract);\n return `'${item.alias}', ${expr}`;\n })\n .join(', ');\n\n const jsonBuildObject = `json_build_object(${childProjection})`;\n\n // Build the ON condition from the include's ON clause - this goes in the WHERE clause\n const onCondition = renderJoinOn(include.child.on);\n\n // Build WHERE clause: combine ON condition with any additional WHERE clauses\n let whereClause = ` WHERE ${onCondition}`;\n if (include.child.where) {\n whereClause += ` AND ${renderWhere(include.child.where, contract)}`;\n }\n\n // Add ORDER BY if present - it goes inside json_agg() call\n const childOrderBy = include.child.orderBy?.length\n ? ` ORDER BY ${include.child.orderBy\n .map(\n (order: { expr: ColumnRef | OperationExpr; dir: string }) =>\n `${renderExpr(order.expr, contract)} ${order.dir.toUpperCase()}`,\n )\n .join(', ')}`\n : '';\n\n // Add LIMIT if present\n const childLimit = typeof include.child.limit === 'number' ? ` LIMIT ${include.child.limit}` : '';\n\n // Build the lateral subquery\n // When ORDER BY is present without LIMIT, it goes inside json_agg() call: json_agg(expr ORDER BY ...)\n // When LIMIT is present (with or without ORDER BY), we need to wrap in a subquery\n const childTable = quoteIdentifier(include.child.table.name);\n let subquery: string;\n if (typeof include.child.limit === 'number') {\n // With LIMIT, we need to wrap in a subquery\n // Select individual columns in inner query, then aggregate\n // Create a map of column references to their aliases for ORDER BY\n // Only ColumnRef can be mapped (OperationExpr doesn't have table/column properties)\n const columnAliasMap = new Map<string, string>();\n for (const item of include.child.project) {\n if (item.expr.kind === 'col') {\n const columnKey = `${item.expr.table}.${item.expr.column}`;\n columnAliasMap.set(columnKey, item.alias);\n }\n }\n\n const innerColumns = include.child.project\n .map((item: { alias: string; expr: ColumnRef | OperationExpr }) => {\n const expr = renderExpr(item.expr, contract);\n return `${expr} AS ${quoteIdentifier(item.alias)}`;\n })\n .join(', ');\n\n // For ORDER BY, use column aliases if the column is in the SELECT list\n const childOrderByWithAliases = include.child.orderBy?.length\n ? ` ORDER BY ${include.child.orderBy\n .map((order: { expr: ColumnRef | OperationExpr; dir: string }) => {\n if (order.expr.kind === 'col') {\n const columnKey = `${order.expr.table}.${order.expr.column}`;\n const alias = columnAliasMap.get(columnKey);\n if (alias) {\n return `${quoteIdentifier(alias)} ${order.dir.toUpperCase()}`;\n }\n }\n return `${renderExpr(order.expr, contract)} ${order.dir.toUpperCase()}`;\n })\n .join(', ')}`\n : '';\n\n const innerSelect = `SELECT ${innerColumns} FROM ${childTable}${whereClause}${childOrderByWithAliases}${childLimit}`;\n subquery = `(SELECT json_agg(row_to_json(sub.*)) AS ${quoteIdentifier(alias)} FROM (${innerSelect}) sub)`;\n } else if (childOrderBy) {\n // With ORDER BY but no LIMIT, ORDER BY goes inside json_agg()\n subquery = `(SELECT json_agg(${jsonBuildObject}${childOrderBy}) AS ${quoteIdentifier(alias)} FROM ${childTable}${whereClause})`;\n } else {\n // No ORDER BY or LIMIT\n subquery = `(SELECT json_agg(${jsonBuildObject}) AS ${quoteIdentifier(alias)} FROM ${childTable}${whereClause})`;\n }\n\n // Return the LATERAL join with ON true (the condition is in the WHERE clause)\n // The subquery returns a single column (the JSON array) with the alias\n // We use a different alias for the table to avoid ambiguity when selecting the column\n const tableAlias = `${alias}_lateral`;\n return `LEFT JOIN LATERAL ${subquery} AS ${quoteIdentifier(tableAlias)} ON true`;\n}\n\nfunction quoteIdentifier(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction renderInsert(ast: InsertAst, contract: PostgresContract): string {\n const table = quoteIdentifier(ast.table.name);\n const columns = Object.keys(ast.values).map((col) => quoteIdentifier(col));\n const tableMeta = contract.storage.tables[ast.table.name];\n const values = Object.entries(ast.values).map(([colName, val]) => {\n if (val.kind === 'param') {\n const columnMeta = tableMeta?.columns[colName];\n const isVector = columnMeta?.codecId === VECTOR_CODEC_ID;\n return isVector ? `$${val.index}::vector` : `$${val.index}`;\n }\n if (val.kind === 'col') {\n return `${quoteIdentifier(val.table)}.${quoteIdentifier(val.column)}`;\n }\n throw new Error(`Unsupported value kind in INSERT: ${(val as { kind: string }).kind}`);\n });\n\n const insertClause = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${values.join(', ')})`;\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `${insertClause}${returningClause}`;\n}\n\nfunction renderUpdate(ast: UpdateAst, contract: PostgresContract): string {\n const table = quoteIdentifier(ast.table.name);\n const tableMeta = contract.storage.tables[ast.table.name];\n const setClauses = Object.entries(ast.set).map(([col, val]) => {\n const column = quoteIdentifier(col);\n let value: string;\n if (val.kind === 'param') {\n const columnMeta = tableMeta?.columns[col];\n const isVector = columnMeta?.codecId === VECTOR_CODEC_ID;\n value = isVector ? `$${val.index}::vector` : `$${val.index}`;\n } else if (val.kind === 'col') {\n value = `${quoteIdentifier(val.table)}.${quoteIdentifier(val.column)}`;\n } else {\n throw new Error(`Unsupported value kind in UPDATE: ${(val as { kind: string }).kind}`);\n }\n return `${column} = ${value}`;\n });\n\n const whereClause = ` WHERE ${renderBinary(ast.where, contract)}`;\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `UPDATE ${table} SET ${setClauses.join(', ')}${whereClause}${returningClause}`;\n}\n\nfunction renderDelete(ast: DeleteAst, contract?: PostgresContract): string {\n const table = quoteIdentifier(ast.table.name);\n const whereClause = ` WHERE ${renderBinary(ast.where, contract)}`;\n const returningClause = ast.returning?.length\n ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(', ')}`\n : '';\n\n return `DELETE FROM ${table}${whereClause}${returningClause}`;\n}\n\nexport function createPostgresAdapter(options?: PostgresAdapterOptions) {\n return Object.freeze(new PostgresAdapterImpl(options));\n}\n"],"mappings":";;;;;AAkBA,SAAS,qBAAqB,uBAAuB;AAIrD,IAAM,kBAAkB;AAExB,IAAM,sBAAsB,OAAO,OAAO;AAAA,EACxC,UAAU;AAAA,IACR,SAAS;AAAA,IACT,OAAO;AAAA,IACP,SAAS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