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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +40 -10
  2. package/dist/factories.d.mts +49 -0
  3. package/dist/factories.d.mts.map +1 -0
  4. package/dist/factories.mjs +82 -0
  5. package/dist/factories.mjs.map +1 -0
  6. package/dist/pack-types.d.mts +13 -0
  7. package/dist/pack-types.d.mts.map +1 -0
  8. package/dist/pack-types.mjs +1 -0
  9. package/dist/types-DTFobApb.d.mts +137 -0
  10. package/dist/types-DTFobApb.d.mts.map +1 -0
  11. package/dist/types-kacOgEya.mjs +17 -0
  12. package/dist/types-kacOgEya.mjs.map +1 -0
  13. package/dist/types.d.mts +2 -0
  14. package/dist/types.mjs +3 -0
  15. package/dist/validate.d.mts +8 -0
  16. package/dist/validate.d.mts.map +1 -0
  17. package/dist/validate.mjs +179 -0
  18. package/dist/validate.mjs.map +1 -0
  19. package/dist/validators-Dfw5_HSi.mjs +162 -0
  20. package/dist/validators-Dfw5_HSi.mjs.map +1 -0
  21. package/dist/{exports/validators.d.ts → validators.d.mts} +17 -4
  22. package/dist/validators.d.mts.map +1 -0
  23. package/dist/validators.mjs +3 -0
  24. package/package.json +26 -28
  25. package/src/exports/factories.ts +11 -0
  26. package/src/exports/pack-types.ts +1 -0
  27. package/src/exports/types.ts +20 -0
  28. package/src/exports/validate.ts +1 -0
  29. package/src/exports/validators.ts +1 -0
  30. package/src/factories.ts +162 -0
  31. package/src/index.ts +4 -0
  32. package/src/pack-types.ts +9 -0
  33. package/src/types.ts +163 -0
  34. package/src/validate.ts +335 -0
  35. package/src/validators.ts +218 -0
  36. package/dist/exports/factories.d.ts +0 -41
  37. package/dist/exports/factories.js +0 -83
  38. package/dist/exports/factories.js.map +0 -1
  39. package/dist/exports/pack-types.d.ts +0 -11
  40. package/dist/exports/pack-types.js +0 -1
  41. package/dist/exports/pack-types.js.map +0 -1
  42. package/dist/exports/types.d.ts +0 -70
  43. package/dist/exports/types.js +0 -1
  44. package/dist/exports/types.js.map +0 -1
  45. package/dist/exports/validators.js +0 -96
  46. package/dist/exports/validators.js.map +0 -1
@@ -0,0 +1,162 @@
1
+ import type {
2
+ ExecutionHashBase,
3
+ ProfileHashBase,
4
+ StorageHashBase,
5
+ } from '@prisma-next/contract/types';
6
+ import type {
7
+ ForeignKey,
8
+ ForeignKeyReferences,
9
+ Index,
10
+ ModelDefinition,
11
+ ModelField,
12
+ ModelStorage,
13
+ PrimaryKey,
14
+ SqlContract,
15
+ SqlMappings,
16
+ SqlStorage,
17
+ StorageColumn,
18
+ StorageTable,
19
+ UniqueConstraint,
20
+ } from './types';
21
+ import { applyFkDefaults } from './types';
22
+
23
+ /**
24
+ * Creates a StorageColumn with nativeType and codecId.
25
+ *
26
+ * @param nativeType - Native database type identifier (e.g., 'int4', 'text', 'vector')
27
+ * @param codecId - Codec identifier (e.g., 'pg/int4@1', 'pg/text@1')
28
+ * @param nullable - Whether the column is nullable (default: false)
29
+ * @returns StorageColumn with nativeType and codecId
30
+ */
31
+ export function col(nativeType: string, codecId: string, nullable = false): StorageColumn {
32
+ return {
33
+ nativeType,
34
+ codecId,
35
+ nullable,
36
+ };
37
+ }
38
+
39
+ export function pk(...columns: readonly string[]): PrimaryKey {
40
+ return {
41
+ columns,
42
+ };
43
+ }
44
+
45
+ export function unique(...columns: readonly string[]): UniqueConstraint {
46
+ return {
47
+ columns,
48
+ };
49
+ }
50
+
51
+ export function index(...columns: readonly string[]): Index {
52
+ return {
53
+ columns,
54
+ };
55
+ }
56
+
57
+ export function fk(
58
+ columns: readonly string[],
59
+ refTable: string,
60
+ refColumns: readonly string[],
61
+ opts?: { name?: string; constraint?: boolean; index?: boolean },
62
+ ): ForeignKey {
63
+ const references: ForeignKeyReferences = {
64
+ table: refTable,
65
+ columns: refColumns,
66
+ };
67
+ return {
68
+ columns,
69
+ references,
70
+ ...applyFkDefaults({ constraint: opts?.constraint, index: opts?.index }),
71
+ ...(opts?.name !== undefined && { name: opts.name }),
72
+ };
73
+ }
74
+
75
+ export function table(
76
+ columns: Record<string, StorageColumn>,
77
+ opts?: {
78
+ pk?: PrimaryKey;
79
+ uniques?: readonly UniqueConstraint[];
80
+ indexes?: readonly Index[];
81
+ fks?: readonly ForeignKey[];
82
+ },
83
+ ): StorageTable {
84
+ return {
85
+ columns,
86
+ ...(opts?.pk !== undefined && { primaryKey: opts.pk }),
87
+ uniques: opts?.uniques ?? [],
88
+ indexes: opts?.indexes ?? [],
89
+ foreignKeys: opts?.fks ?? [],
90
+ };
91
+ }
92
+
93
+ export function model(
94
+ table: string,
95
+ fields: Record<string, ModelField>,
96
+ relations: Record<string, unknown> = {},
97
+ ): ModelDefinition {
98
+ const storage: ModelStorage = { table };
99
+ return {
100
+ storage,
101
+ fields,
102
+ relations,
103
+ };
104
+ }
105
+
106
+ export function storage(tables: Record<string, StorageTable>): SqlStorage {
107
+ return { tables };
108
+ }
109
+
110
+ export function contract<
111
+ TStorageHash extends StorageHashBase<string> = StorageHashBase<string>,
112
+ TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>,
113
+ TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>,
114
+ >(opts: {
115
+ target: string;
116
+ storageHash: TStorageHash;
117
+ executionHash?: TExecutionHash;
118
+ storage: SqlStorage;
119
+ models?: Record<string, ModelDefinition>;
120
+ relations?: Record<string, unknown>;
121
+ mappings?: Partial<SqlMappings>;
122
+ schemaVersion?: '1';
123
+ targetFamily?: 'sql';
124
+ profileHash?: TProfileHash;
125
+ capabilities?: Record<string, Record<string, boolean>>;
126
+ extensionPacks?: Record<string, unknown>;
127
+ meta?: Record<string, unknown>;
128
+ sources?: Record<string, unknown>;
129
+ }): SqlContract<
130
+ SqlStorage,
131
+ Record<string, unknown>,
132
+ Record<string, unknown>,
133
+ SqlMappings,
134
+ TStorageHash,
135
+ TExecutionHash,
136
+ TProfileHash
137
+ > {
138
+ return {
139
+ schemaVersion: opts.schemaVersion ?? '1',
140
+ target: opts.target,
141
+ targetFamily: opts.targetFamily ?? 'sql',
142
+ storageHash: opts.storageHash,
143
+ ...(opts.executionHash !== undefined && { executionHash: opts.executionHash }),
144
+ storage: opts.storage,
145
+ models: opts.models ?? {},
146
+ relations: opts.relations ?? {},
147
+ mappings: (opts.mappings ?? {}) as SqlMappings,
148
+ ...(opts.profileHash !== undefined && { profileHash: opts.profileHash }),
149
+ ...(opts.capabilities !== undefined && { capabilities: opts.capabilities }),
150
+ ...(opts.extensionPacks !== undefined && { extensionPacks: opts.extensionPacks }),
151
+ ...(opts.meta !== undefined && { meta: opts.meta }),
152
+ ...(opts.sources !== undefined && { sources: opts.sources as Record<string, unknown> }),
153
+ } as SqlContract<
154
+ SqlStorage,
155
+ Record<string, unknown>,
156
+ Record<string, unknown>,
157
+ SqlMappings,
158
+ TStorageHash,
159
+ TExecutionHash,
160
+ TProfileHash
161
+ >;
162
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './exports/factories';
2
+ export * from './exports/types';
3
+ export * from './exports/validate';
4
+ export * from './exports/validators';
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Storage type metadata for pack refs.
3
+ */
4
+ export interface StorageTypeMetadata {
5
+ readonly typeId: string;
6
+ readonly familyId: string;
7
+ readonly targetId: string;
8
+ readonly nativeType?: string;
9
+ }
package/src/types.ts ADDED
@@ -0,0 +1,163 @@
1
+ import type {
2
+ ColumnDefault,
3
+ ContractBase,
4
+ ExecutionHashBase,
5
+ ExecutionSection,
6
+ ProfileHashBase,
7
+ StorageHashBase,
8
+ } from '@prisma-next/contract/types';
9
+
10
+ /**
11
+ * A column definition in storage.
12
+ *
13
+ * `typeParams` is optional because most columns use non-parameterized types.
14
+ * Columns with parameterized types can either inline `typeParams` or reference
15
+ * a named {@link StorageTypeInstance} via `typeRef`.
16
+ */
17
+ export type StorageColumn = {
18
+ readonly nativeType: string;
19
+ readonly codecId: string;
20
+ readonly nullable: boolean;
21
+ /**
22
+ * Opaque, codec-owned JS/type parameters.
23
+ * The codec that owns `codecId` defines the shape and semantics.
24
+ * Mutually exclusive with `typeRef`.
25
+ */
26
+ readonly typeParams?: Record<string, unknown>;
27
+ /**
28
+ * Reference to a named type instance in `storage.types`.
29
+ * Mutually exclusive with `typeParams`.
30
+ */
31
+ readonly typeRef?: string;
32
+ /**
33
+ * Default value for the column.
34
+ * Can be a literal value or database function.
35
+ */
36
+ readonly default?: ColumnDefault;
37
+ };
38
+
39
+ export type PrimaryKey = {
40
+ readonly columns: readonly string[];
41
+ readonly name?: string;
42
+ };
43
+
44
+ export type UniqueConstraint = {
45
+ readonly columns: readonly string[];
46
+ readonly name?: string;
47
+ };
48
+
49
+ export type Index = {
50
+ readonly columns: readonly string[];
51
+ readonly name?: string;
52
+ };
53
+
54
+ export type ForeignKeyReferences = {
55
+ readonly table: string;
56
+ readonly columns: readonly string[];
57
+ };
58
+
59
+ export type ForeignKey = {
60
+ readonly columns: readonly string[];
61
+ readonly references: ForeignKeyReferences;
62
+ readonly name?: string;
63
+ /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */
64
+ readonly constraint: boolean;
65
+ /** Whether to emit a backing index for the FK columns. */
66
+ readonly index: boolean;
67
+ };
68
+
69
+ export type StorageTable = {
70
+ readonly columns: Record<string, StorageColumn>;
71
+ readonly primaryKey?: PrimaryKey;
72
+ readonly uniques: ReadonlyArray<UniqueConstraint>;
73
+ readonly indexes: ReadonlyArray<Index>;
74
+ readonly foreignKeys: ReadonlyArray<ForeignKey>;
75
+ };
76
+
77
+ /**
78
+ * A named, parameterized type instance.
79
+ * These are registered in `storage.types` for reuse across columns
80
+ * and to enable ergonomic schema surfaces like `schema.types.MyType`.
81
+ *
82
+ * Unlike {@link StorageColumn}, `typeParams` is required here because
83
+ * `StorageTypeInstance` exists specifically to define reusable parameterized types.
84
+ * A type instance without parameters would be redundant—columns can reference
85
+ * the codec directly via `codecId`.
86
+ */
87
+ export type StorageTypeInstance = {
88
+ readonly codecId: string;
89
+ readonly nativeType: string;
90
+ readonly typeParams: Record<string, unknown>;
91
+ };
92
+
93
+ export type SqlStorage = {
94
+ readonly tables: Record<string, StorageTable>;
95
+ /**
96
+ * Named type instances for parameterized/custom types.
97
+ * Columns can reference these via `typeRef`.
98
+ */
99
+ readonly types?: Record<string, StorageTypeInstance>;
100
+ };
101
+
102
+ export type ModelField = {
103
+ readonly column: string;
104
+ };
105
+
106
+ export type ModelStorage = {
107
+ readonly table: string;
108
+ };
109
+
110
+ export type ModelDefinition = {
111
+ readonly storage: ModelStorage;
112
+ readonly fields: Record<string, ModelField>;
113
+ readonly relations: Record<string, unknown>;
114
+ };
115
+
116
+ export type SqlMappings = {
117
+ readonly modelToTable?: Record<string, string>;
118
+ readonly tableToModel?: Record<string, string>;
119
+ readonly fieldToColumn?: Record<string, Record<string, string>>;
120
+ readonly columnToField?: Record<string, Record<string, string>>;
121
+ readonly codecTypes: Record<string, { readonly output: unknown }>;
122
+ readonly operationTypes: Record<string, Record<string, unknown>>;
123
+ };
124
+
125
+ export const DEFAULT_FK_CONSTRAINT = true;
126
+ export const DEFAULT_FK_INDEX = true;
127
+
128
+ /**
129
+ * Resolves foreign key `constraint` and `index` fields to their effective boolean values,
130
+ * falling back through optional override defaults, then to the global defaults.
131
+ */
132
+ export function applyFkDefaults(
133
+ fk: { constraint?: boolean | undefined; index?: boolean | undefined },
134
+ overrideDefaults?: { constraint?: boolean | undefined; index?: boolean | undefined },
135
+ ): { constraint: boolean; index: boolean } {
136
+ return {
137
+ constraint: fk.constraint ?? overrideDefaults?.constraint ?? DEFAULT_FK_CONSTRAINT,
138
+ index: fk.index ?? overrideDefaults?.index ?? DEFAULT_FK_INDEX,
139
+ };
140
+ }
141
+
142
+ export type SqlContract<
143
+ S extends SqlStorage = SqlStorage,
144
+ M extends Record<string, unknown> = Record<string, unknown>,
145
+ R extends Record<string, unknown> = Record<string, unknown>,
146
+ Map extends SqlMappings = SqlMappings,
147
+ TStorageHash extends StorageHashBase<string> = StorageHashBase<string>,
148
+ TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>,
149
+ TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>,
150
+ > = ContractBase<TStorageHash, TExecutionHash, TProfileHash> & {
151
+ readonly targetFamily: string;
152
+ readonly storage: S;
153
+ readonly models: M;
154
+ readonly relations: R;
155
+ readonly mappings: Map;
156
+ readonly execution?: ExecutionSection;
157
+ };
158
+
159
+ export type ExtractCodecTypes<TContract extends SqlContract<SqlStorage>> =
160
+ TContract['mappings']['codecTypes'];
161
+
162
+ export type ExtractOperationTypes<TContract extends SqlContract<SqlStorage>> =
163
+ TContract['mappings']['operationTypes'];
@@ -0,0 +1,335 @@
1
+ import type { ModelDefinition, SqlContract, SqlMappings, SqlStorage } from './types';
2
+ import { applyFkDefaults } from './types';
3
+ import { validateSqlContract } from './validators';
4
+
5
+ type ResolvedMappings = {
6
+ modelToTable: Record<string, string>;
7
+ tableToModel: Record<string, string>;
8
+ fieldToColumn: Record<string, Record<string, string>>;
9
+ columnToField: Record<string, Record<string, string>>;
10
+ codecTypes: Record<string, { readonly output: unknown }>;
11
+ operationTypes: Record<string, Record<string, unknown>>;
12
+ };
13
+
14
+ function computeDefaultMappings(models: Record<string, ModelDefinition>): ResolvedMappings {
15
+ const modelToTable: Record<string, string> = {};
16
+ const tableToModel: Record<string, string> = {};
17
+ const fieldToColumn: Record<string, Record<string, string>> = {};
18
+ const columnToField: Record<string, Record<string, string>> = {};
19
+
20
+ for (const [modelName, model] of Object.entries(models)) {
21
+ const tableName = model.storage.table;
22
+ modelToTable[modelName] = tableName;
23
+ tableToModel[tableName] = modelName;
24
+
25
+ const modelFieldToColumn: Record<string, string> = {};
26
+ for (const [fieldName, field] of Object.entries(model.fields)) {
27
+ const columnName = field.column;
28
+ modelFieldToColumn[fieldName] = columnName;
29
+ if (!columnToField[tableName]) {
30
+ columnToField[tableName] = {};
31
+ }
32
+ columnToField[tableName][columnName] = fieldName;
33
+ }
34
+
35
+ fieldToColumn[modelName] = modelFieldToColumn;
36
+ }
37
+
38
+ return {
39
+ modelToTable,
40
+ tableToModel,
41
+ fieldToColumn,
42
+ columnToField,
43
+ codecTypes: {},
44
+ operationTypes: {},
45
+ };
46
+ }
47
+
48
+ function assertInverseModelMappings(
49
+ modelToTable: Record<string, string>,
50
+ tableToModel: Record<string, string>,
51
+ ) {
52
+ for (const [model, table] of Object.entries(modelToTable)) {
53
+ if (tableToModel[table] !== model) {
54
+ throw new Error(
55
+ `Mappings override mismatch: modelToTable.${model}="${table}" is not mirrored in tableToModel`,
56
+ );
57
+ }
58
+ }
59
+ for (const [table, model] of Object.entries(tableToModel)) {
60
+ if (modelToTable[model] !== table) {
61
+ throw new Error(
62
+ `Mappings override mismatch: tableToModel.${table}="${model}" is not mirrored in modelToTable`,
63
+ );
64
+ }
65
+ }
66
+ }
67
+
68
+ function assertInverseFieldMappings(
69
+ fieldToColumn: Record<string, Record<string, string>>,
70
+ columnToField: Record<string, Record<string, string>>,
71
+ modelToTable: Record<string, string>,
72
+ tableToModel: Record<string, string>,
73
+ ) {
74
+ for (const [model, fields] of Object.entries(fieldToColumn)) {
75
+ const table = modelToTable[model];
76
+ if (!table) {
77
+ throw new Error(
78
+ `Mappings override mismatch: fieldToColumn references unknown model "${model}"`,
79
+ );
80
+ }
81
+ const reverseFields = columnToField[table];
82
+ if (!reverseFields) {
83
+ throw new Error(
84
+ `Mappings override mismatch: columnToField is missing table "${table}" for model "${model}"`,
85
+ );
86
+ }
87
+ for (const [field, column] of Object.entries(fields)) {
88
+ if (reverseFields[column] !== field) {
89
+ throw new Error(
90
+ `Mappings override mismatch: fieldToColumn.${model}.${field}="${column}" is not mirrored in columnToField.${table}`,
91
+ );
92
+ }
93
+ }
94
+ }
95
+
96
+ for (const [table, columns] of Object.entries(columnToField)) {
97
+ const model = tableToModel[table];
98
+ if (!model) {
99
+ throw new Error(
100
+ `Mappings override mismatch: columnToField references unknown table "${table}"`,
101
+ );
102
+ }
103
+ const forwardFields = fieldToColumn[model];
104
+ if (!forwardFields) {
105
+ throw new Error(
106
+ `Mappings override mismatch: fieldToColumn is missing model "${model}" for table "${table}"`,
107
+ );
108
+ }
109
+ for (const [column, field] of Object.entries(columns)) {
110
+ if (forwardFields[field] !== column) {
111
+ throw new Error(
112
+ `Mappings override mismatch: columnToField.${table}.${column}="${field}" is not mirrored in fieldToColumn.${model}`,
113
+ );
114
+ }
115
+ }
116
+ }
117
+ }
118
+
119
+ function mergeMappings(
120
+ defaults: ResolvedMappings,
121
+ existingMappings?: Partial<SqlMappings>,
122
+ ): ResolvedMappings {
123
+ const hasModelToTable = existingMappings?.modelToTable !== undefined;
124
+ const hasTableToModel = existingMappings?.tableToModel !== undefined;
125
+ if (hasModelToTable !== hasTableToModel) {
126
+ throw new Error(
127
+ 'Mappings override mismatch: modelToTable and tableToModel must be provided together',
128
+ );
129
+ }
130
+
131
+ const hasFieldToColumn = existingMappings?.fieldToColumn !== undefined;
132
+ const hasColumnToField = existingMappings?.columnToField !== undefined;
133
+ if (hasFieldToColumn !== hasColumnToField) {
134
+ throw new Error(
135
+ 'Mappings override mismatch: fieldToColumn and columnToField must be provided together',
136
+ );
137
+ }
138
+
139
+ const modelToTable: Record<string, string> = hasModelToTable
140
+ ? (existingMappings?.modelToTable ?? {})
141
+ : defaults.modelToTable;
142
+ const tableToModel: Record<string, string> = hasTableToModel
143
+ ? (existingMappings?.tableToModel ?? {})
144
+ : defaults.tableToModel;
145
+ assertInverseModelMappings(modelToTable, tableToModel);
146
+
147
+ const fieldToColumn: Record<string, Record<string, string>> = hasFieldToColumn
148
+ ? (existingMappings?.fieldToColumn ?? {})
149
+ : defaults.fieldToColumn;
150
+ const columnToField: Record<string, Record<string, string>> = hasColumnToField
151
+ ? (existingMappings?.columnToField ?? {})
152
+ : defaults.columnToField;
153
+ assertInverseFieldMappings(fieldToColumn, columnToField, modelToTable, tableToModel);
154
+
155
+ return {
156
+ modelToTable,
157
+ tableToModel,
158
+ fieldToColumn,
159
+ columnToField,
160
+ codecTypes: { ...defaults.codecTypes, ...(existingMappings?.codecTypes ?? {}) },
161
+ operationTypes: { ...defaults.operationTypes, ...(existingMappings?.operationTypes ?? {}) },
162
+ };
163
+ }
164
+
165
+ function validateContractLogic(contract: SqlContract<SqlStorage>): void {
166
+ const tableNames = new Set(Object.keys(contract.storage.tables));
167
+
168
+ for (const [tableName, table] of Object.entries(contract.storage.tables)) {
169
+ const columnNames = new Set(Object.keys(table.columns));
170
+
171
+ if (table.primaryKey) {
172
+ for (const colName of table.primaryKey.columns) {
173
+ if (!columnNames.has(colName)) {
174
+ throw new Error(
175
+ `Table "${tableName}" primaryKey references non-existent column "${colName}"`,
176
+ );
177
+ }
178
+ }
179
+ }
180
+
181
+ for (const unique of table.uniques) {
182
+ for (const colName of unique.columns) {
183
+ if (!columnNames.has(colName)) {
184
+ throw new Error(
185
+ `Table "${tableName}" unique constraint references non-existent column "${colName}"`,
186
+ );
187
+ }
188
+ }
189
+ }
190
+
191
+ for (const index of table.indexes) {
192
+ for (const colName of index.columns) {
193
+ if (!columnNames.has(colName)) {
194
+ throw new Error(`Table "${tableName}" index references non-existent column "${colName}"`);
195
+ }
196
+ }
197
+ }
198
+
199
+ for (const fk of table.foreignKeys) {
200
+ for (const colName of fk.columns) {
201
+ if (!columnNames.has(colName)) {
202
+ throw new Error(
203
+ `Table "${tableName}" foreignKey references non-existent column "${colName}"`,
204
+ );
205
+ }
206
+ }
207
+
208
+ if (!tableNames.has(fk.references.table)) {
209
+ throw new Error(
210
+ `Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`,
211
+ );
212
+ }
213
+
214
+ const referencedTable = contract.storage.tables[
215
+ fk.references.table
216
+ ] as (typeof contract.storage.tables)[string];
217
+ const referencedColumnNames = new Set(Object.keys(referencedTable.columns));
218
+ for (const colName of fk.references.columns) {
219
+ if (!referencedColumnNames.has(colName)) {
220
+ throw new Error(
221
+ `Table "${tableName}" foreignKey references non-existent column "${colName}" in table "${fk.references.table}"`,
222
+ );
223
+ }
224
+ }
225
+
226
+ if (fk.columns.length !== fk.references.columns.length) {
227
+ throw new Error(
228
+ `Table "${tableName}" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`,
229
+ );
230
+ }
231
+ }
232
+ }
233
+ }
234
+
235
+ export function normalizeContract(contract: unknown): SqlContract<SqlStorage> {
236
+ if (typeof contract !== 'object' || contract === null) {
237
+ return contract as SqlContract<SqlStorage>;
238
+ }
239
+
240
+ const contractObj = contract as Record<string, unknown>;
241
+
242
+ let normalizedStorage = contractObj['storage'];
243
+ if (normalizedStorage && typeof normalizedStorage === 'object' && normalizedStorage !== null) {
244
+ const storage = normalizedStorage as Record<string, unknown>;
245
+ const tables = storage['tables'] as Record<string, unknown> | undefined;
246
+
247
+ if (tables) {
248
+ const normalizedTables: Record<string, unknown> = {};
249
+ for (const [tableName, table] of Object.entries(tables)) {
250
+ const tableObj = table as Record<string, unknown>;
251
+ const columns = tableObj['columns'] as Record<string, unknown> | undefined;
252
+
253
+ if (columns) {
254
+ const normalizedColumns: Record<string, unknown> = {};
255
+ for (const [columnName, column] of Object.entries(columns)) {
256
+ const columnObj = column as Record<string, unknown>;
257
+ normalizedColumns[columnName] = {
258
+ ...columnObj,
259
+ nullable: columnObj['nullable'] ?? false,
260
+ };
261
+ }
262
+
263
+ // Normalize foreign keys: add constraint/index defaults if missing
264
+ const rawForeignKeys = (tableObj['foreignKeys'] ?? []) as Array<Record<string, unknown>>;
265
+ const normalizedForeignKeys = rawForeignKeys.map((fk) => ({
266
+ ...fk,
267
+ ...applyFkDefaults({
268
+ constraint: typeof fk['constraint'] === 'boolean' ? fk['constraint'] : undefined,
269
+ index: typeof fk['index'] === 'boolean' ? fk['index'] : undefined,
270
+ }),
271
+ }));
272
+
273
+ normalizedTables[tableName] = {
274
+ ...tableObj,
275
+ columns: normalizedColumns,
276
+ uniques: tableObj['uniques'] ?? [],
277
+ indexes: tableObj['indexes'] ?? [],
278
+ foreignKeys: normalizedForeignKeys,
279
+ };
280
+ } else {
281
+ normalizedTables[tableName] = tableObj;
282
+ }
283
+ }
284
+
285
+ normalizedStorage = {
286
+ ...storage,
287
+ tables: normalizedTables,
288
+ };
289
+ }
290
+ }
291
+
292
+ let normalizedModels = contractObj['models'];
293
+ if (normalizedModels && typeof normalizedModels === 'object' && normalizedModels !== null) {
294
+ const models = normalizedModels as Record<string, unknown>;
295
+ const normalizedModelsObj: Record<string, unknown> = {};
296
+ for (const [modelName, model] of Object.entries(models)) {
297
+ const modelObj = model as Record<string, unknown>;
298
+ normalizedModelsObj[modelName] = {
299
+ ...modelObj,
300
+ relations: modelObj['relations'] ?? {},
301
+ };
302
+ }
303
+ normalizedModels = normalizedModelsObj;
304
+ }
305
+
306
+ return {
307
+ ...contractObj,
308
+ models: normalizedModels,
309
+ relations: contractObj['relations'] ?? {},
310
+ storage: normalizedStorage,
311
+ extensionPacks: contractObj['extensionPacks'] ?? {},
312
+ capabilities: contractObj['capabilities'] ?? {},
313
+ meta: contractObj['meta'] ?? {},
314
+ sources: contractObj['sources'] ?? {},
315
+ } as SqlContract<SqlStorage>;
316
+ }
317
+
318
+ export function validateContract<TContract extends SqlContract<SqlStorage>>(
319
+ value: unknown,
320
+ ): TContract {
321
+ const normalized = normalizeContract(value);
322
+ const structurallyValid = validateSqlContract<SqlContract<SqlStorage>>(normalized);
323
+ validateContractLogic(structurallyValid);
324
+
325
+ const existingMappings = (structurallyValid as { mappings?: Partial<SqlMappings> }).mappings;
326
+ const defaultMappings = computeDefaultMappings(
327
+ structurallyValid.models as Record<string, ModelDefinition>,
328
+ );
329
+ const mappings = mergeMappings(defaultMappings, existingMappings);
330
+
331
+ return {
332
+ ...structurallyValid,
333
+ mappings,
334
+ } as TContract;
335
+ }