@prisma-next/sql-contract-ts 0.3.0-dev.4 → 0.3.0-dev.41

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.
@@ -0,0 +1,886 @@
1
+ import type { ExtensionPackRef, TargetPackRef } from '@prisma-next/contract/framework-components';
2
+ import type {
3
+ ColumnDefault,
4
+ ColumnDefaultLiteralInputValue,
5
+ ColumnDefaultLiteralValue,
6
+ ExecutionMutationDefault,
7
+ ExecutionMutationDefaultValue,
8
+ TaggedRaw,
9
+ } from '@prisma-next/contract/types';
10
+ import type {
11
+ ColumnBuilderState,
12
+ ColumnTypeDescriptor,
13
+ ContractBuilderState,
14
+ ForeignKeyDefaultsState,
15
+ ModelBuilderState,
16
+ RelationDefinition,
17
+ TableBuilderState,
18
+ } from '@prisma-next/contract-authoring';
19
+ import {
20
+ type BuildModels,
21
+ type BuildRelations,
22
+ type BuildStorageColumn,
23
+ ContractBuilder,
24
+ createTable,
25
+ type ExtractColumns,
26
+ type ExtractPrimaryKey,
27
+ ModelBuilder,
28
+ type Mutable,
29
+ TableBuilder,
30
+ } from '@prisma-next/contract-authoring';
31
+ import {
32
+ applyFkDefaults,
33
+ type ModelDefinition,
34
+ type ModelField,
35
+ type SqlContract,
36
+ type SqlMappings,
37
+ type SqlStorage,
38
+ type StorageTypeInstance,
39
+ } from '@prisma-next/sql-contract/types';
40
+ import { ifDefined } from '@prisma-next/utils/defined';
41
+ import { computeMappings } from './contract';
42
+
43
+ type ColumnDefaultForCodec<
44
+ CodecTypes extends Record<string, { output: unknown }>,
45
+ CodecId extends string,
46
+ > =
47
+ | {
48
+ readonly kind: 'literal';
49
+ readonly value: CodecId extends keyof CodecTypes ? CodecTypes[CodecId]['output'] : unknown;
50
+ }
51
+ | { readonly kind: 'function'; readonly expression: string };
52
+
53
+ type SqlNullableColumnOptions<
54
+ Descriptor extends ColumnTypeDescriptor,
55
+ CodecTypes extends Record<string, { output: unknown }>,
56
+ > = {
57
+ readonly type: Descriptor;
58
+ readonly nullable: true;
59
+ readonly typeParams?: Record<string, unknown>;
60
+ readonly default?: ColumnDefaultForCodec<CodecTypes, Descriptor['codecId']>;
61
+ };
62
+
63
+ type SqlNonNullableColumnOptions<
64
+ Descriptor extends ColumnTypeDescriptor,
65
+ CodecTypes extends Record<string, { output: unknown }>,
66
+ > = {
67
+ readonly type: Descriptor;
68
+ readonly nullable?: false;
69
+ readonly typeParams?: Record<string, unknown>;
70
+ readonly default?: ColumnDefaultForCodec<CodecTypes, Descriptor['codecId']>;
71
+ };
72
+
73
+ type SqlGeneratedColumnOptions<
74
+ Descriptor extends ColumnTypeDescriptor,
75
+ CodecTypes extends Record<string, { output: unknown }>,
76
+ > = Omit<SqlNonNullableColumnOptions<Descriptor, CodecTypes>, 'default' | 'nullable'> & {
77
+ readonly nullable?: false;
78
+ readonly generated: ExecutionMutationDefaultValue;
79
+ };
80
+
81
+ type SqlColumnOptions<
82
+ Descriptor extends ColumnTypeDescriptor,
83
+ CodecTypes extends Record<string, { output: unknown }>,
84
+ > =
85
+ | SqlNullableColumnOptions<Descriptor, CodecTypes>
86
+ | SqlNonNullableColumnOptions<Descriptor, CodecTypes>;
87
+
88
+ export interface SqlTableBuilder<
89
+ Name extends string,
90
+ CodecTypes extends Record<string, { output: unknown }>,
91
+ Columns extends Record<string, ColumnBuilderState<string, boolean, string>> = Record<
92
+ never,
93
+ ColumnBuilderState<string, boolean, string>
94
+ >,
95
+ PrimaryKey extends readonly string[] | undefined = undefined,
96
+ > extends Omit<TableBuilder<Name, Columns, PrimaryKey>, 'column' | 'generated'> {
97
+ column<ColName extends string, Descriptor extends ColumnTypeDescriptor>(
98
+ name: ColName,
99
+ options: SqlNullableColumnOptions<Descriptor, CodecTypes>,
100
+ ): TableBuilder<
101
+ Name,
102
+ Columns & Record<ColName, ColumnBuilderState<ColName, true, Descriptor['codecId']>>,
103
+ PrimaryKey
104
+ >;
105
+ column<ColName extends string, Descriptor extends ColumnTypeDescriptor>(
106
+ name: ColName,
107
+ options: SqlNonNullableColumnOptions<Descriptor, CodecTypes>,
108
+ ): TableBuilder<
109
+ Name,
110
+ Columns & Record<ColName, ColumnBuilderState<ColName, false, Descriptor['codecId']>>,
111
+ PrimaryKey
112
+ >;
113
+ column<ColName extends string, Descriptor extends ColumnTypeDescriptor>(
114
+ name: ColName,
115
+ options: SqlColumnOptions<Descriptor, CodecTypes>,
116
+ ): TableBuilder<
117
+ Name,
118
+ Columns & Record<ColName, ColumnBuilderState<ColName, boolean, Descriptor['codecId']>>,
119
+ PrimaryKey
120
+ >;
121
+ generated<ColName extends string, Descriptor extends ColumnTypeDescriptor>(
122
+ name: ColName,
123
+ options: SqlGeneratedColumnOptions<Descriptor, CodecTypes>,
124
+ ): TableBuilder<
125
+ Name,
126
+ Columns & Record<ColName, ColumnBuilderState<ColName, false, Descriptor['codecId']>>,
127
+ PrimaryKey
128
+ >;
129
+ }
130
+
131
+ /**
132
+ * Type-level mappings structure for contracts built via `defineContract()`.
133
+ *
134
+ * Compile-time type helper (not a runtime object) that ensures mappings match what the builder
135
+ * produces. `codecTypes` uses the generic `CodecTypes` parameter; `operationTypes` is always
136
+ * empty since operations are added via extensions at runtime.
137
+ *
138
+ * **Difference from ExecutionContext**: This is a compile-time type for contract construction.
139
+ * `ExecutionContext` is a runtime object with populated registries for query execution.
140
+ *
141
+ * @template C - The `CodecTypes` generic parameter passed to `defineContract<CodecTypes>()`
142
+ */
143
+ type ContractBuilderMappings<C extends Record<string, { output: unknown }>> = Omit<
144
+ SqlMappings,
145
+ 'codecTypes' | 'operationTypes'
146
+ > & {
147
+ readonly codecTypes: C;
148
+ readonly operationTypes: Record<string, never>;
149
+ };
150
+
151
+ type BuildStorageTable<
152
+ _TableName extends string,
153
+ Columns extends Record<string, ColumnBuilderState<string, boolean, string>>,
154
+ PK extends readonly string[] | undefined,
155
+ > = {
156
+ readonly columns: {
157
+ readonly [K in keyof Columns]: Columns[K] extends ColumnBuilderState<
158
+ string,
159
+ infer Null,
160
+ infer TType
161
+ >
162
+ ? BuildStorageColumn<Null & boolean, TType>
163
+ : never;
164
+ };
165
+ readonly uniques: ReadonlyArray<{ readonly columns: readonly string[]; readonly name?: string }>;
166
+ readonly indexes: ReadonlyArray<{ readonly columns: readonly string[]; readonly name?: string }>;
167
+ readonly foreignKeys: ReadonlyArray<{
168
+ readonly columns: readonly string[];
169
+ readonly references: { readonly table: string; readonly columns: readonly string[] };
170
+ readonly name?: string;
171
+ readonly constraint: boolean;
172
+ readonly index: boolean;
173
+ }>;
174
+ } & (PK extends readonly string[]
175
+ ? { readonly primaryKey: { readonly columns: PK; readonly name?: string } }
176
+ : Record<string, never>);
177
+
178
+ type BuildStorage<
179
+ Tables extends Record<
180
+ string,
181
+ TableBuilderState<
182
+ string,
183
+ Record<string, ColumnBuilderState<string, boolean, string>>,
184
+ readonly string[] | undefined
185
+ >
186
+ >,
187
+ Types extends Record<string, StorageTypeInstance>,
188
+ > = {
189
+ readonly tables: {
190
+ readonly [K in keyof Tables]: BuildStorageTable<
191
+ K & string,
192
+ ExtractColumns<Tables[K]>,
193
+ ExtractPrimaryKey<Tables[K]>
194
+ >;
195
+ };
196
+ readonly types: Types;
197
+ };
198
+
199
+ type BuildStorageTables<
200
+ Tables extends Record<
201
+ string,
202
+ TableBuilderState<
203
+ string,
204
+ Record<string, ColumnBuilderState<string, boolean, string>>,
205
+ readonly string[] | undefined
206
+ >
207
+ >,
208
+ > = {
209
+ readonly [K in keyof Tables]: BuildStorageTable<
210
+ K & string,
211
+ ExtractColumns<Tables[K]>,
212
+ ExtractPrimaryKey<Tables[K]>
213
+ >;
214
+ };
215
+
216
+ export interface ColumnBuilder<Name extends string, Nullable extends boolean, Type extends string> {
217
+ nullable<Value extends boolean>(value?: Value): ColumnBuilder<Name, Value, Type>;
218
+ type<Id extends string>(id: Id): ColumnBuilder<Name, Nullable, Id>;
219
+ build(): ColumnBuilderState<Name, Nullable, Type>;
220
+ }
221
+
222
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
223
+ if (typeof value !== 'object' || value === null) return false;
224
+ const proto = Object.getPrototypeOf(value);
225
+ return proto === Object.prototype || proto === null;
226
+ }
227
+
228
+ function isJsonValue(value: unknown): value is ColumnDefaultLiteralValue {
229
+ if (value === null) return true;
230
+ const valueType = typeof value;
231
+ if (valueType === 'string' || valueType === 'number' || valueType === 'boolean') return true;
232
+ if (Array.isArray(value)) {
233
+ return value.every((item) => isJsonValue(item));
234
+ }
235
+ if (isPlainObject(value)) {
236
+ return Object.values(value).every((item) => isJsonValue(item));
237
+ }
238
+ return false;
239
+ }
240
+
241
+ function encodeDefaultLiteralValue(
242
+ value: ColumnDefaultLiteralInputValue,
243
+ ): ColumnDefaultLiteralValue {
244
+ if (typeof value === 'bigint') {
245
+ return { $type: 'bigint', value: value.toString() };
246
+ }
247
+ if (value instanceof Date) {
248
+ return value.toISOString();
249
+ }
250
+ if (isJsonValue(value)) {
251
+ if (isPlainObject(value) && '$type' in value) {
252
+ return { $type: 'raw', value } satisfies TaggedRaw;
253
+ }
254
+ return value;
255
+ }
256
+ throw new Error(
257
+ 'Unsupported column default literal value: expected JSON-safe value, bigint, or Date.',
258
+ );
259
+ }
260
+
261
+ function encodeColumnDefault(defaultInput: ColumnDefault): ColumnDefault {
262
+ if (defaultInput.kind === 'function') {
263
+ return { kind: 'function', expression: defaultInput.expression };
264
+ }
265
+ return { kind: 'literal', value: encodeDefaultLiteralValue(defaultInput.value) };
266
+ }
267
+
268
+ class SqlContractBuilder<
269
+ CodecTypes extends Record<string, { output: unknown }> = Record<string, never>,
270
+ Target extends string | undefined = undefined,
271
+ Tables extends Record<
272
+ string,
273
+ TableBuilderState<
274
+ string,
275
+ Record<string, ColumnBuilderState<string, boolean, string>>,
276
+ readonly string[] | undefined
277
+ >
278
+ > = Record<never, never>,
279
+ Models extends Record<
280
+ string,
281
+ ModelBuilderState<string, string, Record<string, string>, Record<string, RelationDefinition>>
282
+ > = Record<never, never>,
283
+ Types extends Record<string, StorageTypeInstance> = Record<never, never>,
284
+ StorageHash extends string | undefined = undefined,
285
+ ExtensionPacks extends Record<string, unknown> | undefined = undefined,
286
+ Capabilities extends Record<string, Record<string, boolean>> | undefined = undefined,
287
+ > extends ContractBuilder<Target, Tables, Models, StorageHash, ExtensionPacks, Capabilities> {
288
+ protected declare readonly state: ContractBuilderState<
289
+ Target,
290
+ Tables,
291
+ Models,
292
+ StorageHash,
293
+ ExtensionPacks,
294
+ Capabilities
295
+ > & {
296
+ readonly storageTypes?: Types;
297
+ };
298
+ /**
299
+ * This method is responsible for normalizing the contract IR by setting default values
300
+ * for all required fields:
301
+ * - `nullable`: defaults to `false` if not provided
302
+ * - `uniques`: defaults to `[]` (empty array)
303
+ * - `indexes`: defaults to `[]` (empty array)
304
+ * - `foreignKeys`: defaults to `[]` (empty array)
305
+ * - `relations`: defaults to `{}` (empty object) for both model-level and contract-level
306
+ * - `nativeType`: required field set from column type descriptor when columns are defined
307
+ *
308
+ * The contract builder is the **only** place where normalization should occur.
309
+ * Validators, parsers, and emitters should assume the contract is already normalized.
310
+ *
311
+ * **Required**: Use column type descriptors (e.g., `int4Column`, `textColumn`) when defining columns.
312
+ * This ensures `nativeType` is set correctly at build time.
313
+ *
314
+ * @returns A normalized SqlContract with all required fields present
315
+ */
316
+ build(): Target extends string
317
+ ? SqlContract<
318
+ BuildStorage<Tables, Types>,
319
+ BuildModels<Models>,
320
+ BuildRelations<Models>,
321
+ ContractBuilderMappings<CodecTypes>
322
+ > & {
323
+ readonly schemaVersion: '1';
324
+ readonly target: Target;
325
+ readonly targetFamily: 'sql';
326
+ readonly storageHash: StorageHash extends string ? StorageHash : string;
327
+ } & (ExtensionPacks extends Record<string, unknown>
328
+ ? { readonly extensionPacks: ExtensionPacks }
329
+ : Record<string, never>) &
330
+ (Capabilities extends Record<string, Record<string, boolean>>
331
+ ? { readonly capabilities: Capabilities }
332
+ : Record<string, never>)
333
+ : never {
334
+ // Type helper to ensure literal types are preserved in return type
335
+ type BuiltContract = Target extends string
336
+ ? SqlContract<
337
+ BuildStorage<Tables, Types>,
338
+ BuildModels<Models>,
339
+ BuildRelations<Models>,
340
+ ContractBuilderMappings<CodecTypes>
341
+ > & {
342
+ readonly schemaVersion: '1';
343
+ readonly target: Target;
344
+ readonly targetFamily: 'sql';
345
+ readonly storageHash: StorageHash extends string ? StorageHash : string;
346
+ } & (ExtensionPacks extends Record<string, unknown>
347
+ ? { readonly extensionPacks: ExtensionPacks }
348
+ : Record<string, never>) &
349
+ (Capabilities extends Record<string, Record<string, boolean>>
350
+ ? { readonly capabilities: Capabilities }
351
+ : Record<string, never>)
352
+ : never;
353
+ if (!this.state.target) {
354
+ throw new Error('target is required. Call .target() before .build()');
355
+ }
356
+
357
+ const target = this.state.target as Target & string;
358
+
359
+ const storageTables = {} as Partial<Mutable<BuildStorageTables<Tables>>>;
360
+ const executionDefaults: ExecutionMutationDefault[] = [];
361
+
362
+ for (const tableName of Object.keys(this.state.tables) as Array<keyof Tables & string>) {
363
+ const tableState = this.state.tables[tableName];
364
+ if (!tableState) continue;
365
+
366
+ type TableKey = typeof tableName;
367
+ type ColumnDefs = ExtractColumns<Tables[TableKey]>;
368
+ type PrimaryKey = ExtractPrimaryKey<Tables[TableKey]>;
369
+
370
+ const columns = {} as Partial<{
371
+ [K in keyof ColumnDefs]: BuildStorageColumn<
372
+ ColumnDefs[K]['nullable'] & boolean,
373
+ ColumnDefs[K]['type']
374
+ >;
375
+ }>;
376
+
377
+ for (const columnName in tableState.columns) {
378
+ const columnState = tableState.columns[columnName];
379
+ if (!columnState) continue;
380
+ const codecId = columnState.type;
381
+ const nativeType = columnState.nativeType;
382
+ const typeRef = columnState.typeRef;
383
+
384
+ const encodedDefault =
385
+ columnState.default !== undefined
386
+ ? encodeColumnDefault(columnState.default as ColumnDefault)
387
+ : undefined;
388
+
389
+ columns[columnName as keyof ColumnDefs] = {
390
+ nativeType,
391
+ codecId,
392
+ nullable: (columnState.nullable ?? false) as ColumnDefs[keyof ColumnDefs]['nullable'] &
393
+ boolean,
394
+ ...ifDefined('typeParams', columnState.typeParams),
395
+ ...ifDefined('default', encodedDefault),
396
+ ...ifDefined('typeRef', typeRef),
397
+ } as BuildStorageColumn<
398
+ ColumnDefs[keyof ColumnDefs]['nullable'] & boolean,
399
+ ColumnDefs[keyof ColumnDefs]['type']
400
+ >;
401
+
402
+ if ('executionDefault' in columnState && columnState.executionDefault) {
403
+ executionDefaults.push({
404
+ ref: { table: tableName, column: columnName },
405
+ onCreate: columnState.executionDefault,
406
+ });
407
+ }
408
+ }
409
+
410
+ // Build uniques from table state
411
+ const uniques = (tableState.uniques ?? []).map((u) => ({
412
+ columns: u.columns,
413
+ ...(u.name ? { name: u.name } : {}),
414
+ }));
415
+
416
+ // Build indexes from table state
417
+ const indexes = (tableState.indexes ?? []).map((i) => ({
418
+ columns: i.columns,
419
+ ...(i.name ? { name: i.name } : {}),
420
+ }));
421
+
422
+ // Build foreign keys from table state, materializing defaults
423
+ const foreignKeys = (tableState.foreignKeys ?? []).map((fk) => ({
424
+ columns: fk.columns,
425
+ references: fk.references,
426
+ ...applyFkDefaults(fk, this.state.foreignKeyDefaults),
427
+ ...(fk.name ? { name: fk.name } : {}),
428
+ }));
429
+
430
+ const table = {
431
+ columns: columns as {
432
+ [K in keyof ColumnDefs]: BuildStorageColumn<
433
+ ColumnDefs[K]['nullable'] & boolean,
434
+ ColumnDefs[K]['type']
435
+ >;
436
+ },
437
+ uniques,
438
+ indexes,
439
+ foreignKeys,
440
+ ...(tableState.primaryKey
441
+ ? {
442
+ primaryKey: {
443
+ columns: tableState.primaryKey,
444
+ ...(tableState.primaryKeyName ? { name: tableState.primaryKeyName } : {}),
445
+ },
446
+ }
447
+ : {}),
448
+ } as unknown as BuildStorageTable<TableKey & string, ColumnDefs, PrimaryKey>;
449
+
450
+ (storageTables as Mutable<BuildStorageTables<Tables>>)[tableName] = table;
451
+ }
452
+
453
+ const storageTypes = (this.state.storageTypes ?? {}) as Types;
454
+ const storage: BuildStorage<Tables, Types> = {
455
+ tables: storageTables as BuildStorageTables<Tables>,
456
+ types: storageTypes,
457
+ };
458
+
459
+ const execution =
460
+ executionDefaults.length > 0
461
+ ? {
462
+ mutations: {
463
+ defaults: executionDefaults.sort((a, b) => {
464
+ const tableCompare = a.ref.table.localeCompare(b.ref.table);
465
+ if (tableCompare !== 0) {
466
+ return tableCompare;
467
+ }
468
+ return a.ref.column.localeCompare(b.ref.column);
469
+ }),
470
+ },
471
+ }
472
+ : undefined;
473
+
474
+ // Build models - construct as partial first, then assert full type
475
+ const modelsPartial: Partial<BuildModels<Models>> = {};
476
+
477
+ // Iterate over models - TypeScript will see keys as string, but type assertion preserves literals
478
+ for (const modelName in this.state.models) {
479
+ const modelState = this.state.models[modelName];
480
+ if (!modelState) continue;
481
+
482
+ const modelStateTyped = modelState as unknown as {
483
+ name: string;
484
+ table: string;
485
+ fields: Record<string, string>;
486
+ };
487
+
488
+ // Build fields object
489
+ const fields: Partial<Record<string, ModelField>> = {};
490
+
491
+ // Iterate over fields
492
+ for (const fieldName in modelStateTyped.fields) {
493
+ const columnName = modelStateTyped.fields[fieldName];
494
+ if (columnName) {
495
+ fields[fieldName] = {
496
+ column: columnName,
497
+ };
498
+ }
499
+ }
500
+
501
+ // Assign to models - type assertion preserves literal keys
502
+ (modelsPartial as unknown as Record<string, ModelDefinition>)[modelName] = {
503
+ storage: {
504
+ table: modelStateTyped.table,
505
+ },
506
+ fields: fields as Record<string, ModelField>,
507
+ relations: {},
508
+ };
509
+ }
510
+
511
+ // Build relations object - organized by table name
512
+ const relationsPartial: Partial<Record<string, Record<string, RelationDefinition>>> = {};
513
+
514
+ // Iterate over models to collect relations
515
+ for (const modelName in this.state.models) {
516
+ const modelState = this.state.models[modelName];
517
+ if (!modelState) continue;
518
+
519
+ const modelStateTyped = modelState as unknown as {
520
+ name: string;
521
+ table: string;
522
+ fields: Record<string, string>;
523
+ relations: Record<string, RelationDefinition>;
524
+ };
525
+
526
+ const tableName = modelStateTyped.table;
527
+ if (!tableName) continue;
528
+
529
+ // Only initialize relations object for this table if it has relations
530
+ if (modelStateTyped.relations && Object.keys(modelStateTyped.relations).length > 0) {
531
+ if (!relationsPartial[tableName]) {
532
+ relationsPartial[tableName] = {};
533
+ }
534
+
535
+ // Add relations from this model to the table's relations
536
+ const tableRelations = relationsPartial[tableName];
537
+ if (tableRelations) {
538
+ for (const relationName in modelStateTyped.relations) {
539
+ const relation = modelStateTyped.relations[relationName];
540
+ if (relation) {
541
+ tableRelations[relationName] = relation;
542
+ }
543
+ }
544
+ }
545
+ }
546
+ }
547
+
548
+ const models = modelsPartial as unknown as BuildModels<Models>;
549
+
550
+ const baseMappings = computeMappings(
551
+ models as unknown as Record<string, ModelDefinition>,
552
+ storage as SqlStorage,
553
+ );
554
+
555
+ const mappings = {
556
+ ...baseMappings,
557
+ codecTypes: {} as CodecTypes,
558
+ operationTypes: {} as Record<string, never>,
559
+ } as ContractBuilderMappings<CodecTypes>;
560
+
561
+ const extensionNamespaces = this.state.extensionNamespaces ?? [];
562
+ const extensionPacks: Record<string, unknown> = { ...(this.state.extensionPacks || {}) };
563
+ for (const namespace of extensionNamespaces) {
564
+ if (!Object.hasOwn(extensionPacks, namespace)) {
565
+ extensionPacks[namespace] = {};
566
+ }
567
+ }
568
+
569
+ // Construct contract with explicit type that matches the generic parameters
570
+ // This ensures TypeScript infers literal types from the generics, not runtime values
571
+ // Always include relations, even if empty (normalized to empty object)
572
+ const contract = {
573
+ schemaVersion: '1' as const,
574
+ target,
575
+ targetFamily: 'sql' as const,
576
+ storageHash: this.state.storageHash || 'sha256:ts-builder-placeholder',
577
+ models,
578
+ relations: relationsPartial,
579
+ storage,
580
+ mappings,
581
+ ...(execution ? { execution } : {}),
582
+ extensionPacks,
583
+ capabilities: this.state.capabilities || {},
584
+ meta: {},
585
+ sources: {},
586
+ } as unknown as BuiltContract;
587
+
588
+ return contract as unknown as ReturnType<
589
+ SqlContractBuilder<
590
+ CodecTypes,
591
+ Target,
592
+ Tables,
593
+ Models,
594
+ Types,
595
+ StorageHash,
596
+ ExtensionPacks,
597
+ Capabilities
598
+ >['build']
599
+ >;
600
+ }
601
+
602
+ override target<T extends string>(
603
+ packRef: TargetPackRef<'sql', T>,
604
+ ): SqlContractBuilder<
605
+ CodecTypes,
606
+ T,
607
+ Tables,
608
+ Models,
609
+ Types,
610
+ StorageHash,
611
+ ExtensionPacks,
612
+ Capabilities
613
+ > {
614
+ return new SqlContractBuilder<
615
+ CodecTypes,
616
+ T,
617
+ Tables,
618
+ Models,
619
+ Types,
620
+ StorageHash,
621
+ ExtensionPacks,
622
+ Capabilities
623
+ >({
624
+ ...this.state,
625
+ target: packRef.targetId,
626
+ });
627
+ }
628
+
629
+ extensionPacks(
630
+ packs: Record<string, ExtensionPackRef<'sql', string>>,
631
+ ): SqlContractBuilder<
632
+ CodecTypes,
633
+ Target,
634
+ Tables,
635
+ Models,
636
+ Types,
637
+ StorageHash,
638
+ ExtensionPacks,
639
+ Capabilities
640
+ > {
641
+ if (!this.state.target) {
642
+ throw new Error('extensionPacks() requires target() to be called first');
643
+ }
644
+
645
+ const namespaces = new Set(this.state.extensionNamespaces ?? []);
646
+
647
+ for (const packRef of Object.values(packs)) {
648
+ if (!packRef) continue;
649
+
650
+ if (packRef.kind !== 'extension') {
651
+ throw new Error(
652
+ `extensionPacks() only accepts extension pack refs. Received kind "${packRef.kind}".`,
653
+ );
654
+ }
655
+
656
+ if (packRef.familyId !== 'sql') {
657
+ throw new Error(
658
+ `extension pack "${packRef.id}" targets family "${packRef.familyId}" but this builder targets "sql".`,
659
+ );
660
+ }
661
+
662
+ if (packRef.targetId && packRef.targetId !== this.state.target) {
663
+ throw new Error(
664
+ `extension pack "${packRef.id}" targets "${packRef.targetId}" but builder target is "${this.state.target}".`,
665
+ );
666
+ }
667
+
668
+ namespaces.add(packRef.id);
669
+ }
670
+
671
+ return new SqlContractBuilder<
672
+ CodecTypes,
673
+ Target,
674
+ Tables,
675
+ Models,
676
+ Types,
677
+ StorageHash,
678
+ ExtensionPacks,
679
+ Capabilities
680
+ >({
681
+ ...this.state,
682
+ extensionNamespaces: [...namespaces],
683
+ });
684
+ }
685
+
686
+ override capabilities<C extends Record<string, Record<string, boolean>>>(
687
+ capabilities: C,
688
+ ): SqlContractBuilder<CodecTypes, Target, Tables, Models, Types, StorageHash, ExtensionPacks, C> {
689
+ return new SqlContractBuilder<
690
+ CodecTypes,
691
+ Target,
692
+ Tables,
693
+ Models,
694
+ Types,
695
+ StorageHash,
696
+ ExtensionPacks,
697
+ C
698
+ >({
699
+ ...this.state,
700
+ capabilities,
701
+ });
702
+ }
703
+
704
+ override storageHash<H extends string>(
705
+ hash: H,
706
+ ): SqlContractBuilder<
707
+ CodecTypes,
708
+ Target,
709
+ Tables,
710
+ Models,
711
+ Types,
712
+ H,
713
+ ExtensionPacks,
714
+ Capabilities
715
+ > {
716
+ return new SqlContractBuilder<
717
+ CodecTypes,
718
+ Target,
719
+ Tables,
720
+ Models,
721
+ Types,
722
+ H,
723
+ ExtensionPacks,
724
+ Capabilities
725
+ >({
726
+ ...this.state,
727
+ storageHash: hash,
728
+ });
729
+ }
730
+
731
+ override table<
732
+ TableName extends string,
733
+ T extends TableBuilder<
734
+ TableName,
735
+ Record<string, ColumnBuilderState<string, boolean, string>>,
736
+ readonly string[] | undefined
737
+ >,
738
+ >(
739
+ name: TableName,
740
+ callback: (t: TableBuilder<TableName>) => T | undefined,
741
+ ): SqlContractBuilder<
742
+ CodecTypes,
743
+ Target,
744
+ Tables & Record<TableName, ReturnType<T['build']>>,
745
+ Models,
746
+ Types,
747
+ StorageHash,
748
+ ExtensionPacks,
749
+ Capabilities
750
+ > {
751
+ const tableBuilder = createTable(name);
752
+ const result = callback(
753
+ tableBuilder as unknown as SqlTableBuilder<
754
+ TableName,
755
+ CodecTypes
756
+ > as unknown as TableBuilder<TableName>,
757
+ );
758
+ const finalBuilder = result instanceof TableBuilder ? result : tableBuilder;
759
+ const tableState = finalBuilder.build();
760
+
761
+ return new SqlContractBuilder<
762
+ CodecTypes,
763
+ Target,
764
+ Tables & Record<TableName, ReturnType<T['build']>>,
765
+ Models,
766
+ Types,
767
+ StorageHash,
768
+ ExtensionPacks,
769
+ Capabilities
770
+ >({
771
+ ...this.state,
772
+ tables: { ...this.state.tables, [name]: tableState } as Tables &
773
+ Record<TableName, ReturnType<T['build']>>,
774
+ });
775
+ }
776
+
777
+ override model<
778
+ ModelName extends string,
779
+ TableName extends string,
780
+ M extends ModelBuilder<
781
+ ModelName,
782
+ TableName,
783
+ Record<string, string>,
784
+ Record<string, RelationDefinition>
785
+ >,
786
+ >(
787
+ name: ModelName,
788
+ table: TableName,
789
+ callback: (
790
+ m: ModelBuilder<ModelName, TableName, Record<string, string>, Record<never, never>>,
791
+ ) => M | undefined,
792
+ ): SqlContractBuilder<
793
+ CodecTypes,
794
+ Target,
795
+ Tables,
796
+ Models & Record<ModelName, ReturnType<M['build']>>,
797
+ Types,
798
+ StorageHash,
799
+ ExtensionPacks,
800
+ Capabilities
801
+ > {
802
+ const modelBuilder = new ModelBuilder<ModelName, TableName>(name, table);
803
+ const result = callback(modelBuilder);
804
+ const finalBuilder = result instanceof ModelBuilder ? result : modelBuilder;
805
+ const modelState = finalBuilder.build();
806
+
807
+ return new SqlContractBuilder<
808
+ CodecTypes,
809
+ Target,
810
+ Tables,
811
+ Models & Record<ModelName, ReturnType<M['build']>>,
812
+ Types,
813
+ StorageHash,
814
+ ExtensionPacks,
815
+ Capabilities
816
+ >({
817
+ ...this.state,
818
+ models: { ...this.state.models, [name]: modelState } as Models &
819
+ Record<ModelName, ReturnType<M['build']>>,
820
+ });
821
+ }
822
+
823
+ override foreignKeyDefaults(
824
+ config: ForeignKeyDefaultsState,
825
+ ): SqlContractBuilder<
826
+ CodecTypes,
827
+ Target,
828
+ Tables,
829
+ Models,
830
+ Types,
831
+ StorageHash,
832
+ ExtensionPacks,
833
+ Capabilities
834
+ > {
835
+ return new SqlContractBuilder<
836
+ CodecTypes,
837
+ Target,
838
+ Tables,
839
+ Models,
840
+ Types,
841
+ StorageHash,
842
+ ExtensionPacks,
843
+ Capabilities
844
+ >({
845
+ ...this.state,
846
+ foreignKeyDefaults: config,
847
+ });
848
+ }
849
+
850
+ storageType<Name extends string, Type extends StorageTypeInstance>(
851
+ name: Name,
852
+ typeInstance: Type,
853
+ ): SqlContractBuilder<
854
+ CodecTypes,
855
+ Target,
856
+ Tables,
857
+ Models,
858
+ Types & Record<Name, Type>,
859
+ StorageHash,
860
+ ExtensionPacks,
861
+ Capabilities
862
+ > {
863
+ return new SqlContractBuilder<
864
+ CodecTypes,
865
+ Target,
866
+ Tables,
867
+ Models,
868
+ Types & Record<Name, Type>,
869
+ StorageHash,
870
+ ExtensionPacks,
871
+ Capabilities
872
+ >({
873
+ ...this.state,
874
+ storageTypes: {
875
+ ...(this.state.storageTypes ?? {}),
876
+ [name]: typeInstance,
877
+ },
878
+ });
879
+ }
880
+ }
881
+
882
+ export function defineContract<
883
+ CodecTypes extends Record<string, { output: unknown }> = Record<string, never>,
884
+ >(): SqlContractBuilder<CodecTypes> {
885
+ return new SqlContractBuilder<CodecTypes>();
886
+ }