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

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,533 @@
1
+ import type {
2
+ ForeignKey,
3
+ ForeignKeyReferences,
4
+ Index,
5
+ ModelDefinition,
6
+ ModelField,
7
+ ModelStorage,
8
+ PrimaryKey,
9
+ SqlContract,
10
+ SqlMappings,
11
+ SqlStorage,
12
+ StorageColumn,
13
+ StorageTable,
14
+ UniqueConstraint,
15
+ } from '@prisma-next/sql-contract/types';
16
+ import { type } from 'arktype';
17
+ import type { O } from 'ts-toolbelt';
18
+
19
+ /**
20
+ * Structural validation schema for SqlContract using Arktype.
21
+ * This validates the shape and types of the contract structure.
22
+ */
23
+ const StorageColumnSchema = type.declare<StorageColumn>().type({
24
+ nativeType: 'string',
25
+ codecId: 'string',
26
+ nullable: 'boolean',
27
+ });
28
+
29
+ const PrimaryKeySchema = type.declare<PrimaryKey>().type({
30
+ columns: type.string.array().readonly(),
31
+ 'name?': 'string',
32
+ });
33
+
34
+ const UniqueConstraintSchema = type.declare<UniqueConstraint>().type({
35
+ columns: type.string.array().readonly(),
36
+ 'name?': 'string',
37
+ });
38
+
39
+ const IndexSchema = type.declare<Index>().type({
40
+ columns: type.string.array().readonly(),
41
+ 'name?': 'string',
42
+ });
43
+
44
+ const ForeignKeyReferencesSchema = type.declare<ForeignKeyReferences>().type({
45
+ table: 'string',
46
+ columns: type.string.array().readonly(),
47
+ });
48
+
49
+ const ForeignKeySchema = type.declare<ForeignKey>().type({
50
+ columns: type.string.array().readonly(),
51
+ references: ForeignKeyReferencesSchema,
52
+ 'name?': 'string',
53
+ });
54
+
55
+ const StorageTableSchema = type.declare<StorageTable>().type({
56
+ columns: type({ '[string]': StorageColumnSchema }),
57
+ 'primaryKey?': PrimaryKeySchema,
58
+ uniques: UniqueConstraintSchema.array().readonly(),
59
+ indexes: IndexSchema.array().readonly(),
60
+ foreignKeys: ForeignKeySchema.array().readonly(),
61
+ });
62
+
63
+ const StorageSchema = type.declare<SqlStorage>().type({
64
+ tables: type({ '[string]': StorageTableSchema }),
65
+ });
66
+
67
+ const ModelFieldSchema = type.declare<ModelField>().type({
68
+ column: 'string',
69
+ });
70
+
71
+ const ModelStorageSchema = type.declare<ModelStorage>().type({
72
+ table: 'string',
73
+ });
74
+
75
+ const ModelSchema = type.declare<ModelDefinition>().type({
76
+ storage: ModelStorageSchema,
77
+ fields: type({ '[string]': ModelFieldSchema }),
78
+ relations: type({ '[string]': 'unknown' }),
79
+ });
80
+
81
+ /**
82
+ * Complete SqlContract schema for structural validation.
83
+ * This validates the entire contract structure at once.
84
+ */
85
+ const SqlContractSchema = type({
86
+ 'schemaVersion?': "'1'",
87
+ target: 'string',
88
+ targetFamily: "'sql'",
89
+ coreHash: 'string',
90
+ 'profileHash?': 'string',
91
+ 'capabilities?': 'Record<string, Record<string, boolean>>',
92
+ 'extensionPacks?': 'Record<string, unknown>',
93
+ 'meta?': 'Record<string, unknown>',
94
+ 'sources?': 'Record<string, unknown>',
95
+ models: type({ '[string]': ModelSchema }),
96
+ storage: StorageSchema,
97
+ });
98
+
99
+ /**
100
+ * Validates the structural shape of a SqlContract using Arktype.
101
+ *
102
+ * **Responsibility: Validation Only**
103
+ * This function validates that the contract has the correct structure and types.
104
+ * It does NOT normalize the contract - normalization must happen in the contract builder.
105
+ *
106
+ * The contract passed to this function must already be normalized (all required fields present).
107
+ * If normalization is needed, it should be done by the contract builder before calling this function.
108
+ *
109
+ * This ensures all required fields are present and have the correct types.
110
+ *
111
+ * @param value - The contract value to validate (typically from a JSON import)
112
+ * @returns The validated contract if structure is valid
113
+ * @throws Error if the contract structure is invalid
114
+ */
115
+ function validateContractStructure<T extends SqlContract<SqlStorage>>(
116
+ value: unknown,
117
+ ): O.Overwrite<T, { targetFamily: 'sql' }> {
118
+ // Check targetFamily first to provide a clear error message for unsupported target families
119
+ const rawValue = value as { targetFamily?: string };
120
+ if (rawValue.targetFamily !== undefined && rawValue.targetFamily !== 'sql') {
121
+ /* c8 ignore next */
122
+ throw new Error(`Unsupported target family: ${rawValue.targetFamily}`);
123
+ }
124
+
125
+ const contractResult = SqlContractSchema(value);
126
+
127
+ if (contractResult instanceof type.errors) {
128
+ const messages = contractResult.map((p: { message: string }) => p.message).join('; ');
129
+ throw new Error(`Contract structural validation failed: ${messages}`);
130
+ }
131
+
132
+ // After validation, contractResult matches the schema and preserves the input structure
133
+ // TypeScript needs an assertion here due to exactOptionalPropertyTypes differences
134
+ // between Arktype's inferred type and the generic T, but runtime-wise they're compatible
135
+ return contractResult as O.Overwrite<T, { targetFamily: 'sql' }>;
136
+ }
137
+
138
+ /**
139
+ * Computes mapping dictionaries from models and storage structures.
140
+ * Assumes valid input - validation happens separately in validateContractLogic().
141
+ *
142
+ * @param models - Models object from contract
143
+ * @param storage - Storage object from contract
144
+ * @param existingMappings - Existing mappings from contract input (optional)
145
+ * @returns Computed mappings dictionary
146
+ */
147
+ export function computeMappings(
148
+ models: Record<string, ModelDefinition>,
149
+ _storage: SqlStorage,
150
+ existingMappings?: Partial<SqlMappings>,
151
+ ): SqlMappings {
152
+ const modelToTable: Record<string, string> = {};
153
+ const tableToModel: Record<string, string> = {};
154
+ const fieldToColumn: Record<string, Record<string, string>> = {};
155
+ const columnToField: Record<string, Record<string, string>> = {};
156
+
157
+ for (const [modelName, model] of Object.entries(models)) {
158
+ const tableName = model.storage.table;
159
+ modelToTable[modelName] = tableName;
160
+ tableToModel[tableName] = modelName;
161
+
162
+ const modelFieldToColumn: Record<string, string> = {};
163
+ for (const [fieldName, field] of Object.entries(model.fields)) {
164
+ const columnName = field.column;
165
+ modelFieldToColumn[fieldName] = columnName;
166
+
167
+ if (!columnToField[tableName]) {
168
+ columnToField[tableName] = {};
169
+ }
170
+ columnToField[tableName][columnName] = fieldName;
171
+ }
172
+ fieldToColumn[modelName] = modelFieldToColumn;
173
+ }
174
+
175
+ // Preserve existing mappings if provided, otherwise use computed ones
176
+ return {
177
+ modelToTable: existingMappings?.modelToTable ?? modelToTable,
178
+ tableToModel: existingMappings?.tableToModel ?? tableToModel,
179
+ fieldToColumn: existingMappings?.fieldToColumn ?? fieldToColumn,
180
+ columnToField: existingMappings?.columnToField ?? columnToField,
181
+ codecTypes: existingMappings?.codecTypes ?? {},
182
+ operationTypes: existingMappings?.operationTypes ?? {},
183
+ };
184
+ }
185
+
186
+ /**
187
+ * Validates logical consistency of a **structurally validated** SqlContract.
188
+ * This checks that references (e.g., foreign keys, primary keys, uniques) point to storage objects that already exist.
189
+ * Structural validation is expected to have already completed before this helper runs.
190
+ *
191
+ * @param structurallyValidatedContract - The contract whose structure has already been validated
192
+ * @throws Error if logical validation fails
193
+ */
194
+ function validateContractLogic(structurallyValidatedContract: SqlContract<SqlStorage>): void {
195
+ const { storage, models } = structurallyValidatedContract;
196
+ const tableNames = new Set(Object.keys(storage.tables));
197
+
198
+ // Validate models
199
+ for (const [modelName, modelUnknown] of Object.entries(models)) {
200
+ const model = modelUnknown as ModelDefinition;
201
+ // Validate model has storage.table
202
+ if (!model.storage?.table) {
203
+ /* c8 ignore next */
204
+ throw new Error(`Model "${modelName}" is missing storage.table`);
205
+ }
206
+
207
+ const tableName = model.storage.table;
208
+
209
+ // Validate model's table exists in storage
210
+ if (!tableNames.has(tableName)) {
211
+ /* c8 ignore next */
212
+ throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`);
213
+ }
214
+
215
+ const table = storage.tables[tableName];
216
+ if (!table) {
217
+ /* c8 ignore next */
218
+ throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`);
219
+ }
220
+
221
+ // Validate model's table has a primary key
222
+ if (!table.primaryKey) {
223
+ /* c8 ignore next */
224
+ throw new Error(`Model "${modelName}" table "${tableName}" is missing a primary key`);
225
+ }
226
+
227
+ const columnNames = new Set(Object.keys(table.columns));
228
+
229
+ // Validate model fields
230
+ if (!model.fields) {
231
+ /* c8 ignore next */
232
+ throw new Error(`Model "${modelName}" is missing fields`);
233
+ }
234
+
235
+ for (const [fieldName, fieldUnknown] of Object.entries(model.fields)) {
236
+ const field = fieldUnknown as { column: string };
237
+ // Validate field has column property
238
+ if (!field.column) {
239
+ /* c8 ignore next */
240
+ throw new Error(`Model "${modelName}" field "${fieldName}" is missing column property`);
241
+ }
242
+
243
+ // Validate field's column exists in the model's backing table
244
+ if (!columnNames.has(field.column)) {
245
+ /* c8 ignore next */
246
+ throw new Error(
247
+ `Model "${modelName}" field "${fieldName}" references non-existent column "${field.column}" in table "${tableName}"`,
248
+ );
249
+ }
250
+ }
251
+
252
+ // Validate model relations have corresponding foreign keys
253
+ if (model.relations) {
254
+ for (const [relationName, relation] of Object.entries(model.relations)) {
255
+ // For now, we'll do basic validation. Full FK validation can be added later
256
+ // This would require checking that the relation's on.parentCols/childCols match FKs
257
+ if (
258
+ typeof relation === 'object' &&
259
+ relation !== null &&
260
+ 'on' in relation &&
261
+ 'to' in relation
262
+ ) {
263
+ const on = relation.on as { parentCols?: string[]; childCols?: string[] };
264
+ const cardinality = (relation as { cardinality?: string }).cardinality;
265
+ if (on.parentCols && on.childCols) {
266
+ // For 1:N relations, the foreign key is on the child table
267
+ // For N:1 relations, the foreign key is on the parent table (this table)
268
+ // For now, we'll skip validation for 1:N relations as the FK is on the child table
269
+ // and we'll validate it when we process the child model
270
+ if (cardinality === '1:N') {
271
+ // Foreign key is on the child table, skip validation here
272
+ // It will be validated when we process the child model
273
+ continue;
274
+ }
275
+
276
+ // For N:1 relations, check that there's a foreign key matching this relation
277
+ const hasMatchingFk = table.foreignKeys?.some((fk) => {
278
+ return (
279
+ fk.columns.length === on.childCols?.length &&
280
+ fk.columns.every((col, i) => col === on.childCols?.[i]) &&
281
+ fk.references.table &&
282
+ fk.references.columns.length === on.parentCols?.length &&
283
+ fk.references.columns.every((col, i) => col === on.parentCols?.[i])
284
+ );
285
+ });
286
+
287
+ if (!hasMatchingFk) {
288
+ /* c8 ignore next */
289
+ throw new Error(
290
+ `Model "${modelName}" relation "${relationName}" does not have a corresponding foreign key in table "${tableName}"`,
291
+ );
292
+ }
293
+ }
294
+ }
295
+ }
296
+ }
297
+ }
298
+
299
+ for (const [tableName, table] of Object.entries(storage.tables)) {
300
+ const columnNames = new Set(Object.keys(table.columns));
301
+
302
+ // Validate primaryKey references existing columns
303
+ if (table.primaryKey) {
304
+ for (const colName of table.primaryKey.columns) {
305
+ if (!columnNames.has(colName)) {
306
+ /* c8 ignore next */
307
+ throw new Error(
308
+ `Table "${tableName}" primaryKey references non-existent column "${colName}"`,
309
+ );
310
+ }
311
+ }
312
+ }
313
+
314
+ // Validate unique constraints reference existing columns
315
+ for (const unique of table.uniques) {
316
+ for (const colName of unique.columns) {
317
+ if (!columnNames.has(colName)) {
318
+ /* c8 ignore next */
319
+ throw new Error(
320
+ `Table "${tableName}" unique constraint references non-existent column "${colName}"`,
321
+ );
322
+ }
323
+ }
324
+ }
325
+
326
+ // Validate indexes reference existing columns
327
+ for (const index of table.indexes) {
328
+ for (const colName of index.columns) {
329
+ if (!columnNames.has(colName)) {
330
+ /* c8 ignore next */
331
+ throw new Error(`Table "${tableName}" index references non-existent column "${colName}"`);
332
+ }
333
+ }
334
+ }
335
+
336
+ // Validate foreignKeys reference existing tables and columns
337
+ for (const fk of table.foreignKeys) {
338
+ // Validate FK columns exist in the referencing table
339
+ for (const colName of fk.columns) {
340
+ if (!columnNames.has(colName)) {
341
+ /* c8 ignore next */
342
+ throw new Error(
343
+ `Table "${tableName}" foreignKey references non-existent column "${colName}"`,
344
+ );
345
+ }
346
+ }
347
+
348
+ // Validate referenced table exists
349
+ if (!tableNames.has(fk.references.table)) {
350
+ /* c8 ignore next */
351
+ throw new Error(
352
+ `Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`,
353
+ );
354
+ }
355
+
356
+ // Validate referenced columns exist in the referenced table
357
+ const referencedTable = storage.tables[fk.references.table];
358
+ if (!referencedTable) {
359
+ /* c8 ignore next */
360
+ throw new Error(
361
+ `Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`,
362
+ );
363
+ }
364
+ const referencedColumnNames = new Set(Object.keys(referencedTable.columns));
365
+
366
+ for (const colName of fk.references.columns) {
367
+ if (!referencedColumnNames.has(colName)) {
368
+ /* c8 ignore next */
369
+ throw new Error(
370
+ `Table "${tableName}" foreignKey references non-existent column "${colName}" in table "${fk.references.table}"`,
371
+ );
372
+ }
373
+ }
374
+
375
+ if (fk.columns.length !== fk.references.columns.length) {
376
+ /* c8 ignore next */
377
+ throw new Error(
378
+ `Table "${tableName}" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`,
379
+ );
380
+ }
381
+ }
382
+ }
383
+ }
384
+
385
+ export function normalizeContract(contract: unknown): SqlContract<SqlStorage> {
386
+ const contractObj = contract as Record<string, unknown>;
387
+
388
+ // Only normalize if storage exists (validation will catch if it's missing)
389
+ let normalizedStorage = contractObj['storage'];
390
+ if (normalizedStorage && typeof normalizedStorage === 'object' && normalizedStorage !== null) {
391
+ const storage = normalizedStorage as Record<string, unknown>;
392
+ const tables = storage['tables'] as Record<string, unknown> | undefined;
393
+
394
+ if (tables) {
395
+ // Normalize storage tables
396
+ const normalizedTables: Record<string, unknown> = {};
397
+ for (const [tableName, table] of Object.entries(tables)) {
398
+ const tableObj = table as Record<string, unknown>;
399
+ const columns = tableObj['columns'] as Record<string, unknown> | undefined;
400
+
401
+ if (columns) {
402
+ // Normalize columns: add nullable: false if missing
403
+ const normalizedColumns: Record<string, unknown> = {};
404
+ for (const [columnName, column] of Object.entries(columns)) {
405
+ const columnObj = column as Record<string, unknown>;
406
+ const normalizedColumn: Record<string, unknown> = {
407
+ ...columnObj,
408
+ nullable: columnObj['nullable'] ?? false,
409
+ };
410
+
411
+ normalizedColumns[columnName] = normalizedColumn;
412
+ }
413
+
414
+ // Normalize table arrays: add empty arrays if missing
415
+ normalizedTables[tableName] = {
416
+ ...tableObj,
417
+ columns: normalizedColumns,
418
+ uniques: tableObj['uniques'] ?? [],
419
+ indexes: tableObj['indexes'] ?? [],
420
+ foreignKeys: tableObj['foreignKeys'] ?? [],
421
+ };
422
+ } else {
423
+ normalizedTables[tableName] = tableObj;
424
+ }
425
+ }
426
+
427
+ normalizedStorage = {
428
+ ...storage,
429
+ tables: normalizedTables,
430
+ };
431
+ }
432
+ }
433
+
434
+ // Only normalize if models exists (validation will catch if it's missing)
435
+ let normalizedModels = contractObj['models'];
436
+ if (normalizedModels && typeof normalizedModels === 'object' && normalizedModels !== null) {
437
+ const models = normalizedModels as Record<string, unknown>;
438
+ const normalizedModelsObj: Record<string, unknown> = {};
439
+ for (const [modelName, model] of Object.entries(models)) {
440
+ const modelObj = model as Record<string, unknown>;
441
+ normalizedModelsObj[modelName] = {
442
+ ...modelObj,
443
+ relations: modelObj['relations'] ?? {},
444
+ };
445
+ }
446
+ normalizedModels = normalizedModelsObj;
447
+ }
448
+
449
+ // Normalize top-level fields: add empty objects if missing
450
+ return {
451
+ ...contractObj,
452
+ models: normalizedModels,
453
+ relations: contractObj['relations'] ?? {},
454
+ storage: normalizedStorage,
455
+ extensionPacks: contractObj['extensionPacks'] ?? {},
456
+ capabilities: contractObj['capabilities'] ?? {},
457
+ meta: contractObj['meta'] ?? {},
458
+ sources: contractObj['sources'] ?? {},
459
+ } as SqlContract<SqlStorage>;
460
+ }
461
+
462
+ /**
463
+ * Validates that a JSON import conforms to the SqlContract structure
464
+ * and returns a fully typed SqlContract.
465
+ *
466
+ * This function is specifically for validating JSON imports (e.g., from contract.json).
467
+ * Contracts created via the builder API (defineContract) are already valid and should
468
+ * not be passed to this function - use them directly without validation.
469
+ *
470
+ * Performs both structural validation (using Arktype) and logical validation
471
+ * (ensuring all references are valid).
472
+ *
473
+ *
474
+ * The type parameter `TContract` must be a fully-typed contract type (e.g., from `contract.d.ts`),
475
+ * NOT a generic `SqlContract<SqlStorage>`.
476
+ *
477
+ * **Correct:**
478
+ * ```typescript
479
+ * import type { Contract } from './contract.d';
480
+ * const contract = validateContract<Contract>(contractJson);
481
+ * ```
482
+ *
483
+ * **Incorrect:**
484
+ * ```typescript
485
+ * import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';
486
+ * const contract = validateContract<SqlContract<SqlStorage>>(contractJson);
487
+ * // ❌ Types will be inferred as 'unknown' - this won't work!
488
+ * ```
489
+ *
490
+ * The type parameter provides the specific table structure, column types, and model definitions.
491
+ * This function validates the runtime structure matches the type, but does not infer types
492
+ * from JSON (as JSON imports lose literal type information).
493
+ *
494
+ * @param value - The contract value to validate (must be from a JSON import, not a builder)
495
+ * @returns A validated contract matching the TContract type
496
+ * @throws Error if the contract structure or logic is invalid
497
+ */
498
+ export function validateContract<TContract extends SqlContract<SqlStorage>>(
499
+ value: unknown,
500
+ ): TContract {
501
+ // Normalize contract first (add defaults for missing fields)
502
+ const normalized = normalizeContract(value);
503
+
504
+ const structurallyValid = validateContractStructure<SqlContract<SqlStorage>>(normalized);
505
+
506
+ const contractForValidation = structurallyValid as SqlContract<SqlStorage>;
507
+
508
+ // Validate contract logic (contracts must already have fully qualified type IDs)
509
+ validateContractLogic(contractForValidation);
510
+
511
+ // Extract existing mappings (optional - will be computed if missing)
512
+ const existingMappings = (contractForValidation as { mappings?: Partial<SqlMappings> }).mappings;
513
+
514
+ // Compute mappings from models and storage
515
+ const mappings = computeMappings(
516
+ contractForValidation.models as Record<string, ModelDefinition>,
517
+ contractForValidation.storage,
518
+ existingMappings,
519
+ );
520
+
521
+ // Add default values for optional metadata fields if missing
522
+ const contractWithMappings = {
523
+ ...structurallyValid,
524
+ models: contractForValidation.models,
525
+ relations: contractForValidation.relations,
526
+ storage: contractForValidation.storage,
527
+ mappings,
528
+ };
529
+
530
+ // Type assertion: The caller provides the strict type via TContract.
531
+ // We validate the structure matches, but the precise types come from contract.d.ts
532
+ return contractWithMappings as TContract;
533
+ }
@@ -0,0 +1,2 @@
1
+ export type { ColumnBuilder } from '../contract-builder';
2
+ export { defineContract } from '../contract-builder';
@@ -0,0 +1 @@
1
+ export { computeMappings, validateContract } from '../contract';
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/contract.ts"],"sourcesContent":["import type {\n ForeignKey,\n ForeignKeyReferences,\n Index,\n ModelDefinition,\n ModelField,\n ModelStorage,\n PrimaryKey,\n SqlContract,\n SqlMappings,\n SqlStorage,\n StorageColumn,\n StorageTable,\n UniqueConstraint,\n} from '@prisma-next/sql-contract/types';\nimport { type } from 'arktype';\nimport type { O } from 'ts-toolbelt';\n\n/**\n * Structural validation schema for SqlContract using Arktype.\n * This validates the shape and types of the contract structure.\n */\nconst StorageColumnSchema = type.declare<StorageColumn>().type({\n nativeType: 'string',\n codecId: 'string',\n nullable: 'boolean',\n});\n\nconst PrimaryKeySchema = type.declare<PrimaryKey>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst UniqueConstraintSchema = type.declare<UniqueConstraint>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst IndexSchema = type.declare<Index>().type({\n columns: type.string.array().readonly(),\n 'name?': 'string',\n});\n\nconst ForeignKeyReferencesSchema = type.declare<ForeignKeyReferences>().type({\n table: 'string',\n columns: type.string.array().readonly(),\n});\n\nconst ForeignKeySchema = type.declare<ForeignKey>().type({\n columns: type.string.array().readonly(),\n references: ForeignKeyReferencesSchema,\n 'name?': 'string',\n});\n\nconst StorageTableSchema = type.declare<StorageTable>().type({\n columns: type({ '[string]': StorageColumnSchema }),\n 'primaryKey?': PrimaryKeySchema,\n uniques: UniqueConstraintSchema.array().readonly(),\n indexes: IndexSchema.array().readonly(),\n foreignKeys: ForeignKeySchema.array().readonly(),\n});\n\nconst StorageSchema = type.declare<SqlStorage>().type({\n tables: type({ '[string]': StorageTableSchema }),\n});\n\nconst ModelFieldSchema = type.declare<ModelField>().type({\n column: 'string',\n});\n\nconst ModelStorageSchema = type.declare<ModelStorage>().type({\n table: 'string',\n});\n\nconst ModelSchema = type.declare<ModelDefinition>().type({\n storage: ModelStorageSchema,\n fields: type({ '[string]': ModelFieldSchema }),\n relations: type({ '[string]': 'unknown' }),\n});\n\n/**\n * Complete SqlContract schema for structural validation.\n * This validates the entire contract structure at once.\n */\nconst SqlContractSchema = type({\n 'schemaVersion?': \"'1'\",\n target: 'string',\n targetFamily: \"'sql'\",\n coreHash: 'string',\n 'profileHash?': 'string',\n 'capabilities?': 'Record<string, Record<string, boolean>>',\n 'extensionPacks?': 'Record<string, unknown>',\n 'meta?': 'Record<string, unknown>',\n 'sources?': 'Record<string, unknown>',\n models: type({ '[string]': ModelSchema }),\n storage: StorageSchema,\n});\n\n/**\n * Validates the structural shape of a SqlContract using Arktype.\n *\n * **Responsibility: Validation Only**\n * This function validates that the contract has the correct structure and types.\n * It does NOT normalize the contract - normalization must happen in the contract builder.\n *\n * The contract passed to this function must already be normalized (all required fields present).\n * If normalization is needed, it should be done by the contract builder before calling this function.\n *\n * This ensures all required fields are present and have the correct types.\n *\n * @param value - The contract value to validate (typically from a JSON import)\n * @returns The validated contract if structure is valid\n * @throws Error if the contract structure is invalid\n */\nfunction validateContractStructure<T extends SqlContract<SqlStorage>>(\n value: unknown,\n): O.Overwrite<T, { targetFamily: 'sql' }> {\n // Check targetFamily first to provide a clear error message for unsupported target families\n const rawValue = value as { targetFamily?: string };\n if (rawValue.targetFamily !== undefined && rawValue.targetFamily !== 'sql') {\n /* c8 ignore next */\n throw new Error(`Unsupported target family: ${rawValue.targetFamily}`);\n }\n\n const contractResult = SqlContractSchema(value);\n\n if (contractResult instanceof type.errors) {\n const messages = contractResult.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Contract structural validation failed: ${messages}`);\n }\n\n // After validation, contractResult matches the schema and preserves the input structure\n // TypeScript needs an assertion here due to exactOptionalPropertyTypes differences\n // between Arktype's inferred type and the generic T, but runtime-wise they're compatible\n return contractResult as O.Overwrite<T, { targetFamily: 'sql' }>;\n}\n\n/**\n * Computes mapping dictionaries from models and storage structures.\n * Assumes valid input - validation happens separately in validateContractLogic().\n *\n * @param models - Models object from contract\n * @param storage - Storage object from contract\n * @param existingMappings - Existing mappings from contract input (optional)\n * @returns Computed mappings dictionary\n */\nexport function computeMappings(\n models: Record<string, ModelDefinition>,\n _storage: SqlStorage,\n existingMappings?: Partial<SqlMappings>,\n): SqlMappings {\n const modelToTable: Record<string, string> = {};\n const tableToModel: Record<string, string> = {};\n const fieldToColumn: Record<string, Record<string, string>> = {};\n const columnToField: Record<string, Record<string, string>> = {};\n\n for (const [modelName, model] of Object.entries(models)) {\n const tableName = model.storage.table;\n modelToTable[modelName] = tableName;\n tableToModel[tableName] = modelName;\n\n const modelFieldToColumn: Record<string, string> = {};\n for (const [fieldName, field] of Object.entries(model.fields)) {\n const columnName = field.column;\n modelFieldToColumn[fieldName] = columnName;\n\n if (!columnToField[tableName]) {\n columnToField[tableName] = {};\n }\n columnToField[tableName][columnName] = fieldName;\n }\n fieldToColumn[modelName] = modelFieldToColumn;\n }\n\n // Preserve existing mappings if provided, otherwise use computed ones\n return {\n modelToTable: existingMappings?.modelToTable ?? modelToTable,\n tableToModel: existingMappings?.tableToModel ?? tableToModel,\n fieldToColumn: existingMappings?.fieldToColumn ?? fieldToColumn,\n columnToField: existingMappings?.columnToField ?? columnToField,\n codecTypes: existingMappings?.codecTypes ?? {},\n operationTypes: existingMappings?.operationTypes ?? {},\n };\n}\n\n/**\n * Validates logical consistency of a **structurally validated** SqlContract.\n * This checks that references (e.g., foreign keys, primary keys, uniques) point to storage objects that already exist.\n * Structural validation is expected to have already completed before this helper runs.\n *\n * @param structurallyValidatedContract - The contract whose structure has already been validated\n * @throws Error if logical validation fails\n */\nfunction validateContractLogic(structurallyValidatedContract: SqlContract<SqlStorage>): void {\n const { storage, models } = structurallyValidatedContract;\n const tableNames = new Set(Object.keys(storage.tables));\n\n // Validate models\n for (const [modelName, modelUnknown] of Object.entries(models)) {\n const model = modelUnknown as ModelDefinition;\n // Validate model has storage.table\n if (!model.storage?.table) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" is missing storage.table`);\n }\n\n const tableName = model.storage.table;\n\n // Validate model's table exists in storage\n if (!tableNames.has(tableName)) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" references non-existent table \"${tableName}\"`);\n }\n\n const table = storage.tables[tableName];\n if (!table) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" references non-existent table \"${tableName}\"`);\n }\n\n // Validate model's table has a primary key\n if (!table.primaryKey) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" table \"${tableName}\" is missing a primary key`);\n }\n\n const columnNames = new Set(Object.keys(table.columns));\n\n // Validate model fields\n if (!model.fields) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" is missing fields`);\n }\n\n for (const [fieldName, fieldUnknown] of Object.entries(model.fields)) {\n const field = fieldUnknown as { column: string };\n // Validate field has column property\n if (!field.column) {\n /* c8 ignore next */\n throw new Error(`Model \"${modelName}\" field \"${fieldName}\" is missing column property`);\n }\n\n // Validate field's column exists in the model's backing table\n if (!columnNames.has(field.column)) {\n /* c8 ignore next */\n throw new Error(\n `Model \"${modelName}\" field \"${fieldName}\" references non-existent column \"${field.column}\" in table \"${tableName}\"`,\n );\n }\n }\n\n // Validate model relations have corresponding foreign keys\n if (model.relations) {\n for (const [relationName, relation] of Object.entries(model.relations)) {\n // For now, we'll do basic validation. Full FK validation can be added later\n // This would require checking that the relation's on.parentCols/childCols match FKs\n if (\n typeof relation === 'object' &&\n relation !== null &&\n 'on' in relation &&\n 'to' in relation\n ) {\n const on = relation.on as { parentCols?: string[]; childCols?: string[] };\n const cardinality = (relation as { cardinality?: string }).cardinality;\n if (on.parentCols && on.childCols) {\n // For 1:N relations, the foreign key is on the child table\n // For N:1 relations, the foreign key is on the parent table (this table)\n // For now, we'll skip validation for 1:N relations as the FK is on the child table\n // and we'll validate it when we process the child model\n if (cardinality === '1:N') {\n // Foreign key is on the child table, skip validation here\n // It will be validated when we process the child model\n continue;\n }\n\n // For N:1 relations, check that there's a foreign key matching this relation\n const hasMatchingFk = table.foreignKeys?.some((fk) => {\n return (\n fk.columns.length === on.childCols?.length &&\n fk.columns.every((col, i) => col === on.childCols?.[i]) &&\n fk.references.table &&\n fk.references.columns.length === on.parentCols?.length &&\n fk.references.columns.every((col, i) => col === on.parentCols?.[i])\n );\n });\n\n if (!hasMatchingFk) {\n /* c8 ignore next */\n throw new Error(\n `Model \"${modelName}\" relation \"${relationName}\" does not have a corresponding foreign key in table \"${tableName}\"`,\n );\n }\n }\n }\n }\n }\n }\n\n for (const [tableName, table] of Object.entries(storage.tables)) {\n const columnNames = new Set(Object.keys(table.columns));\n\n // Validate primaryKey references existing columns\n if (table.primaryKey) {\n for (const colName of table.primaryKey.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" primaryKey references non-existent column \"${colName}\"`,\n );\n }\n }\n }\n\n // Validate unique constraints reference existing columns\n for (const unique of table.uniques) {\n for (const colName of unique.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" unique constraint references non-existent column \"${colName}\"`,\n );\n }\n }\n }\n\n // Validate indexes reference existing columns\n for (const index of table.indexes) {\n for (const colName of index.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(`Table \"${tableName}\" index references non-existent column \"${colName}\"`);\n }\n }\n }\n\n // Validate foreignKeys reference existing tables and columns\n for (const fk of table.foreignKeys) {\n // Validate FK columns exist in the referencing table\n for (const colName of fk.columns) {\n if (!columnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\"`,\n );\n }\n }\n\n // Validate referenced table exists\n if (!tableNames.has(fk.references.table)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n );\n }\n\n // Validate referenced columns exist in the referenced table\n const referencedTable = storage.tables[fk.references.table];\n if (!referencedTable) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n );\n }\n const referencedColumnNames = new Set(Object.keys(referencedTable.columns));\n\n for (const colName of fk.references.columns) {\n if (!referencedColumnNames.has(colName)) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\" in table \"${fk.references.table}\"`,\n );\n }\n }\n\n if (fk.columns.length !== fk.references.columns.length) {\n /* c8 ignore next */\n throw new Error(\n `Table \"${tableName}\" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`,\n );\n }\n }\n }\n}\n\nexport function normalizeContract(contract: unknown): SqlContract<SqlStorage> {\n const contractObj = contract as Record<string, unknown>;\n\n // Only normalize if storage exists (validation will catch if it's missing)\n let normalizedStorage = contractObj['storage'];\n if (normalizedStorage && typeof normalizedStorage === 'object' && normalizedStorage !== null) {\n const storage = normalizedStorage as Record<string, unknown>;\n const tables = storage['tables'] as Record<string, unknown> | undefined;\n\n if (tables) {\n // Normalize storage tables\n const normalizedTables: Record<string, unknown> = {};\n for (const [tableName, table] of Object.entries(tables)) {\n const tableObj = table as Record<string, unknown>;\n const columns = tableObj['columns'] as Record<string, unknown> | undefined;\n\n if (columns) {\n // Normalize columns: add nullable: false if missing\n const normalizedColumns: Record<string, unknown> = {};\n for (const [columnName, column] of Object.entries(columns)) {\n const columnObj = column as Record<string, unknown>;\n const normalizedColumn: Record<string, unknown> = {\n ...columnObj,\n nullable: columnObj['nullable'] ?? false,\n };\n\n normalizedColumns[columnName] = normalizedColumn;\n }\n\n // Normalize table arrays: add empty arrays if missing\n normalizedTables[tableName] = {\n ...tableObj,\n columns: normalizedColumns,\n uniques: tableObj['uniques'] ?? [],\n indexes: tableObj['indexes'] ?? [],\n foreignKeys: tableObj['foreignKeys'] ?? [],\n };\n } else {\n normalizedTables[tableName] = tableObj;\n }\n }\n\n normalizedStorage = {\n ...storage,\n tables: normalizedTables,\n };\n }\n }\n\n // Only normalize if models exists (validation will catch if it's missing)\n let normalizedModels = contractObj['models'];\n if (normalizedModels && typeof normalizedModels === 'object' && normalizedModels !== null) {\n const models = normalizedModels as Record<string, unknown>;\n const normalizedModelsObj: Record<string, unknown> = {};\n for (const [modelName, model] of Object.entries(models)) {\n const modelObj = model as Record<string, unknown>;\n normalizedModelsObj[modelName] = {\n ...modelObj,\n relations: modelObj['relations'] ?? {},\n };\n }\n normalizedModels = normalizedModelsObj;\n }\n\n // Normalize top-level fields: add empty objects if missing\n return {\n ...contractObj,\n models: normalizedModels,\n relations: contractObj['relations'] ?? {},\n storage: normalizedStorage,\n extensionPacks: contractObj['extensionPacks'] ?? {},\n capabilities: contractObj['capabilities'] ?? {},\n meta: contractObj['meta'] ?? {},\n sources: contractObj['sources'] ?? {},\n } as SqlContract<SqlStorage>;\n}\n\n/**\n * Validates that a JSON import conforms to the SqlContract structure\n * and returns a fully typed SqlContract.\n *\n * This function is specifically for validating JSON imports (e.g., from contract.json).\n * Contracts created via the builder API (defineContract) are already valid and should\n * not be passed to this function - use them directly without validation.\n *\n * Performs both structural validation (using Arktype) and logical validation\n * (ensuring all references are valid).\n *\n *\n * The type parameter `TContract` must be a fully-typed contract type (e.g., from `contract.d.ts`),\n * NOT a generic `SqlContract<SqlStorage>`.\n *\n * **Correct:**\n * ```typescript\n * import type { Contract } from './contract.d';\n * const contract = validateContract<Contract>(contractJson);\n * ```\n *\n * **Incorrect:**\n * ```typescript\n * import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';\n * const contract = validateContract<SqlContract<SqlStorage>>(contractJson);\n * // ❌ Types will be inferred as 'unknown' - this won't work!\n * ```\n *\n * The type parameter provides the specific table structure, column types, and model definitions.\n * This function validates the runtime structure matches the type, but does not infer types\n * from JSON (as JSON imports lose literal type information).\n *\n * @param value - The contract value to validate (must be from a JSON import, not a builder)\n * @returns A validated contract matching the TContract type\n * @throws Error if the contract structure or logic is invalid\n */\nexport function validateContract<TContract extends SqlContract<SqlStorage>>(\n value: unknown,\n): TContract {\n // Normalize contract first (add defaults for missing fields)\n const normalized = normalizeContract(value);\n\n const structurallyValid = validateContractStructure<SqlContract<SqlStorage>>(normalized);\n\n const contractForValidation = structurallyValid as SqlContract<SqlStorage>;\n\n // Validate contract logic (contracts must already have fully qualified type IDs)\n validateContractLogic(contractForValidation);\n\n // Extract existing mappings (optional - will be computed if missing)\n const existingMappings = (contractForValidation as { mappings?: Partial<SqlMappings> }).mappings;\n\n // Compute mappings from models and storage\n const mappings = computeMappings(\n contractForValidation.models as Record<string, ModelDefinition>,\n contractForValidation.storage,\n existingMappings,\n );\n\n // Add default values for optional metadata fields if missing\n const contractWithMappings = {\n ...structurallyValid,\n models: contractForValidation.models,\n relations: contractForValidation.relations,\n storage: contractForValidation.storage,\n mappings,\n };\n\n // Type assertion: The caller provides the strict type via TContract.\n // We validate the structure matches, but the precise types come from contract.d.ts\n return contractWithMappings as TContract;\n}\n"],"mappings":";AAeA,SAAS,YAAY;AAOrB,IAAM,sBAAsB,KAAK,QAAuB,EAAE,KAAK;AAAA,EAC7D,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,UAAU;AACZ,CAAC;AAED,IAAM,mBAAmB,KAAK,QAAoB,EAAE,KAAK;AAAA,EACvD,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,SAAS;AACX,CAAC;AAED,IAAM,yBAAyB,KAAK,QAA0B,EAAE,KAAK;AAAA,EACnE,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,SAAS;AACX,CAAC;AAED,IAAM,cAAc,KAAK,QAAe,EAAE,KAAK;AAAA,EAC7C,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,SAAS;AACX,CAAC;AAED,IAAM,6BAA6B,KAAK,QAA8B,EAAE,KAAK;AAAA,EAC3E,OAAO;AAAA,EACP,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AACxC,CAAC;AAED,IAAM,mBAAmB,KAAK,QAAoB,EAAE,KAAK;AAAA,E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