@prisma-next/sql-contract 0.3.0-dev.4 → 0.3.0-dev.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -10
- package/dist/factories.d.mts +49 -0
- package/dist/factories.d.mts.map +1 -0
- package/dist/factories.mjs +82 -0
- package/dist/factories.mjs.map +1 -0
- package/dist/pack-types.d.mts +13 -0
- package/dist/pack-types.d.mts.map +1 -0
- package/dist/pack-types.mjs +1 -0
- package/dist/types-DTFobApb.d.mts +137 -0
- package/dist/types-DTFobApb.d.mts.map +1 -0
- package/dist/types-kacOgEya.mjs +17 -0
- package/dist/types-kacOgEya.mjs.map +1 -0
- package/dist/types.d.mts +2 -0
- package/dist/types.mjs +3 -0
- package/dist/validate.d.mts +8 -0
- package/dist/validate.d.mts.map +1 -0
- package/dist/validate.mjs +179 -0
- package/dist/validate.mjs.map +1 -0
- package/dist/validators-Dfw5_HSi.mjs +162 -0
- package/dist/validators-Dfw5_HSi.mjs.map +1 -0
- package/dist/{exports/validators.d.ts → validators.d.mts} +17 -4
- package/dist/validators.d.mts.map +1 -0
- package/dist/validators.mjs +3 -0
- package/package.json +26 -28
- package/src/exports/factories.ts +11 -0
- package/src/exports/pack-types.ts +1 -0
- package/src/exports/types.ts +20 -0
- package/src/exports/validate.ts +1 -0
- package/src/exports/validators.ts +1 -0
- package/src/factories.ts +162 -0
- package/src/index.ts +4 -0
- package/src/pack-types.ts +9 -0
- package/src/types.ts +163 -0
- package/src/validate.ts +335 -0
- package/src/validators.ts +218 -0
- package/dist/exports/factories.d.ts +0 -41
- package/dist/exports/factories.js +0 -83
- package/dist/exports/factories.js.map +0 -1
- package/dist/exports/pack-types.d.ts +0 -11
- package/dist/exports/pack-types.js +0 -1
- package/dist/exports/pack-types.js.map +0 -1
- package/dist/exports/types.d.ts +0 -70
- package/dist/exports/types.js +0 -1
- package/dist/exports/types.js.map +0 -1
- package/dist/exports/validators.js +0 -96
- package/dist/exports/validators.js.map +0 -1
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { r as applyFkDefaults } from "./types-kacOgEya.mjs";
|
|
2
|
+
import { a as validateSqlContract } from "./validators-Dfw5_HSi.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/validate.ts
|
|
5
|
+
function computeDefaultMappings(models) {
|
|
6
|
+
const modelToTable = {};
|
|
7
|
+
const tableToModel = {};
|
|
8
|
+
const fieldToColumn = {};
|
|
9
|
+
const columnToField = {};
|
|
10
|
+
for (const [modelName, model] of Object.entries(models)) {
|
|
11
|
+
const tableName = model.storage.table;
|
|
12
|
+
modelToTable[modelName] = tableName;
|
|
13
|
+
tableToModel[tableName] = modelName;
|
|
14
|
+
const modelFieldToColumn = {};
|
|
15
|
+
for (const [fieldName, field] of Object.entries(model.fields)) {
|
|
16
|
+
const columnName = field.column;
|
|
17
|
+
modelFieldToColumn[fieldName] = columnName;
|
|
18
|
+
if (!columnToField[tableName]) columnToField[tableName] = {};
|
|
19
|
+
columnToField[tableName][columnName] = fieldName;
|
|
20
|
+
}
|
|
21
|
+
fieldToColumn[modelName] = modelFieldToColumn;
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
modelToTable,
|
|
25
|
+
tableToModel,
|
|
26
|
+
fieldToColumn,
|
|
27
|
+
columnToField,
|
|
28
|
+
codecTypes: {},
|
|
29
|
+
operationTypes: {}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function assertInverseModelMappings(modelToTable, tableToModel) {
|
|
33
|
+
for (const [model, table] of Object.entries(modelToTable)) if (tableToModel[table] !== model) throw new Error(`Mappings override mismatch: modelToTable.${model}="${table}" is not mirrored in tableToModel`);
|
|
34
|
+
for (const [table, model] of Object.entries(tableToModel)) if (modelToTable[model] !== table) throw new Error(`Mappings override mismatch: tableToModel.${table}="${model}" is not mirrored in modelToTable`);
|
|
35
|
+
}
|
|
36
|
+
function assertInverseFieldMappings(fieldToColumn, columnToField, modelToTable, tableToModel) {
|
|
37
|
+
for (const [model, fields] of Object.entries(fieldToColumn)) {
|
|
38
|
+
const table = modelToTable[model];
|
|
39
|
+
if (!table) throw new Error(`Mappings override mismatch: fieldToColumn references unknown model "${model}"`);
|
|
40
|
+
const reverseFields = columnToField[table];
|
|
41
|
+
if (!reverseFields) throw new Error(`Mappings override mismatch: columnToField is missing table "${table}" for model "${model}"`);
|
|
42
|
+
for (const [field, column] of Object.entries(fields)) if (reverseFields[column] !== field) throw new Error(`Mappings override mismatch: fieldToColumn.${model}.${field}="${column}" is not mirrored in columnToField.${table}`);
|
|
43
|
+
}
|
|
44
|
+
for (const [table, columns] of Object.entries(columnToField)) {
|
|
45
|
+
const model = tableToModel[table];
|
|
46
|
+
if (!model) throw new Error(`Mappings override mismatch: columnToField references unknown table "${table}"`);
|
|
47
|
+
const forwardFields = fieldToColumn[model];
|
|
48
|
+
if (!forwardFields) throw new Error(`Mappings override mismatch: fieldToColumn is missing model "${model}" for table "${table}"`);
|
|
49
|
+
for (const [column, field] of Object.entries(columns)) if (forwardFields[field] !== column) throw new Error(`Mappings override mismatch: columnToField.${table}.${column}="${field}" is not mirrored in fieldToColumn.${model}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function mergeMappings(defaults, existingMappings) {
|
|
53
|
+
const hasModelToTable = existingMappings?.modelToTable !== void 0;
|
|
54
|
+
const hasTableToModel = existingMappings?.tableToModel !== void 0;
|
|
55
|
+
if (hasModelToTable !== hasTableToModel) throw new Error("Mappings override mismatch: modelToTable and tableToModel must be provided together");
|
|
56
|
+
const hasFieldToColumn = existingMappings?.fieldToColumn !== void 0;
|
|
57
|
+
const hasColumnToField = existingMappings?.columnToField !== void 0;
|
|
58
|
+
if (hasFieldToColumn !== hasColumnToField) throw new Error("Mappings override mismatch: fieldToColumn and columnToField must be provided together");
|
|
59
|
+
const modelToTable = hasModelToTable ? existingMappings?.modelToTable ?? {} : defaults.modelToTable;
|
|
60
|
+
const tableToModel = hasTableToModel ? existingMappings?.tableToModel ?? {} : defaults.tableToModel;
|
|
61
|
+
assertInverseModelMappings(modelToTable, tableToModel);
|
|
62
|
+
const fieldToColumn = hasFieldToColumn ? existingMappings?.fieldToColumn ?? {} : defaults.fieldToColumn;
|
|
63
|
+
const columnToField = hasColumnToField ? existingMappings?.columnToField ?? {} : defaults.columnToField;
|
|
64
|
+
assertInverseFieldMappings(fieldToColumn, columnToField, modelToTable, tableToModel);
|
|
65
|
+
return {
|
|
66
|
+
modelToTable,
|
|
67
|
+
tableToModel,
|
|
68
|
+
fieldToColumn,
|
|
69
|
+
columnToField,
|
|
70
|
+
codecTypes: {
|
|
71
|
+
...defaults.codecTypes,
|
|
72
|
+
...existingMappings?.codecTypes ?? {}
|
|
73
|
+
},
|
|
74
|
+
operationTypes: {
|
|
75
|
+
...defaults.operationTypes,
|
|
76
|
+
...existingMappings?.operationTypes ?? {}
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function validateContractLogic(contract) {
|
|
81
|
+
const tableNames = new Set(Object.keys(contract.storage.tables));
|
|
82
|
+
for (const [tableName, table] of Object.entries(contract.storage.tables)) {
|
|
83
|
+
const columnNames = new Set(Object.keys(table.columns));
|
|
84
|
+
if (table.primaryKey) {
|
|
85
|
+
for (const colName of table.primaryKey.columns) if (!columnNames.has(colName)) throw new Error(`Table "${tableName}" primaryKey references non-existent column "${colName}"`);
|
|
86
|
+
}
|
|
87
|
+
for (const unique of table.uniques) for (const colName of unique.columns) if (!columnNames.has(colName)) throw new Error(`Table "${tableName}" unique constraint references non-existent column "${colName}"`);
|
|
88
|
+
for (const index of table.indexes) for (const colName of index.columns) if (!columnNames.has(colName)) throw new Error(`Table "${tableName}" index references non-existent column "${colName}"`);
|
|
89
|
+
for (const fk of table.foreignKeys) {
|
|
90
|
+
for (const colName of fk.columns) if (!columnNames.has(colName)) throw new Error(`Table "${tableName}" foreignKey references non-existent column "${colName}"`);
|
|
91
|
+
if (!tableNames.has(fk.references.table)) throw new Error(`Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`);
|
|
92
|
+
const referencedTable = contract.storage.tables[fk.references.table];
|
|
93
|
+
const referencedColumnNames = new Set(Object.keys(referencedTable.columns));
|
|
94
|
+
for (const colName of fk.references.columns) if (!referencedColumnNames.has(colName)) throw new Error(`Table "${tableName}" foreignKey references non-existent column "${colName}" in table "${fk.references.table}"`);
|
|
95
|
+
if (fk.columns.length !== fk.references.columns.length) throw new Error(`Table "${tableName}" foreignKey column count (${fk.columns.length}) does not match referenced column count (${fk.references.columns.length})`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function normalizeContract(contract) {
|
|
100
|
+
if (typeof contract !== "object" || contract === null) return contract;
|
|
101
|
+
const contractObj = contract;
|
|
102
|
+
let normalizedStorage = contractObj["storage"];
|
|
103
|
+
if (normalizedStorage && typeof normalizedStorage === "object" && normalizedStorage !== null) {
|
|
104
|
+
const storage = normalizedStorage;
|
|
105
|
+
const tables = storage["tables"];
|
|
106
|
+
if (tables) {
|
|
107
|
+
const normalizedTables = {};
|
|
108
|
+
for (const [tableName, table] of Object.entries(tables)) {
|
|
109
|
+
const tableObj = table;
|
|
110
|
+
const columns = tableObj["columns"];
|
|
111
|
+
if (columns) {
|
|
112
|
+
const normalizedColumns = {};
|
|
113
|
+
for (const [columnName, column] of Object.entries(columns)) {
|
|
114
|
+
const columnObj = column;
|
|
115
|
+
normalizedColumns[columnName] = {
|
|
116
|
+
...columnObj,
|
|
117
|
+
nullable: columnObj["nullable"] ?? false
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
const normalizedForeignKeys = (tableObj["foreignKeys"] ?? []).map((fk) => ({
|
|
121
|
+
...fk,
|
|
122
|
+
...applyFkDefaults({
|
|
123
|
+
constraint: typeof fk["constraint"] === "boolean" ? fk["constraint"] : void 0,
|
|
124
|
+
index: typeof fk["index"] === "boolean" ? fk["index"] : void 0
|
|
125
|
+
})
|
|
126
|
+
}));
|
|
127
|
+
normalizedTables[tableName] = {
|
|
128
|
+
...tableObj,
|
|
129
|
+
columns: normalizedColumns,
|
|
130
|
+
uniques: tableObj["uniques"] ?? [],
|
|
131
|
+
indexes: tableObj["indexes"] ?? [],
|
|
132
|
+
foreignKeys: normalizedForeignKeys
|
|
133
|
+
};
|
|
134
|
+
} else normalizedTables[tableName] = tableObj;
|
|
135
|
+
}
|
|
136
|
+
normalizedStorage = {
|
|
137
|
+
...storage,
|
|
138
|
+
tables: normalizedTables
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
let normalizedModels = contractObj["models"];
|
|
143
|
+
if (normalizedModels && typeof normalizedModels === "object" && normalizedModels !== null) {
|
|
144
|
+
const models = normalizedModels;
|
|
145
|
+
const normalizedModelsObj = {};
|
|
146
|
+
for (const [modelName, model] of Object.entries(models)) {
|
|
147
|
+
const modelObj = model;
|
|
148
|
+
normalizedModelsObj[modelName] = {
|
|
149
|
+
...modelObj,
|
|
150
|
+
relations: modelObj["relations"] ?? {}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
normalizedModels = normalizedModelsObj;
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
...contractObj,
|
|
157
|
+
models: normalizedModels,
|
|
158
|
+
relations: contractObj["relations"] ?? {},
|
|
159
|
+
storage: normalizedStorage,
|
|
160
|
+
extensionPacks: contractObj["extensionPacks"] ?? {},
|
|
161
|
+
capabilities: contractObj["capabilities"] ?? {},
|
|
162
|
+
meta: contractObj["meta"] ?? {},
|
|
163
|
+
sources: contractObj["sources"] ?? {}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
function validateContract(value) {
|
|
167
|
+
const structurallyValid = validateSqlContract(normalizeContract(value));
|
|
168
|
+
validateContractLogic(structurallyValid);
|
|
169
|
+
const existingMappings = structurallyValid.mappings;
|
|
170
|
+
const mappings = mergeMappings(computeDefaultMappings(structurallyValid.models), existingMappings);
|
|
171
|
+
return {
|
|
172
|
+
...structurallyValid,
|
|
173
|
+
mappings
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
//#endregion
|
|
178
|
+
export { normalizeContract, validateContract };
|
|
179
|
+
//# sourceMappingURL=validate.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validate.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/validate.ts"],"sourcesContent":["import type { ModelDefinition, SqlContract, SqlMappings, SqlStorage } from './types';\nimport { applyFkDefaults } from './types';\nimport { validateSqlContract } from './validators';\n\ntype ResolvedMappings = {\n modelToTable: Record<string, string>;\n tableToModel: Record<string, string>;\n fieldToColumn: Record<string, Record<string, string>>;\n columnToField: Record<string, Record<string, string>>;\n codecTypes: Record<string, { readonly output: unknown }>;\n operationTypes: Record<string, Record<string, unknown>>;\n};\n\nfunction computeDefaultMappings(models: Record<string, ModelDefinition>): ResolvedMappings {\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 if (!columnToField[tableName]) {\n columnToField[tableName] = {};\n }\n columnToField[tableName][columnName] = fieldName;\n }\n\n fieldToColumn[modelName] = modelFieldToColumn;\n }\n\n return {\n modelToTable,\n tableToModel,\n fieldToColumn,\n columnToField,\n codecTypes: {},\n operationTypes: {},\n };\n}\n\nfunction assertInverseModelMappings(\n modelToTable: Record<string, string>,\n tableToModel: Record<string, string>,\n) {\n for (const [model, table] of Object.entries(modelToTable)) {\n if (tableToModel[table] !== model) {\n throw new Error(\n `Mappings override mismatch: modelToTable.${model}=\"${table}\" is not mirrored in tableToModel`,\n );\n }\n }\n for (const [table, model] of Object.entries(tableToModel)) {\n if (modelToTable[model] !== table) {\n throw new Error(\n `Mappings override mismatch: tableToModel.${table}=\"${model}\" is not mirrored in modelToTable`,\n );\n }\n }\n}\n\nfunction assertInverseFieldMappings(\n fieldToColumn: Record<string, Record<string, string>>,\n columnToField: Record<string, Record<string, string>>,\n modelToTable: Record<string, string>,\n tableToModel: Record<string, string>,\n) {\n for (const [model, fields] of Object.entries(fieldToColumn)) {\n const table = modelToTable[model];\n if (!table) {\n throw new Error(\n `Mappings override mismatch: fieldToColumn references unknown model \"${model}\"`,\n );\n }\n const reverseFields = columnToField[table];\n if (!reverseFields) {\n throw new Error(\n `Mappings override mismatch: columnToField is missing table \"${table}\" for model \"${model}\"`,\n );\n }\n for (const [field, column] of Object.entries(fields)) {\n if (reverseFields[column] !== field) {\n throw new Error(\n `Mappings override mismatch: fieldToColumn.${model}.${field}=\"${column}\" is not mirrored in columnToField.${table}`,\n );\n }\n }\n }\n\n for (const [table, columns] of Object.entries(columnToField)) {\n const model = tableToModel[table];\n if (!model) {\n throw new Error(\n `Mappings override mismatch: columnToField references unknown table \"${table}\"`,\n );\n }\n const forwardFields = fieldToColumn[model];\n if (!forwardFields) {\n throw new Error(\n `Mappings override mismatch: fieldToColumn is missing model \"${model}\" for table \"${table}\"`,\n );\n }\n for (const [column, field] of Object.entries(columns)) {\n if (forwardFields[field] !== column) {\n throw new Error(\n `Mappings override mismatch: columnToField.${table}.${column}=\"${field}\" is not mirrored in fieldToColumn.${model}`,\n );\n }\n }\n }\n}\n\nfunction mergeMappings(\n defaults: ResolvedMappings,\n existingMappings?: Partial<SqlMappings>,\n): ResolvedMappings {\n const hasModelToTable = existingMappings?.modelToTable !== undefined;\n const hasTableToModel = existingMappings?.tableToModel !== undefined;\n if (hasModelToTable !== hasTableToModel) {\n throw new Error(\n 'Mappings override mismatch: modelToTable and tableToModel must be provided together',\n );\n }\n\n const hasFieldToColumn = existingMappings?.fieldToColumn !== undefined;\n const hasColumnToField = existingMappings?.columnToField !== undefined;\n if (hasFieldToColumn !== hasColumnToField) {\n throw new Error(\n 'Mappings override mismatch: fieldToColumn and columnToField must be provided together',\n );\n }\n\n const modelToTable: Record<string, string> = hasModelToTable\n ? (existingMappings?.modelToTable ?? {})\n : defaults.modelToTable;\n const tableToModel: Record<string, string> = hasTableToModel\n ? (existingMappings?.tableToModel ?? {})\n : defaults.tableToModel;\n assertInverseModelMappings(modelToTable, tableToModel);\n\n const fieldToColumn: Record<string, Record<string, string>> = hasFieldToColumn\n ? (existingMappings?.fieldToColumn ?? {})\n : defaults.fieldToColumn;\n const columnToField: Record<string, Record<string, string>> = hasColumnToField\n ? (existingMappings?.columnToField ?? {})\n : defaults.columnToField;\n assertInverseFieldMappings(fieldToColumn, columnToField, modelToTable, tableToModel);\n\n return {\n modelToTable,\n tableToModel,\n fieldToColumn,\n columnToField,\n codecTypes: { ...defaults.codecTypes, ...(existingMappings?.codecTypes ?? {}) },\n operationTypes: { ...defaults.operationTypes, ...(existingMappings?.operationTypes ?? {}) },\n };\n}\n\nfunction validateContractLogic(contract: SqlContract<SqlStorage>): void {\n const tableNames = new Set(Object.keys(contract.storage.tables));\n\n for (const [tableName, table] of Object.entries(contract.storage.tables)) {\n const columnNames = new Set(Object.keys(table.columns));\n\n if (table.primaryKey) {\n for (const colName of table.primaryKey.columns) {\n if (!columnNames.has(colName)) {\n throw new Error(\n `Table \"${tableName}\" primaryKey references non-existent column \"${colName}\"`,\n );\n }\n }\n }\n\n for (const unique of table.uniques) {\n for (const colName of unique.columns) {\n if (!columnNames.has(colName)) {\n throw new Error(\n `Table \"${tableName}\" unique constraint references non-existent column \"${colName}\"`,\n );\n }\n }\n }\n\n for (const index of table.indexes) {\n for (const colName of index.columns) {\n if (!columnNames.has(colName)) {\n throw new Error(`Table \"${tableName}\" index references non-existent column \"${colName}\"`);\n }\n }\n }\n\n for (const fk of table.foreignKeys) {\n for (const colName of fk.columns) {\n if (!columnNames.has(colName)) {\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent column \"${colName}\"`,\n );\n }\n }\n\n if (!tableNames.has(fk.references.table)) {\n throw new Error(\n `Table \"${tableName}\" foreignKey references non-existent table \"${fk.references.table}\"`,\n );\n }\n\n const referencedTable = contract.storage.tables[\n fk.references.table\n ] as (typeof contract.storage.tables)[string];\n const referencedColumnNames = new Set(Object.keys(referencedTable.columns));\n for (const colName of fk.references.columns) {\n if (!referencedColumnNames.has(colName)) {\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 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 if (typeof contract !== 'object' || contract === null) {\n return contract as SqlContract<SqlStorage>;\n }\n\n const contractObj = contract as Record<string, unknown>;\n\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 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 const normalizedColumns: Record<string, unknown> = {};\n for (const [columnName, column] of Object.entries(columns)) {\n const columnObj = column as Record<string, unknown>;\n normalizedColumns[columnName] = {\n ...columnObj,\n nullable: columnObj['nullable'] ?? false,\n };\n }\n\n // Normalize foreign keys: add constraint/index defaults if missing\n const rawForeignKeys = (tableObj['foreignKeys'] ?? []) as Array<Record<string, unknown>>;\n const normalizedForeignKeys = rawForeignKeys.map((fk) => ({\n ...fk,\n ...applyFkDefaults({\n constraint: typeof fk['constraint'] === 'boolean' ? fk['constraint'] : undefined,\n index: typeof fk['index'] === 'boolean' ? fk['index'] : undefined,\n }),\n }));\n\n normalizedTables[tableName] = {\n ...tableObj,\n columns: normalizedColumns,\n uniques: tableObj['uniques'] ?? [],\n indexes: tableObj['indexes'] ?? [],\n foreignKeys: normalizedForeignKeys,\n };\n } else {\n normalizedTables[tableName] = tableObj;\n }\n }\n\n normalizedStorage = {\n ...storage,\n tables: normalizedTables,\n };\n }\n }\n\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 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\nexport function validateContract<TContract extends SqlContract<SqlStorage>>(\n value: unknown,\n): TContract {\n const normalized = normalizeContract(value);\n const structurallyValid = validateSqlContract<SqlContract<SqlStorage>>(normalized);\n validateContractLogic(structurallyValid);\n\n const existingMappings = (structurallyValid as { mappings?: Partial<SqlMappings> }).mappings;\n const defaultMappings = computeDefaultMappings(\n structurallyValid.models as Record<string, ModelDefinition>,\n );\n const mappings = mergeMappings(defaultMappings, existingMappings);\n\n return {\n ...structurallyValid,\n mappings,\n } as TContract;\n}\n"],"mappings":";;;;AAaA,SAAS,uBAA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AI,oBAAoB,OAAO,qBAAqB,YAAY,qBAAqB,MAAM;EACzF,MAAM,SAAS;EACf,MAAMC,sBAA+C,EAAE;AACvD,OAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,OAAO,EAAE;GACvD,MAAM,WAAW;AACjB,uBAAoB,aAAa;IAC/B,GAAG;IACH,WAAW,SAAS,gBAAgB,EAAE;IACvC;;AAEH,qBAAmB;;AAGrB,QAAO;EACL,GAAG;EACH,QAAQ;EACR,WAAW,YAAY,gBAAgB,EAAE;EACzC,SAAS;EACT,gBAAgB,YAAY,qBAAqB,EAAE;EACnD,cAAc,YAAY,mBAAmB,EAAE;EAC/C,MAAM,YAAY,WAAW,EAAE;EAC/B,SAAS,YAAY,cAAc,EAAE;EACtC;;AAGH,SAAgB,iBACd,OACW;CAEX,MAAM,oBAAoB,oBADP,kBAAkB,MAAM,CACuC;AAClF,uBAAsB,kBAAkB;CAExC,MAAM,mBAAoB,kBAA0D;CAIpF,MAAM,WAAW,cAHO,uBACtB,kBAAkB,OACnB,EAC+C,iBAAiB;AAEjE,QAAO;EACL,GAAG;EACH;EACD"}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { type } from "arktype";
|
|
2
|
+
|
|
3
|
+
//#region src/validators.ts
|
|
4
|
+
const literalKindSchema = type("'literal'");
|
|
5
|
+
const functionKindSchema = type("'function'");
|
|
6
|
+
const generatorKindSchema = type("'generator'");
|
|
7
|
+
const generatorIdSchema = type("'ulid' | 'nanoid' | 'uuidv7' | 'uuidv4' | 'cuid2' | 'ksuid'");
|
|
8
|
+
const ColumnDefaultLiteralSchema = type.declare().type({
|
|
9
|
+
kind: literalKindSchema,
|
|
10
|
+
expression: "string"
|
|
11
|
+
});
|
|
12
|
+
const ColumnDefaultFunctionSchema = type.declare().type({
|
|
13
|
+
kind: functionKindSchema,
|
|
14
|
+
expression: "string"
|
|
15
|
+
});
|
|
16
|
+
const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema);
|
|
17
|
+
const ExecutionMutationDefaultValueSchema = type({
|
|
18
|
+
kind: generatorKindSchema,
|
|
19
|
+
id: generatorIdSchema,
|
|
20
|
+
"params?": "Record<string, unknown>"
|
|
21
|
+
});
|
|
22
|
+
const ExecutionSchema = type({ mutations: { defaults: type({
|
|
23
|
+
ref: {
|
|
24
|
+
table: "string",
|
|
25
|
+
column: "string"
|
|
26
|
+
},
|
|
27
|
+
"onCreate?": ExecutionMutationDefaultValueSchema,
|
|
28
|
+
"onUpdate?": ExecutionMutationDefaultValueSchema
|
|
29
|
+
}).array().readonly() } });
|
|
30
|
+
const StorageColumnSchema = type({
|
|
31
|
+
nativeType: "string",
|
|
32
|
+
codecId: "string",
|
|
33
|
+
nullable: "boolean",
|
|
34
|
+
"typeParams?": "Record<string, unknown>",
|
|
35
|
+
"typeRef?": "string",
|
|
36
|
+
"default?": ColumnDefaultSchema
|
|
37
|
+
}).narrow((col, ctx) => {
|
|
38
|
+
if (col.typeParams !== void 0 && col.typeRef !== void 0) return ctx.mustBe("a column with either typeParams or typeRef, not both");
|
|
39
|
+
return true;
|
|
40
|
+
});
|
|
41
|
+
const StorageTypeInstanceSchema = type.declare().type({
|
|
42
|
+
codecId: "string",
|
|
43
|
+
nativeType: "string",
|
|
44
|
+
typeParams: "Record<string, unknown>"
|
|
45
|
+
});
|
|
46
|
+
const PrimaryKeySchema = type.declare().type({
|
|
47
|
+
columns: type.string.array().readonly(),
|
|
48
|
+
"name?": "string"
|
|
49
|
+
});
|
|
50
|
+
const UniqueConstraintSchema = type.declare().type({
|
|
51
|
+
columns: type.string.array().readonly(),
|
|
52
|
+
"name?": "string"
|
|
53
|
+
});
|
|
54
|
+
const IndexSchema = type.declare().type({
|
|
55
|
+
columns: type.string.array().readonly(),
|
|
56
|
+
"name?": "string"
|
|
57
|
+
});
|
|
58
|
+
const ForeignKeyReferencesSchema = type.declare().type({
|
|
59
|
+
table: "string",
|
|
60
|
+
columns: type.string.array().readonly()
|
|
61
|
+
});
|
|
62
|
+
const ForeignKeySchema = type.declare().type({
|
|
63
|
+
columns: type.string.array().readonly(),
|
|
64
|
+
references: ForeignKeyReferencesSchema,
|
|
65
|
+
"name?": "string",
|
|
66
|
+
constraint: "boolean",
|
|
67
|
+
index: "boolean"
|
|
68
|
+
});
|
|
69
|
+
const StorageTableSchema = type.declare().type({
|
|
70
|
+
columns: type({ "[string]": StorageColumnSchema }),
|
|
71
|
+
"primaryKey?": PrimaryKeySchema,
|
|
72
|
+
uniques: UniqueConstraintSchema.array().readonly(),
|
|
73
|
+
indexes: IndexSchema.array().readonly(),
|
|
74
|
+
foreignKeys: ForeignKeySchema.array().readonly()
|
|
75
|
+
});
|
|
76
|
+
const StorageSchema = type.declare().type({
|
|
77
|
+
tables: type({ "[string]": StorageTableSchema }),
|
|
78
|
+
"types?": type({ "[string]": StorageTypeInstanceSchema })
|
|
79
|
+
});
|
|
80
|
+
const ModelFieldSchema = type.declare().type({ column: "string" });
|
|
81
|
+
const ModelStorageSchema = type.declare().type({ table: "string" });
|
|
82
|
+
const ModelSchema = type.declare().type({
|
|
83
|
+
storage: ModelStorageSchema,
|
|
84
|
+
fields: type({ "[string]": ModelFieldSchema }),
|
|
85
|
+
relations: type({ "[string]": "unknown" })
|
|
86
|
+
});
|
|
87
|
+
const SqlContractSchema = type({
|
|
88
|
+
"schemaVersion?": "'1'",
|
|
89
|
+
target: "string",
|
|
90
|
+
targetFamily: "'sql'",
|
|
91
|
+
storageHash: "string",
|
|
92
|
+
"executionHash?": "string",
|
|
93
|
+
"profileHash?": "string",
|
|
94
|
+
"capabilities?": "Record<string, Record<string, boolean>>",
|
|
95
|
+
"extensionPacks?": "Record<string, unknown>",
|
|
96
|
+
"meta?": "Record<string, unknown>",
|
|
97
|
+
"sources?": "Record<string, unknown>",
|
|
98
|
+
models: type({ "[string]": ModelSchema }),
|
|
99
|
+
storage: StorageSchema,
|
|
100
|
+
"execution?": ExecutionSchema
|
|
101
|
+
});
|
|
102
|
+
/**
|
|
103
|
+
* Validates the structural shape of SqlStorage using Arktype.
|
|
104
|
+
*
|
|
105
|
+
* @param value - The storage value to validate
|
|
106
|
+
* @returns The validated storage if structure is valid
|
|
107
|
+
* @throws Error if the storage structure is invalid
|
|
108
|
+
*/
|
|
109
|
+
function validateStorage(value) {
|
|
110
|
+
const result = StorageSchema(value);
|
|
111
|
+
if (result instanceof type.errors) {
|
|
112
|
+
const messages = result.map((p) => p.message).join("; ");
|
|
113
|
+
throw new Error(`Storage validation failed: ${messages}`);
|
|
114
|
+
}
|
|
115
|
+
return result;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Validates the structural shape of ModelDefinition using Arktype.
|
|
119
|
+
*
|
|
120
|
+
* @param value - The model value to validate
|
|
121
|
+
* @returns The validated model if structure is valid
|
|
122
|
+
* @throws Error if the model structure is invalid
|
|
123
|
+
*/
|
|
124
|
+
function validateModel(value) {
|
|
125
|
+
const result = ModelSchema(value);
|
|
126
|
+
if (result instanceof type.errors) {
|
|
127
|
+
const messages = result.map((p) => p.message).join("; ");
|
|
128
|
+
throw new Error(`Model validation failed: ${messages}`);
|
|
129
|
+
}
|
|
130
|
+
return result;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Validates the structural shape of a SqlContract using Arktype.
|
|
134
|
+
*
|
|
135
|
+
* **Responsibility: Validation Only**
|
|
136
|
+
* This function validates that the contract has the correct structure and types.
|
|
137
|
+
* It does NOT normalize the contract - normalization must happen in the contract builder.
|
|
138
|
+
*
|
|
139
|
+
* The contract passed to this function must already be normalized (all required fields present).
|
|
140
|
+
* If normalization is needed, it should be done by the contract builder before calling this function.
|
|
141
|
+
*
|
|
142
|
+
* This ensures all required fields are present and have the correct types.
|
|
143
|
+
*
|
|
144
|
+
* @param value - The contract value to validate (typically from a JSON import)
|
|
145
|
+
* @returns The validated contract if structure is valid
|
|
146
|
+
* @throws Error if the contract structure is invalid
|
|
147
|
+
*/
|
|
148
|
+
function validateSqlContract(value) {
|
|
149
|
+
if (typeof value !== "object" || value === null) throw new Error("Contract structural validation failed: value must be an object");
|
|
150
|
+
const rawValue = value;
|
|
151
|
+
if (rawValue.targetFamily !== void 0 && rawValue.targetFamily !== "sql") throw new Error(`Unsupported target family: ${rawValue.targetFamily}`);
|
|
152
|
+
const contractResult = SqlContractSchema(value);
|
|
153
|
+
if (contractResult instanceof type.errors) {
|
|
154
|
+
const messages = contractResult.map((p) => p.message).join("; ");
|
|
155
|
+
throw new Error(`Contract structural validation failed: ${messages}`);
|
|
156
|
+
}
|
|
157
|
+
return contractResult;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
//#endregion
|
|
161
|
+
export { validateSqlContract as a, validateModel as i, ColumnDefaultLiteralSchema as n, validateStorage as o, ColumnDefaultSchema as r, ColumnDefaultFunctionSchema as t };
|
|
162
|
+
//# sourceMappingURL=validators-Dfw5_HSi.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators-Dfw5_HSi.mjs","names":[],"sources":["../src/validators.ts"],"sourcesContent":["import { type } from 'arktype';\nimport type {\n ForeignKey,\n ForeignKeyReferences,\n Index,\n ModelDefinition,\n ModelField,\n ModelStorage,\n PrimaryKey,\n SqlContract,\n SqlStorage,\n StorageTable,\n StorageTypeInstance,\n UniqueConstraint,\n} from './types';\n\ntype ColumnDefaultLiteral = { readonly kind: 'literal'; readonly expression: string };\ntype ColumnDefaultFunction = { readonly kind: 'function'; readonly expression: string };\nconst literalKindSchema = type(\"'literal'\");\nconst functionKindSchema = type(\"'function'\");\nconst generatorKindSchema = type(\"'generator'\");\nconst generatorIdSchema = type(\"'ulid' | 'nanoid' | 'uuidv7' | 'uuidv4' | 'cuid2' | 'ksuid'\");\n\nexport const ColumnDefaultLiteralSchema = type.declare<ColumnDefaultLiteral>().type({\n kind: literalKindSchema,\n expression: 'string',\n});\n\nexport const ColumnDefaultFunctionSchema = type.declare<ColumnDefaultFunction>().type({\n kind: functionKindSchema,\n expression: 'string',\n});\n\nexport const ColumnDefaultSchema = ColumnDefaultLiteralSchema.or(ColumnDefaultFunctionSchema);\n\nconst ExecutionMutationDefaultValueSchema = type({\n kind: generatorKindSchema,\n id: generatorIdSchema,\n 'params?': 'Record<string, unknown>',\n});\n\nconst ExecutionMutationDefaultSchema = type({\n ref: {\n table: 'string',\n column: 'string',\n },\n 'onCreate?': ExecutionMutationDefaultValueSchema,\n 'onUpdate?': ExecutionMutationDefaultValueSchema,\n});\n\nconst ExecutionSchema = type({\n mutations: {\n defaults: ExecutionMutationDefaultSchema.array().readonly(),\n },\n});\n\nconst StorageColumnSchema = type({\n nativeType: 'string',\n codecId: 'string',\n nullable: 'boolean',\n 'typeParams?': 'Record<string, unknown>',\n 'typeRef?': 'string',\n 'default?': ColumnDefaultSchema,\n}).narrow((col, ctx) => {\n if (col.typeParams !== undefined && col.typeRef !== undefined) {\n return ctx.mustBe('a column with either typeParams or typeRef, not both');\n }\n return true;\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 constraint: 'boolean',\n index: 'boolean',\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\nconst SqlContractSchema = type({\n 'schemaVersion?': \"'1'\",\n target: 'string',\n targetFamily: \"'sql'\",\n storageHash: 'string',\n 'executionHash?': '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 'execution?': ExecutionSchema,\n});\n\n/**\n * Validates the structural shape of SqlStorage using Arktype.\n *\n * @param value - The storage value to validate\n * @returns The validated storage if structure is valid\n * @throws Error if the storage structure is invalid\n */\nexport function validateStorage(value: unknown): SqlStorage {\n const result = StorageSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Storage validation failed: ${messages}`);\n }\n return result;\n}\n\n/**\n * Validates the structural shape of ModelDefinition using Arktype.\n *\n * @param value - The model value to validate\n * @returns The validated model if structure is valid\n * @throws Error if the model structure is invalid\n */\nexport function validateModel(value: unknown): ModelDefinition {\n const result = ModelSchema(value);\n if (result instanceof type.errors) {\n const messages = result.map((p: { message: string }) => p.message).join('; ');\n throw new Error(`Model validation failed: ${messages}`);\n }\n return result;\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 */\nexport function validateSqlContract<T extends SqlContract<SqlStorage>>(value: unknown): T {\n if (typeof value !== 'object' || value === null) {\n throw new Error('Contract structural validation failed: value must be an object');\n }\n\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 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 T;\n}\n"],"mappings":";;;AAkBA,MAAM,oBAAoB,KAAK,YAAY;AAC3C,MAAM,qBAAqB,KAAK,aAAa;AAC7C,MAAM,sBAAsB,KAAK,cAAc;AAC/C,MAAM,oBAAoB,KAAK,8DAA8D;AAE7F,MAAa,6BAA6B,KAAK,SAA+B,CAAC,KAAK;CAClF,MAAM;CACN,YAAY;CACb,CAAC;AAEF,MAAa,8BAA8B,KAAK,SAAgC,CAAC,KAAK;CACpF,MAAM;CACN,YAAY;CACb,CAAC;AAEF,MAAa,sBAAsB,2BAA2B,GAAG,4BAA4B;AAE7F,MAAM,sCAAsC,KAAK;CAC/C,MAAM;CACN,IAAI;CACJ,WAAW;CACZ,CAAC;AAWF,MAAM,kBAAkB,KAAK,EAC3B,WAAW,EACT,UAXmC,KAAK;CAC1C,KAAK;EACH,OAAO;EACP,QAAQ;EACT;CACD,aAAa;C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B,KAAI,SAAS,iBAAiB,UAAa,SAAS,iBAAiB,MACnE,OAAM,IAAI,MAAM,8BAA8B,SAAS,eAAe;CAGxE,MAAM,iBAAiB,kBAAkB,MAAM;AAE/C,KAAI,0BAA0B,KAAK,QAAQ;EACzC,MAAM,WAAW,eAAe,KAAK,MAA2B,EAAE,QAAQ,CAAC,KAAK,KAAK;AACrF,QAAM,IAAI,MAAM,0CAA0C,WAAW;;AAMvE,QAAO"}
|
|
@@ -1,6 +1,18 @@
|
|
|
1
|
-
import { ModelDefinition, SqlContract, SqlStorage } from
|
|
2
|
-
import
|
|
1
|
+
import { c as ModelDefinition, f as SqlContract, m as SqlStorage } from "./types-DTFobApb.mjs";
|
|
2
|
+
import * as arktype_internal_variants_object_ts0 from "arktype/internal/variants/object.ts";
|
|
3
3
|
|
|
4
|
+
//#region src/validators.d.ts
|
|
5
|
+
type ColumnDefaultLiteral = {
|
|
6
|
+
readonly kind: 'literal';
|
|
7
|
+
readonly expression: string;
|
|
8
|
+
};
|
|
9
|
+
type ColumnDefaultFunction = {
|
|
10
|
+
readonly kind: 'function';
|
|
11
|
+
readonly expression: string;
|
|
12
|
+
};
|
|
13
|
+
declare const ColumnDefaultLiteralSchema: arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultLiteral, {}>;
|
|
14
|
+
declare const ColumnDefaultFunctionSchema: arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultFunction, {}>;
|
|
15
|
+
declare const ColumnDefaultSchema: arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultLiteral | ColumnDefaultFunction, {}>;
|
|
4
16
|
/**
|
|
5
17
|
* Validates the structural shape of SqlStorage using Arktype.
|
|
6
18
|
*
|
|
@@ -34,5 +46,6 @@ declare function validateModel(value: unknown): ModelDefinition;
|
|
|
34
46
|
* @throws Error if the contract structure is invalid
|
|
35
47
|
*/
|
|
36
48
|
declare function validateSqlContract<T extends SqlContract<SqlStorage>>(value: unknown): T;
|
|
37
|
-
|
|
38
|
-
export { validateModel, validateSqlContract, validateStorage };
|
|
49
|
+
//#endregion
|
|
50
|
+
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, validateModel, validateSqlContract, validateStorage };
|
|
51
|
+
//# sourceMappingURL=validators.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators.d.mts","names":[],"sources":["../src/validators.ts"],"sourcesContent":[],"mappings":";;;;KAgBK,oBAAA;;;AAFY,CAAA;AAEQ,KACpB,qBAAA,GAAqB;EAMb,SAAA,IAAA,EAAA,UAAA;EAKA,SAAA,UAAA,EAAA,MAAA;AAKb,CAAA;AAAgC,cAVnB,0BAUmB,EAVO,oCAAA,CAAA,UAUP,CAVO,oBAUP,EAAA,CAAA,CAAA,CAAA;AAAA,cALnB,2BAKmB,EALQ,oCAAA,CAAA,UAKR,CALQ,qBAKR,EAAA,CAAA,CAAA,CAAA;AAAA,cAAnB,mBAAmB,EAAA,oCAAA,CAAA,UAAA,CAAA,oBAAA,GAAA,qBAAA,EAAA,CAAA,CAAA,CAAA;;AAyHhC;AAgBA;AAyBA;;;;AAAyF,iBAzCzE,eAAA,CAyCyE,KAAA,EAAA,OAAA,CAAA,EAzCxC,UAyCwC;;;;;;;;iBAzBzE,aAAA,kBAA+B;;;;;;;;;;;;;;;;;iBAyB/B,8BAA8B,YAAY,8BAA8B"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { a as validateSqlContract, i as validateModel, n as ColumnDefaultLiteralSchema, o as validateStorage, r as ColumnDefaultSchema, t as ColumnDefaultFunctionSchema } from "./validators-Dfw5_HSi.mjs";
|
|
2
|
+
|
|
3
|
+
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, validateModel, validateSqlContract, validateStorage };
|
package/package.json
CHANGED
|
@@ -1,49 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/sql-contract",
|
|
3
|
-
"version": "0.3.0-dev.
|
|
3
|
+
"version": "0.3.0-dev.40",
|
|
4
4
|
"type": "module",
|
|
5
|
+
"plane": "shared",
|
|
5
6
|
"sideEffects": false,
|
|
6
7
|
"description": "SQL contract types, validators, and IR factories for Prisma Next",
|
|
7
8
|
"dependencies": {
|
|
8
9
|
"arktype": "^2.1.25",
|
|
9
|
-
"@prisma-next/contract": "0.3.0-dev.
|
|
10
|
+
"@prisma-next/contract": "0.3.0-dev.40"
|
|
10
11
|
},
|
|
11
12
|
"devDependencies": {
|
|
12
|
-
"
|
|
13
|
-
"tsup": "8.5.1",
|
|
13
|
+
"tsdown": "0.18.4",
|
|
14
14
|
"typescript": "5.9.3",
|
|
15
|
-
"vitest": "4.0.
|
|
15
|
+
"vitest": "4.0.17",
|
|
16
|
+
"@prisma-next/tsconfig": "0.0.0",
|
|
17
|
+
"@prisma-next/tsdown": "0.0.0",
|
|
16
18
|
"@prisma-next/test-utils": "0.0.1"
|
|
17
19
|
},
|
|
18
20
|
"files": [
|
|
19
|
-
"dist"
|
|
21
|
+
"dist",
|
|
22
|
+
"src"
|
|
20
23
|
],
|
|
21
24
|
"exports": {
|
|
22
|
-
"./
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
"./validators":
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
},
|
|
34
|
-
"./pack-types": {
|
|
35
|
-
"types": "./dist/exports/pack-types.d.ts",
|
|
36
|
-
"import": "./dist/exports/pack-types.js"
|
|
37
|
-
}
|
|
25
|
+
"./factories": "./dist/factories.mjs",
|
|
26
|
+
"./pack-types": "./dist/pack-types.mjs",
|
|
27
|
+
"./types": "./dist/types.mjs",
|
|
28
|
+
"./validate": "./dist/validate.mjs",
|
|
29
|
+
"./validators": "./dist/validators.mjs",
|
|
30
|
+
"./package.json": "./package.json"
|
|
31
|
+
},
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "https://github.com/prisma/prisma-next.git",
|
|
35
|
+
"directory": "packages/2-sql/1-core/contract"
|
|
38
36
|
},
|
|
39
37
|
"scripts": {
|
|
40
|
-
"build": "
|
|
38
|
+
"build": "tsdown",
|
|
41
39
|
"test": "vitest run",
|
|
42
40
|
"test:coverage": "vitest run --coverage",
|
|
43
|
-
"typecheck": "tsc --
|
|
44
|
-
"lint": "biome check . --
|
|
45
|
-
"lint:fix": "biome check --write .
|
|
46
|
-
"lint:fix:unsafe": "biome check --write --unsafe .
|
|
47
|
-
"clean": "
|
|
41
|
+
"typecheck": "tsc --noEmit",
|
|
42
|
+
"lint": "biome check . --error-on-warnings",
|
|
43
|
+
"lint:fix": "biome check --write .",
|
|
44
|
+
"lint:fix:unsafe": "biome check --write --unsafe .",
|
|
45
|
+
"clean": "rm -rf dist dist-tsc dist-tsc-prod coverage .tmp-output"
|
|
48
46
|
}
|
|
49
47
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type { StorageTypeMetadata } from '../pack-types';
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export type {
|
|
2
|
+
ExtractCodecTypes,
|
|
3
|
+
ExtractOperationTypes,
|
|
4
|
+
ForeignKey,
|
|
5
|
+
ForeignKeyReferences,
|
|
6
|
+
Index,
|
|
7
|
+
ModelDefinition,
|
|
8
|
+
ModelField,
|
|
9
|
+
ModelStorage,
|
|
10
|
+
PrimaryKey,
|
|
11
|
+
SqlContract,
|
|
12
|
+
SqlMappings,
|
|
13
|
+
SqlStorage,
|
|
14
|
+
StorageColumn,
|
|
15
|
+
StorageTable,
|
|
16
|
+
StorageTypeInstance,
|
|
17
|
+
UniqueConstraint,
|
|
18
|
+
} from '../types';
|
|
19
|
+
|
|
20
|
+
export { applyFkDefaults, DEFAULT_FK_CONSTRAINT, DEFAULT_FK_INDEX } from '../types';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { normalizeContract, validateContract } from '../validate';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '../validators';
|