@prisma-next/sql-contract-ts 0.3.0-pr.93.5 → 0.3.0-pr.94.2

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,331 @@
1
+ import { type } from "arktype";
2
+
3
+ //#region src/contract.ts
4
+ /**
5
+ * Structural validation schema for SqlContract using Arktype.
6
+ * This validates the shape and types of the contract structure.
7
+ */
8
+ const StorageColumnSchema = type.declare().type({
9
+ nativeType: "string",
10
+ codecId: "string",
11
+ nullable: "boolean"
12
+ });
13
+ const PrimaryKeySchema = type.declare().type({
14
+ columns: type.string.array().readonly(),
15
+ "name?": "string"
16
+ });
17
+ const UniqueConstraintSchema = type.declare().type({
18
+ columns: type.string.array().readonly(),
19
+ "name?": "string"
20
+ });
21
+ const IndexSchema = type.declare().type({
22
+ columns: type.string.array().readonly(),
23
+ "name?": "string"
24
+ });
25
+ const ForeignKeyReferencesSchema = type.declare().type({
26
+ table: "string",
27
+ columns: type.string.array().readonly()
28
+ });
29
+ const ForeignKeySchema = type.declare().type({
30
+ columns: type.string.array().readonly(),
31
+ references: ForeignKeyReferencesSchema,
32
+ "name?": "string"
33
+ });
34
+ const StorageTableSchema = type.declare().type({
35
+ columns: type({ "[string]": StorageColumnSchema }),
36
+ "primaryKey?": PrimaryKeySchema,
37
+ uniques: UniqueConstraintSchema.array().readonly(),
38
+ indexes: IndexSchema.array().readonly(),
39
+ foreignKeys: ForeignKeySchema.array().readonly()
40
+ });
41
+ const StorageSchema = type.declare().type({ tables: type({ "[string]": StorageTableSchema }) });
42
+ const ModelFieldSchema = type.declare().type({ column: "string" });
43
+ const ModelStorageSchema = type.declare().type({ table: "string" });
44
+ const ModelSchema = type.declare().type({
45
+ storage: ModelStorageSchema,
46
+ fields: type({ "[string]": ModelFieldSchema }),
47
+ relations: type({ "[string]": "unknown" })
48
+ });
49
+ /**
50
+ * Complete SqlContract schema for structural validation.
51
+ * This validates the entire contract structure at once.
52
+ */
53
+ const SqlContractSchema = type({
54
+ "schemaVersion?": "'1'",
55
+ target: "string",
56
+ targetFamily: "'sql'",
57
+ coreHash: "string",
58
+ "profileHash?": "string",
59
+ "capabilities?": "Record<string, Record<string, boolean>>",
60
+ "extensionPacks?": "Record<string, unknown>",
61
+ "meta?": "Record<string, unknown>",
62
+ "sources?": "Record<string, unknown>",
63
+ models: type({ "[string]": ModelSchema }),
64
+ storage: StorageSchema
65
+ });
66
+ /**
67
+ * Validates the structural shape of a SqlContract using Arktype.
68
+ *
69
+ * **Responsibility: Validation Only**
70
+ * This function validates that the contract has the correct structure and types.
71
+ * It does NOT normalize the contract - normalization must happen in the contract builder.
72
+ *
73
+ * The contract passed to this function must already be normalized (all required fields present).
74
+ * If normalization is needed, it should be done by the contract builder before calling this function.
75
+ *
76
+ * This ensures all required fields are present and have the correct types.
77
+ *
78
+ * @param value - The contract value to validate (typically from a JSON import)
79
+ * @returns The validated contract if structure is valid
80
+ * @throws Error if the contract structure is invalid
81
+ */
82
+ function validateContractStructure(value) {
83
+ const rawValue = value;
84
+ if (rawValue.targetFamily !== void 0 && rawValue.targetFamily !== "sql")
85
+ /* c8 ignore next */
86
+ throw new Error(`Unsupported target family: ${rawValue.targetFamily}`);
87
+ const contractResult = SqlContractSchema(value);
88
+ if (contractResult instanceof type.errors) {
89
+ const messages = contractResult.map((p) => p.message).join("; ");
90
+ throw new Error(`Contract structural validation failed: ${messages}`);
91
+ }
92
+ return contractResult;
93
+ }
94
+ /**
95
+ * Computes mapping dictionaries from models and storage structures.
96
+ * Assumes valid input - validation happens separately in validateContractLogic().
97
+ *
98
+ * @param models - Models object from contract
99
+ * @param storage - Storage object from contract
100
+ * @param existingMappings - Existing mappings from contract input (optional)
101
+ * @returns Computed mappings dictionary
102
+ */
103
+ function computeMappings(models, _storage, existingMappings) {
104
+ const modelToTable = {};
105
+ const tableToModel = {};
106
+ const fieldToColumn = {};
107
+ const columnToField = {};
108
+ for (const [modelName, model] of Object.entries(models)) {
109
+ const tableName = model.storage.table;
110
+ modelToTable[modelName] = tableName;
111
+ tableToModel[tableName] = modelName;
112
+ const modelFieldToColumn = {};
113
+ for (const [fieldName, field] of Object.entries(model.fields)) {
114
+ const columnName = field.column;
115
+ modelFieldToColumn[fieldName] = columnName;
116
+ if (!columnToField[tableName]) columnToField[tableName] = {};
117
+ columnToField[tableName][columnName] = fieldName;
118
+ }
119
+ fieldToColumn[modelName] = modelFieldToColumn;
120
+ }
121
+ return {
122
+ modelToTable: existingMappings?.modelToTable ?? modelToTable,
123
+ tableToModel: existingMappings?.tableToModel ?? tableToModel,
124
+ fieldToColumn: existingMappings?.fieldToColumn ?? fieldToColumn,
125
+ columnToField: existingMappings?.columnToField ?? columnToField,
126
+ codecTypes: existingMappings?.codecTypes ?? {},
127
+ operationTypes: existingMappings?.operationTypes ?? {}
128
+ };
129
+ }
130
+ /**
131
+ * Validates logical consistency of a **structurally validated** SqlContract.
132
+ * This checks that references (e.g., foreign keys, primary keys, uniques) point to storage objects that already exist.
133
+ * Structural validation is expected to have already completed before this helper runs.
134
+ *
135
+ * @param structurallyValidatedContract - The contract whose structure has already been validated
136
+ * @throws Error if logical validation fails
137
+ */
138
+ function validateContractLogic(structurallyValidatedContract) {
139
+ const { storage, models } = structurallyValidatedContract;
140
+ const tableNames = new Set(Object.keys(storage.tables));
141
+ for (const [modelName, modelUnknown] of Object.entries(models)) {
142
+ const model = modelUnknown;
143
+ if (!model.storage?.table)
144
+ /* c8 ignore next */
145
+ throw new Error(`Model "${modelName}" is missing storage.table`);
146
+ const tableName = model.storage.table;
147
+ if (!tableNames.has(tableName))
148
+ /* c8 ignore next */
149
+ throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`);
150
+ const table = storage.tables[tableName];
151
+ if (!table)
152
+ /* c8 ignore next */
153
+ throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`);
154
+ if (!table.primaryKey)
155
+ /* c8 ignore next */
156
+ throw new Error(`Model "${modelName}" table "${tableName}" is missing a primary key`);
157
+ const columnNames = new Set(Object.keys(table.columns));
158
+ if (!model.fields)
159
+ /* c8 ignore next */
160
+ throw new Error(`Model "${modelName}" is missing fields`);
161
+ for (const [fieldName, fieldUnknown] of Object.entries(model.fields)) {
162
+ const field = fieldUnknown;
163
+ if (!field.column)
164
+ /* c8 ignore next */
165
+ throw new Error(`Model "${modelName}" field "${fieldName}" is missing column property`);
166
+ if (!columnNames.has(field.column))
167
+ /* c8 ignore next */
168
+ throw new Error(`Model "${modelName}" field "${fieldName}" references non-existent column "${field.column}" in table "${tableName}"`);
169
+ }
170
+ if (model.relations) {
171
+ for (const [relationName, relation] of Object.entries(model.relations)) if (typeof relation === "object" && relation !== null && "on" in relation && "to" in relation) {
172
+ const on = relation.on;
173
+ const cardinality = relation.cardinality;
174
+ if (on.parentCols && on.childCols) {
175
+ if (cardinality === "1:N") continue;
176
+ if (!table.foreignKeys?.some((fk) => {
177
+ return fk.columns.length === on.childCols?.length && fk.columns.every((col, i) => col === on.childCols?.[i]) && fk.references.table && fk.references.columns.length === on.parentCols?.length && fk.references.columns.every((col, i) => col === on.parentCols?.[i]);
178
+ }))
179
+ /* c8 ignore next */
180
+ throw new Error(`Model "${modelName}" relation "${relationName}" does not have a corresponding foreign key in table "${tableName}"`);
181
+ }
182
+ }
183
+ }
184
+ }
185
+ for (const [tableName, table] of Object.entries(storage.tables)) {
186
+ const columnNames = new Set(Object.keys(table.columns));
187
+ if (table.primaryKey) {
188
+ for (const colName of table.primaryKey.columns) if (!columnNames.has(colName))
189
+ /* c8 ignore next */
190
+ throw new Error(`Table "${tableName}" primaryKey references non-existent column "${colName}"`);
191
+ }
192
+ for (const unique of table.uniques) for (const colName of unique.columns) if (!columnNames.has(colName))
193
+ /* c8 ignore next */
194
+ throw new Error(`Table "${tableName}" unique constraint references non-existent column "${colName}"`);
195
+ for (const index of table.indexes) for (const colName of index.columns) if (!columnNames.has(colName))
196
+ /* c8 ignore next */
197
+ throw new Error(`Table "${tableName}" index references non-existent column "${colName}"`);
198
+ for (const fk of table.foreignKeys) {
199
+ for (const colName of fk.columns) if (!columnNames.has(colName))
200
+ /* c8 ignore next */
201
+ throw new Error(`Table "${tableName}" foreignKey references non-existent column "${colName}"`);
202
+ if (!tableNames.has(fk.references.table))
203
+ /* c8 ignore next */
204
+ throw new Error(`Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`);
205
+ const referencedTable = storage.tables[fk.references.table];
206
+ if (!referencedTable)
207
+ /* c8 ignore next */
208
+ throw new Error(`Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`);
209
+ const referencedColumnNames = new Set(Object.keys(referencedTable.columns));
210
+ for (const colName of fk.references.columns) if (!referencedColumnNames.has(colName))
211
+ /* c8 ignore next */
212
+ throw new Error(`Table "${tableName}" foreignKey references non-existent column "${colName}" in table "${fk.references.table}"`);
213
+ if (fk.columns.length !== fk.references.columns.length)
214
+ /* c8 ignore next */
215
+ throw new Error(`Table "${tableName}" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`);
216
+ }
217
+ }
218
+ }
219
+ function normalizeContract(contract) {
220
+ const contractObj = contract;
221
+ let normalizedStorage = contractObj["storage"];
222
+ if (normalizedStorage && typeof normalizedStorage === "object" && normalizedStorage !== null) {
223
+ const storage = normalizedStorage;
224
+ const tables = storage["tables"];
225
+ if (tables) {
226
+ const normalizedTables = {};
227
+ for (const [tableName, table] of Object.entries(tables)) {
228
+ const tableObj = table;
229
+ const columns = tableObj["columns"];
230
+ if (columns) {
231
+ const normalizedColumns = {};
232
+ for (const [columnName, column] of Object.entries(columns)) {
233
+ const columnObj = column;
234
+ normalizedColumns[columnName] = {
235
+ ...columnObj,
236
+ nullable: columnObj["nullable"] ?? false
237
+ };
238
+ }
239
+ normalizedTables[tableName] = {
240
+ ...tableObj,
241
+ columns: normalizedColumns,
242
+ uniques: tableObj["uniques"] ?? [],
243
+ indexes: tableObj["indexes"] ?? [],
244
+ foreignKeys: tableObj["foreignKeys"] ?? []
245
+ };
246
+ } else normalizedTables[tableName] = tableObj;
247
+ }
248
+ normalizedStorage = {
249
+ ...storage,
250
+ tables: normalizedTables
251
+ };
252
+ }
253
+ }
254
+ let normalizedModels = contractObj["models"];
255
+ if (normalizedModels && typeof normalizedModels === "object" && normalizedModels !== null) {
256
+ const models = normalizedModels;
257
+ const normalizedModelsObj = {};
258
+ for (const [modelName, model] of Object.entries(models)) {
259
+ const modelObj = model;
260
+ normalizedModelsObj[modelName] = {
261
+ ...modelObj,
262
+ relations: modelObj["relations"] ?? {}
263
+ };
264
+ }
265
+ normalizedModels = normalizedModelsObj;
266
+ }
267
+ return {
268
+ ...contractObj,
269
+ models: normalizedModels,
270
+ relations: contractObj["relations"] ?? {},
271
+ storage: normalizedStorage,
272
+ extensionPacks: contractObj["extensionPacks"] ?? {},
273
+ capabilities: contractObj["capabilities"] ?? {},
274
+ meta: contractObj["meta"] ?? {},
275
+ sources: contractObj["sources"] ?? {}
276
+ };
277
+ }
278
+ /**
279
+ * Validates that a JSON import conforms to the SqlContract structure
280
+ * and returns a fully typed SqlContract.
281
+ *
282
+ * This function is specifically for validating JSON imports (e.g., from contract.json).
283
+ * Contracts created via the builder API (defineContract) are already valid and should
284
+ * not be passed to this function - use them directly without validation.
285
+ *
286
+ * Performs both structural validation (using Arktype) and logical validation
287
+ * (ensuring all references are valid).
288
+ *
289
+ *
290
+ * The type parameter `TContract` must be a fully-typed contract type (e.g., from `contract.d.ts`),
291
+ * NOT a generic `SqlContract<SqlStorage>`.
292
+ *
293
+ * **Correct:**
294
+ * ```typescript
295
+ * import type { Contract } from './contract.d';
296
+ * const contract = validateContract<Contract>(contractJson);
297
+ * ```
298
+ *
299
+ * **Incorrect:**
300
+ * ```typescript
301
+ * import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';
302
+ * const contract = validateContract<SqlContract<SqlStorage>>(contractJson);
303
+ * // ❌ Types will be inferred as 'unknown' - this won't work!
304
+ * ```
305
+ *
306
+ * The type parameter provides the specific table structure, column types, and model definitions.
307
+ * This function validates the runtime structure matches the type, but does not infer types
308
+ * from JSON (as JSON imports lose literal type information).
309
+ *
310
+ * @param value - The contract value to validate (must be from a JSON import, not a builder)
311
+ * @returns A validated contract matching the TContract type
312
+ * @throws Error if the contract structure or logic is invalid
313
+ */
314
+ function validateContract(value) {
315
+ const structurallyValid = validateContractStructure(normalizeContract(value));
316
+ const contractForValidation = structurallyValid;
317
+ validateContractLogic(contractForValidation);
318
+ const existingMappings = contractForValidation.mappings;
319
+ const mappings = computeMappings(contractForValidation.models, contractForValidation.storage, existingMappings);
320
+ return {
321
+ ...structurallyValid,
322
+ models: contractForValidation.models,
323
+ relations: contractForValidation.relations,
324
+ storage: contractForValidation.storage,
325
+ mappings
326
+ };
327
+ }
328
+
329
+ //#endregion
330
+ export { validateContract as n, computeMappings as t };
331
+ //# sourceMappingURL=contract-CbxDA5bF.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-CbxDA5bF.mjs","names":["modelToTable: Record<string, string>","tableToModel: Record<string, string>","fieldToColumn: Record<string, Record<string, string>>","columnToField: Record<string, Record<string, string>>","modelFieldToColumn: Record<string, string>","normalizedTables: Record<string, unknown>","normalizedColumns: Record<string, unknown>","normalizedModelsObj: Record<string, unknown>"],"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 prec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ryKey, ModelBuilder, ModelBuilderState, RelationDefinition, TableBuilder, TableBuilderState } from "@prisma-next/contract-authoring";
2
+ import { ExtensionPackRef, TargetPackRef } from "@prisma-next/contract/framework-components";
3
+ import { SqlContract, SqlMappings } from "@prisma-next/sql-contract/types";
4
+
5
+ //#region src/contract-builder.d.ts
6
+
7
+ /**
8
+ * Type-level mappings structure for contracts built via `defineContract()`.
9
+ *
10
+ * Compile-time type helper (not a runtime object) that ensures mappings match what the builder
11
+ * produces. `codecTypes` uses the generic `CodecTypes` parameter; `operationTypes` is always
12
+ * empty since operations are added via extensions at runtime.
13
+ *
14
+ * **Difference from RuntimeContext**: This is a compile-time type for contract construction.
15
+ * `RuntimeContext` is a runtime object with populated registries for query execution.
16
+ *
17
+ * @template C - The `CodecTypes` generic parameter passed to `defineContract<CodecTypes>()`
18
+ */
19
+ type ContractBuilderMappings<C extends Record<string, {
20
+ output: unknown;
21
+ }>> = Omit<SqlMappings, 'codecTypes' | 'operationTypes'> & {
22
+ readonly codecTypes: C;
23
+ readonly operationTypes: Record<string, never>;
24
+ };
25
+ type BuildStorageTable<_TableName extends string, Columns extends Record<string, ColumnBuilderState<string, boolean, string>>, PK extends readonly string[] | undefined> = {
26
+ readonly columns: { readonly [K in keyof Columns]: Columns[K] extends ColumnBuilderState<string, infer Null, infer TType> ? BuildStorageColumn<Null & boolean, TType> : never };
27
+ readonly uniques: ReadonlyArray<{
28
+ readonly columns: readonly string[];
29
+ readonly name?: string;
30
+ }>;
31
+ readonly indexes: ReadonlyArray<{
32
+ readonly columns: readonly string[];
33
+ readonly name?: string;
34
+ }>;
35
+ readonly foreignKeys: ReadonlyArray<{
36
+ readonly columns: readonly string[];
37
+ readonly references: {
38
+ readonly table: string;
39
+ readonly columns: readonly string[];
40
+ };
41
+ readonly name?: string;
42
+ }>;
43
+ } & (PK extends readonly string[] ? {
44
+ readonly primaryKey: {
45
+ readonly columns: PK;
46
+ readonly name?: string;
47
+ };
48
+ } : Record<string, never>);
49
+ type BuildStorage<Tables extends Record<string, TableBuilderState<string, Record<string, ColumnBuilderState<string, boolean, string>>, readonly string[] | undefined>>> = {
50
+ readonly tables: { readonly [K in keyof Tables]: BuildStorageTable<K & string, ExtractColumns<Tables[K]>, ExtractPrimaryKey<Tables[K]>> };
51
+ };
52
+ interface ColumnBuilder<Name extends string, Nullable extends boolean, Type extends string> {
53
+ nullable<Value extends boolean>(value?: Value): ColumnBuilder<Name, Value, Type>;
54
+ type<Id extends string>(id: Id): ColumnBuilder<Name, Nullable, Id>;
55
+ build(): ColumnBuilderState<Name, Nullable, Type>;
56
+ }
57
+ declare class SqlContractBuilder<CodecTypes extends Record<string, {
58
+ output: unknown;
59
+ }> = Record<string, never>, Target extends string | undefined = undefined, Tables extends Record<string, TableBuilderState<string, Record<string, ColumnBuilderState<string, boolean, string>>, readonly string[] | undefined>> = Record<never, never>, Models extends Record<string, ModelBuilderState<string, string, Record<string, string>, Record<string, RelationDefinition>>> = Record<never, never>, CoreHash extends string | undefined = undefined, ExtensionPacks extends Record<string, unknown> | undefined = undefined, Capabilities extends Record<string, Record<string, boolean>> | undefined = undefined> extends ContractBuilder<Target, Tables, Models, CoreHash, ExtensionPacks, Capabilities> {
60
+ /**
61
+ * This method is responsible for normalizing the contract IR by setting default values
62
+ * for all required fields:
63
+ * - `nullable`: defaults to `false` if not provided
64
+ * - `uniques`: defaults to `[]` (empty array)
65
+ * - `indexes`: defaults to `[]` (empty array)
66
+ * - `foreignKeys`: defaults to `[]` (empty array)
67
+ * - `relations`: defaults to `{}` (empty object) for both model-level and contract-level
68
+ * - `nativeType`: required field set from column type descriptor when columns are defined
69
+ *
70
+ * The contract builder is the **only** place where normalization should occur.
71
+ * Validators, parsers, and emitters should assume the contract is already normalized.
72
+ *
73
+ * **Required**: Use column type descriptors (e.g., `int4Column`, `textColumn`) when defining columns.
74
+ * This ensures `nativeType` is set correctly at build time.
75
+ *
76
+ * @returns A normalized SqlContract with all required fields present
77
+ */
78
+ build(): Target extends string ? SqlContract<BuildStorage<Tables>, BuildModels<Models>, BuildRelations<Models>, ContractBuilderMappings<CodecTypes>> & {
79
+ readonly schemaVersion: '1';
80
+ readonly target: Target;
81
+ readonly targetFamily: 'sql';
82
+ readonly coreHash: CoreHash extends string ? CoreHash : string;
83
+ } & (ExtensionPacks extends Record<string, unknown> ? {
84
+ readonly extensionPacks: ExtensionPacks;
85
+ } : Record<string, never>) & (Capabilities extends Record<string, Record<string, boolean>> ? {
86
+ readonly capabilities: Capabilities;
87
+ } : Record<string, never>) : never;
88
+ target<T extends string>(packRef: TargetPackRef<'sql', T>): SqlContractBuilder<CodecTypes, T, Tables, Models, CoreHash, ExtensionPacks, Capabilities>;
89
+ extensionPacks(packs: Record<string, ExtensionPackRef<'sql', string>>): SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, ExtensionPacks, Capabilities>;
90
+ capabilities<C extends Record<string, Record<string, boolean>>>(capabilities: C): SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, ExtensionPacks, C>;
91
+ coreHash<H extends string>(hash: H): SqlContractBuilder<CodecTypes, Target, Tables, Models, H, ExtensionPacks, Capabilities>;
92
+ table<TableName extends string, T extends TableBuilder<TableName, Record<string, ColumnBuilderState<string, boolean, string>>, readonly string[] | undefined>>(name: TableName, callback: (t: TableBuilder<TableName>) => T | undefined): SqlContractBuilder<CodecTypes, Target, Tables & Record<TableName, ReturnType<T['build']>>, Models, CoreHash, ExtensionPacks, Capabilities>;
93
+ model<ModelName extends string, TableName extends string, M extends ModelBuilder<ModelName, TableName, Record<string, string>, Record<string, RelationDefinition>>>(name: ModelName, table: TableName, callback: (m: ModelBuilder<ModelName, TableName, Record<string, string>, Record<never, never>>) => M | undefined): SqlContractBuilder<CodecTypes, Target, Tables, Models & Record<ModelName, ReturnType<M['build']>>, CoreHash, ExtensionPacks, Capabilities>;
94
+ }
95
+ declare function defineContract<CodecTypes extends Record<string, {
96
+ output: unknown;
97
+ }> = Record<string, never>>(): SqlContractBuilder<CodecTypes>;
98
+ //#endregion
99
+ export { type ColumnBuilder, defineContract };
100
+ //# sourceMappingURL=contract-builder.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-builder.d.mts","names":[],"sources":["../src/contract-builder.ts"],"sourcesContent":[],"mappings":";;;;;;;AAyByC;;;;;;;AAoBR;;;;KAL5B,uBAc8B,CAAA,UAdI,MAcJ,CAAA,MAAA,EAAA;EAAQ,MAAA,EAAA,OAAA;CAAW,CAAA,CAAA,GAdwB,IAcxB,CAbpD,WAaoD,EAAA,YAAA,GAAA,gBAAA,CAAA,GAAA;EAK3B,SAAA,UAAA,EAfJ,CAeI;EAAgB,SAAA,cAAA,EAdhB,MAcgB,CAAA,MAAA,EAAA,KAAA,CAAA;CAAnC;KAXH,iBAce,CAAA,mBAAA,MAAA,EAAA,gBAZF,MAYE,CAAA,MAAA,EAZa,kBAYb,CAAA,MAAA,EAAA,OAAA,EAAA,MAAA,CAAA,CAAA,EAAA,WAAA,SAAA,MAAA,EAAA,GAAA,SAAA,CAAA,GAAA;EACA,SAAA,OAAA,EAAA,iBACI,MAVC,OAUD,GAVW,OAUX,CAVmB,CAUnB,CAAA,SAV8B,kBAU9B,CAAA,MAAA,EAAA,KAAA,KAAA,EAAA,KAAA,MAAA,CAAA,GALhB,kBAKgB,CALG,IAKH,GAAA,OAAA,EALmB,KAKnB,CAAA,GAAA,KAAA,EAKnB;EAC0C,SAAA,OAAA,EAR3B,aAQ2B,CAAA;IAC3C,SAAA,OAAA,EAAA,SAAA,MAAA,EAAA;IAAM,SAAA,IAAA,CAAA,EAAA,MAAA;EAEL,CAAA,CAAA;EAKgB,SAAA,OAAA,EAfD,aAeC,CAAA;IAAf,SAAA,OAAA,EAAA,SAAA,MAAA,EAAA;IAFF,SAAA,IAAA,CAAA,EAAA,MAAA;EAFa,CAAA,CAAA;EAUQ,SAAA,WAAA,EApBD,aAoBC,CAAA;IACnB,SAAA,OAAA,EAAA,SAAA,MAAA,EAAA;IACe,SAAA,UAA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