@prisma-next/sql-contract-ts 0.3.0-dev.9 → 0.3.0-dev.91

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Prisma Data, Inc]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -16,15 +16,15 @@ This package contains the SQL-specific TypeScript contract authoring surface for
16
16
 
17
17
  This package is part of the SQL family namespace (`packages/2-sql/2-authoring/contract-ts`) and provides:
18
18
  - SQL contract builder (`defineContract`) - TypeScript builder for creating SQL contracts programmatically
19
- - SQL contract validation (`validateContract`) - Structural and logical validation for SQL contracts
20
19
  - SQL contract JSON schema - JSON schema for validating contract structure
21
20
 
22
21
  ## Responsibilities
23
22
 
24
23
  - **SQL Contract Builder**: Provides the `defineContract()` builder API for creating SQL contracts programmatically with type safety, including pack-ref based `.target()` and `.extensionPacks()` helpers
25
- - **SQL Contract Validation**: Implements SQL-specific contract validation (`validateContractStructure`, `validateContractLogic`, `validateContract`) and normalization
24
+ - **Storage Type Authoring**: Supports `storage.types` declarations and `typeRef` columns via the SQL builder
26
25
  - **SQL Contract JSON Schema**: Provides JSON schema for validating contract structure in IDEs and tooling
27
26
  - **Composition Layer**: Composes the target-agnostic builder core from `@prisma-next/contract-authoring` with SQL-specific types and validation logic
27
+ - **Generated Defaults**: Supports client-generated defaults via `ColumnDefault.kind = 'generated'` in contract authoring
28
28
 
29
29
  ## Package Status
30
30
 
@@ -34,9 +34,16 @@ This package was created in Phase 1 and refactored in Phase 2. It now composes t
34
34
 
35
35
  - **Composes generic core**: Uses `@prisma-next/contract-authoring` for generic builder state management (`TableBuilder`, `ModelBuilder`, `ContractBuilder` base class)
36
36
  - **SQL-specific types**: Provides SQL-specific contract types (`SqlContract`, `SqlStorage`, `SqlMappings`) from `@prisma-next/sql-contract/types`
37
- - **SQL-specific validation**: Implements SQL-specific contract validation (`validateContractStructure`, `validateContractLogic`, `validateContract`) and normalization (`normalizeContract`)
38
37
  - **SQL-specific build()**: Implements SQL-specific `build()` method in `SqlContractBuilder` that constructs `SqlContract` instances with SQL-specific structure (uniques, indexes, foreignKeys arrays)
39
38
 
39
+ ```mermaid
40
+ flowchart LR
41
+ builderInput[TS builder calls] --> sqlContractTs[@prisma-next/sql-contract-ts]
42
+ sqlContractTs --> authoringCore[@prisma-next/contract-authoring]
43
+ sqlContractTs --> sqlTypes[@prisma-next/sql-contract/types]
44
+ sqlContractTs --> contractIR[SQL ContractIR]
45
+ ```
46
+
40
47
  This package is part of the package layering architecture:
41
48
  - **Location**: `packages/2-sql/2-authoring/contract-ts` (SQL family namespace)
42
49
  - **Ring**: SQL family namespace (can import from core, authoring, targets, and other SQL family packages)
@@ -44,7 +51,7 @@ This package is part of the package layering architecture:
44
51
  ## Exports
45
52
 
46
53
  - `./contract-builder` - Contract builder API (`defineContract`, `ColumnBuilder`)
47
- - `./contract` - Contract validation (`validateContract`, `computeMappings`)
54
+ - `./config-types` - TypeScript contract config helper (`typescriptContract`)
48
55
  - `./schema-sql` - SQL contract JSON schema (`data-contract-sql-v1.json`)
49
56
 
50
57
  ## Usage
@@ -53,42 +60,98 @@ This package is part of the package layering architecture:
53
60
 
54
61
  ```typescript
55
62
  import { defineContract } from '@prisma-next/sql-contract-ts/contract-builder';
56
- import type { CodecTypes } from '@prisma-next/adapter-postgres/codec-types';
57
63
  import postgresPack from '@prisma-next/target-postgres/pack';
58
64
  import pgvector from '@prisma-next/extension-pgvector/pack';
59
- import { int4Column, textColumn } from '@prisma-next/adapter-postgres/column-types';
65
+ import { enumColumn, enumType, int4Column, textColumn } from '@prisma-next/adapter-postgres/column-types';
60
66
 
61
- const contract = defineContract<CodecTypes>()
67
+ const contract = defineContract()
62
68
  .target(postgresPack)
63
69
  .extensionPacks({ pgvector })
70
+ .storageType('Role', enumType('role', ['USER', 'ADMIN']))
64
71
  .table('user', (t) =>
65
72
  t
66
73
  .column('id', { type: int4Column, nullable: false })
67
74
  .column('email', { type: textColumn, nullable: false })
68
- .primaryKey(['id']),
75
+ .column('role', { type: enumColumn('Role', 'role') })
76
+ .primaryKey(['id'], 'user_pkey') // Named primary key
77
+ .unique(['email'], 'user_email_unique') // Named unique constraint
78
+ .index(['email'], 'user_email_idx'), // Named index
79
+ )
80
+ .table('post', (t) =>
81
+ t
82
+ .column('id', { type: int4Column, nullable: false })
83
+ .column('userId', { type: int4Column, nullable: false })
84
+ .column('title', { type: textColumn, nullable: false })
85
+ .primaryKey(['id'])
86
+ .foreignKey(['userId'], { table: 'user', columns: ['id'] }, 'post_userId_fkey'), // Named FK
69
87
  )
70
88
  .model('User', 'user', (m) => m.field('id', 'id').field('email', 'email'))
89
+ .model('Post', 'post', (m) => m.field('id', 'id').field('userId', 'userId').field('title', 'title'))
90
+ .foreignKeys({ constraints: true, indexes: false }) // Optional FK config
91
+ .build();
92
+ ```
93
+
94
+ #### Table Builder Methods
95
+
96
+ The table builder supports the following constraint methods:
97
+
98
+ | Method | Description |
99
+ |--------|-------------|
100
+ | `.primaryKey(columns, name?)` | Define primary key with optional name |
101
+ | `.unique(columns, name?)` | Add unique constraint with optional name |
102
+ | `.index(columns, name?)` | Add index with optional name |
103
+ | `.foreignKey(columns, references, name?)` | Add foreign key with optional name |
104
+
105
+ #### Contract-Level Foreign Key Configuration
106
+
107
+ The builder supports a `.foreignKeys()` method to control FK constraint and index emission:
108
+
109
+ ```typescript
110
+ const contract = defineContract<CodecTypes>()
111
+ .target(postgresPack)
112
+ // ...tables and models...
113
+ .foreignKeys({ constraints: true, indexes: false }) // Emit FK constraints but skip backing indexes
71
114
  .build();
72
115
  ```
73
116
 
117
+ | Config | Default | Description |
118
+ |--------|---------|-------------|
119
+ | `constraints` | `true` | Emit `FOREIGN KEY` constraints in DDL |
120
+ | `indexes` | `true` | Emit FK-backing indexes (e.g., `CREATE INDEX ... ON post (user_id)`) |
121
+
122
+ When `.foreignKeys()` is not called, defaults to `{ constraints: true, indexes: true }`. See [ADR 161](../../../docs/architecture%20docs/adrs/ADR%20161%20-%20Explicit%20foreign%20key%20constraint%20and%20index%20configuration.md).
123
+
74
124
  ### Validating Contracts
75
125
 
126
+ Contract JSON validation now lives in `@prisma-next/sql-contract/validate` (shared plane), while this package focuses on authoring/building contracts.
127
+
76
128
  ```typescript
77
- import { validateContract } from '@prisma-next/sql-contract-ts/contract';
78
- import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';
129
+ import { validateContract } from '@prisma-next/sql-contract/validate';
79
130
  import type { Contract } from './contract.d';
80
131
 
81
- // From JSON import
82
132
  const contract = validateContract<Contract>(contractJson);
133
+ ```
83
134
 
84
- // Or with generic type (less type-safe)
85
- const contract = validateContract<SqlContract<SqlStorage>>(contractJson);
135
+ ### Config Helper
136
+
137
+ Use `typescriptContract` from this package when wiring TS-authored contracts in `prisma-next.config.ts`.
138
+
139
+ ```typescript
140
+ import { defineConfig } from '@prisma-next/cli/config-types';
141
+ import { typescriptContract } from '@prisma-next/sql-contract-ts/config-types';
142
+ import { contract } from './src/prisma/contract';
143
+
144
+ export default defineConfig({
145
+ // ...
146
+ contract: typescriptContract(contract, 'src/prisma/contract.json'),
147
+ });
86
148
  ```
87
149
 
88
150
  ## Dependencies
89
151
 
90
152
  - **`@prisma-next/contract-authoring`** - Target-agnostic builder core (builder state types, builder classes, type helpers)
91
153
  - **`@prisma-next/contract`** - Core contract types (`ContractBase`)
154
+ - **`@prisma-next/core-control-plane`** - Contract config types used by `typescriptContract`
92
155
  - **`@prisma-next/sql-contract`** - SQL contract types (`SqlContract`, `SqlStorage`, `SqlMappings`)
93
156
  - **`arktype`** - Runtime validation
94
157
  - **`ts-toolbelt`** - Type utilities
@@ -106,4 +169,6 @@ Integration tests that depend on both `sql-contract-ts` and `sql-query` are loca
106
169
  ## See Also
107
170
 
108
171
  - `@prisma-next/contract-authoring` - Target-agnostic builder core that this package composes
172
+ - `@prisma-next/sql-contract-psl` - PSL parser-output to SQL `ContractIR` interpreter for provider-based flows
173
+ - `@prisma-next/sql-contract-psl/provider` - SQL PSL-first `prismaContract()` helper (read -> parse -> interpret)
109
174
 
@@ -0,0 +1,8 @@
1
+ import { ContractConfig, ContractConfig as ContractConfig$1 } from "@prisma-next/config/config-types";
2
+ import { ContractIR } from "@prisma-next/contract/ir";
3
+
4
+ //#region src/config-types.d.ts
5
+ declare function typescriptContract(contractIR: ContractIR, output?: string): ContractConfig$1;
6
+ //#endregion
7
+ export { type ContractConfig, typescriptContract };
8
+ //# sourceMappingURL=config-types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-types.d.mts","names":[],"sources":["../src/config-types.ts"],"sourcesContent":[],"mappings":";;;;iBAKgB,kBAAA,aAA+B,8BAA8B"}
@@ -0,0 +1,14 @@
1
+ import { ifDefined } from "@prisma-next/utils/defined";
2
+ import { ok } from "@prisma-next/utils/result";
3
+
4
+ //#region src/config-types.ts
5
+ function typescriptContract(contractIR, output) {
6
+ return {
7
+ source: async (_context) => ok(contractIR),
8
+ ...ifDefined("output", output)
9
+ };
10
+ }
11
+
12
+ //#endregion
13
+ export { typescriptContract };
14
+ //# sourceMappingURL=config-types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-types.mjs","names":[],"sources":["../src/config-types.ts"],"sourcesContent":["import type { ContractConfig } from '@prisma-next/config/config-types';\nimport type { ContractIR } from '@prisma-next/contract/ir';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { ok } from '@prisma-next/utils/result';\n\nexport function typescriptContract(contractIR: ContractIR, output?: string): ContractConfig {\n return {\n source: async (_context) => ok(contractIR),\n ...ifDefined('output', output),\n };\n}\n"],"mappings":";;;;AAKA,SAAgB,mBAAmB,YAAwB,QAAiC;AAC1F,QAAO;EACL,QAAQ,OAAO,aAAa,GAAG,WAAW;EAC1C,GAAG,UAAU,UAAU,OAAO;EAC/B"}
@@ -0,0 +1,97 @@
1
+ import { BuildModels, BuildRelations, BuildStorageColumn, ColumnBuilderState, ContractBuilder, ContractBuilderState, ExtractColumns, ExtractPrimaryKey, ForeignKeyDefaultsState, ModelBuilder, ModelBuilderState, RelationDefinition, TableBuilder, TableBuilderState } from "@prisma-next/contract-authoring";
2
+ import { ContractWithTypeMaps, Index, ReferentialAction, SqlContract, SqlMappings, StorageTypeInstance, TypeMaps } from "@prisma-next/sql-contract/types";
3
+ import { ExtensionPackRef, TargetPackRef } from "@prisma-next/contract/framework-components";
4
+
5
+ //#region src/contract-builder.d.ts
6
+
7
+ type ContractBuilderMappings = SqlMappings;
8
+ type ExtractCodecTypesFromPack<P> = P extends {
9
+ __codecTypes?: infer C;
10
+ } ? C extends Record<string, {
11
+ output: unknown;
12
+ }> ? C : Record<string, never> : Record<string, never>;
13
+ type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
14
+ type MergeExtensionCodecTypes<Packs extends Record<string, unknown>> = UnionToIntersection<{ [K in keyof Packs]: ExtractCodecTypesFromPack<Packs[K]> }[keyof Packs]>;
15
+ type BuildStorageTable<_TableName extends string, Columns extends Record<string, ColumnBuilderState<string, boolean, string>>, PK extends readonly string[] | undefined> = {
16
+ readonly columns: { readonly [K in keyof Columns]: Columns[K] extends ColumnBuilderState<string, infer Null, infer TType> ? BuildStorageColumn<Null & boolean, TType> : never };
17
+ readonly uniques: ReadonlyArray<{
18
+ readonly columns: readonly string[];
19
+ readonly name?: string;
20
+ }>;
21
+ readonly indexes: ReadonlyArray<Index>;
22
+ readonly foreignKeys: ReadonlyArray<{
23
+ readonly columns: readonly string[];
24
+ readonly references: {
25
+ readonly table: string;
26
+ readonly columns: readonly string[];
27
+ };
28
+ readonly name?: string;
29
+ readonly onDelete?: ReferentialAction;
30
+ readonly onUpdate?: ReferentialAction;
31
+ readonly constraint: boolean;
32
+ readonly index: boolean;
33
+ }>;
34
+ } & (PK extends readonly string[] ? {
35
+ readonly primaryKey: {
36
+ readonly columns: PK;
37
+ readonly name?: string;
38
+ };
39
+ } : Record<string, never>);
40
+ type BuildStorage<Tables extends Record<string, TableBuilderState<string, Record<string, ColumnBuilderState<string, boolean, string>>, readonly string[] | undefined>>, Types extends Record<string, StorageTypeInstance>> = {
41
+ readonly tables: { readonly [K in keyof Tables]: BuildStorageTable<K & string, ExtractColumns<Tables[K]>, ExtractPrimaryKey<Tables[K]>> };
42
+ readonly types: Types;
43
+ };
44
+ interface ColumnBuilder<Name extends string, Nullable extends boolean, Type extends string> {
45
+ nullable<Value extends boolean>(value?: Value): ColumnBuilder<Name, Value, Type>;
46
+ type<Id extends string>(id: Id): ColumnBuilder<Name, Nullable, Id>;
47
+ build(): ColumnBuilderState<Name, Nullable, Type>;
48
+ }
49
+ declare class SqlContractBuilder<CodecTypes extends Record<string, {
50
+ output: unknown;
51
+ }> = Record<string, never>, Target extends string | undefined = undefined, Tables extends Record<string, TableBuilderState<string, Record<string, ColumnBuilderState<string, boolean, string>>, readonly string[] | undefined>> = Record<never, never>, Models extends Record<string, ModelBuilderState<string, string, Record<string, string>, Record<string, RelationDefinition>>> = Record<never, never>, Types extends Record<string, StorageTypeInstance> = Record<never, never>, StorageHash extends string | undefined = undefined, ExtensionPacks extends Record<string, unknown> | undefined = undefined, Capabilities extends Record<string, Record<string, boolean>> | undefined = undefined> extends ContractBuilder<Target, Tables, Models, StorageHash, ExtensionPacks, Capabilities> {
52
+ protected readonly state: ContractBuilderState<Target, Tables, Models, StorageHash, ExtensionPacks, Capabilities> & {
53
+ readonly storageTypes?: Types;
54
+ };
55
+ /**
56
+ * This method is responsible for normalizing the contract IR by setting default values
57
+ * for all required fields:
58
+ * - `nullable`: defaults to `false` if not provided
59
+ * - `uniques`: defaults to `[]` (empty array)
60
+ * - `indexes`: defaults to `[]` (empty array)
61
+ * - `foreignKeys`: defaults to `[]` (empty array)
62
+ * - `relations`: defaults to `{}` (empty object) for both model-level and contract-level
63
+ * - `nativeType`: required field set from column type descriptor when columns are defined
64
+ *
65
+ * The contract builder is the **only** place where normalization should occur.
66
+ * Validators, parsers, and emitters should assume the contract is already normalized.
67
+ *
68
+ * **Required**: Use column type descriptors (e.g., `int4Column`, `textColumn`) when defining columns.
69
+ * This ensures `nativeType` is set correctly at build time.
70
+ *
71
+ * @returns A normalized SqlContract with all required fields present
72
+ */
73
+ build(): Target extends string ? ContractWithTypeMaps<SqlContract<BuildStorage<Tables, Types>, BuildModels<Models>, BuildRelations<Models>, ContractBuilderMappings> & {
74
+ readonly schemaVersion: '1';
75
+ readonly target: Target;
76
+ readonly targetFamily: 'sql';
77
+ readonly storageHash: StorageHash extends string ? StorageHash : string;
78
+ } & (ExtensionPacks extends Record<string, unknown> ? {
79
+ readonly extensionPacks: ExtensionPacks;
80
+ } : Record<string, never>) & (Capabilities extends Record<string, Record<string, boolean>> ? {
81
+ readonly capabilities: Capabilities;
82
+ } : Record<string, never>), TypeMaps<CodecTypes, Record<string, never>>> : never;
83
+ target<T extends string, TPack extends TargetPackRef<string, T> = TargetPackRef<string, T>>(packRef: TPack & TargetPackRef<string, T>): SqlContractBuilder<ExtractCodecTypesFromPack<TPack> extends Record<string, never> ? CodecTypes : ExtractCodecTypesFromPack<TPack>, T, Tables, Models, Types, StorageHash, ExtensionPacks, Capabilities>;
84
+ extensionPacks<const Packs extends Record<string, ExtensionPackRef<'sql', string>>>(packs: Packs): SqlContractBuilder<CodecTypes & MergeExtensionCodecTypes<Packs>, Target, Tables, Models, Types, StorageHash, ExtensionPacks, Capabilities>;
85
+ capabilities<C extends Record<string, Record<string, boolean>>>(capabilities: C): SqlContractBuilder<CodecTypes, Target, Tables, Models, Types, StorageHash, ExtensionPacks, C>;
86
+ storageHash<H extends string>(hash: H): SqlContractBuilder<CodecTypes, Target, Tables, Models, Types, H, ExtensionPacks, Capabilities>;
87
+ table<TableName extends string, T extends TableBuilder<TableName, Record<string, ColumnBuilderState<string, boolean, string>>, readonly string[] | undefined>>(name: TableName, callback: (t: TableBuilder<TableName>) => T | undefined): SqlContractBuilder<CodecTypes, Target, Tables & Record<TableName, ReturnType<T['build']>>, Models, Types, StorageHash, ExtensionPacks, Capabilities>;
88
+ model<ModelName extends string, TableName extends string, M extends ModelBuilder<ModelName, TableName, Record<string, string>, Record<string, RelationDefinition>>>(name: ModelName, table: TableName, callback: (m: ModelBuilder<ModelName, TableName, Record<never, never>, Record<never, never>>) => M | undefined): SqlContractBuilder<CodecTypes, Target, Tables, Models & Record<ModelName, ReturnType<M['build']>>, Types, StorageHash, ExtensionPacks, Capabilities>;
89
+ foreignKeyDefaults(config: ForeignKeyDefaultsState): SqlContractBuilder<CodecTypes, Target, Tables, Models, Types, StorageHash, ExtensionPacks, Capabilities>;
90
+ storageType<Name extends string, Type extends StorageTypeInstance>(name: Name, typeInstance: Type): SqlContractBuilder<CodecTypes, Target, Tables, Models, Types & Record<Name, Type>, StorageHash, ExtensionPacks, Capabilities>;
91
+ }
92
+ declare function defineContract<CodecTypes extends Record<string, {
93
+ output: unknown;
94
+ }> = Record<string, never>>(): SqlContractBuilder<CodecTypes>;
95
+ //#endregion
96
+ export { type ColumnBuilder, defineContract };
97
+ //# sourceMappingURL=contract-builder.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-builder.d.mts","names":[],"sources":["../src/contract-builder.ts"],"sourcesContent":[],"mappings":";;;;;;KAsIK,uBAAA,GAA0B,WA0DA;KAxD1B,yBAwDW,CAAA,CAAA,CAAA,GAxDoB,CAwDpB,SAAA;EAGS,YAAA,CAAA,EAAA,KAAA,EAAA;CACnB,GAAA,CAAA,SA3DQ,MA2DR,CAAA,MAAA,EAAA;EACe,MAAA,EAAA,OAAA;CAAO,CAAA,GAAA,CAAA,GA1DtB,MA0DsB,CAAA,MAAA,EAAA,KAAA,CAAA,GAzDxB,MAyDwB,CAAA,MAAA,EAAA,KAAA,CAAA;KAvDvB,mBAuDC,CAAA,CAAA,CAAA,GAAA,CAvDyB,CAuDzB,SAAA,OAAA,GAAA,CAAA,CAAA,EAvDiD,CAuDjD,EAAA,GAAA,IAAA,GAAA,KAAA,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