@prisma-next/sql-contract 0.3.0-dev.40 → 0.3.0-dev.43
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 +39 -0
- package/dist/factories.d.mts +2 -3
- package/dist/factories.d.mts.map +1 -1
- package/dist/factories.mjs +4 -2
- package/dist/factories.mjs.map +1 -1
- package/dist/{types-DTFobApb.d.mts → types-T6o5-ZB3.d.mts} +10 -2
- package/dist/types-T6o5-ZB3.d.mts.map +1 -0
- package/dist/types-kacOgEya.mjs.map +1 -1
- package/dist/types.d.mts +2 -2
- package/dist/validate.d.mts +5 -2
- package/dist/validate.d.mts.map +1 -1
- package/dist/validate.mjs +69 -4
- package/dist/validate.mjs.map +1 -1
- package/dist/{validators-Dfw5_HSi.mjs → validators-CNMPzxwB.mjs} +29 -5
- package/dist/validators-CNMPzxwB.mjs.map +1 -0
- package/dist/validators.d.mts +17 -3
- package/dist/validators.d.mts.map +1 -1
- package/dist/validators.mjs +2 -2
- package/package.json +2 -2
- package/src/exports/types.ts +2 -0
- package/src/exports/validate.ts +6 -1
- package/src/factories.ts +6 -2
- package/src/types.ts +10 -0
- package/src/validate.ts +117 -4
- package/src/validators.ts +69 -8
- package/dist/types-DTFobApb.d.mts.map +0 -1
- package/dist/validators-Dfw5_HSi.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -58,6 +58,45 @@ type ForeignKeysConfig = {
|
|
|
58
58
|
|
|
59
59
|
When omitted, defaults to `{ constraints: true, indexes: true }`. See [ADR 161](../../../docs/architecture%20docs/adrs/ADR%20161%20-%20Explicit%20foreign%20key%20constraint%20and%20index%20configuration.md) for design rationale.
|
|
60
60
|
|
|
61
|
+
### Referential Actions
|
|
62
|
+
|
|
63
|
+
`ForeignKey` supports optional `onDelete` and `onUpdate` fields of type `ReferentialAction`:
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';
|
|
67
|
+
|
|
68
|
+
type ForeignKey = {
|
|
69
|
+
readonly columns: readonly string[];
|
|
70
|
+
readonly references: ForeignKeyReferences;
|
|
71
|
+
readonly name?: string;
|
|
72
|
+
readonly onDelete?: ReferentialAction;
|
|
73
|
+
readonly onUpdate?: ReferentialAction;
|
|
74
|
+
};
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
When omitted, the database applies its default behavior (Postgres: `NO ACTION`). See [ADR 162](../../../docs/architecture%20docs/adrs/ADR%20162%20-%20Referential%20actions%20for%20foreign%20keys.md) for design rationale.
|
|
78
|
+
|
|
79
|
+
The `fk()` factory accepts referential actions via an options object:
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import { fk } from '@prisma-next/sql-contract/factories';
|
|
83
|
+
|
|
84
|
+
// Simple FK (no referential actions)
|
|
85
|
+
const simple = fk(['userId'], 'user', ['id']);
|
|
86
|
+
|
|
87
|
+
// FK with onDelete cascade
|
|
88
|
+
const cascading = fk(['userId'], 'user', ['id'], { onDelete: 'cascade' });
|
|
89
|
+
|
|
90
|
+
// FK with name and both actions
|
|
91
|
+
const named = fk(['userId'], 'user', ['id'], {
|
|
92
|
+
name: 'post_userId_fkey',
|
|
93
|
+
onDelete: 'cascade',
|
|
94
|
+
onUpdate: 'noAction',
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
**Semantic validation:** `validateStorageSemantics()` rejects `setNull` when the FK column is `NOT NULL` (the database would fail at runtime).
|
|
99
|
+
|
|
61
100
|
### Validators
|
|
62
101
|
|
|
63
102
|
Validate contract structures using Arktype validators:
|
package/dist/factories.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ForeignKey,
|
|
1
|
+
import { _ as StorageColumn, a as ForeignKey, b as UniqueConstraint, c as Index, f as PrimaryKey, g as SqlStorage, h as SqlMappings, l as ModelDefinition, m as SqlContract, o as ForeignKeyOptions, u as ModelField, v as StorageTable } from "./types-T6o5-ZB3.mjs";
|
|
2
2
|
import { ExecutionHashBase, ProfileHashBase, StorageHashBase } from "@prisma-next/contract/types";
|
|
3
3
|
|
|
4
4
|
//#region src/factories.d.ts
|
|
@@ -15,8 +15,7 @@ declare function col(nativeType: string, codecId: string, nullable?: boolean): S
|
|
|
15
15
|
declare function pk(...columns: readonly string[]): PrimaryKey;
|
|
16
16
|
declare function unique(...columns: readonly string[]): UniqueConstraint;
|
|
17
17
|
declare function index(...columns: readonly string[]): Index;
|
|
18
|
-
declare function fk(columns: readonly string[], refTable: string, refColumns: readonly string[], opts?: {
|
|
19
|
-
name?: string;
|
|
18
|
+
declare function fk(columns: readonly string[], refTable: string, refColumns: readonly string[], opts?: ForeignKeyOptions & {
|
|
20
19
|
constraint?: boolean;
|
|
21
20
|
index?: boolean;
|
|
22
21
|
}): ForeignKey;
|
package/dist/factories.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factories.d.mts","names":[],"sources":["../src/factories.ts"],"sourcesContent":[],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"factories.d.mts","names":[],"sources":["../src/factories.ts"],"sourcesContent":[],"mappings":";;;;;;;AA+BA;AAQA;AAMA;AAMA;AAMA;AAqBA;AAC0B,iBAhDV,GAAA,CAgDU,UAAA,EAAA,MAAA,EAAA,OAAA,EAAA,MAAA,EAAA,QAAA,CAAA,EAAA,OAAA,CAAA,EAhDkD,aAgDlD;AAAf,iBAxCK,EAAA,CAwCL,GAAA,OAAA,EAAA,SAAA,MAAA,EAAA,CAAA,EAxCwC,UAwCxC;AAEF,iBApCO,MAAA,CAoCP,GAAA,OAAA,EAAA,SAAA,MAAA,EAAA,CAAA,EApC8C,gBAoC9C;AACc,iBA/BP,KAAA,CA+BO,GAAA,OAAA,EAAA,SAAA,MAAA,EAAA,CAAA,EA/B+B,KA+B/B;AACA,iBA1BP,EAAA,CA0BO,OAAA,EAAA,SAAA,MAAA,EAAA,EAAA,QAAA,EA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B,QAAA,CAAA,EASxC,OATwC,CAShC,WATgC,CAAA;EAC9B,aAAA,CAAA,EAAA,GAAA;EAA0B,YAAA,CAAA,EAAA,KAAA;EAGlC,WAAA,CAAA,EAQC,YARD;EACG,YAAA,CAAA,EAQD,MARC,CAAA,MAAA,EAQc,MARd,CAAA,MAAA,EAAA,OAAA,CAAA,CAAA;EACP,cAAA,CAAA,EAQQ,MARR,CAAA,MAAA,EAAA,OAAA,CAAA;EACe,IAAA,CAAA,EAQjB,MARiB,CAAA,MAAA,EAAA,OAAA,CAAA;EAAf,OAAA,CAAA,EASC,MATD,CAAA,MAAA,EAAA,OAAA,CAAA;CACG,CAAA,EASV,WATU,CAUZ,UAVY,EAWZ,MAXY,CAAA,MAAA,EAAA,OAAA,CAAA,EAYZ,MAZY,CAAA,MAAA,EAAA,OAAA,CAAA,EAaZ,WAbY,EAcZ,YAdY,EAeZ,cAfY,EAgBZ,YAhBY,CAAA"}
|
package/dist/factories.mjs
CHANGED
|
@@ -32,11 +32,13 @@ function fk(columns, refTable, refColumns, opts) {
|
|
|
32
32
|
table: refTable,
|
|
33
33
|
columns: refColumns
|
|
34
34
|
},
|
|
35
|
+
...opts?.name !== void 0 && { name: opts.name },
|
|
36
|
+
...opts?.onDelete !== void 0 && { onDelete: opts.onDelete },
|
|
37
|
+
...opts?.onUpdate !== void 0 && { onUpdate: opts.onUpdate },
|
|
35
38
|
...applyFkDefaults({
|
|
36
39
|
constraint: opts?.constraint,
|
|
37
40
|
index: opts?.index
|
|
38
|
-
})
|
|
39
|
-
...opts?.name !== void 0 && { name: opts.name }
|
|
41
|
+
})
|
|
40
42
|
};
|
|
41
43
|
}
|
|
42
44
|
function table(columns, opts) {
|
package/dist/factories.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factories.mjs","names":[],"sources":["../src/factories.ts"],"sourcesContent":["import type {\n ExecutionHashBase,\n ProfileHashBase,\n StorageHashBase,\n} from '@prisma-next/contract/types';\nimport type {\n ForeignKey,\n ForeignKeyReferences,\n Index,\n ModelDefinition,\n ModelField,\n ModelStorage,\n PrimaryKey,\n SqlContract,\n SqlMappings,\n SqlStorage,\n StorageColumn,\n StorageTable,\n UniqueConstraint,\n} from './types';\nimport { applyFkDefaults } from './types';\n\n/**\n * Creates a StorageColumn with nativeType and codecId.\n *\n * @param nativeType - Native database type identifier (e.g., 'int4', 'text', 'vector')\n * @param codecId - Codec identifier (e.g., 'pg/int4@1', 'pg/text@1')\n * @param nullable - Whether the column is nullable (default: false)\n * @returns StorageColumn with nativeType and codecId\n */\nexport function col(nativeType: string, codecId: string, nullable = false): StorageColumn {\n return {\n nativeType,\n codecId,\n nullable,\n };\n}\n\nexport function pk(...columns: readonly string[]): PrimaryKey {\n return {\n columns,\n };\n}\n\nexport function unique(...columns: readonly string[]): UniqueConstraint {\n return {\n columns,\n };\n}\n\nexport function index(...columns: readonly string[]): Index {\n return {\n columns,\n };\n}\n\nexport function fk(\n columns: readonly string[],\n refTable: string,\n refColumns: readonly string[],\n opts?:
|
|
1
|
+
{"version":3,"file":"factories.mjs","names":[],"sources":["../src/factories.ts"],"sourcesContent":["import type {\n ExecutionHashBase,\n ProfileHashBase,\n StorageHashBase,\n} from '@prisma-next/contract/types';\nimport type {\n ForeignKey,\n ForeignKeyOptions,\n ForeignKeyReferences,\n Index,\n ModelDefinition,\n ModelField,\n ModelStorage,\n PrimaryKey,\n SqlContract,\n SqlMappings,\n SqlStorage,\n StorageColumn,\n StorageTable,\n UniqueConstraint,\n} from './types';\nimport { applyFkDefaults } from './types';\n\n/**\n * Creates a StorageColumn with nativeType and codecId.\n *\n * @param nativeType - Native database type identifier (e.g., 'int4', 'text', 'vector')\n * @param codecId - Codec identifier (e.g., 'pg/int4@1', 'pg/text@1')\n * @param nullable - Whether the column is nullable (default: false)\n * @returns StorageColumn with nativeType and codecId\n */\nexport function col(nativeType: string, codecId: string, nullable = false): StorageColumn {\n return {\n nativeType,\n codecId,\n nullable,\n };\n}\n\nexport function pk(...columns: readonly string[]): PrimaryKey {\n return {\n columns,\n };\n}\n\nexport function unique(...columns: readonly string[]): UniqueConstraint {\n return {\n columns,\n };\n}\n\nexport function index(...columns: readonly string[]): Index {\n return {\n columns,\n };\n}\n\nexport function fk(\n columns: readonly string[],\n refTable: string,\n refColumns: readonly string[],\n opts?: ForeignKeyOptions & { constraint?: boolean; index?: boolean },\n): ForeignKey {\n const references: ForeignKeyReferences = {\n table: refTable,\n columns: refColumns,\n };\n\n return {\n columns,\n references,\n ...(opts?.name !== undefined && { name: opts.name }),\n ...(opts?.onDelete !== undefined && { onDelete: opts.onDelete }),\n ...(opts?.onUpdate !== undefined && { onUpdate: opts.onUpdate }),\n ...applyFkDefaults({ constraint: opts?.constraint, index: opts?.index }),\n };\n}\n\nexport function table(\n columns: Record<string, StorageColumn>,\n opts?: {\n pk?: PrimaryKey;\n uniques?: readonly UniqueConstraint[];\n indexes?: readonly Index[];\n fks?: readonly ForeignKey[];\n },\n): StorageTable {\n return {\n columns,\n ...(opts?.pk !== undefined && { primaryKey: opts.pk }),\n uniques: opts?.uniques ?? [],\n indexes: opts?.indexes ?? [],\n foreignKeys: opts?.fks ?? [],\n };\n}\n\nexport function model(\n table: string,\n fields: Record<string, ModelField>,\n relations: Record<string, unknown> = {},\n): ModelDefinition {\n const storage: ModelStorage = { table };\n return {\n storage,\n fields,\n relations,\n };\n}\n\nexport function storage(tables: Record<string, StorageTable>): SqlStorage {\n return { tables };\n}\n\nexport function contract<\n TStorageHash extends StorageHashBase<string> = StorageHashBase<string>,\n TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>,\n TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>,\n>(opts: {\n target: string;\n storageHash: TStorageHash;\n executionHash?: TExecutionHash;\n storage: SqlStorage;\n models?: Record<string, ModelDefinition>;\n relations?: Record<string, unknown>;\n mappings?: Partial<SqlMappings>;\n schemaVersion?: '1';\n targetFamily?: 'sql';\n profileHash?: TProfileHash;\n capabilities?: Record<string, Record<string, boolean>>;\n extensionPacks?: Record<string, unknown>;\n meta?: Record<string, unknown>;\n sources?: Record<string, unknown>;\n}): SqlContract<\n SqlStorage,\n Record<string, unknown>,\n Record<string, unknown>,\n SqlMappings,\n TStorageHash,\n TExecutionHash,\n TProfileHash\n> {\n return {\n schemaVersion: opts.schemaVersion ?? '1',\n target: opts.target,\n targetFamily: opts.targetFamily ?? 'sql',\n storageHash: opts.storageHash,\n ...(opts.executionHash !== undefined && { executionHash: opts.executionHash }),\n storage: opts.storage,\n models: opts.models ?? {},\n relations: opts.relations ?? {},\n mappings: (opts.mappings ?? {}) as SqlMappings,\n ...(opts.profileHash !== undefined && { profileHash: opts.profileHash }),\n ...(opts.capabilities !== undefined && { capabilities: opts.capabilities }),\n ...(opts.extensionPacks !== undefined && { extensionPacks: opts.extensionPacks }),\n ...(opts.meta !== undefined && { meta: opts.meta }),\n ...(opts.sources !== undefined && { sources: opts.sources as Record<string, unknown> }),\n } as SqlContract<\n SqlStorage,\n Record<string, unknown>,\n Record<string, unknown>,\n SqlMappings,\n TStorageHash,\n TExecutionHash,\n TProfileHash\n >;\n}\n"],"mappings":";;;;;;;;;;;AA+BA,SAAgB,IAAI,YAAoB,SAAiB,WAAW,OAAsB;AACxF,QAAO;EACL;EACA;EACA;EACD;;AAGH,SAAgB,GAAG,GAAG,SAAwC;AAC5D,QAAO,EACL,SACD;;AAGH,SAAgB,OAAO,GAAG,SAA8C;AACtE,QAAO,EACL,SACD;;AAGH,SAAgB,MAAM,GAAG,SAAmC;AAC1D,QAAO,EACL,SACD;;AAGH,SAAgB,GACd,SACA,UACA,YACA,MACY;AAMZ,QAAO;EACL;EACA,YAPuC;GACvC,OAAO;GACP,SAAS;GACV;EAKC,GAAI,MAAM,SAAS,UAAa,EAAE,MAAM,KAAK,MAAM;EACnD,GAAI,MAAM,aAAa,UAAa,EAAE,UAAU,KAAK,UAAU;EAC/D,GAAI,MAAM,aAAa,UAAa,EAAE,UAAU,KAAK,UAAU;EAC/D,GAAG,gBAAgB;GAAE,YAAY,MAAM;GAAY,OAAO,MAAM;GAAO,CAAC;EACzE;;AAGH,SAAgB,MACd,SACA,MAMc;AACd,QAAO;EACL;EACA,GAAI,MAAM,OAAO,UAAa,EAAE,YAAY,KAAK,IAAI;EACrD,SAAS,MAAM,WAAW,EAAE;EAC5B,SAAS,MAAM,WAAW,EAAE;EAC5B,aAAa,MAAM,OAAO,EAAE;EAC7B;;AAGH,SAAgB,MACd,SACA,QACA,YAAqC,EAAE,EACtB;AAEjB,QAAO;EACL,SAF4B,EAAE,gBAAO;EAGrC;EACA;EACD;;AAGH,SAAgB,QAAQ,QAAkD;AACxE,QAAO,EAAE,QAAQ;;AAGnB,SAAgB,SAId,MAuBA;AACA,QAAO;EACL,eAAe,KAAK,iBAAiB;EACrC,QAAQ,KAAK;EACb,cAAc,KAAK,gBAAgB;EACnC,aAAa,KAAK;EAClB,GAAI,KAAK,kBAAkB,UAAa,EAAE,eAAe,KAAK,eAAe;EAC7E,SAAS,KAAK;EACd,QAAQ,KAAK,UAAU,EAAE;EACzB,WAAW,KAAK,aAAa,EAAE;EAC/B,UAAW,KAAK,YAAY,EAAE;EAC9B,GAAI,KAAK,gBAAgB,UAAa,EAAE,aAAa,KAAK,aAAa;EACvE,GAAI,KAAK,iBAAiB,UAAa,EAAE,cAAc,KAAK,cAAc;EAC1E,GAAI,KAAK,mBAAmB,UAAa,EAAE,gBAAgB,KAAK,gBAAgB;EAChF,GAAI,KAAK,SAAS,UAAa,EAAE,MAAM,KAAK,MAAM;EAClD,GAAI,KAAK,YAAY,UAAa,EAAE,SAAS,KAAK,SAAoC;EACvF"}
|
|
@@ -46,10 +46,18 @@ type ForeignKeyReferences = {
|
|
|
46
46
|
readonly table: string;
|
|
47
47
|
readonly columns: readonly string[];
|
|
48
48
|
};
|
|
49
|
+
type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';
|
|
50
|
+
type ForeignKeyOptions = {
|
|
51
|
+
readonly name?: string;
|
|
52
|
+
readonly onDelete?: ReferentialAction;
|
|
53
|
+
readonly onUpdate?: ReferentialAction;
|
|
54
|
+
};
|
|
49
55
|
type ForeignKey = {
|
|
50
56
|
readonly columns: readonly string[];
|
|
51
57
|
readonly references: ForeignKeyReferences;
|
|
52
58
|
readonly name?: string;
|
|
59
|
+
readonly onDelete?: ReferentialAction;
|
|
60
|
+
readonly onUpdate?: ReferentialAction;
|
|
53
61
|
/** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */
|
|
54
62
|
readonly constraint: boolean;
|
|
55
63
|
/** Whether to emit a backing index for the FK columns. */
|
|
@@ -133,5 +141,5 @@ type SqlContract<S extends SqlStorage = SqlStorage, M extends Record<string, unk
|
|
|
133
141
|
type ExtractCodecTypes<TContract extends SqlContract<SqlStorage>> = TContract['mappings']['codecTypes'];
|
|
134
142
|
type ExtractOperationTypes<TContract extends SqlContract<SqlStorage>> = TContract['mappings']['operationTypes'];
|
|
135
143
|
//#endregion
|
|
136
|
-
export {
|
|
137
|
-
//# sourceMappingURL=types-
|
|
144
|
+
export { StorageColumn as _, ForeignKey as a, UniqueConstraint as b, Index as c, ModelStorage as d, PrimaryKey as f, SqlStorage as g, SqlMappings as h, ExtractOperationTypes as i, ModelDefinition as l, SqlContract as m, DEFAULT_FK_INDEX as n, ForeignKeyOptions as o, ReferentialAction as p, ExtractCodecTypes as r, ForeignKeyReferences as s, DEFAULT_FK_CONSTRAINT as t, ModelField as u, StorageTable as v, applyFkDefaults as x, StorageTypeInstance as y };
|
|
145
|
+
//# sourceMappingURL=types-T6o5-ZB3.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-T6o5-ZB3.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;AAgBA;AAsBA;AAKA;AAKA;AAKA;AAKY,KA1CA,aAAA,GA0CiB;EAEjB,SAAA,UAAA,EAAiB,MAAA;E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AAA,GA6EE;EAAc,SAAA,OAAA,EA5ER,MA4EQ,CAAA,MAAA,EA5EO,aA4EP,CAAA;EACL,SAAA,UAAA,CAAA,EA5EC,UA4ED;EAA0B,SAAA,OAAA,EA3E7B,aA2E6B,CA3Ef,gBA2Ee,CAAA;EACxB,SAAA,OAAA,EA3EL,aA2EK,CA3ES,KA2ET,CAAA;EAA4B,SAAA,WAAA,EA1E7B,aA0E6B,CA1Ef,UA0Ee,CAAA;CAC9B;;;;;;;;;;;AAOgB,KArE3B,mBAAA,GAqE2B;EAG3B,SAAA,OAAA,EAAA,MAAiB;EAA+B,SAAA,UAAA,EAAA,MAAA;EAAZ,SAAA,UAAA,EArEzB,MAqEyB,CAAA,MAAA,EAAA,OAAA,CAAA;CAC9C;AAAS,KAnEC,UAAA,GAmED;EAEC,SAAA,MAAA,EApEO,MAoEP,CAAqB,MAAA,EApEC,YAoED,CAAA;EAA+B;;;;mBA/D7C,eAAe;;KAGtB,UAAA;;;KAIA,YAAA;;;KAIA,eAAA;oBACQ;mBACD,eAAe;sBACZ;;KAGV,WAAA;0BACc;0BACA;2BACC,eAAe;2BACf,eAAe;uBACnB;;;2BACI,eAAe;;cAG7B,qBAAA;cACA,gBAAA;;;;;iBAMG,eAAA;;;;;;;;;;KAUJ,sBACA,aAAa,sBACb,0BAA0B,mCAC1B,0BAA0B,qCACxB,cAAc,kCACL,0BAA0B,gDACxB,4BAA4B,gDAC9B,0BAA0B,2BAC7C,aAAa,cAAc,gBAAgB;;oBAE3B;mBACD;sBACG;qBACD;uBACE;;KAGX,oCAAoC,YAAY,eAC1D;KAEU,wCAAwC,YAAY,eAC9D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-kacOgEya.mjs","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n ColumnDefault,\n ContractBase,\n ExecutionHashBase,\n ExecutionSection,\n ProfileHashBase,\n StorageHashBase,\n} from '@prisma-next/contract/types';\n\n/**\n * A column definition in storage.\n *\n * `typeParams` is optional because most columns use non-parameterized types.\n * Columns with parameterized types can either inline `typeParams` or reference\n * a named {@link StorageTypeInstance} via `typeRef`.\n */\nexport type StorageColumn = {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n /**\n * Opaque, codec-owned JS/type parameters.\n * The codec that owns `codecId` defines the shape and semantics.\n * Mutually exclusive with `typeRef`.\n */\n readonly typeParams?: Record<string, unknown>;\n /**\n * Reference to a named type instance in `storage.types`.\n * Mutually exclusive with `typeParams`.\n */\n readonly typeRef?: string;\n /**\n * Default value for the column.\n * Can be a literal value or database function.\n */\n readonly default?: ColumnDefault;\n};\n\nexport type PrimaryKey = {\n readonly columns: readonly string[];\n readonly name?: string;\n};\n\nexport type UniqueConstraint = {\n readonly columns: readonly string[];\n readonly name?: string;\n};\n\nexport type Index = {\n readonly columns: readonly string[];\n readonly name?: string;\n};\n\nexport type ForeignKeyReferences = {\n readonly table: string;\n readonly columns: readonly string[];\n};\n\nexport type ForeignKey = {\n readonly columns: readonly string[];\n readonly references: ForeignKeyReferences;\n readonly name?: string;\n /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */\n readonly constraint: boolean;\n /** Whether to emit a backing index for the FK columns. */\n readonly index: boolean;\n};\n\nexport type StorageTable = {\n readonly columns: Record<string, StorageColumn>;\n readonly primaryKey?: PrimaryKey;\n readonly uniques: ReadonlyArray<UniqueConstraint>;\n readonly indexes: ReadonlyArray<Index>;\n readonly foreignKeys: ReadonlyArray<ForeignKey>;\n};\n\n/**\n * A named, parameterized type instance.\n * These are registered in `storage.types` for reuse across columns\n * and to enable ergonomic schema surfaces like `schema.types.MyType`.\n *\n * Unlike {@link StorageColumn}, `typeParams` is required here because\n * `StorageTypeInstance` exists specifically to define reusable parameterized types.\n * A type instance without parameters would be redundant—columns can reference\n * the codec directly via `codecId`.\n */\nexport type StorageTypeInstance = {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams: Record<string, unknown>;\n};\n\nexport type SqlStorage = {\n readonly tables: Record<string, StorageTable>;\n /**\n * Named type instances for parameterized/custom types.\n * Columns can reference these via `typeRef`.\n */\n readonly types?: Record<string, StorageTypeInstance>;\n};\n\nexport type ModelField = {\n readonly column: string;\n};\n\nexport type ModelStorage = {\n readonly table: string;\n};\n\nexport type ModelDefinition = {\n readonly storage: ModelStorage;\n readonly fields: Record<string, ModelField>;\n readonly relations: Record<string, unknown>;\n};\n\nexport type SqlMappings = {\n readonly modelToTable?: Record<string, string>;\n readonly tableToModel?: Record<string, string>;\n readonly fieldToColumn?: Record<string, Record<string, string>>;\n readonly columnToField?: Record<string, Record<string, string>>;\n readonly codecTypes: Record<string, { readonly output: unknown }>;\n readonly operationTypes: Record<string, Record<string, unknown>>;\n};\n\nexport const DEFAULT_FK_CONSTRAINT = true;\nexport const DEFAULT_FK_INDEX = true;\n\n/**\n * Resolves foreign key `constraint` and `index` fields to their effective boolean values,\n * falling back through optional override defaults, then to the global defaults.\n */\nexport function applyFkDefaults(\n fk: { constraint?: boolean | undefined; index?: boolean | undefined },\n overrideDefaults?: { constraint?: boolean | undefined; index?: boolean | undefined },\n): { constraint: boolean; index: boolean } {\n return {\n constraint: fk.constraint ?? overrideDefaults?.constraint ?? DEFAULT_FK_CONSTRAINT,\n index: fk.index ?? overrideDefaults?.index ?? DEFAULT_FK_INDEX,\n };\n}\n\nexport type SqlContract<\n S extends SqlStorage = SqlStorage,\n M extends Record<string, unknown> = Record<string, unknown>,\n R extends Record<string, unknown> = Record<string, unknown>,\n Map extends SqlMappings = SqlMappings,\n TStorageHash extends StorageHashBase<string> = StorageHashBase<string>,\n TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>,\n TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>,\n> = ContractBase<TStorageHash, TExecutionHash, TProfileHash> & {\n readonly targetFamily: string;\n readonly storage: S;\n readonly models: M;\n readonly relations: R;\n readonly mappings: Map;\n readonly execution?: ExecutionSection;\n};\n\nexport type ExtractCodecTypes<TContract extends SqlContract<SqlStorage>> =\n TContract['mappings']['codecTypes'];\n\nexport type ExtractOperationTypes<TContract extends SqlContract<SqlStorage>> =\n TContract['mappings']['operationTypes'];\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"types-kacOgEya.mjs","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n ColumnDefault,\n ContractBase,\n ExecutionHashBase,\n ExecutionSection,\n ProfileHashBase,\n StorageHashBase,\n} from '@prisma-next/contract/types';\n\n/**\n * A column definition in storage.\n *\n * `typeParams` is optional because most columns use non-parameterized types.\n * Columns with parameterized types can either inline `typeParams` or reference\n * a named {@link StorageTypeInstance} via `typeRef`.\n */\nexport type StorageColumn = {\n readonly nativeType: string;\n readonly codecId: string;\n readonly nullable: boolean;\n /**\n * Opaque, codec-owned JS/type parameters.\n * The codec that owns `codecId` defines the shape and semantics.\n * Mutually exclusive with `typeRef`.\n */\n readonly typeParams?: Record<string, unknown>;\n /**\n * Reference to a named type instance in `storage.types`.\n * Mutually exclusive with `typeParams`.\n */\n readonly typeRef?: string;\n /**\n * Default value for the column.\n * Can be a literal value or database function.\n */\n readonly default?: ColumnDefault;\n};\n\nexport type PrimaryKey = {\n readonly columns: readonly string[];\n readonly name?: string;\n};\n\nexport type UniqueConstraint = {\n readonly columns: readonly string[];\n readonly name?: string;\n};\n\nexport type Index = {\n readonly columns: readonly string[];\n readonly name?: string;\n};\n\nexport type ForeignKeyReferences = {\n readonly table: string;\n readonly columns: readonly string[];\n};\n\nexport type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';\n\nexport type ForeignKeyOptions = {\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n};\n\nexport type ForeignKey = {\n readonly columns: readonly string[];\n readonly references: ForeignKeyReferences;\n readonly name?: string;\n readonly onDelete?: ReferentialAction;\n readonly onUpdate?: ReferentialAction;\n /** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */\n readonly constraint: boolean;\n /** Whether to emit a backing index for the FK columns. */\n readonly index: boolean;\n};\n\nexport type StorageTable = {\n readonly columns: Record<string, StorageColumn>;\n readonly primaryKey?: PrimaryKey;\n readonly uniques: ReadonlyArray<UniqueConstraint>;\n readonly indexes: ReadonlyArray<Index>;\n readonly foreignKeys: ReadonlyArray<ForeignKey>;\n};\n\n/**\n * A named, parameterized type instance.\n * These are registered in `storage.types` for reuse across columns\n * and to enable ergonomic schema surfaces like `schema.types.MyType`.\n *\n * Unlike {@link StorageColumn}, `typeParams` is required here because\n * `StorageTypeInstance` exists specifically to define reusable parameterized types.\n * A type instance without parameters would be redundant—columns can reference\n * the codec directly via `codecId`.\n */\nexport type StorageTypeInstance = {\n readonly codecId: string;\n readonly nativeType: string;\n readonly typeParams: Record<string, unknown>;\n};\n\nexport type SqlStorage = {\n readonly tables: Record<string, StorageTable>;\n /**\n * Named type instances for parameterized/custom types.\n * Columns can reference these via `typeRef`.\n */\n readonly types?: Record<string, StorageTypeInstance>;\n};\n\nexport type ModelField = {\n readonly column: string;\n};\n\nexport type ModelStorage = {\n readonly table: string;\n};\n\nexport type ModelDefinition = {\n readonly storage: ModelStorage;\n readonly fields: Record<string, ModelField>;\n readonly relations: Record<string, unknown>;\n};\n\nexport type SqlMappings = {\n readonly modelToTable?: Record<string, string>;\n readonly tableToModel?: Record<string, string>;\n readonly fieldToColumn?: Record<string, Record<string, string>>;\n readonly columnToField?: Record<string, Record<string, string>>;\n readonly codecTypes: Record<string, { readonly output: unknown }>;\n readonly operationTypes: Record<string, Record<string, unknown>>;\n};\n\nexport const DEFAULT_FK_CONSTRAINT = true;\nexport const DEFAULT_FK_INDEX = true;\n\n/**\n * Resolves foreign key `constraint` and `index` fields to their effective boolean values,\n * falling back through optional override defaults, then to the global defaults.\n */\nexport function applyFkDefaults(\n fk: { constraint?: boolean | undefined; index?: boolean | undefined },\n overrideDefaults?: { constraint?: boolean | undefined; index?: boolean | undefined },\n): { constraint: boolean; index: boolean } {\n return {\n constraint: fk.constraint ?? overrideDefaults?.constraint ?? DEFAULT_FK_CONSTRAINT,\n index: fk.index ?? overrideDefaults?.index ?? DEFAULT_FK_INDEX,\n };\n}\n\nexport type SqlContract<\n S extends SqlStorage = SqlStorage,\n M extends Record<string, unknown> = Record<string, unknown>,\n R extends Record<string, unknown> = Record<string, unknown>,\n Map extends SqlMappings = SqlMappings,\n TStorageHash extends StorageHashBase<string> = StorageHashBase<string>,\n TExecutionHash extends ExecutionHashBase<string> = ExecutionHashBase<string>,\n TProfileHash extends ProfileHashBase<string> = ProfileHashBase<string>,\n> = ContractBase<TStorageHash, TExecutionHash, TProfileHash> & {\n readonly targetFamily: string;\n readonly storage: S;\n readonly models: M;\n readonly relations: R;\n readonly mappings: Map;\n readonly execution?: ExecutionSection;\n};\n\nexport type ExtractCodecTypes<TContract extends SqlContract<SqlStorage>> =\n TContract['mappings']['codecTypes'];\n\nexport type ExtractOperationTypes<TContract extends SqlContract<SqlStorage>> =\n TContract['mappings']['operationTypes'];\n"],"mappings":";AAsIA,MAAa,wBAAwB;AACrC,MAAa,mBAAmB;;;;;AAMhC,SAAgB,gBACd,IACA,kBACyC;AACzC,QAAO;EACL,YAAY,GAAG,cAAc,kBAAkB,cAAc;EAC7D,OAAO,GAAG,SAAS,kBAAkB,SAAS;EAC/C"}
|
package/dist/types.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as
|
|
2
|
-
export { DEFAULT_FK_CONSTRAINT, DEFAULT_FK_INDEX, type ExtractCodecTypes, type ExtractOperationTypes, type ForeignKey, type ForeignKeyReferences, type Index, type ModelDefinition, type ModelField, type ModelStorage, type PrimaryKey, type SqlContract, type SqlMappings, type SqlStorage, type StorageColumn, type StorageTable, type StorageTypeInstance, type UniqueConstraint, applyFkDefaults };
|
|
1
|
+
import { _ as StorageColumn, a as ForeignKey, b as UniqueConstraint, c as Index, d as ModelStorage, f as PrimaryKey, g as SqlStorage, h as SqlMappings, i as ExtractOperationTypes, l as ModelDefinition, m as SqlContract, n as DEFAULT_FK_INDEX, o as ForeignKeyOptions, p as ReferentialAction, r as ExtractCodecTypes, s as ForeignKeyReferences, t as DEFAULT_FK_CONSTRAINT, u as ModelField, v as StorageTable, x as applyFkDefaults, y as StorageTypeInstance } from "./types-T6o5-ZB3.mjs";
|
|
2
|
+
export { DEFAULT_FK_CONSTRAINT, DEFAULT_FK_INDEX, type ExtractCodecTypes, type ExtractOperationTypes, type ForeignKey, type ForeignKeyOptions, type ForeignKeyReferences, type Index, type ModelDefinition, type ModelField, type ModelStorage, type PrimaryKey, type ReferentialAction, type SqlContract, type SqlMappings, type SqlStorage, type StorageColumn, type StorageTable, type StorageTypeInstance, type UniqueConstraint, applyFkDefaults };
|
package/dist/validate.d.mts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as StorageColumn, g as SqlStorage, m as SqlContract } from "./types-T6o5-ZB3.mjs";
|
|
2
|
+
import "@prisma-next/contract/types";
|
|
2
3
|
|
|
3
4
|
//#region src/validate.d.ts
|
|
5
|
+
declare function isBigIntColumn(column: StorageColumn): boolean;
|
|
6
|
+
declare function decodeContractDefaults<T extends SqlContract<SqlStorage>>(contract: T): T;
|
|
4
7
|
declare function normalizeContract(contract: unknown): SqlContract<SqlStorage>;
|
|
5
8
|
declare function validateContract<TContract extends SqlContract<SqlStorage>>(value: unknown): TContract;
|
|
6
9
|
//#endregion
|
|
7
|
-
export { normalizeContract, validateContract };
|
|
10
|
+
export { decodeContractDefaults, isBigIntColumn, normalizeContract, validateContract };
|
|
8
11
|
//# sourceMappingURL=validate.d.mts.map
|
package/dist/validate.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate.d.mts","names":[],"sources":["../src/validate.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"validate.d.mts","names":[],"sources":["../src/validate.ts"],"sourcesContent":[],"mappings":";;;;iBA6PgB,cAAA,SAAuB;AAAvB,iBAkCA,sBAlCuB,CAAa,UAkCH,WAlCG,CAkCS,UAlCT,CAAA,CAAA,CAAA,QAAA,EAkCgC,CAlChC,CAAA,EAkCoC,CAlCpC;AAkCpC,iBAqDA,iBAAA,CArDsB,QAAA,EAAA,OAAA,CAAA,EAqDgB,WArDhB,CAqD4B,UArD5B,CAAA;AAAuB,iBAwI7C,gBAxI6C,CAAA,kBAwIV,WAxIU,CAwIE,UAxIF,CAAA,CAAA,CAAA,KAAA,EAAA,OAAA,CAAA,EA0I1D,SA1I0D"}
|
package/dist/validate.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { r as applyFkDefaults } from "./types-kacOgEya.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { c as validateSqlContract, u as validateStorageSemantics } from "./validators-CNMPzxwB.mjs";
|
|
3
|
+
import { isTaggedBigInt, isTaggedRaw } from "@prisma-next/contract/types";
|
|
3
4
|
|
|
4
5
|
//#region src/validate.ts
|
|
5
6
|
function computeDefaultMappings(models) {
|
|
@@ -86,6 +87,7 @@ function validateContractLogic(contract) {
|
|
|
86
87
|
}
|
|
87
88
|
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
89
|
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}"`);
|
|
90
|
+
for (const [colName, column] of Object.entries(table.columns)) if (!column.nullable && column.default?.kind === "literal" && column.default.value === null) throw new Error(`Table "${tableName}" column "${colName}" is NOT NULL but has a literal null default`);
|
|
89
91
|
for (const fk of table.foreignKeys) {
|
|
90
92
|
for (const colName of fk.columns) if (!columnNames.has(colName)) throw new Error(`Table "${tableName}" foreignKey references non-existent column "${colName}"`);
|
|
91
93
|
if (!tableNames.has(fk.references.table)) throw new Error(`Table "${tableName}" foreignKey references non-existent table "${fk.references.table}"`);
|
|
@@ -96,6 +98,67 @@ function validateContractLogic(contract) {
|
|
|
96
98
|
}
|
|
97
99
|
}
|
|
98
100
|
}
|
|
101
|
+
const BIGINT_NATIVE_TYPES = new Set(["bigint", "int8"]);
|
|
102
|
+
function isBigIntColumn(column) {
|
|
103
|
+
const nativeType = column.nativeType?.toLowerCase() ?? "";
|
|
104
|
+
if (BIGINT_NATIVE_TYPES.has(nativeType)) return true;
|
|
105
|
+
const codecId = column.codecId?.toLowerCase() ?? "";
|
|
106
|
+
return codecId.includes("int8") || codecId.includes("bigint");
|
|
107
|
+
}
|
|
108
|
+
function decodeDefaultLiteralValue(value, column, tableName, columnName) {
|
|
109
|
+
if (value instanceof Date) return value;
|
|
110
|
+
if (isTaggedRaw(value)) return value.value;
|
|
111
|
+
if (isTaggedBigInt(value)) {
|
|
112
|
+
if (!isBigIntColumn(column)) return value;
|
|
113
|
+
try {
|
|
114
|
+
return BigInt(value.value);
|
|
115
|
+
} catch {
|
|
116
|
+
throw new Error(`Invalid tagged bigint for default value on "${tableName}.${columnName}": "${value.value}" is not a valid integer`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
function decodeContractDefaults(contract) {
|
|
122
|
+
const tables = contract.storage.tables;
|
|
123
|
+
let tablesChanged = false;
|
|
124
|
+
const decodedTables = {};
|
|
125
|
+
for (const [tableName, table] of Object.entries(tables)) {
|
|
126
|
+
let columnsChanged = false;
|
|
127
|
+
const decodedColumns = {};
|
|
128
|
+
for (const [columnName, column] of Object.entries(table.columns)) {
|
|
129
|
+
if (column.default?.kind === "literal") {
|
|
130
|
+
const decodedValue = decodeDefaultLiteralValue(column.default.value, column, tableName, columnName);
|
|
131
|
+
if (decodedValue !== column.default.value) {
|
|
132
|
+
columnsChanged = true;
|
|
133
|
+
decodedColumns[columnName] = {
|
|
134
|
+
...column,
|
|
135
|
+
default: {
|
|
136
|
+
kind: "literal",
|
|
137
|
+
value: decodedValue
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
decodedColumns[columnName] = column;
|
|
144
|
+
}
|
|
145
|
+
if (columnsChanged) {
|
|
146
|
+
tablesChanged = true;
|
|
147
|
+
decodedTables[tableName] = {
|
|
148
|
+
...table,
|
|
149
|
+
columns: decodedColumns
|
|
150
|
+
};
|
|
151
|
+
} else decodedTables[tableName] = table;
|
|
152
|
+
}
|
|
153
|
+
if (!tablesChanged) return contract;
|
|
154
|
+
return {
|
|
155
|
+
...contract,
|
|
156
|
+
storage: {
|
|
157
|
+
...contract.storage,
|
|
158
|
+
tables: decodedTables
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
99
162
|
function normalizeContract(contract) {
|
|
100
163
|
if (typeof contract !== "object" || contract === null) return contract;
|
|
101
164
|
const contractObj = contract;
|
|
@@ -166,14 +229,16 @@ function normalizeContract(contract) {
|
|
|
166
229
|
function validateContract(value) {
|
|
167
230
|
const structurallyValid = validateSqlContract(normalizeContract(value));
|
|
168
231
|
validateContractLogic(structurallyValid);
|
|
232
|
+
const semanticErrors = validateStorageSemantics(structurallyValid.storage);
|
|
233
|
+
if (semanticErrors.length > 0) throw new Error(`Contract semantic validation failed: ${semanticErrors.join("; ")}`);
|
|
169
234
|
const existingMappings = structurallyValid.mappings;
|
|
170
235
|
const mappings = mergeMappings(computeDefaultMappings(structurallyValid.models), existingMappings);
|
|
171
|
-
return {
|
|
236
|
+
return decodeContractDefaults({
|
|
172
237
|
...structurallyValid,
|
|
173
238
|
mappings
|
|
174
|
-
};
|
|
239
|
+
});
|
|
175
240
|
}
|
|
176
241
|
|
|
177
242
|
//#endregion
|
|
178
|
-
export { normalizeContract, validateContract };
|
|
243
|
+
export { decodeContractDefaults, isBigIntColumn, normalizeContract, validateContract };
|
|
179
244
|
//# sourceMappingURL=validate.mjs.map
|
package/dist/validate.mjs.map
CHANGED
|
@@ -1 +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,uBAAuB,QAA2D;CACzF,MAAMA,eAAuC,EAAE;CAC/C,MAAMC,eAAuC,EAAE;CAC/C,MAAMC,gBAAwD,EAAE;CAChE,MAAMC,gBAAwD,EAAE;AAEhE,MAAK,MAAM,CAAC,WAAW,UAAU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,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"}
|
|
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>","decodedTables: Record<string, StorageTable>","decodedColumns: Record<string, StorageColumn>","normalizedTables: Record<string, unknown>","normalizedColumns: Record<string, unknown>","normalizedModelsObj: Record<string, unknown>"],"sources":["../src/validate.ts"],"sourcesContent":["import type { ColumnDefaultLiteralInputValue } from '@prisma-next/contract/types';\nimport { isTaggedBigInt, isTaggedRaw } from '@prisma-next/contract/types';\nimport type {\n ModelDefinition,\n SqlContract,\n SqlMappings,\n SqlStorage,\n StorageColumn,\n StorageTable,\n} from './types';\nimport { applyFkDefaults } from './types';\nimport { validateSqlContract, validateStorageSemantics } 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 [colName, column] of Object.entries(table.columns)) {\n if (!column.nullable && column.default?.kind === 'literal' && column.default.value === null) {\n throw new Error(\n `Table \"${tableName}\" column \"${colName}\" is NOT NULL but has a literal null default`,\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\nconst BIGINT_NATIVE_TYPES = new Set(['bigint', 'int8']);\n\nexport function isBigIntColumn(column: StorageColumn): boolean {\n const nativeType = column.nativeType?.toLowerCase() ?? '';\n if (BIGINT_NATIVE_TYPES.has(nativeType)) return true;\n const codecId = column.codecId?.toLowerCase() ?? '';\n return codecId.includes('int8') || codecId.includes('bigint');\n}\n\nexport function decodeDefaultLiteralValue(\n value: ColumnDefaultLiteralInputValue,\n column: StorageColumn,\n tableName: string,\n columnName: string,\n): ColumnDefaultLiteralInputValue {\n if (value instanceof Date) {\n return value;\n }\n if (isTaggedRaw(value)) {\n return value.value;\n }\n if (isTaggedBigInt(value)) {\n if (!isBigIntColumn(column)) {\n return value;\n }\n try {\n return BigInt(value.value);\n } catch {\n throw new Error(\n `Invalid tagged bigint for default value on \"${tableName}.${columnName}\": \"${value.value}\" is not a valid integer`,\n );\n }\n }\n return value;\n}\n\nexport function decodeContractDefaults<T extends SqlContract<SqlStorage>>(contract: T): T {\n const tables = contract.storage.tables;\n let tablesChanged = false;\n const decodedTables: Record<string, StorageTable> = {};\n\n for (const [tableName, table] of Object.entries(tables)) {\n let columnsChanged = false;\n const decodedColumns: Record<string, StorageColumn> = {};\n\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.default?.kind === 'literal') {\n const decodedValue = decodeDefaultLiteralValue(\n column.default.value,\n column,\n tableName,\n columnName,\n );\n if (decodedValue !== column.default.value) {\n columnsChanged = true;\n decodedColumns[columnName] = {\n ...column,\n default: { kind: 'literal', value: decodedValue },\n };\n continue;\n }\n }\n decodedColumns[columnName] = column;\n }\n\n if (columnsChanged) {\n tablesChanged = true;\n decodedTables[tableName] = { ...table, columns: decodedColumns };\n } else {\n decodedTables[tableName] = table;\n }\n }\n\n if (!tablesChanged) {\n return contract;\n }\n\n // The spread widens to SqlContract<SqlStorage>, but this transformation only\n // decodes tagged bigint defaults for bigint-like columns and preserves all\n // other properties of T.\n return {\n ...contract,\n storage: {\n ...contract.storage,\n tables: decodedTables,\n },\n } as T;\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 semanticErrors = validateStorageSemantics(structurallyValid.storage);\n if (semanticErrors.length > 0) {\n throw new Error(`Contract semantic validation failed: ${semanticErrors.join('; ')}`);\n }\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 const contractWithMappings = {\n ...structurallyValid,\n mappings,\n };\n\n return decodeContractDefaults(contractWithMappings) as TContract;\n}\n"],"mappings":";;;;;AAsBA,SAAS,uBAAuB,QAA2D;CACzF,MAAMA,eAAuC,EAAE;CAC/C,MAAMC,eAAuC,EAAE;CAC/C,MAAMC,gBAAwD,EAAE;CAChE,MAAMC,gBAAwD,EAAE;AAEhE,MAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,OAAO,EAAE;EACvD,MAAM,YAAY,MAAM,QAAQ;AAChC,eAAa,aAAa;AAC1B,eAAa,aAAa;EAE1B,MAAMC,qBAA6C,EAAE;AACrD,OAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,MAAM,OAAO,EAAE;GAC7D,MAAM,aAAa,MAAM;AACzB,sBAAm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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,iBAAiB,yBAAyB,kBAAkB,QAAQ;AAC1E,KAAI,eAAe,SAAS,EAC1B,OAAM,IAAI,MAAM,wCAAwC,eAAe,KAAK,KAAK,GAAG;CAGtF,MAAM,mBAAoB,kBAA0D;CAIpF,MAAM,WAAW,cAHO,uBACtB,kBAAkB,OACnB,EAC+C,iBAAiB;AAOjE,QAAO,uBALsB;EAC3B,GAAG;EACH;EACD,CAEkD"}
|
|
@@ -7,7 +7,7 @@ const generatorKindSchema = type("'generator'");
|
|
|
7
7
|
const generatorIdSchema = type("'ulid' | 'nanoid' | 'uuidv7' | 'uuidv4' | 'cuid2' | 'ksuid'");
|
|
8
8
|
const ColumnDefaultLiteralSchema = type.declare().type({
|
|
9
9
|
kind: literalKindSchema,
|
|
10
|
-
|
|
10
|
+
value: "string | number | boolean | null | unknown[] | Record<string, unknown>"
|
|
11
11
|
});
|
|
12
12
|
const ColumnDefaultFunctionSchema = type.declare().type({
|
|
13
13
|
kind: functionKindSchema,
|
|
@@ -59,21 +59,24 @@ const ForeignKeyReferencesSchema = type.declare().type({
|
|
|
59
59
|
table: "string",
|
|
60
60
|
columns: type.string.array().readonly()
|
|
61
61
|
});
|
|
62
|
+
const ReferentialActionSchema = type.declare().type("'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'");
|
|
62
63
|
const ForeignKeySchema = type.declare().type({
|
|
63
64
|
columns: type.string.array().readonly(),
|
|
64
65
|
references: ForeignKeyReferencesSchema,
|
|
65
66
|
"name?": "string",
|
|
67
|
+
"onDelete?": ReferentialActionSchema,
|
|
68
|
+
"onUpdate?": ReferentialActionSchema,
|
|
66
69
|
constraint: "boolean",
|
|
67
70
|
index: "boolean"
|
|
68
71
|
});
|
|
69
|
-
const StorageTableSchema = type
|
|
72
|
+
const StorageTableSchema = type({
|
|
70
73
|
columns: type({ "[string]": StorageColumnSchema }),
|
|
71
74
|
"primaryKey?": PrimaryKeySchema,
|
|
72
75
|
uniques: UniqueConstraintSchema.array().readonly(),
|
|
73
76
|
indexes: IndexSchema.array().readonly(),
|
|
74
77
|
foreignKeys: ForeignKeySchema.array().readonly()
|
|
75
78
|
});
|
|
76
|
-
const StorageSchema = type
|
|
79
|
+
const StorageSchema = type({
|
|
77
80
|
tables: type({ "[string]": StorageTableSchema }),
|
|
78
81
|
"types?": type({ "[string]": StorageTypeInstanceSchema })
|
|
79
82
|
});
|
|
@@ -156,7 +159,28 @@ function validateSqlContract(value) {
|
|
|
156
159
|
}
|
|
157
160
|
return contractResult;
|
|
158
161
|
}
|
|
162
|
+
/**
|
|
163
|
+
* Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.
|
|
164
|
+
*
|
|
165
|
+
* Returns an array of human-readable error strings. Empty array = valid.
|
|
166
|
+
*
|
|
167
|
+
* Currently checks:
|
|
168
|
+
* - `setNull` referential action on a non-nullable FK column (would fail at runtime)
|
|
169
|
+
* - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)
|
|
170
|
+
*/
|
|
171
|
+
function validateStorageSemantics(storage) {
|
|
172
|
+
const errors = [];
|
|
173
|
+
for (const [tableName, table] of Object.entries(storage.tables)) for (const fk of table.foreignKeys) for (const colName of fk.columns) {
|
|
174
|
+
const column = table.columns[colName];
|
|
175
|
+
if (!column) continue;
|
|
176
|
+
if (fk.onDelete === "setNull" && !column.nullable) errors.push(`Table "${tableName}": onDelete setNull on foreign key column "${colName}" which is NOT NULL`);
|
|
177
|
+
if (fk.onUpdate === "setNull" && !column.nullable) errors.push(`Table "${tableName}": onUpdate setNull on foreign key column "${colName}" which is NOT NULL`);
|
|
178
|
+
if (fk.onDelete === "setDefault" && !column.nullable && column.default === void 0) errors.push(`Table "${tableName}": onDelete setDefault on foreign key column "${colName}" which is NOT NULL and has no DEFAULT`);
|
|
179
|
+
if (fk.onUpdate === "setDefault" && !column.nullable && column.default === void 0) errors.push(`Table "${tableName}": onUpdate setDefault on foreign key column "${colName}" which is NOT NULL and has no DEFAULT`);
|
|
180
|
+
}
|
|
181
|
+
return errors;
|
|
182
|
+
}
|
|
159
183
|
|
|
160
184
|
//#endregion
|
|
161
|
-
export {
|
|
162
|
-
//# sourceMappingURL=validators-
|
|
185
|
+
export { ForeignKeySchema as a, validateSqlContract as c, ForeignKeyReferencesSchema as i, validateStorage as l, ColumnDefaultLiteralSchema as n, ReferentialActionSchema as o, ColumnDefaultSchema as r, validateModel as s, ColumnDefaultFunctionSchema as t, validateStorageSemantics as u };
|
|
186
|
+
//# sourceMappingURL=validators-CNMPzxwB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators-CNMPzxwB.mjs","names":["errors: string[]"],"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 ReferentialAction,\n SqlContract,\n SqlStorage,\n StorageTypeInstance,\n UniqueConstraint,\n} from './types';\n\ntype ColumnDefaultLiteral = {\n readonly kind: 'literal';\n readonly value: string | number | boolean | Record<string, unknown> | unknown[] | null;\n};\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 value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',\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\nexport const ForeignKeyReferencesSchema = type.declare<ForeignKeyReferences>().type({\n table: 'string',\n columns: type.string.array().readonly(),\n});\n\nexport const ReferentialActionSchema = type\n .declare<ReferentialAction>()\n .type(\"'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'\");\n\nexport const ForeignKeySchema = type.declare<ForeignKey>().type({\n columns: type.string.array().readonly(),\n references: ForeignKeyReferencesSchema,\n 'name?': 'string',\n 'onDelete?': ReferentialActionSchema,\n 'onUpdate?': ReferentialActionSchema,\n constraint: 'boolean',\n index: 'boolean',\n});\n\nconst StorageTableSchema = 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({\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// NOTE: StorageColumnSchema, StorageTableSchema, and StorageSchema use bare type()\n// instead of type.declare<T>().type() because the ColumnDefault union's value field\n// includes bigint | Date (runtime-only types after decoding) which cannot be expressed\n// in Arktype's JSON validation DSL. The `as SqlStorage` cast in validateStorage() bridges\n// the gap between the JSON-safe Arktype output and the runtime TypeScript type.\n// See decodeContractDefaults() in validate.ts for the decoding step.\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 as SqlStorage;\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\n/**\n * Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.\n *\n * Returns an array of human-readable error strings. Empty array = valid.\n *\n * Currently checks:\n * - `setNull` referential action on a non-nullable FK column (would fail at runtime)\n * - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)\n */\nexport function validateStorageSemantics(storage: SqlStorage): string[] {\n const errors: string[] = [];\n\n for (const [tableName, table] of Object.entries(storage.tables)) {\n for (const fk of table.foreignKeys) {\n for (const colName of fk.columns) {\n const column = table.columns[colName];\n if (!column) continue;\n\n if (fk.onDelete === 'setNull' && !column.nullable) {\n errors.push(\n `Table \"${tableName}\": onDelete setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onUpdate === 'setNull' && !column.nullable) {\n errors.push(\n `Table \"${tableName}\": onUpdate setNull on foreign key column \"${colName}\" which is NOT NULL`,\n );\n }\n if (fk.onDelete === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Table \"${tableName}\": onDelete setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n if (fk.onUpdate === 'setDefault' && !column.nullable && column.default === undefined) {\n errors.push(\n `Table \"${tableName}\": onUpdate setDefault on foreign key column \"${colName}\" which is NOT NULL and has no DEFAULT`,\n );\n }\n }\n }\n }\n\n return errors;\n}\n"],"mappings":";;;AAqBA,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,OAAO;CACR,CAAC;AAEF,MAAa,8BAA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,YAAY,OACzE,QAAO,KACL,UAAU,UAAU,gDAAgD,QAAQ,wCAC7E;;AAMT,QAAO"}
|
package/dist/validators.d.mts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as ForeignKey, g as SqlStorage, l as ModelDefinition, m as SqlContract, p as ReferentialAction, s as ForeignKeyReferences } from "./types-T6o5-ZB3.mjs";
|
|
2
2
|
import * as arktype_internal_variants_object_ts0 from "arktype/internal/variants/object.ts";
|
|
3
|
+
import * as arktype_internal_variants_string_ts0 from "arktype/internal/variants/string.ts";
|
|
3
4
|
|
|
4
5
|
//#region src/validators.d.ts
|
|
5
6
|
type ColumnDefaultLiteral = {
|
|
6
7
|
readonly kind: 'literal';
|
|
7
|
-
readonly
|
|
8
|
+
readonly value: string | number | boolean | Record<string, unknown> | unknown[] | null;
|
|
8
9
|
};
|
|
9
10
|
type ColumnDefaultFunction = {
|
|
10
11
|
readonly kind: 'function';
|
|
@@ -13,6 +14,9 @@ type ColumnDefaultFunction = {
|
|
|
13
14
|
declare const ColumnDefaultLiteralSchema: arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultLiteral, {}>;
|
|
14
15
|
declare const ColumnDefaultFunctionSchema: arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultFunction, {}>;
|
|
15
16
|
declare const ColumnDefaultSchema: arktype_internal_variants_object_ts0.ObjectType<ColumnDefaultLiteral | ColumnDefaultFunction, {}>;
|
|
17
|
+
declare const ForeignKeyReferencesSchema: arktype_internal_variants_object_ts0.ObjectType<ForeignKeyReferences, {}>;
|
|
18
|
+
declare const ReferentialActionSchema: arktype_internal_variants_string_ts0.StringType<ReferentialAction, {}>;
|
|
19
|
+
declare const ForeignKeySchema: arktype_internal_variants_object_ts0.ObjectType<ForeignKey, {}>;
|
|
16
20
|
/**
|
|
17
21
|
* Validates the structural shape of SqlStorage using Arktype.
|
|
18
22
|
*
|
|
@@ -46,6 +50,16 @@ declare function validateModel(value: unknown): ModelDefinition;
|
|
|
46
50
|
* @throws Error if the contract structure is invalid
|
|
47
51
|
*/
|
|
48
52
|
declare function validateSqlContract<T extends SqlContract<SqlStorage>>(value: unknown): T;
|
|
53
|
+
/**
|
|
54
|
+
* Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.
|
|
55
|
+
*
|
|
56
|
+
* Returns an array of human-readable error strings. Empty array = valid.
|
|
57
|
+
*
|
|
58
|
+
* Currently checks:
|
|
59
|
+
* - `setNull` referential action on a non-nullable FK column (would fail at runtime)
|
|
60
|
+
* - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)
|
|
61
|
+
*/
|
|
62
|
+
declare function validateStorageSemantics(storage: SqlStorage): string[];
|
|
49
63
|
//#endregion
|
|
50
|
-
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, validateModel, validateSqlContract, validateStorage };
|
|
64
|
+
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ForeignKeyReferencesSchema, ForeignKeySchema, ReferentialActionSchema, validateModel, validateSqlContract, validateStorage, validateStorageSemantics };
|
|
51
65
|
//# sourceMappingURL=validators.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validators.d.mts","names":[],"sources":["../src/validators.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"validators.d.mts","names":[],"sources":["../src/validators.ts"],"sourcesContent":[],"mappings":";;;;;KAgBK,oBAAA;;8CAEyC;;AAJ7B,KAMZ,qBAAA,GAJoB;EAIpB,SAAA,IAAA,EAAA,UAAqB;EAMb,SAAA,UAAA,EAAA,MAAA;AAKb,CAAA;AAKa,cAVA,0BAUgF,EAVtD,oCAAA,CAAA,UAUsD,CAVtD,oBAUsD,EAAA,CAAA,CAAA,CAAA;AAA7D,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;AAAA,cA0DnB,0BA1DmB,EA0DO,oCAAA,CAAA,UA1DP,CA0DO,oBA1DP,EAAA,CAAA,CAAA,CAAA;AAAA,cA+DnB,uBA/DmB,EA+DI,oCAAA,CAAA,UA/DJ,CA+DI,iBA/DJ,EAAA,CAAA,CAAA,CAAA;AA0DnB,cASA,gBANX,EAM2B,oCAAA,CAAA,UATU,CASV,UATU,EAAA,CAAA,CAAA,CAAA;AAKvC;AAIA;AAmEA;AAgBA;AAyBA;;;AAAwF,iBAzCxE,eAAA,CAyCwE,KAAA,EAAA,OAAA,CAAA,EAzCvC,UAyCuC;;AAiCxF;;;;;;iBA1DgB,aAAA,kBAA+B;;;;;;;;;;;;;;;;;iBAyB/B,8BAA8B,YAAY,8BAA8B;;;;;;;;;;iBAiCxE,wBAAA,UAAkC"}
|
package/dist/validators.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as validateSqlContract, i as
|
|
1
|
+
import { a as ForeignKeySchema, c as validateSqlContract, i as ForeignKeyReferencesSchema, l as validateStorage, n as ColumnDefaultLiteralSchema, o as ReferentialActionSchema, r as ColumnDefaultSchema, s as validateModel, t as ColumnDefaultFunctionSchema, u as validateStorageSemantics } from "./validators-CNMPzxwB.mjs";
|
|
2
2
|
|
|
3
|
-
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, validateModel, validateSqlContract, validateStorage };
|
|
3
|
+
export { ColumnDefaultFunctionSchema, ColumnDefaultLiteralSchema, ColumnDefaultSchema, ForeignKeyReferencesSchema, ForeignKeySchema, ReferentialActionSchema, validateModel, validateSqlContract, validateStorage, validateStorageSemantics };
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/sql-contract",
|
|
3
|
-
"version": "0.3.0-dev.
|
|
3
|
+
"version": "0.3.0-dev.43",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"plane": "shared",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"description": "SQL contract types, validators, and IR factories for Prisma Next",
|
|
8
8
|
"dependencies": {
|
|
9
9
|
"arktype": "^2.1.25",
|
|
10
|
-
"@prisma-next/contract": "0.3.0-dev.
|
|
10
|
+
"@prisma-next/contract": "0.3.0-dev.43"
|
|
11
11
|
},
|
|
12
12
|
"devDependencies": {
|
|
13
13
|
"tsdown": "0.18.4",
|
package/src/exports/types.ts
CHANGED
|
@@ -2,12 +2,14 @@ export type {
|
|
|
2
2
|
ExtractCodecTypes,
|
|
3
3
|
ExtractOperationTypes,
|
|
4
4
|
ForeignKey,
|
|
5
|
+
ForeignKeyOptions,
|
|
5
6
|
ForeignKeyReferences,
|
|
6
7
|
Index,
|
|
7
8
|
ModelDefinition,
|
|
8
9
|
ModelField,
|
|
9
10
|
ModelStorage,
|
|
10
11
|
PrimaryKey,
|
|
12
|
+
ReferentialAction,
|
|
11
13
|
SqlContract,
|
|
12
14
|
SqlMappings,
|
|
13
15
|
SqlStorage,
|
package/src/exports/validate.ts
CHANGED
package/src/factories.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type {
|
|
|
5
5
|
} from '@prisma-next/contract/types';
|
|
6
6
|
import type {
|
|
7
7
|
ForeignKey,
|
|
8
|
+
ForeignKeyOptions,
|
|
8
9
|
ForeignKeyReferences,
|
|
9
10
|
Index,
|
|
10
11
|
ModelDefinition,
|
|
@@ -58,17 +59,20 @@ export function fk(
|
|
|
58
59
|
columns: readonly string[],
|
|
59
60
|
refTable: string,
|
|
60
61
|
refColumns: readonly string[],
|
|
61
|
-
opts?:
|
|
62
|
+
opts?: ForeignKeyOptions & { constraint?: boolean; index?: boolean },
|
|
62
63
|
): ForeignKey {
|
|
63
64
|
const references: ForeignKeyReferences = {
|
|
64
65
|
table: refTable,
|
|
65
66
|
columns: refColumns,
|
|
66
67
|
};
|
|
68
|
+
|
|
67
69
|
return {
|
|
68
70
|
columns,
|
|
69
71
|
references,
|
|
70
|
-
...applyFkDefaults({ constraint: opts?.constraint, index: opts?.index }),
|
|
71
72
|
...(opts?.name !== undefined && { name: opts.name }),
|
|
73
|
+
...(opts?.onDelete !== undefined && { onDelete: opts.onDelete }),
|
|
74
|
+
...(opts?.onUpdate !== undefined && { onUpdate: opts.onUpdate }),
|
|
75
|
+
...applyFkDefaults({ constraint: opts?.constraint, index: opts?.index }),
|
|
72
76
|
};
|
|
73
77
|
}
|
|
74
78
|
|
package/src/types.ts
CHANGED
|
@@ -56,10 +56,20 @@ export type ForeignKeyReferences = {
|
|
|
56
56
|
readonly columns: readonly string[];
|
|
57
57
|
};
|
|
58
58
|
|
|
59
|
+
export type ReferentialAction = 'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault';
|
|
60
|
+
|
|
61
|
+
export type ForeignKeyOptions = {
|
|
62
|
+
readonly name?: string;
|
|
63
|
+
readonly onDelete?: ReferentialAction;
|
|
64
|
+
readonly onUpdate?: ReferentialAction;
|
|
65
|
+
};
|
|
66
|
+
|
|
59
67
|
export type ForeignKey = {
|
|
60
68
|
readonly columns: readonly string[];
|
|
61
69
|
readonly references: ForeignKeyReferences;
|
|
62
70
|
readonly name?: string;
|
|
71
|
+
readonly onDelete?: ReferentialAction;
|
|
72
|
+
readonly onUpdate?: ReferentialAction;
|
|
63
73
|
/** Whether to emit FK constraint DDL (ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY). */
|
|
64
74
|
readonly constraint: boolean;
|
|
65
75
|
/** Whether to emit a backing index for the FK columns. */
|
package/src/validate.ts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ColumnDefaultLiteralInputValue } from '@prisma-next/contract/types';
|
|
2
|
+
import { isTaggedBigInt, isTaggedRaw } from '@prisma-next/contract/types';
|
|
3
|
+
import type {
|
|
4
|
+
ModelDefinition,
|
|
5
|
+
SqlContract,
|
|
6
|
+
SqlMappings,
|
|
7
|
+
SqlStorage,
|
|
8
|
+
StorageColumn,
|
|
9
|
+
StorageTable,
|
|
10
|
+
} from './types';
|
|
2
11
|
import { applyFkDefaults } from './types';
|
|
3
|
-
import { validateSqlContract } from './validators';
|
|
12
|
+
import { validateSqlContract, validateStorageSemantics } from './validators';
|
|
4
13
|
|
|
5
14
|
type ResolvedMappings = {
|
|
6
15
|
modelToTable: Record<string, string>;
|
|
@@ -196,6 +205,14 @@ function validateContractLogic(contract: SqlContract<SqlStorage>): void {
|
|
|
196
205
|
}
|
|
197
206
|
}
|
|
198
207
|
|
|
208
|
+
for (const [colName, column] of Object.entries(table.columns)) {
|
|
209
|
+
if (!column.nullable && column.default?.kind === 'literal' && column.default.value === null) {
|
|
210
|
+
throw new Error(
|
|
211
|
+
`Table "${tableName}" column "${colName}" is NOT NULL but has a literal null default`,
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
199
216
|
for (const fk of table.foreignKeys) {
|
|
200
217
|
for (const colName of fk.columns) {
|
|
201
218
|
if (!columnNames.has(colName)) {
|
|
@@ -232,6 +249,95 @@ function validateContractLogic(contract: SqlContract<SqlStorage>): void {
|
|
|
232
249
|
}
|
|
233
250
|
}
|
|
234
251
|
|
|
252
|
+
const BIGINT_NATIVE_TYPES = new Set(['bigint', 'int8']);
|
|
253
|
+
|
|
254
|
+
export function isBigIntColumn(column: StorageColumn): boolean {
|
|
255
|
+
const nativeType = column.nativeType?.toLowerCase() ?? '';
|
|
256
|
+
if (BIGINT_NATIVE_TYPES.has(nativeType)) return true;
|
|
257
|
+
const codecId = column.codecId?.toLowerCase() ?? '';
|
|
258
|
+
return codecId.includes('int8') || codecId.includes('bigint');
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function decodeDefaultLiteralValue(
|
|
262
|
+
value: ColumnDefaultLiteralInputValue,
|
|
263
|
+
column: StorageColumn,
|
|
264
|
+
tableName: string,
|
|
265
|
+
columnName: string,
|
|
266
|
+
): ColumnDefaultLiteralInputValue {
|
|
267
|
+
if (value instanceof Date) {
|
|
268
|
+
return value;
|
|
269
|
+
}
|
|
270
|
+
if (isTaggedRaw(value)) {
|
|
271
|
+
return value.value;
|
|
272
|
+
}
|
|
273
|
+
if (isTaggedBigInt(value)) {
|
|
274
|
+
if (!isBigIntColumn(column)) {
|
|
275
|
+
return value;
|
|
276
|
+
}
|
|
277
|
+
try {
|
|
278
|
+
return BigInt(value.value);
|
|
279
|
+
} catch {
|
|
280
|
+
throw new Error(
|
|
281
|
+
`Invalid tagged bigint for default value on "${tableName}.${columnName}": "${value.value}" is not a valid integer`,
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return value;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function decodeContractDefaults<T extends SqlContract<SqlStorage>>(contract: T): T {
|
|
289
|
+
const tables = contract.storage.tables;
|
|
290
|
+
let tablesChanged = false;
|
|
291
|
+
const decodedTables: Record<string, StorageTable> = {};
|
|
292
|
+
|
|
293
|
+
for (const [tableName, table] of Object.entries(tables)) {
|
|
294
|
+
let columnsChanged = false;
|
|
295
|
+
const decodedColumns: Record<string, StorageColumn> = {};
|
|
296
|
+
|
|
297
|
+
for (const [columnName, column] of Object.entries(table.columns)) {
|
|
298
|
+
if (column.default?.kind === 'literal') {
|
|
299
|
+
const decodedValue = decodeDefaultLiteralValue(
|
|
300
|
+
column.default.value,
|
|
301
|
+
column,
|
|
302
|
+
tableName,
|
|
303
|
+
columnName,
|
|
304
|
+
);
|
|
305
|
+
if (decodedValue !== column.default.value) {
|
|
306
|
+
columnsChanged = true;
|
|
307
|
+
decodedColumns[columnName] = {
|
|
308
|
+
...column,
|
|
309
|
+
default: { kind: 'literal', value: decodedValue },
|
|
310
|
+
};
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
decodedColumns[columnName] = column;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (columnsChanged) {
|
|
318
|
+
tablesChanged = true;
|
|
319
|
+
decodedTables[tableName] = { ...table, columns: decodedColumns };
|
|
320
|
+
} else {
|
|
321
|
+
decodedTables[tableName] = table;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (!tablesChanged) {
|
|
326
|
+
return contract;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// The spread widens to SqlContract<SqlStorage>, but this transformation only
|
|
330
|
+
// decodes tagged bigint defaults for bigint-like columns and preserves all
|
|
331
|
+
// other properties of T.
|
|
332
|
+
return {
|
|
333
|
+
...contract,
|
|
334
|
+
storage: {
|
|
335
|
+
...contract.storage,
|
|
336
|
+
tables: decodedTables,
|
|
337
|
+
},
|
|
338
|
+
} as T;
|
|
339
|
+
}
|
|
340
|
+
|
|
235
341
|
export function normalizeContract(contract: unknown): SqlContract<SqlStorage> {
|
|
236
342
|
if (typeof contract !== 'object' || contract === null) {
|
|
237
343
|
return contract as SqlContract<SqlStorage>;
|
|
@@ -322,14 +428,21 @@ export function validateContract<TContract extends SqlContract<SqlStorage>>(
|
|
|
322
428
|
const structurallyValid = validateSqlContract<SqlContract<SqlStorage>>(normalized);
|
|
323
429
|
validateContractLogic(structurallyValid);
|
|
324
430
|
|
|
431
|
+
const semanticErrors = validateStorageSemantics(structurallyValid.storage);
|
|
432
|
+
if (semanticErrors.length > 0) {
|
|
433
|
+
throw new Error(`Contract semantic validation failed: ${semanticErrors.join('; ')}`);
|
|
434
|
+
}
|
|
435
|
+
|
|
325
436
|
const existingMappings = (structurallyValid as { mappings?: Partial<SqlMappings> }).mappings;
|
|
326
437
|
const defaultMappings = computeDefaultMappings(
|
|
327
438
|
structurallyValid.models as Record<string, ModelDefinition>,
|
|
328
439
|
);
|
|
329
440
|
const mappings = mergeMappings(defaultMappings, existingMappings);
|
|
330
441
|
|
|
331
|
-
|
|
442
|
+
const contractWithMappings = {
|
|
332
443
|
...structurallyValid,
|
|
333
444
|
mappings,
|
|
334
|
-
}
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
return decodeContractDefaults(contractWithMappings) as TContract;
|
|
335
448
|
}
|
package/src/validators.ts
CHANGED
|
@@ -7,14 +7,17 @@ import type {
|
|
|
7
7
|
ModelField,
|
|
8
8
|
ModelStorage,
|
|
9
9
|
PrimaryKey,
|
|
10
|
+
ReferentialAction,
|
|
10
11
|
SqlContract,
|
|
11
12
|
SqlStorage,
|
|
12
|
-
StorageTable,
|
|
13
13
|
StorageTypeInstance,
|
|
14
14
|
UniqueConstraint,
|
|
15
15
|
} from './types';
|
|
16
16
|
|
|
17
|
-
type ColumnDefaultLiteral = {
|
|
17
|
+
type ColumnDefaultLiteral = {
|
|
18
|
+
readonly kind: 'literal';
|
|
19
|
+
readonly value: string | number | boolean | Record<string, unknown> | unknown[] | null;
|
|
20
|
+
};
|
|
18
21
|
type ColumnDefaultFunction = { readonly kind: 'function'; readonly expression: string };
|
|
19
22
|
const literalKindSchema = type("'literal'");
|
|
20
23
|
const functionKindSchema = type("'function'");
|
|
@@ -23,7 +26,7 @@ const generatorIdSchema = type("'ulid' | 'nanoid' | 'uuidv7' | 'uuidv4' | 'cuid2
|
|
|
23
26
|
|
|
24
27
|
export const ColumnDefaultLiteralSchema = type.declare<ColumnDefaultLiteral>().type({
|
|
25
28
|
kind: literalKindSchema,
|
|
26
|
-
|
|
29
|
+
value: 'string | number | boolean | null | unknown[] | Record<string, unknown>',
|
|
27
30
|
});
|
|
28
31
|
|
|
29
32
|
export const ColumnDefaultFunctionSchema = type.declare<ColumnDefaultFunction>().type({
|
|
@@ -89,20 +92,26 @@ const IndexSchema = type.declare<Index>().type({
|
|
|
89
92
|
'name?': 'string',
|
|
90
93
|
});
|
|
91
94
|
|
|
92
|
-
const ForeignKeyReferencesSchema = type.declare<ForeignKeyReferences>().type({
|
|
95
|
+
export const ForeignKeyReferencesSchema = type.declare<ForeignKeyReferences>().type({
|
|
93
96
|
table: 'string',
|
|
94
97
|
columns: type.string.array().readonly(),
|
|
95
98
|
});
|
|
96
99
|
|
|
97
|
-
const
|
|
100
|
+
export const ReferentialActionSchema = type
|
|
101
|
+
.declare<ReferentialAction>()
|
|
102
|
+
.type("'noAction' | 'restrict' | 'cascade' | 'setNull' | 'setDefault'");
|
|
103
|
+
|
|
104
|
+
export const ForeignKeySchema = type.declare<ForeignKey>().type({
|
|
98
105
|
columns: type.string.array().readonly(),
|
|
99
106
|
references: ForeignKeyReferencesSchema,
|
|
100
107
|
'name?': 'string',
|
|
108
|
+
'onDelete?': ReferentialActionSchema,
|
|
109
|
+
'onUpdate?': ReferentialActionSchema,
|
|
101
110
|
constraint: 'boolean',
|
|
102
111
|
index: 'boolean',
|
|
103
112
|
});
|
|
104
113
|
|
|
105
|
-
const StorageTableSchema = type
|
|
114
|
+
const StorageTableSchema = type({
|
|
106
115
|
columns: type({ '[string]': StorageColumnSchema }),
|
|
107
116
|
'primaryKey?': PrimaryKeySchema,
|
|
108
117
|
uniques: UniqueConstraintSchema.array().readonly(),
|
|
@@ -110,7 +119,7 @@ const StorageTableSchema = type.declare<StorageTable>().type({
|
|
|
110
119
|
foreignKeys: ForeignKeySchema.array().readonly(),
|
|
111
120
|
});
|
|
112
121
|
|
|
113
|
-
const StorageSchema = type
|
|
122
|
+
const StorageSchema = type({
|
|
114
123
|
tables: type({ '[string]': StorageTableSchema }),
|
|
115
124
|
'types?': type({ '[string]': StorageTypeInstanceSchema }),
|
|
116
125
|
});
|
|
@@ -145,6 +154,13 @@ const SqlContractSchema = type({
|
|
|
145
154
|
'execution?': ExecutionSchema,
|
|
146
155
|
});
|
|
147
156
|
|
|
157
|
+
// NOTE: StorageColumnSchema, StorageTableSchema, and StorageSchema use bare type()
|
|
158
|
+
// instead of type.declare<T>().type() because the ColumnDefault union's value field
|
|
159
|
+
// includes bigint | Date (runtime-only types after decoding) which cannot be expressed
|
|
160
|
+
// in Arktype's JSON validation DSL. The `as SqlStorage` cast in validateStorage() bridges
|
|
161
|
+
// the gap between the JSON-safe Arktype output and the runtime TypeScript type.
|
|
162
|
+
// See decodeContractDefaults() in validate.ts for the decoding step.
|
|
163
|
+
|
|
148
164
|
/**
|
|
149
165
|
* Validates the structural shape of SqlStorage using Arktype.
|
|
150
166
|
*
|
|
@@ -158,7 +174,7 @@ export function validateStorage(value: unknown): SqlStorage {
|
|
|
158
174
|
const messages = result.map((p: { message: string }) => p.message).join('; ');
|
|
159
175
|
throw new Error(`Storage validation failed: ${messages}`);
|
|
160
176
|
}
|
|
161
|
-
return result;
|
|
177
|
+
return result as SqlStorage;
|
|
162
178
|
}
|
|
163
179
|
|
|
164
180
|
/**
|
|
@@ -216,3 +232,48 @@ export function validateSqlContract<T extends SqlContract<SqlStorage>>(value: un
|
|
|
216
232
|
// between Arktype's inferred type and the generic T, but runtime-wise they're compatible
|
|
217
233
|
return contractResult as T;
|
|
218
234
|
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Validates semantic constraints on SqlStorage that cannot be expressed in Arktype schemas.
|
|
238
|
+
*
|
|
239
|
+
* Returns an array of human-readable error strings. Empty array = valid.
|
|
240
|
+
*
|
|
241
|
+
* Currently checks:
|
|
242
|
+
* - `setNull` referential action on a non-nullable FK column (would fail at runtime)
|
|
243
|
+
* - `setDefault` referential action on a non-nullable FK column without a DEFAULT (would fail at runtime)
|
|
244
|
+
*/
|
|
245
|
+
export function validateStorageSemantics(storage: SqlStorage): string[] {
|
|
246
|
+
const errors: string[] = [];
|
|
247
|
+
|
|
248
|
+
for (const [tableName, table] of Object.entries(storage.tables)) {
|
|
249
|
+
for (const fk of table.foreignKeys) {
|
|
250
|
+
for (const colName of fk.columns) {
|
|
251
|
+
const column = table.columns[colName];
|
|
252
|
+
if (!column) continue;
|
|
253
|
+
|
|
254
|
+
if (fk.onDelete === 'setNull' && !column.nullable) {
|
|
255
|
+
errors.push(
|
|
256
|
+
`Table "${tableName}": onDelete setNull on foreign key column "${colName}" which is NOT NULL`,
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
if (fk.onUpdate === 'setNull' && !column.nullable) {
|
|
260
|
+
errors.push(
|
|
261
|
+
`Table "${tableName}": onUpdate setNull on foreign key column "${colName}" which is NOT NULL`,
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
if (fk.onDelete === 'setDefault' && !column.nullable && column.default === undefined) {
|
|
265
|
+
errors.push(
|
|
266
|
+
`Table "${tableName}": onDelete setDefault on foreign key column "${colName}" which is NOT NULL and has no DEFAULT`,
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
if (fk.onUpdate === 'setDefault' && !column.nullable && column.default === undefined) {
|
|
270
|
+
errors.push(
|
|
271
|
+
`Table "${tableName}": onUpdate setDefault on foreign key column "${colName}" which is NOT NULL and has no DEFAULT`,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return errors;
|
|
279
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types-DTFobApb.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;AAgBA;AAsBA;AAKA;AAKA;AAKA;AAKY,KA1CA,aAAA,GA4CW;EAQX,SAAA,UAAY,EAAA,MAAA;EACW,SAAA,OAAA,EAAA,MAAA;EAAf,SAAA,QAAA,EAAA,OAAA;EACI;;;;;EAGc,SAAA,UAAA,CAAA,EAhDd,MAgDc,CAAA,MAAA,EAAA,OAAA,CAAA;EAAd;;AAaxB;AAMA;EACkC,SAAA,OAAA,CAAA,EAAA,MAAA;EAAf;;;;EAQP,SAAA,OAAU,CAAA,EAlED,aAkEC;AAItB,CAAA;AAIY,KAvEA,UAAA,GAuEe;EACP,SAAA,OAAA,EAAA,SAAA,MAAA,EAAA;EACc,SAAA,IAAA,CAAA,EAAA,MAAA;CAAf;AACG,KArEV,gBAAA,GAqEU;EAAM,SAAA,OAAA,EAAA,SAAA,MAAA,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A;0BACc;0BACA;2BACC,eAAe;2BACf,eAAe;uBACnB;;;2BACI,eAAe;;cAG7B,qBAAA;cACA,gBAAA;;;;;iBAMG,eAAA;;;;;;;;;;KAUJ,sBACA,aAAa,sBACb,0BAA0B,mCAC1B,0BAA0B,qCACxB,cAAc,kCACL,0BAA0B,gDACxB,4BAA4B,gDAC9B,0BAA0B,2BAC7C,aAAa,cAAc,gBAAgB;;oBAE3B;mBACD;sBACG;qBACD;uBACE;;KAGX,oCAAoC,YAAY,eAC1D;KAEU,wCAAwC,YAAY,eAC9D"}
|
|
@@ -1 +0,0 @@
|
|
|
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;CACb,aAAa;CACd,CAAC,CAI2C,OAAO,CAAC,UAAU,EAC5D,EACF,CAAC;AAEF,MAAM,sBAAsB,KAAK;CAC/B,YAAY;CACZ,SAAS;CACT,UAAU;CACV,eAAe;CACf,YAAY;CACZ,YAAY;CACb,CAAC,CAAC,QAAQ,KAAK,QAAQ;AACtB,KAAI,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