@prisma-next/contract 0.11.0-dev.6 → 0.11.0-dev.61

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.
Files changed (45) hide show
  1. package/dist/canonicalization-C3dTO0j1.d.mts +69 -0
  2. package/dist/canonicalization-C3dTO0j1.d.mts.map +1 -0
  3. package/dist/{contract-types-Bt2uyqs3.d.mts → contract-types-CZPm4Ooy.d.mts} +27 -6
  4. package/dist/contract-types-CZPm4Ooy.d.mts.map +1 -0
  5. package/dist/contract-validation-error-Dp2vHZt5.mjs.map +1 -1
  6. package/dist/cross-reference-t0TDbBTP.d.mts +18 -0
  7. package/dist/cross-reference-t0TDbBTP.d.mts.map +1 -0
  8. package/dist/{hashing-rZiqFOlc.mjs → hashing-C25nwocN.mjs} +23 -76
  9. package/dist/hashing-C25nwocN.mjs.map +1 -0
  10. package/dist/hashing-utils.d.mts +19 -0
  11. package/dist/hashing-utils.d.mts.map +1 -0
  12. package/dist/hashing-utils.mjs +71 -0
  13. package/dist/hashing-utils.mjs.map +1 -0
  14. package/dist/hashing.d.mts +8 -37
  15. package/dist/hashing.d.mts.map +1 -1
  16. package/dist/hashing.mjs +1 -1
  17. package/dist/testing.d.mts +6 -2
  18. package/dist/testing.d.mts.map +1 -1
  19. package/dist/testing.mjs +4 -2
  20. package/dist/testing.mjs.map +1 -1
  21. package/dist/types-CVGwkRLa.mjs.map +1 -1
  22. package/dist/types.d.mts +3 -2
  23. package/dist/types.mjs +24 -1
  24. package/dist/types.mjs.map +1 -0
  25. package/dist/validate-domain.d.mts +5 -3
  26. package/dist/validate-domain.d.mts.map +1 -1
  27. package/dist/validate-domain.mjs +16 -10
  28. package/dist/validate-domain.mjs.map +1 -1
  29. package/package.json +6 -5
  30. package/src/canonicalization-path-match.ts +44 -0
  31. package/src/canonicalization-storage-sort.ts +88 -0
  32. package/src/canonicalization.ts +57 -142
  33. package/src/contract-types.ts +2 -1
  34. package/src/cross-reference.ts +28 -0
  35. package/src/domain-types.ts +5 -3
  36. package/src/exports/hashing-utils.ts +12 -0
  37. package/src/exports/hashing.ts +2 -0
  38. package/src/exports/types.ts +6 -0
  39. package/src/hashing.ts +27 -10
  40. package/src/namespace-id.ts +10 -0
  41. package/src/testing-factories.ts +7 -1
  42. package/src/types.ts +21 -0
  43. package/src/validate-domain.ts +23 -16
  44. package/dist/contract-types-Bt2uyqs3.d.mts.map +0 -1
  45. package/dist/hashing-rZiqFOlc.mjs.map +0 -1
@@ -14,6 +14,25 @@ import type { Contract } from './contract-types';
14
14
  */
15
15
  export type SerializeContract = (contract: Contract) => JsonObject;
16
16
 
17
+ /**
18
+ * Family-contributed predicate for the default-omission walk. Called when
19
+ * a value at `path` is a default (empty object/array or `false`); if this
20
+ * returns `true` the value is kept rather than stripped.
21
+ *
22
+ * The framework only calls the predicate inside the `isDefaultValue` branch,
23
+ * so there is no need to guard against non-default values.
24
+ */
25
+ export type PreserveEmptyPredicate = (path: readonly string[]) => boolean;
26
+
27
+ /**
28
+ * Family-contributed storage sort. Applied to the serialized `storage`
29
+ * subtree after the default-omission walk; the result replaces the
30
+ * `storage` field before the final key sort. Use to establish a
31
+ * deterministic order for storage arrays (indexes, uniques) that the
32
+ * family-agnostic `sortObjectKeys` pass cannot handle.
33
+ */
34
+ export type StorageSort = (storage: unknown) => unknown;
35
+
17
36
  const TOP_LEVEL_ORDER = [
18
37
  'schemaVersion',
19
38
  'canonicalVersion',
@@ -42,13 +61,17 @@ function isDefaultValue(value: unknown): boolean {
42
61
  return false;
43
62
  }
44
63
 
45
- function omitDefaults(obj: unknown, path: readonly string[]): unknown {
64
+ function omitDefaults(
65
+ obj: unknown,
66
+ path: readonly string[],
67
+ shouldPreserveEmpty: PreserveEmptyPredicate | undefined,
68
+ ): unknown {
46
69
  if (obj === null || typeof obj !== 'object') {
47
70
  return obj;
48
71
  }
49
72
 
50
73
  if (Array.isArray(obj)) {
51
- return obj.map((item) => omitDefaults(item, path));
74
+ return obj.map((item) => omitDefaults(item, path, shouldPreserveEmpty));
52
75
  }
53
76
 
54
77
  const result: Record<string, unknown> = {};
@@ -74,20 +97,6 @@ function omitDefaults(obj: unknown, path: readonly string[]): unknown {
74
97
  const isNamespaceSlot =
75
98
  currentPath.length === 3 &&
76
99
  isArrayEqual([currentPath[0], currentPath[1]], ['storage', 'namespaces']);
77
- const isRequiredNamespaceTables =
78
- currentPath.length === 4 &&
79
- currentPath[0] === 'storage' &&
80
- currentPath[1] === 'namespaces' &&
81
- currentPath[3] === 'tables';
82
- // Preserve per-table payloads even when empty. SQL tables are never
83
- // emitted empty; Mongo collections legitimately are (a declared
84
- // collection with no schema is a valid representation), and the
85
- // family-agnostic canonicalizer must not strip them.
86
- const isNamespaceTableEntry =
87
- currentPath.length === 5 &&
88
- currentPath[0] === 'storage' &&
89
- currentPath[1] === 'namespaces' &&
90
- currentPath[3] === 'tables';
91
100
  const isRequiredRoots = isArrayEqual(currentPath, ['roots']);
92
101
  const isRequiredExtensionPacks = isArrayEqual(currentPath, ['extensionPacks']);
93
102
  const isRequiredCapabilities = isArrayEqual(currentPath, ['capabilities']);
@@ -104,50 +113,21 @@ function omitDefaults(obj: unknown, path: readonly string[]): unknown {
104
113
  const isModelStorage =
105
114
  currentPath.length === 3 &&
106
115
  isArrayEqual([currentPath[0], currentPath[2]], ['models', 'storage']);
107
- const isNamespaceTableUniques =
108
- currentPath.length === 6 &&
109
- currentPath[0] === 'storage' &&
110
- currentPath[1] === 'namespaces' &&
111
- currentPath[3] === 'tables' &&
112
- currentPath[5] === 'uniques';
113
- const isNamespaceTableIndexes =
114
- currentPath.length === 6 &&
115
- currentPath[0] === 'storage' &&
116
- currentPath[1] === 'namespaces' &&
117
- currentPath[3] === 'tables' &&
118
- currentPath[5] === 'indexes';
119
- const isNamespaceTableForeignKeys =
120
- currentPath.length === 6 &&
121
- currentPath[0] === 'storage' &&
122
- currentPath[1] === 'namespaces' &&
123
- currentPath[3] === 'tables' &&
124
- currentPath[5] === 'foreignKeys';
125
116
 
126
- // `storage.types.<name>.typeParams` is part of the StorageTypeInstance
127
- // shape (validators require it). Preserve it even when empty so the
128
- // emitted contract.json remains structurally valid after a round-trip.
129
- const isStorageTypeTypeParams =
130
- currentPath.length === 4 &&
131
- currentPath[0] === 'storage' &&
132
- currentPath[1] === 'types' &&
117
+ const isDomainUnboundTypeParams =
118
+ currentPath.length === 5 &&
119
+ currentPath[0] === 'domain' &&
120
+ currentPath[2] === 'types' &&
133
121
  key === 'typeParams';
134
122
 
135
- const isFkBooleanField =
136
- currentPath.length === 7 &&
137
- currentPath[0] === 'storage' &&
138
- currentPath[1] === 'namespaces' &&
139
- currentPath[3] === 'tables' &&
140
- currentPath[5] === 'foreignKeys' &&
141
- (key === 'constraint' || key === 'index');
142
-
143
123
  const isNullableField = key === 'nullable';
144
124
 
125
+ const isFamilyPreserved = shouldPreserveEmpty?.(currentPath) ?? false;
126
+
145
127
  if (
146
128
  !isRequiredModels &&
147
129
  !isRequiredNamespaces &&
148
130
  !isNamespaceSlot &&
149
- !isRequiredNamespaceTables &&
150
- !isNamespaceTableEntry &&
151
131
  !isRequiredRoots &&
152
132
  !isRequiredExtensionPacks &&
153
133
  !isRequiredCapabilities &&
@@ -156,18 +136,15 @@ function omitDefaults(obj: unknown, path: readonly string[]): unknown {
156
136
  !isExtensionNamespace &&
157
137
  !isModelRelations &&
158
138
  !isModelStorage &&
159
- !isNamespaceTableUniques &&
160
- !isNamespaceTableIndexes &&
161
- !isNamespaceTableForeignKeys &&
162
- !isFkBooleanField &&
163
139
  !isNullableField &&
164
- !isStorageTypeTypeParams
140
+ !isDomainUnboundTypeParams &&
141
+ !isFamilyPreserved
165
142
  ) {
166
143
  continue;
167
144
  }
168
145
  }
169
146
 
170
- result[key] = omitDefaults(value, currentPath);
147
+ result[key] = omitDefaults(value, currentPath, shouldPreserveEmpty);
171
148
  }
172
149
 
173
150
  return result;
@@ -191,88 +168,6 @@ function sortObjectKeys(obj: unknown): unknown {
191
168
  return sorted;
192
169
  }
193
170
 
194
- type NamespaceObject = {
195
- tables?: Record<string, unknown>;
196
- [key: string]: unknown;
197
- };
198
-
199
- type StorageObject = {
200
- namespaces?: Record<string, unknown>;
201
- [key: string]: unknown;
202
- };
203
-
204
- type TableObject = {
205
- indexes?: unknown[];
206
- uniques?: unknown[];
207
- [key: string]: unknown;
208
- };
209
-
210
- function sortTableArrays(tableObj: TableObject): TableObject {
211
- const sortedTable: TableObject = { ...tableObj };
212
-
213
- if (Array.isArray(tableObj.indexes)) {
214
- sortedTable.indexes = [...tableObj.indexes].sort((a, b) => {
215
- const nameA = (a as { name?: string })?.name || '';
216
- const nameB = (b as { name?: string })?.name || '';
217
- return nameA.localeCompare(nameB);
218
- });
219
- }
220
-
221
- if (Array.isArray(tableObj.uniques)) {
222
- sortedTable.uniques = [...tableObj.uniques].sort((a, b) => {
223
- const nameA = (a as { name?: string })?.name || '';
224
- const nameB = (b as { name?: string })?.name || '';
225
- return nameA.localeCompare(nameB);
226
- });
227
- }
228
-
229
- return sortedTable;
230
- }
231
-
232
- function sortIndexesAndUniques(storage: unknown): unknown {
233
- if (!storage || typeof storage !== 'object') {
234
- return storage;
235
- }
236
-
237
- const storageObj = storage as StorageObject;
238
- if (!storageObj.namespaces || typeof storageObj.namespaces !== 'object') {
239
- return storage;
240
- }
241
-
242
- const namespaces = storageObj.namespaces;
243
- const result: StorageObject = { ...storageObj, namespaces: {} };
244
- const resultNamespaces = result.namespaces as Record<string, unknown>;
245
-
246
- for (const nsId of Object.keys(namespaces)) {
247
- const ns = namespaces[nsId];
248
- if (!ns || typeof ns !== 'object') {
249
- resultNamespaces[nsId] = ns;
250
- continue;
251
- }
252
-
253
- const nsObj = ns as NamespaceObject;
254
- if (!nsObj.tables || typeof nsObj.tables !== 'object') {
255
- resultNamespaces[nsId] = ns;
256
- continue;
257
- }
258
-
259
- const sortedTables: Record<string, unknown> = {};
260
- const sortedTableNames = Object.keys(nsObj.tables).sort();
261
- for (const tableName of sortedTableNames) {
262
- const table = nsObj.tables[tableName];
263
- if (!table || typeof table !== 'object') {
264
- sortedTables[tableName] = table;
265
- continue;
266
- }
267
- sortedTables[tableName] = sortTableArrays(table as TableObject);
268
- }
269
-
270
- resultNamespaces[nsId] = { ...nsObj, tables: sortedTables };
271
- }
272
-
273
- return result;
274
- }
275
-
276
171
  export function orderTopLevel(obj: Record<string, unknown>): Record<string, unknown> {
277
172
  const ordered: Record<string, unknown> = {};
278
173
  const remaining = new Set(Object.keys(obj));
@@ -304,6 +199,21 @@ export interface CanonicalizeContractOptions {
304
199
  * the per-target serializer not putting them in the JSON shape.
305
200
  */
306
201
  readonly serializeContract: SerializeContract;
202
+ /**
203
+ * Family-contributed preserve-empty predicate. When the walk encounters a
204
+ * default value (empty object/array or `false`) at `path`, calling this
205
+ * with the full path allows the family to veto the omission. If absent,
206
+ * only the framework's family-agnostic required-slot rules apply.
207
+ */
208
+ readonly shouldPreserveEmpty?: PreserveEmptyPredicate;
209
+ /**
210
+ * Family-contributed storage sort. Applied to the serialized `storage`
211
+ * subtree after the default-omission walk, before the final key sort.
212
+ * SQL family uses this to impose a deterministic order on `indexes` and
213
+ * `uniques` arrays within each namespace table. Families that require no
214
+ * special storage ordering omit this hook.
215
+ */
216
+ readonly sortStorage?: StorageSort;
307
217
  }
308
218
 
309
219
  /**
@@ -324,15 +234,20 @@ export function canonicalizeContractToObject(
324
234
  roots: serialized['roots'],
325
235
  models: serialized['models'],
326
236
  ...ifDefined('valueObjects', serialized['valueObjects']),
237
+ ...ifDefined('domain', serialized['domain']),
327
238
  storage: serialized['storage'],
328
239
  ...ifDefined('execution', serialized['execution']),
329
240
  extensionPacks: serialized['extensionPacks'],
330
241
  capabilities: serialized['capabilities'],
331
242
  meta: serialized['meta'],
332
243
  };
333
- const withDefaultsOmitted = omitDefaults(normalized, []) as Record<string, unknown>;
334
- const withSortedIndexes = sortIndexesAndUniques(withDefaultsOmitted['storage']);
335
- const withSortedStorage = { ...withDefaultsOmitted, storage: withSortedIndexes };
244
+ const withDefaultsOmitted = omitDefaults(normalized, [], options.shouldPreserveEmpty) as Record<
245
+ string,
246
+ unknown
247
+ >;
248
+ const withSortedStorage = options.sortStorage
249
+ ? { ...withDefaultsOmitted, storage: options.sortStorage(withDefaultsOmitted['storage']) }
250
+ : withDefaultsOmitted;
336
251
  const withSortedKeys = sortObjectKeys(withSortedStorage) as Record<string, unknown>;
337
252
  return orderTopLevel(withSortedKeys);
338
253
  }
@@ -1,3 +1,4 @@
1
+ import type { CrossReference } from './cross-reference';
1
2
  import type { ContractModelBase, ContractValueObject } from './domain-types';
2
3
  import type {
3
4
  ExecutionHashBase,
@@ -43,7 +44,7 @@ export interface Contract<
43
44
  > {
44
45
  readonly target: string;
45
46
  readonly targetFamily: string;
46
- readonly roots: Record<string, string>;
47
+ readonly roots: Record<string, CrossReference>;
47
48
  readonly models: TModels;
48
49
  readonly valueObjects?: Record<string, ContractValueObject>;
49
50
  /**
@@ -0,0 +1,28 @@
1
+ import { blindCast } from '@prisma-next/utils/casts';
2
+ import { type Type, type } from 'arktype';
3
+ import { asNamespaceId, type NamespaceId } from './namespace-id';
4
+
5
+ export interface CrossReference {
6
+ readonly namespace: NamespaceId;
7
+ readonly model: string;
8
+ }
9
+
10
+ export const CrossReferenceSchema = blindCast<
11
+ Type<CrossReference>,
12
+ 'namespace is validated as string at runtime and branded to NamespaceId by asNamespaceId in crossRef(); the schema accepts plain strings but the public type reflects the branded shape'
13
+ >(
14
+ type({
15
+ '+': 'reject',
16
+ namespace: 'string',
17
+ model: 'string',
18
+ }),
19
+ );
20
+
21
+ const DEFAULT_CROSS_REF_NAMESPACE = '__unbound__';
22
+
23
+ export function crossRef(
24
+ model: string,
25
+ namespace: string = DEFAULT_CROSS_REF_NAMESPACE,
26
+ ): CrossReference {
27
+ return { namespace: asNamespaceId(namespace), model };
28
+ }
@@ -1,3 +1,5 @@
1
+ import type { CrossReference } from './cross-reference';
2
+
1
3
  export type ScalarFieldType = {
2
4
  readonly kind: 'scalar';
3
5
  readonly codecId: string;
@@ -29,13 +31,13 @@ export type ContractRelationOn = {
29
31
  };
30
32
 
31
33
  export type ContractReferenceRelation = {
32
- readonly to: string;
34
+ readonly to: CrossReference;
33
35
  readonly cardinality: '1:1' | '1:N' | 'N:1';
34
36
  readonly on: ContractRelationOn;
35
37
  };
36
38
 
37
39
  export type ContractEmbedRelation = {
38
- readonly to: string;
40
+ readonly to: CrossReference;
39
41
  readonly cardinality: '1:1' | '1:N';
40
42
  };
41
43
 
@@ -61,7 +63,7 @@ export interface ContractModelBase<TModelStorage extends ModelStorageBase = Mode
61
63
  readonly storage: TModelStorage;
62
64
  readonly discriminator?: ContractDiscriminator;
63
65
  readonly variants?: Record<string, ContractVariantEntry>;
64
- readonly base?: string;
66
+ readonly base?: CrossReference;
65
67
  readonly owner?: string;
66
68
  }
67
69
 
@@ -0,0 +1,12 @@
1
+ export {
2
+ createPreserveEmptyPredicate,
3
+ matchesPathPattern,
4
+ type PathPattern,
5
+ type PathSegment as PreserveEmptyPathSegment,
6
+ } from '../canonicalization-path-match';
7
+ export {
8
+ compareByNameProperty,
9
+ createStorageSort,
10
+ type NamedArraySortTarget,
11
+ type PathSegment as StorageSortPathSegment,
12
+ } from '../canonicalization-storage-sort';
@@ -2,6 +2,8 @@ export {
2
2
  type CanonicalizeContractOptions,
3
3
  canonicalizeContract,
4
4
  canonicalizeContractToObject,
5
+ type PreserveEmptyPredicate,
5
6
  type SerializeContract,
7
+ type StorageSort,
6
8
  } from '../canonicalization';
7
9
  export { computeExecutionHash, computeProfileHash, computeStorageHash } from '../hashing';
@@ -1,4 +1,6 @@
1
1
  export type { Contract, ContractExecutionSection } from '../contract-types';
2
+ export type { CrossReference } from '../cross-reference';
3
+ export { CrossReferenceSchema, crossRef } from '../cross-reference';
2
4
  export type {
3
5
  ContractDiscriminator,
4
6
  ContractEmbedRelation,
@@ -18,6 +20,8 @@ export type {
18
20
  UnionFieldType,
19
21
  ValueObjectFieldType,
20
22
  } from '../domain-types';
23
+ export type { NamespaceId } from '../namespace-id';
24
+ export { asNamespaceId } from '../namespace-id';
21
25
  export type {
22
26
  $,
23
27
  Brand,
@@ -41,7 +45,9 @@ export type {
41
45
  ProfileHashBase,
42
46
  Source,
43
47
  StorageBase,
48
+ StorageEntitySlot,
44
49
  StorageHashBase,
50
+ StorageNamespace,
45
51
  } from '../types';
46
52
  export {
47
53
  coreHash,
package/src/hashing.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { ifDefined } from '@prisma-next/utils/defined';
2
3
  import type { JsonObject } from '@prisma-next/utils/json';
3
- import { canonicalizeContract } from './canonicalization';
4
+ import {
5
+ canonicalizeContract,
6
+ type PreserveEmptyPredicate,
7
+ type StorageSort,
8
+ } from './canonicalization';
4
9
  import type { Contract } from './contract-types';
5
10
  import type { ExecutionHashBase, ProfileHashBase, StorageHashBase } from './types';
6
11
 
@@ -12,7 +17,13 @@ function sha256(content: string): string {
12
17
  return `sha256:${hash.digest('hex')}`;
13
18
  }
14
19
 
15
- function hashContract(section: Record<string, unknown>): string {
20
+ type HashContractSection = Record<string, unknown> & {
21
+ readonly shouldPreserveEmpty?: PreserveEmptyPredicate;
22
+ readonly sortStorage?: StorageSort;
23
+ };
24
+
25
+ function hashContract(section: HashContractSection): string {
26
+ const { shouldPreserveEmpty, sortStorage, ...sectionData } = section;
16
27
  // Blind cast: the synthesised object is a hash-only stand-in
17
28
  // — never returned to callers, never executed as a Contract.
18
29
  // `canonicalizeContract` only walks the storage / execution /
@@ -20,29 +31,35 @@ function hashContract(section: Record<string, unknown>): string {
20
31
  // missing precise Contract typing on the other slots is
21
32
  // immaterial for the hash result.
22
33
  const contract = {
23
- targetFamily: section['targetFamily'],
24
- target: section['target'],
34
+ targetFamily: sectionData['targetFamily'],
35
+ target: sectionData['target'],
25
36
  roots: {},
26
37
  models: {},
27
- storage: section['storage'] ?? {},
28
- execution: section['execution'],
38
+ storage: sectionData['storage'] ?? {},
39
+ execution: sectionData['execution'],
29
40
  extensionPacks: {},
30
- capabilities: section['capabilities'] ?? {},
41
+ capabilities: sectionData['capabilities'] ?? {},
31
42
  meta: {},
32
43
  profileHash: '',
33
- ...section,
44
+ ...sectionData,
34
45
  } as unknown as Contract;
35
46
  return canonicalizeContract(contract, {
36
47
  schemaVersion: SCHEMA_VERSION,
37
48
  serializeContract: (c) => JSON.parse(JSON.stringify(c)) as JsonObject,
49
+ ...ifDefined('shouldPreserveEmpty', shouldPreserveEmpty),
50
+ ...ifDefined('sortStorage', sortStorage),
38
51
  });
39
52
  }
40
53
 
41
- export function computeStorageHash(args: {
54
+ export type ComputeStorageHashArgs = {
42
55
  target: string;
43
56
  targetFamily: string;
44
57
  storage: Record<string, unknown>;
45
- }): StorageHashBase<string> {
58
+ readonly shouldPreserveEmpty?: PreserveEmptyPredicate;
59
+ readonly sortStorage?: StorageSort;
60
+ };
61
+
62
+ export function computeStorageHash(args: ComputeStorageHashArgs): StorageHashBase<string> {
46
63
  return sha256(hashContract(args)) as StorageHashBase<string>;
47
64
  }
48
65
 
@@ -0,0 +1,10 @@
1
+ import { blindCast } from '@prisma-next/utils/casts';
2
+
3
+ export type NamespaceId = string & { readonly __brand: 'NamespaceId' };
4
+
5
+ export function asNamespaceId(value: string): NamespaceId {
6
+ return blindCast<
7
+ NamespaceId,
8
+ 'NamespaceId is a compile-time-only brand on string; this factory is the sole assertion site'
9
+ >(value);
10
+ }
@@ -1,5 +1,7 @@
1
1
  import { ifDefined } from '@prisma-next/utils/defined';
2
+ import type { PreserveEmptyPredicate, StorageSort } from './canonicalization';
2
3
  import type { Contract } from './contract-types';
4
+ import type { CrossReference } from './cross-reference';
3
5
  import type {
4
6
  ContractModel,
5
7
  ContractModelBase,
@@ -16,7 +18,7 @@ type ContractOverrides<
16
18
  > = {
17
19
  target?: string;
18
20
  targetFamily?: string;
19
- roots?: Record<string, string>;
21
+ roots?: Record<string, CrossReference>;
20
22
  models?: TModels;
21
23
  storage?: Omit<TStorage, 'storageHash'>;
22
24
  valueObjects?: Record<string, ContractValueObject>;
@@ -25,6 +27,8 @@ type ContractOverrides<
25
27
  execution?: Omit<ExecutionSection, 'executionHash'>;
26
28
  profileHash?: ProfileHashBase<string>;
27
29
  meta?: Record<string, unknown>;
30
+ shouldPreserveEmpty?: PreserveEmptyPredicate;
31
+ sortStorage?: StorageSort;
28
32
  };
29
33
 
30
34
  const DUMMY_HASH = coreHash('sha256:test');
@@ -56,6 +60,8 @@ export function createContract<
56
60
  target,
57
61
  targetFamily,
58
62
  storage: rawStorage as Record<string, unknown>,
63
+ ...ifDefined('shouldPreserveEmpty', overrides.shouldPreserveEmpty),
64
+ ...ifDefined('sortStorage', overrides.sortStorage),
59
65
  });
60
66
 
61
67
  const storage = {
package/src/types.ts CHANGED
@@ -48,13 +48,34 @@ export function profileHash<const T extends string>(value: T): ProfileHashBase<T
48
48
  return value as ProfileHashBase<T>;
49
49
  }
50
50
 
51
+ /**
52
+ * One entity-kind slot in a namespace — a map of entity name to entry.
53
+ * Values are opaque at the foundation layer; family and target concretions
54
+ * refine them to typed IR classes.
55
+ */
56
+ export type StorageEntitySlot = Readonly<Record<string, unknown>>;
57
+
58
+ /**
59
+ * Plain-data namespace entry in a storage block. Every hydrated contract
60
+ * carries at least `id` plus zero or more entity-kind slot maps (`tables`,
61
+ * `collections`, …). Foundation declares only this shape — no IR machinery.
62
+ */
63
+ export interface StorageNamespace {
64
+ readonly id: string;
65
+ }
66
+
51
67
  /**
52
68
  * Base type for family-specific storage blocks.
53
69
  * Family storage types (SqlStorage, MongoStorage, etc.) extend this to carry the
54
70
  * storage hash alongside family-specific data (tables, collections, etc.).
71
+ *
72
+ * The `namespaces` map is carried by every hydrated storage block. Serialized
73
+ * envelope shape is target-owned; this types the in-memory contract after
74
+ * `deserializeContract`.
55
75
  */
56
76
  export interface StorageBase<THash extends string = string> {
57
77
  readonly storageHash: StorageHashBase<THash>;
78
+ readonly namespaces: Readonly<Record<string, StorageNamespace>>;
58
79
  }
59
80
 
60
81
  export interface FieldType {
@@ -1,16 +1,17 @@
1
1
  import { ContractValidationError } from './contract-validation-error';
2
+ import type { CrossReference } from './cross-reference';
2
3
 
3
4
  export interface DomainModelShape {
4
5
  readonly fields: Record<string, unknown>;
5
- readonly relations?: Record<string, { readonly to: string }>;
6
+ readonly relations?: Record<string, { readonly to: CrossReference }>;
6
7
  readonly discriminator?: { readonly field: string };
7
8
  readonly variants?: Record<string, unknown>;
8
- readonly base?: string;
9
+ readonly base?: CrossReference;
9
10
  readonly owner?: string;
10
11
  }
11
12
 
12
13
  export interface DomainContractShape {
13
- readonly roots: Record<string, string>;
14
+ readonly roots: Record<string, CrossReference>;
14
15
  readonly models: Record<string, DomainModelShape>;
15
16
  readonly valueObjects?: Record<string, { readonly fields: Record<string, unknown> }>;
16
17
  }
@@ -41,11 +42,13 @@ function validateRoots(
41
42
  errors: string[],
42
43
  ): void {
43
44
  const seenValues = new Set<string>();
44
- for (const [rootKey, modelName] of Object.entries(contract.roots)) {
45
- if (seenValues.has(modelName)) {
45
+ for (const [rootKey, crossRef] of Object.entries(contract.roots)) {
46
+ const modelName = crossRef.model;
47
+ const dedupeKey = `${crossRef.namespace}:${modelName}`;
48
+ if (seenValues.has(dedupeKey)) {
46
49
  errors.push(`Duplicate root value: "${modelName}" is mapped by multiple root keys`);
47
50
  }
48
- seenValues.add(modelName);
51
+ seenValues.add(dedupeKey);
49
52
 
50
53
  if (!modelNames.has(modelName)) {
51
54
  errors.push(
@@ -73,24 +76,27 @@ function validateVariantsAndBases(
73
76
  }
74
77
  const variantModel = models.get(variantName);
75
78
  if (!variantModel) continue;
76
- if (variantModel.base !== modelName) {
79
+ if (variantModel.base?.model !== modelName) {
77
80
  errors.push(
78
- `Variant "${variantName}" has base "${variantModel.base ?? '(none)'}" but expected "${modelName}"`,
81
+ `Variant "${variantName}" has base "${variantModel.base?.model ?? '(none)'}" but expected "${modelName}"`,
79
82
  );
80
83
  }
81
84
  }
82
85
  }
83
86
 
84
87
  if (model.base) {
85
- if (!modelNames.has(model.base)) {
86
- errors.push(`Model "${modelName}" has base "${model.base}" which does not exist in models`);
88
+ const baseModelName = model.base.model;
89
+ if (!modelNames.has(baseModelName)) {
90
+ errors.push(
91
+ `Model "${modelName}" has base "${baseModelName}" which does not exist in models`,
92
+ );
87
93
  continue;
88
94
  }
89
- const baseModel = models.get(model.base);
95
+ const baseModel = models.get(baseModelName);
90
96
  if (!baseModel) continue;
91
97
  if (!baseModel.variants || !Object.hasOwn(baseModel.variants, modelName)) {
92
98
  errors.push(
93
- `Model "${modelName}" has base "${model.base}" which does not list it as a variant`,
99
+ `Model "${modelName}" has base "${baseModelName}" which does not list it as a variant`,
94
100
  );
95
101
  }
96
102
  }
@@ -104,9 +110,10 @@ function validateRelationTargets(
104
110
  ): void {
105
111
  for (const [modelName, model] of Object.entries(contract.models)) {
106
112
  for (const [relName, relation] of Object.entries(model.relations ?? {})) {
107
- if (!modelNames.has(relation.to)) {
113
+ const targetModelName = relation.to.model;
114
+ if (!modelNames.has(targetModelName)) {
108
115
  errors.push(
109
- `Relation "${relName}" on model "${modelName}" targets "${relation.to}" which does not exist in models`,
116
+ `Relation "${relName}" on model "${modelName}" targets "${targetModelName}" which does not exist in models`,
110
117
  );
111
118
  }
112
119
  }
@@ -157,8 +164,8 @@ function validateOwnership(
157
164
  errors.push(`Model "${modelName}" has owner "${model.owner}" which does not exist in models`);
158
165
  }
159
166
 
160
- for (const [rootKey, rootModel] of Object.entries(contract.roots)) {
161
- if (rootModel === modelName) {
167
+ for (const [rootKey, rootRef] of Object.entries(contract.roots)) {
168
+ if (rootRef.model === modelName) {
162
169
  errors.push(
163
170
  `Owned model "${modelName}" must not appear in roots (found as root "${rootKey}")`,
164
171
  );
@@ -1 +0,0 @@
1
- {"version":3,"file":"contract-types-Bt2uyqs3.d.mts","names":[],"sources":["../src/domain-types.ts","../src/types.ts","../src/contract-types.ts"],"mappings":";KAAY,eAAA;EAAA,SACD,IAAA;EAAA,SACA,OAAA;EAAA,SACA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