@prisma-next/sql-contract-ts 0.3.0-pr.94.3 → 0.3.0-pr.95.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,346 @@
1
+ // src/contract.ts
2
+ import { type } from "arktype";
3
+ var StorageColumnSchema = type.declare().type({
4
+ nativeType: "string",
5
+ codecId: "string",
6
+ nullable: "boolean",
7
+ "typeParams?": "Record<string, unknown>",
8
+ "typeRef?": "string"
9
+ });
10
+ var StorageTypeInstanceSchema = type.declare().type({
11
+ codecId: "string",
12
+ nativeType: "string",
13
+ typeParams: "Record<string, unknown>"
14
+ });
15
+ var PrimaryKeySchema = type.declare().type({
16
+ columns: type.string.array().readonly(),
17
+ "name?": "string"
18
+ });
19
+ var UniqueConstraintSchema = type.declare().type({
20
+ columns: type.string.array().readonly(),
21
+ "name?": "string"
22
+ });
23
+ var IndexSchema = type.declare().type({
24
+ columns: type.string.array().readonly(),
25
+ "name?": "string"
26
+ });
27
+ var ForeignKeyReferencesSchema = type.declare().type({
28
+ table: "string",
29
+ columns: type.string.array().readonly()
30
+ });
31
+ var ForeignKeySchema = type.declare().type({
32
+ columns: type.string.array().readonly(),
33
+ references: ForeignKeyReferencesSchema,
34
+ "name?": "string"
35
+ });
36
+ var StorageTableSchema = type.declare().type({
37
+ columns: type({ "[string]": StorageColumnSchema }),
38
+ "primaryKey?": PrimaryKeySchema,
39
+ uniques: UniqueConstraintSchema.array().readonly(),
40
+ indexes: IndexSchema.array().readonly(),
41
+ foreignKeys: ForeignKeySchema.array().readonly()
42
+ });
43
+ var StorageSchema = type.declare().type({
44
+ tables: type({ "[string]": StorageTableSchema }),
45
+ "types?": type({ "[string]": StorageTypeInstanceSchema })
46
+ });
47
+ var ModelFieldSchema = type.declare().type({
48
+ column: "string"
49
+ });
50
+ var ModelStorageSchema = type.declare().type({
51
+ table: "string"
52
+ });
53
+ var ModelSchema = type.declare().type({
54
+ storage: ModelStorageSchema,
55
+ fields: type({ "[string]": ModelFieldSchema }),
56
+ relations: type({ "[string]": "unknown" })
57
+ });
58
+ var SqlContractSchema = type({
59
+ "schemaVersion?": "'1'",
60
+ target: "string",
61
+ targetFamily: "'sql'",
62
+ coreHash: "string",
63
+ "profileHash?": "string",
64
+ "capabilities?": "Record<string, Record<string, boolean>>",
65
+ "extensionPacks?": "Record<string, unknown>",
66
+ "meta?": "Record<string, unknown>",
67
+ "sources?": "Record<string, unknown>",
68
+ models: type({ "[string]": ModelSchema }),
69
+ storage: StorageSchema
70
+ });
71
+ function validateContractStructure(value) {
72
+ const rawValue = value;
73
+ if (rawValue.targetFamily !== void 0 && rawValue.targetFamily !== "sql") {
74
+ throw new Error(`Unsupported target family: ${rawValue.targetFamily}`);
75
+ }
76
+ const contractResult = SqlContractSchema(value);
77
+ if (contractResult instanceof type.errors) {
78
+ const messages = contractResult.map((p) => p.message).join("; ");
79
+ throw new Error(`Contract structural validation failed: ${messages}`);
80
+ }
81
+ return contractResult;
82
+ }
83
+ function computeMappings(models, _storage, existingMappings) {
84
+ const modelToTable = {};
85
+ const tableToModel = {};
86
+ const fieldToColumn = {};
87
+ const columnToField = {};
88
+ for (const [modelName, model] of Object.entries(models)) {
89
+ const tableName = model.storage.table;
90
+ modelToTable[modelName] = tableName;
91
+ tableToModel[tableName] = modelName;
92
+ const modelFieldToColumn = {};
93
+ for (const [fieldName, field] of Object.entries(model.fields)) {
94
+ const columnName = field.column;
95
+ modelFieldToColumn[fieldName] = columnName;
96
+ if (!columnToField[tableName]) {
97
+ columnToField[tableName] = {};
98
+ }
99
+ columnToField[tableName][columnName] = fieldName;
100
+ }
101
+ fieldToColumn[modelName] = modelFieldToColumn;
102
+ }
103
+ return {
104
+ modelToTable: existingMappings?.modelToTable ?? modelToTable,
105
+ tableToModel: existingMappings?.tableToModel ?? tableToModel,
106
+ fieldToColumn: existingMappings?.fieldToColumn ?? fieldToColumn,
107
+ columnToField: existingMappings?.columnToField ?? columnToField,
108
+ codecTypes: existingMappings?.codecTypes ?? {},
109
+ operationTypes: existingMappings?.operationTypes ?? {}
110
+ };
111
+ }
112
+ function validateContractLogic(structurallyValidatedContract) {
113
+ const { storage, models } = structurallyValidatedContract;
114
+ const tableNames = new Set(Object.keys(storage.tables));
115
+ const typeInstanceNames = new Set(Object.keys(storage.types ?? {}));
116
+ if (storage.types) {
117
+ for (const [typeName, typeInstance] of Object.entries(storage.types)) {
118
+ if (Array.isArray(typeInstance.typeParams)) {
119
+ throw new Error(
120
+ `Type instance "${typeName}" has invalid typeParams: must be a plain object, not an array`
121
+ );
122
+ }
123
+ }
124
+ }
125
+ for (const [tableName, table] of Object.entries(storage.tables)) {
126
+ for (const [columnName, column] of Object.entries(table.columns)) {
127
+ if (column.typeParams !== void 0 && column.typeRef !== void 0) {
128
+ throw new Error(
129
+ `Column "${columnName}" in table "${tableName}" has both typeParams and typeRef; these are mutually exclusive`
130
+ );
131
+ }
132
+ if (column.typeParams !== void 0 && Array.isArray(column.typeParams)) {
133
+ throw new Error(
134
+ `Column "${columnName}" in table "${tableName}" has invalid typeParams: must be a plain object, not an array`
135
+ );
136
+ }
137
+ if (column.typeRef !== void 0 && !typeInstanceNames.has(column.typeRef)) {
138
+ throw new Error(
139
+ `Column "${columnName}" in table "${tableName}" references non-existent type instance "${column.typeRef}" (not found in storage.types)`
140
+ );
141
+ }
142
+ }
143
+ }
144
+ for (const [modelName, modelUnknown] of Object.entries(models)) {
145
+ const model = modelUnknown;
146
+ if (!model.storage?.table) {
147
+ throw new Error(`Model "${modelName}" is missing storage.table`);
148
+ }
149
+ const tableName = model.storage.table;
150
+ if (!tableNames.has(tableName)) {
151
+ throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`);
152
+ }
153
+ const table = storage.tables[tableName];
154
+ if (!table) {
155
+ throw new Error(`Model "${modelName}" references non-existent table "${tableName}"`);
156
+ }
157
+ if (!table.primaryKey) {
158
+ throw new Error(`Model "${modelName}" table "${tableName}" is missing a primary key`);
159
+ }
160
+ const columnNames = new Set(Object.keys(table.columns));
161
+ if (!model.fields) {
162
+ throw new Error(`Model "${modelName}" is missing fields`);
163
+ }
164
+ for (const [fieldName, fieldUnknown] of Object.entries(model.fields)) {
165
+ const field = fieldUnknown;
166
+ if (!field.column) {
167
+ throw new Error(`Model "${modelName}" field "${fieldName}" is missing column property`);
168
+ }
169
+ if (!columnNames.has(field.column)) {
170
+ throw new Error(
171
+ `Model "${modelName}" field "${fieldName}" references non-existent column "${field.column}" in table "${tableName}"`
172
+ );
173
+ }
174
+ }
175
+ if (model.relations) {
176
+ for (const [relationName, relation] of Object.entries(model.relations)) {
177
+ if (typeof relation === "object" && relation !== null && "on" in relation && "to" in relation) {
178
+ const on = relation.on;
179
+ const cardinality = relation.cardinality;
180
+ if (on.parentCols && on.childCols) {
181
+ if (cardinality === "1:N") {
182
+ continue;
183
+ }
184
+ const hasMatchingFk = table.foreignKeys?.some((fk) => {
185
+ 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]);
186
+ });
187
+ if (!hasMatchingFk) {
188
+ throw new Error(
189
+ `Model "${modelName}" relation "${relationName}" does not have a corresponding foreign key in table "${tableName}"`
190
+ );
191
+ }
192
+ }
193
+ }
194
+ }
195
+ }
196
+ }
197
+ for (const [tableName, table] of Object.entries(storage.tables)) {
198
+ const columnNames = new Set(Object.keys(table.columns));
199
+ if (table.primaryKey) {
200
+ for (const colName of table.primaryKey.columns) {
201
+ if (!columnNames.has(colName)) {
202
+ throw new Error(
203
+ `Table "${tableName}" primaryKey references non-existent column "${colName}"`
204
+ );
205
+ }
206
+ }
207
+ }
208
+ for (const unique of table.uniques) {
209
+ for (const colName of unique.columns) {
210
+ if (!columnNames.has(colName)) {
211
+ throw new Error(
212
+ `Table "${tableName}" unique constraint references non-existent column "${colName}"`
213
+ );
214
+ }
215
+ }
216
+ }
217
+ for (const index of table.indexes) {
218
+ for (const colName of index.columns) {
219
+ if (!columnNames.has(colName)) {
220
+ throw new Error(`Table "${tableName}" index references non-existent column "${colName}"`);
221
+ }
222
+ }
223
+ }
224
+ for (const fk of table.foreignKeys) {
225
+ for (const colName of fk.columns) {
226
+ if (!columnNames.has(colName)) {
227
+ throw new Error(
228
+ `Table "${tableName}" foreignKey references non-existent column "${colName}"`
229
+ );
230
+ }
231
+ }
232
+ if (!tableNames.has(fk.references.table)) {
233
+ throw new Error(
234
+ `Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`
235
+ );
236
+ }
237
+ const referencedTable = storage.tables[fk.references.table];
238
+ if (!referencedTable) {
239
+ throw new Error(
240
+ `Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`
241
+ );
242
+ }
243
+ const referencedColumnNames = new Set(Object.keys(referencedTable.columns));
244
+ for (const colName of fk.references.columns) {
245
+ if (!referencedColumnNames.has(colName)) {
246
+ throw new Error(
247
+ `Table "${tableName}" foreignKey references non-existent column "${colName}" in table "${fk.references.table}"`
248
+ );
249
+ }
250
+ }
251
+ if (fk.columns.length !== fk.references.columns.length) {
252
+ throw new Error(
253
+ `Table "${tableName}" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`
254
+ );
255
+ }
256
+ }
257
+ }
258
+ }
259
+ function normalizeContract(contract) {
260
+ const contractObj = contract;
261
+ let normalizedStorage = contractObj["storage"];
262
+ if (normalizedStorage && typeof normalizedStorage === "object" && normalizedStorage !== null) {
263
+ const storage = normalizedStorage;
264
+ const tables = storage["tables"];
265
+ if (tables) {
266
+ const normalizedTables = {};
267
+ for (const [tableName, table] of Object.entries(tables)) {
268
+ const tableObj = table;
269
+ const columns = tableObj["columns"];
270
+ if (columns) {
271
+ const normalizedColumns = {};
272
+ for (const [columnName, column] of Object.entries(columns)) {
273
+ const columnObj = column;
274
+ const normalizedColumn = {
275
+ ...columnObj,
276
+ nullable: columnObj["nullable"] ?? false
277
+ };
278
+ normalizedColumns[columnName] = normalizedColumn;
279
+ }
280
+ normalizedTables[tableName] = {
281
+ ...tableObj,
282
+ columns: normalizedColumns,
283
+ uniques: tableObj["uniques"] ?? [],
284
+ indexes: tableObj["indexes"] ?? [],
285
+ foreignKeys: tableObj["foreignKeys"] ?? []
286
+ };
287
+ } else {
288
+ normalizedTables[tableName] = tableObj;
289
+ }
290
+ }
291
+ normalizedStorage = {
292
+ ...storage,
293
+ tables: normalizedTables
294
+ };
295
+ }
296
+ }
297
+ let normalizedModels = contractObj["models"];
298
+ if (normalizedModels && typeof normalizedModels === "object" && normalizedModels !== null) {
299
+ const models = normalizedModels;
300
+ const normalizedModelsObj = {};
301
+ for (const [modelName, model] of Object.entries(models)) {
302
+ const modelObj = model;
303
+ normalizedModelsObj[modelName] = {
304
+ ...modelObj,
305
+ relations: modelObj["relations"] ?? {}
306
+ };
307
+ }
308
+ normalizedModels = normalizedModelsObj;
309
+ }
310
+ return {
311
+ ...contractObj,
312
+ models: normalizedModels,
313
+ relations: contractObj["relations"] ?? {},
314
+ storage: normalizedStorage,
315
+ extensionPacks: contractObj["extensionPacks"] ?? {},
316
+ capabilities: contractObj["capabilities"] ?? {},
317
+ meta: contractObj["meta"] ?? {},
318
+ sources: contractObj["sources"] ?? {}
319
+ };
320
+ }
321
+ function validateContract(value) {
322
+ const normalized = normalizeContract(value);
323
+ const structurallyValid = validateContractStructure(normalized);
324
+ const contractForValidation = structurallyValid;
325
+ validateContractLogic(contractForValidation);
326
+ const existingMappings = contractForValidation.mappings;
327
+ const mappings = computeMappings(
328
+ contractForValidation.models,
329
+ contractForValidation.storage,
330
+ existingMappings
331
+ );
332
+ const contractWithMappings = {
333
+ ...structurallyValid,
334
+ models: contractForValidation.models,
335
+ relations: contractForValidation.relations,
336
+ storage: contractForValidation.storage,
337
+ mappings
338
+ };
339
+ return contractWithMappings;
340
+ }
341
+
342
+ export {
343
+ computeMappings,
344
+ validateContract
345
+ };
346
+ //# sourceMappingURL=chunk-HTNUNGA2.js.map
@@ -0,0 +1 @@
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 StorageTypeInstance,\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 'typeParams?': 'Record<string, unknown>',\n 'typeRef?': 'string',\n});\n\nconst StorageTypeInstanceSchema = type.declare<StorageTypeInstance>().type({\n codecId: 'string',\n nativeType: 'string',\n typeParams: 'Record<string, unknown>',\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 'types?': type({ '[string]': StorageTypeInstanceSchema }),\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 const typeInstanceNames = new Set(Object.keys(storage.types ?? {}));\n\n // Validate storage.types if present\n if (storage.types) {\n for (const [typeName, typeInstance] of Object.entries(storage.types)) {\n // Validate typeParams is not an array (arrays are objects in JS but not valid here)\n if (Array.isArray(typeInstance.typeParams)) {\n throw new Error(\n `Type instance \"${typeName}\" has invalid typeParams: must be a plain object, not an array`,\n );\n }\n }\n }\n\n // Validate columns in all tables\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n // Validate typeParams and typeRef are mutually exclusive\n if (column.typeParams !== undefined && column.typeRef !== undefined) {\n throw new Error(\n `Column \"${columnName}\" in table \"${tableName}\" has both typeParams and typeRef; these are mutually exclusive`,\n );\n }\n\n // Validate typeParams is not an array (arrays are objects in JS but not valid here)\n if (column.typeParams !== undefined && Array.isArray(column.typeParams)) {\n throw new Error(\n `Column \"${columnName}\" in table \"${tableName}\" has invalid typeParams: must be a plain object, not an array`,\n );\n }\n\n // Validate typeRef points to an existing storage.types key\n if (column.typeRef !== undefined && !typeInstanceNames.has(column.typeRef)) {\n throw new Error(\n `Column \"${columnName}\" in table \"${tableName}\" references non-existent type instance \"${column.typeRef}\" (not found in storage.types)`,\n );\n }\n }\n }\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":";AAgBA,SAAS,YAAY;AAOrB,IAAM,sBAAsB,KAAK,QAAuB,EAAE,KAAK;AAAA,EAC7D,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,UAAU;AAAA,EACV,eAAe;AAAA,EACf,YAAY;AACd,CAAC;AAED,IAAM,4BAA4B,KAAK,QAA6B,EAAE,KAAK;AAAA,EACzE,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,YAAY;AACd,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,EACvD,SAAS,KAAK,OAAO,MAAM,EAAE,SAAS;AAAA,EACtC,YAAY;AAAA,EACZ,SAAS;AACX,CAAC;AAED,IAAM,qBAAqB,KAAK,QAAsB,EAAE,KAAK;AAAA,EAC3D,SAAS,KAAK,EAAE,Y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AAM,uBAAuB;AAAA,IAC3B,GAAG;AAAA,IACH,QAAQ,sBAAsB;AAAA,IAC9B,WAAW,sBAAsB;AAAA,IACjC,SAAS,sBAAsB;AAAA,IAC/B;AAAA,EACF;AAIA,SAAO;AACT;","names":[]}
@@ -0,0 +1,101 @@
1
+ import type { ExtensionPackRef, TargetPackRef } from '@prisma-next/contract/framework-components';
2
+ import type { ColumnBuilderState, ModelBuilderState, RelationDefinition, TableBuilderState } from '@prisma-next/contract-authoring';
3
+ import { type BuildModels, type BuildRelations, type BuildStorageColumn, ContractBuilder, type ExtractColumns, type ExtractPrimaryKey, ModelBuilder, TableBuilder } from '@prisma-next/contract-authoring';
4
+ import type { SqlContract, SqlMappings } from '@prisma-next/sql-contract/types';
5
+ /**
6
+ * Type-level mappings structure for contracts built via `defineContract()`.
7
+ *
8
+ * Compile-time type helper (not a runtime object) that ensures mappings match what the builder
9
+ * produces. `codecTypes` uses the generic `CodecTypes` parameter; `operationTypes` is always
10
+ * empty since operations are added via extensions at runtime.
11
+ *
12
+ * **Difference from RuntimeContext**: This is a compile-time type for contract construction.
13
+ * `RuntimeContext` is a runtime object with populated registries for query execution.
14
+ *
15
+ * @template C - The `CodecTypes` generic parameter passed to `defineContract<CodecTypes>()`
16
+ */
17
+ type ContractBuilderMappings<C extends Record<string, {
18
+ output: unknown;
19
+ }>> = Omit<SqlMappings, 'codecTypes' | 'operationTypes'> & {
20
+ readonly codecTypes: C;
21
+ readonly operationTypes: Record<string, never>;
22
+ };
23
+ type BuildStorageTable<_TableName extends string, Columns extends Record<string, ColumnBuilderState<string, boolean, string>>, PK extends readonly string[] | undefined> = {
24
+ readonly columns: {
25
+ readonly [K in keyof Columns]: Columns[K] extends ColumnBuilderState<string, infer Null, infer TType> ? BuildStorageColumn<Null & boolean, TType> : never;
26
+ };
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: {
51
+ readonly [K in keyof Tables]: BuildStorageTable<K & string, ExtractColumns<Tables[K]>, ExtractPrimaryKey<Tables[K]>>;
52
+ };
53
+ };
54
+ export interface ColumnBuilder<Name extends string, Nullable extends boolean, Type extends string> {
55
+ nullable<Value extends boolean>(value?: Value): ColumnBuilder<Name, Value, Type>;
56
+ type<Id extends string>(id: Id): ColumnBuilder<Name, Nullable, Id>;
57
+ build(): ColumnBuilderState<Name, Nullable, Type>;
58
+ }
59
+ declare class SqlContractBuilder<CodecTypes extends Record<string, {
60
+ output: unknown;
61
+ }> = 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> {
62
+ /**
63
+ * This method is responsible for normalizing the contract IR by setting default values
64
+ * for all required fields:
65
+ * - `nullable`: defaults to `false` if not provided
66
+ * - `uniques`: defaults to `[]` (empty array)
67
+ * - `indexes`: defaults to `[]` (empty array)
68
+ * - `foreignKeys`: defaults to `[]` (empty array)
69
+ * - `relations`: defaults to `{}` (empty object) for both model-level and contract-level
70
+ * - `nativeType`: required field set from column type descriptor when columns are defined
71
+ *
72
+ * The contract builder is the **only** place where normalization should occur.
73
+ * Validators, parsers, and emitters should assume the contract is already normalized.
74
+ *
75
+ * **Required**: Use column type descriptors (e.g., `int4Column`, `textColumn`) when defining columns.
76
+ * This ensures `nativeType` is set correctly at build time.
77
+ *
78
+ * @returns A normalized SqlContract with all required fields present
79
+ */
80
+ build(): Target extends string ? SqlContract<BuildStorage<Tables>, BuildModels<Models>, BuildRelations<Models>, ContractBuilderMappings<CodecTypes>> & {
81
+ readonly schemaVersion: '1';
82
+ readonly target: Target;
83
+ readonly targetFamily: 'sql';
84
+ readonly coreHash: CoreHash extends string ? CoreHash : string;
85
+ } & (ExtensionPacks extends Record<string, unknown> ? {
86
+ readonly extensionPacks: ExtensionPacks;
87
+ } : Record<string, never>) & (Capabilities extends Record<string, Record<string, boolean>> ? {
88
+ readonly capabilities: Capabilities;
89
+ } : Record<string, never>) : never;
90
+ target<T extends string>(packRef: TargetPackRef<'sql', T>): SqlContractBuilder<CodecTypes, T, Tables, Models, CoreHash, ExtensionPacks, Capabilities>;
91
+ extensionPacks(packs: Record<string, ExtensionPackRef<'sql', string>>): SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, ExtensionPacks, Capabilities>;
92
+ capabilities<C extends Record<string, Record<string, boolean>>>(capabilities: C): SqlContractBuilder<CodecTypes, Target, Tables, Models, CoreHash, ExtensionPacks, C>;
93
+ coreHash<H extends string>(hash: H): SqlContractBuilder<CodecTypes, Target, Tables, Models, H, ExtensionPacks, Capabilities>;
94
+ 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>;
95
+ 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>;
96
+ }
97
+ export declare function defineContract<CodecTypes extends Record<string, {
98
+ output: unknown;
99
+ }> = Record<string, never>>(): SqlContractBuilder<CodecTypes>;
100
+ export {};
101
+ //# sourceMappingURL=contract-builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-builder.d.ts","sourceRoot":"","sources":["../src/contract-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,KAAK,EACV,kBAAkB,EAClB,iBAAiB,EACjB,kBAAkB,EAClB,iBAAiB,EAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,eAAe,EAEf,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACtB,YAAY,EAEZ,YAAY,EACb,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EAGV,WAAW,EACX,WAAW,EAEZ,MAAM,iCAAiC,CAAC;AAGzC;;;;;;;;;;;GAWG;AACH,KAAK,uBAAuB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE;IAAE,MAAM,EAAE,OAAO,CAAA;CAAE,CAAC,IAAI,IAAI,CAChF,WAAW,EACX,YAAY,GAAG,gBAAgB,CAChC,GAAG;IACF,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;IACvB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;CAChD,CAAC;AAEF,KAAK,iBAAiB,CACpB,UAAU,SAAS,MAAM,EACzB,OAAO,SAAS,MAAM,CAAC,M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C9B,EAED,IAAI,EAAE,SAAS,EACf,QAAQ,EAAE,CAAC,CAAC,EAAE,YAAY,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,SAAS,GACtD,kBAAkB,CACnB,UAAU,EACV,MAAM,EACN,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAClD,MAAM,EACN,QAAQ,EACR,cAAc,EACd,YAAY,CACb;IAqBQ,KAAK,CACZ,SAAS,SAAS,MAAM,EACxB,SAAS,SAAS,MAAM,EACxB,CAAC,SAAS,YAAY,CACpB,SAAS,EACT,SAAS,EACT,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACtB,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CACnC,EAED,IAAI,EAAE,SAAS,EACf,KAAK,EAAE,SAAS,EAChB,QAAQ,EAAE,CACR,CAAC,EAAE,YAAY,CAAC,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,KAChF,CAAC,GAAG,SAAS,GACjB,kBAAkB,CACnB,UAAU,EACV,MAAM,EACN,MAAM,EACN,MAAM,GAAG,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAClD,QAAQ,EACR,cAAc,EACd,YAAY,CACb;CAoBF;AAED,wBAAgB,cAAc,CAC5B,UAAU,SAAS,MAAM,CAAC,MAAM,EAAE;IAAE,MAAM,EAAE,OAAO,CAAA;CAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,KAC3E,kBAAkB,CAAC,UAAU,CAAC,CAElC"}
@@ -1,7 +1,4 @@
1
- import { ModelDefinition, SqlContract, SqlMappings, SqlStorage } from "@prisma-next/sql-contract/types";
2
-
3
- //#region src/contract.d.ts
4
-
1
+ import type { ModelDefinition, SqlContract, SqlMappings, SqlStorage } from '@prisma-next/sql-contract/types';
5
2
  /**
6
3
  * Computes mapping dictionaries from models and storage structures.
7
4
  * Assumes valid input - validation happens separately in validateContractLogic().
@@ -11,7 +8,8 @@ import { ModelDefinition, SqlContract, SqlMappings, SqlStorage } from "@prisma-n
11
8
  * @param existingMappings - Existing mappings from contract input (optional)
12
9
  * @returns Computed mappings dictionary
13
10
  */
14
- declare function computeMappings(models: Record<string, ModelDefinition>, _storage: SqlStorage, existingMappings?: Partial<SqlMappings>): SqlMappings;
11
+ export declare function computeMappings(models: Record<string, ModelDefinition>, _storage: SqlStorage, existingMappings?: Partial<SqlMappings>): SqlMappings;
12
+ export declare function normalizeContract(contract: unknown): SqlContract<SqlStorage>;
15
13
  /**
16
14
  * Validates that a JSON import conforms to the SqlContract structure
17
15
  * and returns a fully typed SqlContract.
@@ -48,7 +46,5 @@ declare function computeMappings(models: Record<string, ModelDefinition>, _stora
48
46
  * @returns A validated contract matching the TContract type
49
47
  * @throws Error if the contract structure or logic is invalid
50
48
  */
51
- declare function validateContract<TContract extends SqlContract<SqlStorage>>(value: unknown): TContract;
52
- //#endregion
53
- export { computeMappings, validateContract };
54
- //# sourceMappingURL=contract.d.mts.map
49
+ export declare function validateContract<TContract extends SqlContract<SqlStorage>>(value: unknown): TContract;
50
+ //# sourceMappingURL=contract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAIV,eAAe,EAIf,WAAW,EACX,WAAW,EACX,UAAU,EAKX,MAAM,iCAAiC,CAAC;AAoIzC;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,EACvC,QAAQ,EAAE,UAAU,EACpB,gBAAgB,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,GACtC,WAAW,CAiCb;AAgPD,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,OAAO,GAAG,WAAW,CAAC,UAAU,CAAC,CA2E5E;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,SAAS,WAAW,CAAC,UAAU,CAAC,EACxE,KAAK,EAAE,OAAO,GACb,SAAS,CAiCX"}
@@ -0,0 +1,3 @@
1
+ export type { ColumnBuilder } from '../contract-builder';
2
+ export { defineContract } from '../contract-builder';
3
+ //# sourceMappingURL=contract-builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-builder.d.ts","sourceRoot":"","sources":["../../src/exports/contract-builder.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC"}