@prisma-next/contract 0.12.0-dev.23 → 0.12.0-dev.25
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/dist/hashing.d.mts.map +1 -1
- package/dist/hashing.mjs +27 -8
- package/dist/hashing.mjs.map +1 -1
- package/package.json +4 -4
- package/src/hashing.ts +42 -13
package/dist/hashing.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hashing.d.mts","names":[],"sources":["../src/hashing.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"hashing.d.mts","names":[],"sources":["../src/hashing.ts"],"mappings":";;;;KA4EY,sBAAA;EACV,MAAA;EACA,YAAA;EACA,OAAA,EAAS,MAAA;EAAA,SACA,mBAAA,GAAsB,sBAAA;EAAA,SACtB,WAAA,GAAc,WAAA;AAAA;AAAA,iBAGT,kBAAA,CAAmB,IAAA,EAAM,sBAAA,GAAyB,eAAe;AAAA,iBAMjE,oBAAA,CAAqB,IAAA;EACnC,MAAA;EACA,YAAA;EACA,SAAA,EAAW,MAAA;AAAA,IACT,iBAAiB;AAAA,iBAML,kBAAA,CAAmB,IAAA;EACjC,MAAA;EACA,YAAA;EACA,YAAA,EAAc,MAAA,SAAe,MAAA;AAAA,IAC3B,eAAA"}
|
package/dist/hashing.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { n as matchesPathPattern } from "./canonicalization-path-match-Czn4Vds5.mjs";
|
|
2
|
+
import { blindCast, castAs } from "@prisma-next/utils/casts";
|
|
2
3
|
import { isArrayEqual } from "@prisma-next/utils/array-equal";
|
|
3
4
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
4
5
|
import { createHash } from "node:crypto";
|
|
@@ -135,6 +136,23 @@ function canonicalizeContract(contract, options) {
|
|
|
135
136
|
//#endregion
|
|
136
137
|
//#region src/hashing.ts
|
|
137
138
|
const SCHEMA_VERSION = "1";
|
|
139
|
+
function isPlainRecord(value) {
|
|
140
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
141
|
+
}
|
|
142
|
+
function omitNamespaceKindsForHash(storage) {
|
|
143
|
+
if (!isPlainRecord(storage)) return storage;
|
|
144
|
+
const namespaces = storage["namespaces"];
|
|
145
|
+
if (!isPlainRecord(namespaces)) return storage;
|
|
146
|
+
const stripped = {};
|
|
147
|
+
for (const [nsId, ns] of Object.entries(namespaces)) if (isPlainRecord(ns)) {
|
|
148
|
+
const { kind: _kind, ...rest } = ns;
|
|
149
|
+
stripped[nsId] = rest;
|
|
150
|
+
} else stripped[nsId] = ns;
|
|
151
|
+
return {
|
|
152
|
+
...storage,
|
|
153
|
+
namespaces: stripped
|
|
154
|
+
};
|
|
155
|
+
}
|
|
138
156
|
function sha256(content) {
|
|
139
157
|
const hash = createHash("sha256");
|
|
140
158
|
hash.update(content);
|
|
@@ -142,33 +160,34 @@ function sha256(content) {
|
|
|
142
160
|
}
|
|
143
161
|
function hashContract(section) {
|
|
144
162
|
const { shouldPreserveEmpty, sortStorage, ...sectionData } = section;
|
|
145
|
-
|
|
163
|
+
const storageForHash = omitNamespaceKindsForHash(sectionData["storage"] ?? {});
|
|
164
|
+
return canonicalizeContract(blindCast({
|
|
146
165
|
targetFamily: sectionData["targetFamily"],
|
|
147
166
|
target: sectionData["target"],
|
|
148
167
|
roots: {},
|
|
149
168
|
domain: { namespaces: {} },
|
|
150
|
-
storage: sectionData["storage"] ?? {},
|
|
151
169
|
execution: sectionData["execution"],
|
|
152
170
|
extensionPacks: {},
|
|
153
171
|
capabilities: sectionData["capabilities"] ?? {},
|
|
154
172
|
meta: {},
|
|
155
173
|
profileHash: "",
|
|
156
|
-
...sectionData
|
|
157
|
-
|
|
174
|
+
...sectionData,
|
|
175
|
+
storage: storageForHash
|
|
176
|
+
}), {
|
|
158
177
|
schemaVersion: SCHEMA_VERSION,
|
|
159
|
-
serializeContract: (c) => JSON.parse(JSON.stringify(c)),
|
|
178
|
+
serializeContract: (c) => castAs(JSON.parse(JSON.stringify(c))),
|
|
160
179
|
...ifDefined("shouldPreserveEmpty", shouldPreserveEmpty),
|
|
161
180
|
...ifDefined("sortStorage", sortStorage)
|
|
162
181
|
});
|
|
163
182
|
}
|
|
164
183
|
function computeStorageHash(args) {
|
|
165
|
-
return sha256(hashContract(args));
|
|
184
|
+
return blindCast(sha256(hashContract(args)));
|
|
166
185
|
}
|
|
167
186
|
function computeExecutionHash(args) {
|
|
168
|
-
return sha256(hashContract(args));
|
|
187
|
+
return blindCast(sha256(hashContract(args)));
|
|
169
188
|
}
|
|
170
189
|
function computeProfileHash(args) {
|
|
171
|
-
return sha256(hashContract(args));
|
|
190
|
+
return blindCast(sha256(hashContract(args)));
|
|
172
191
|
}
|
|
173
192
|
//#endregion
|
|
174
193
|
export { canonicalizeContract, canonicalizeContractToObject, computeExecutionHash, computeProfileHash, computeStorageHash };
|
package/dist/hashing.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hashing.mjs","names":[],"sources":["../src/canonicalization.ts","../src/hashing.ts"],"sourcesContent":["import { isArrayEqual } from '@prisma-next/utils/array-equal';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport { matchesPathPattern, type PathPattern } from './canonicalization-path-match';\nimport type { Contract } from './contract-types';\n\n/**\n * Per-target contract serializer hook. The framework canonicalizer uses\n * this to convert an in-memory contract (which may carry class-instance\n * IR nodes whose runtime-only fields must not appear in the on-disk\n * envelope) into a plain JsonObject before applying the family-agnostic\n * canonical-key ordering / default-omission / sort steps. Targets whose\n * contract is JSON-clean by construction return the contract unchanged.\n */\nexport type SerializeContract = (contract: Contract) => JsonObject;\n\n/**\n * Family-contributed predicate for the default-omission walk. Called when\n * a value at `path` is a default (empty object/array or `false`); if this\n * returns `true` the value is kept rather than stripped.\n *\n * The framework only calls the predicate inside the `isDefaultValue` branch,\n * so there is no need to guard against non-default values.\n */\nexport type PreserveEmptyPredicate = (path: readonly string[]) => boolean;\n\n/**\n * Family-contributed storage sort. Applied to the serialized `storage`\n * subtree after the default-omission walk; the result replaces the\n * `storage` field before the final key sort. Use to establish a\n * deterministic order for storage arrays (indexes, uniques) that the\n * family-agnostic `sortObjectKeys` pass cannot handle.\n */\nexport type StorageSort = (storage: unknown) => unknown;\n\nconst DOMAIN_NAMESPACE_SLOT_PATTERN = ['domain', 'namespaces', '*'] as const satisfies PathPattern;\nconst DOMAIN_MODELS_CONTAINER_PATTERN = [\n 'domain',\n 'namespaces',\n '*',\n 'models',\n] as const satisfies PathPattern;\nconst DOMAIN_MODEL_RELATIONS_PATTERN = [\n 'domain',\n 'namespaces',\n '*',\n 'models',\n '*',\n 'relations',\n] as const satisfies PathPattern;\nconst DOMAIN_MODEL_STORAGE_PATTERN = [\n 'domain',\n 'namespaces',\n '*',\n 'models',\n '*',\n 'storage',\n] as const satisfies PathPattern;\n\nconst TOP_LEVEL_ORDER = [\n 'schemaVersion',\n 'canonicalVersion',\n 'targetFamily',\n 'target',\n 'profileHash',\n 'roots',\n 'domain',\n 'storage',\n 'execution',\n 'capabilities',\n 'extensionPacks',\n 'meta',\n] as const;\n\nfunction isDefaultValue(value: unknown): boolean {\n if (value === false) return true;\n if (value === null) return false;\n if (Array.isArray(value) && value.length === 0) return true;\n if (typeof value === 'object' && value !== null) {\n const keys = Object.keys(value);\n return keys.length === 0;\n }\n return false;\n}\n\nfunction omitDefaults(\n obj: unknown,\n path: readonly string[],\n shouldPreserveEmpty: PreserveEmptyPredicate | undefined,\n): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => omitDefaults(item, path, shouldPreserveEmpty));\n }\n\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const currentPath = [...path, key];\n\n if (key === '_generated') {\n continue;\n }\n\n if (key === 'generated' && value === false) {\n continue;\n }\n\n if ((key === 'onDelete' || key === 'onUpdate') && value === 'noAction') {\n continue;\n }\n\n if (isDefaultValue(value)) {\n const isRequiredDomainNamespaces = isArrayEqual(currentPath, ['domain', 'namespaces']);\n const isDomainNamespaceSlot = matchesPathPattern(currentPath, DOMAIN_NAMESPACE_SLOT_PATTERN);\n const isRequiredDomainModels = matchesPathPattern(\n currentPath,\n DOMAIN_MODELS_CONTAINER_PATTERN,\n );\n const isRequiredStorageNamespaces = isArrayEqual(currentPath, ['storage', 'namespaces']);\n const isStorageNamespaceSlot =\n currentPath.length === 3 &&\n isArrayEqual([currentPath[0], currentPath[1]], ['storage', 'namespaces']);\n const isRequiredRoots = isArrayEqual(currentPath, ['roots']);\n const isRequiredExtensionPacks = isArrayEqual(currentPath, ['extensionPacks']);\n const isRequiredCapabilities = isArrayEqual(currentPath, ['capabilities']);\n const isRequiredMeta = isArrayEqual(currentPath, ['meta']);\n const isRequiredExecutionDefaults = isArrayEqual(currentPath, [\n 'execution',\n 'mutations',\n 'defaults',\n ]);\n const isExtensionNamespace = currentPath.length === 2 && currentPath[0] === 'extensionPacks';\n const isModelRelations = matchesPathPattern(currentPath, DOMAIN_MODEL_RELATIONS_PATTERN);\n const isModelStorage = matchesPathPattern(currentPath, DOMAIN_MODEL_STORAGE_PATTERN);\n\n const isNullableField = key === 'nullable';\n\n const isFamilyPreserved = shouldPreserveEmpty?.(currentPath) ?? false;\n\n if (\n !isRequiredDomainNamespaces &&\n !isDomainNamespaceSlot &&\n !isRequiredDomainModels &&\n !isRequiredStorageNamespaces &&\n !isStorageNamespaceSlot &&\n !isRequiredRoots &&\n !isRequiredExtensionPacks &&\n !isRequiredCapabilities &&\n !isRequiredMeta &&\n !isRequiredExecutionDefaults &&\n !isExtensionNamespace &&\n !isModelRelations &&\n !isModelStorage &&\n !isNullableField &&\n !isFamilyPreserved\n ) {\n continue;\n }\n }\n\n result[key] = omitDefaults(value, currentPath, shouldPreserveEmpty);\n }\n\n return result;\n}\n\nfunction sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => sortObjectKeys(item));\n }\n\n const sorted: Record<string, unknown> = {};\n const keys = Object.keys(obj).sort();\n for (const key of keys) {\n sorted[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n\n return sorted;\n}\n\nexport function orderTopLevel(obj: Record<string, unknown>): Record<string, unknown> {\n const ordered: Record<string, unknown> = {};\n const remaining = new Set(Object.keys(obj));\n\n for (const key of TOP_LEVEL_ORDER) {\n if (remaining.has(key)) {\n ordered[key] = obj[key];\n remaining.delete(key);\n }\n }\n\n for (const key of Array.from(remaining).sort()) {\n ordered[key] = obj[key];\n }\n\n return ordered;\n}\n\nexport interface CanonicalizeContractOptions {\n readonly schemaVersion?: string;\n /**\n * Per-target hook that converts the in-memory contract (which may\n * carry class-instance IR nodes) into a plain JsonObject before the\n * family-agnostic canonicalization steps run.\n *\n * Routing through the hook is what lets each target decide which\n * fields appear in the on-disk envelope; runtime-only class API\n * fields stay invisible to the canonicalization walk by virtue of\n * the per-target serializer not putting them in the JSON shape.\n */\n readonly serializeContract: SerializeContract;\n /**\n * Family-contributed preserve-empty predicate. When the walk encounters a\n * default value (empty object/array or `false`) at `path`, calling this\n * with the full path allows the family to veto the omission. If absent,\n * only the framework's family-agnostic required-slot rules apply.\n */\n readonly shouldPreserveEmpty?: PreserveEmptyPredicate;\n /**\n * Family-contributed storage sort. Applied to the serialized `storage`\n * subtree after the default-omission walk, before the final key sort.\n * SQL family uses this to impose a deterministic order on `indexes` and\n * `uniques` arrays within each namespace table. Families that require no\n * special storage ordering omit this hook.\n */\n readonly sortStorage?: StorageSort;\n}\n\n/**\n * Object-form variant of {@link canonicalizeContract}. Exported because the\n * emitter writes the canonical contract through a separate JSON-stringify\n * pass and consumes the structured object directly.\n */\nexport function canonicalizeContractToObject(\n contract: Contract,\n options: CanonicalizeContractOptions,\n): Record<string, unknown> {\n const serialized = options.serializeContract(contract);\n const normalized: Record<string, unknown> = {\n ...ifDefined('schemaVersion', options.schemaVersion),\n targetFamily: serialized['targetFamily'],\n target: serialized['target'],\n profileHash: serialized['profileHash'],\n roots: serialized['roots'],\n domain: serialized['domain'],\n storage: serialized['storage'],\n ...ifDefined('execution', serialized['execution']),\n extensionPacks: serialized['extensionPacks'],\n capabilities: serialized['capabilities'],\n meta: serialized['meta'],\n };\n const withDefaultsOmitted = omitDefaults(normalized, [], options.shouldPreserveEmpty) as Record<\n string,\n unknown\n >;\n const withSortedStorage = options.sortStorage\n ? { ...withDefaultsOmitted, storage: options.sortStorage(withDefaultsOmitted['storage']) }\n : withDefaultsOmitted;\n const withSortedKeys = sortObjectKeys(withSortedStorage) as Record<string, unknown>;\n return orderTopLevel(withSortedKeys);\n}\n\nexport function canonicalizeContract(\n contract: Contract,\n options: CanonicalizeContractOptions,\n): string {\n return JSON.stringify(canonicalizeContractToObject(contract, options), null, 2);\n}\n","import { createHash } from 'node:crypto';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport {\n canonicalizeContract,\n type PreserveEmptyPredicate,\n type StorageSort,\n} from './canonicalization';\nimport type { Contract } from './contract-types';\nimport type { ExecutionHashBase, ProfileHashBase, StorageHashBase } from './types';\n\nconst SCHEMA_VERSION = '1';\n\nfunction sha256(content: string): string {\n const hash = createHash('sha256');\n hash.update(content);\n return `sha256:${hash.digest('hex')}`;\n}\n\ntype HashContractSection = Record<string, unknown> & {\n readonly shouldPreserveEmpty?: PreserveEmptyPredicate;\n readonly sortStorage?: StorageSort;\n};\n\nfunction hashContract(section: HashContractSection): string {\n const { shouldPreserveEmpty, sortStorage, ...sectionData } = section;\n // Blind cast: the synthesised object is a hash-only stand-in\n // — never returned to callers, never executed as a Contract.\n // `canonicalizeContract` only walks the storage / execution /\n // capabilities slices, all of which are populated above, so the\n // missing precise Contract typing on the other slots is\n // immaterial for the hash result.\n const contract = {\n targetFamily: sectionData['targetFamily'],\n target: sectionData['target'],\n roots: {},\n domain: { namespaces: {} },\n storage: sectionData['storage'] ?? {},\n execution: sectionData['execution'],\n extensionPacks: {},\n capabilities: sectionData['capabilities'] ?? {},\n meta: {},\n profileHash: '',\n ...sectionData,\n } as unknown as Contract;\n return canonicalizeContract(contract, {\n schemaVersion: SCHEMA_VERSION,\n serializeContract: (c) => JSON.parse(JSON.stringify(c)) as JsonObject,\n ...ifDefined('shouldPreserveEmpty', shouldPreserveEmpty),\n ...ifDefined('sortStorage', sortStorage),\n });\n}\n\nexport type ComputeStorageHashArgs = {\n target: string;\n targetFamily: string;\n storage: Record<string, unknown>;\n readonly shouldPreserveEmpty?: PreserveEmptyPredicate;\n readonly sortStorage?: StorageSort;\n};\n\nexport function computeStorageHash(args: ComputeStorageHashArgs): StorageHashBase<string> {\n return sha256(hashContract(args)) as StorageHashBase<string>;\n}\n\nexport function computeExecutionHash(args: {\n target: string;\n targetFamily: string;\n execution: Record<string, unknown>;\n}): ExecutionHashBase<string> {\n return sha256(hashContract(args)) as ExecutionHashBase<string>;\n}\n\nexport function computeProfileHash(args: {\n target: string;\n targetFamily: string;\n capabilities: Record<string, Record<string, boolean>>;\n}): ProfileHashBase<string> {\n return sha256(hashContract(args)) as ProfileHashBase<string>;\n}\n"],"mappings":";;;;;AAmCA,MAAM,gCAAgC;CAAC;CAAU;CAAc;AAAG;AAClE,MAAM,kCAAkC;CACtC;CACA;CACA;CACA;AACF;AACA,MAAM,iCAAiC;CACrC;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,+BAA+B;CACnC;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,eAAe,OAAyB;CAC/C,IAAI,UAAU,OAAO,OAAO;CAC5B,IAAI,UAAU,MAAM,OAAO;CAC3B,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,GAAG,OAAO;CACvD,IAAI,OAAO,UAAU,YA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file":"hashing.mjs","names":[],"sources":["../src/canonicalization.ts","../src/hashing.ts"],"sourcesContent":["import { isArrayEqual } from '@prisma-next/utils/array-equal';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport { matchesPathPattern, type PathPattern } from './canonicalization-path-match';\nimport type { Contract } from './contract-types';\n\n/**\n * Per-target contract serializer hook. The framework canonicalizer uses\n * this to convert an in-memory contract (which may carry class-instance\n * IR nodes whose runtime-only fields must not appear in the on-disk\n * envelope) into a plain JsonObject before applying the family-agnostic\n * canonical-key ordering / default-omission / sort steps. Targets whose\n * contract is JSON-clean by construction return the contract unchanged.\n */\nexport type SerializeContract = (contract: Contract) => JsonObject;\n\n/**\n * Family-contributed predicate for the default-omission walk. Called when\n * a value at `path` is a default (empty object/array or `false`); if this\n * returns `true` the value is kept rather than stripped.\n *\n * The framework only calls the predicate inside the `isDefaultValue` branch,\n * so there is no need to guard against non-default values.\n */\nexport type PreserveEmptyPredicate = (path: readonly string[]) => boolean;\n\n/**\n * Family-contributed storage sort. Applied to the serialized `storage`\n * subtree after the default-omission walk; the result replaces the\n * `storage` field before the final key sort. Use to establish a\n * deterministic order for storage arrays (indexes, uniques) that the\n * family-agnostic `sortObjectKeys` pass cannot handle.\n */\nexport type StorageSort = (storage: unknown) => unknown;\n\nconst DOMAIN_NAMESPACE_SLOT_PATTERN = ['domain', 'namespaces', '*'] as const satisfies PathPattern;\nconst DOMAIN_MODELS_CONTAINER_PATTERN = [\n 'domain',\n 'namespaces',\n '*',\n 'models',\n] as const satisfies PathPattern;\nconst DOMAIN_MODEL_RELATIONS_PATTERN = [\n 'domain',\n 'namespaces',\n '*',\n 'models',\n '*',\n 'relations',\n] as const satisfies PathPattern;\nconst DOMAIN_MODEL_STORAGE_PATTERN = [\n 'domain',\n 'namespaces',\n '*',\n 'models',\n '*',\n 'storage',\n] as const satisfies PathPattern;\n\nconst TOP_LEVEL_ORDER = [\n 'schemaVersion',\n 'canonicalVersion',\n 'targetFamily',\n 'target',\n 'profileHash',\n 'roots',\n 'domain',\n 'storage',\n 'execution',\n 'capabilities',\n 'extensionPacks',\n 'meta',\n] as const;\n\nfunction isDefaultValue(value: unknown): boolean {\n if (value === false) return true;\n if (value === null) return false;\n if (Array.isArray(value) && value.length === 0) return true;\n if (typeof value === 'object' && value !== null) {\n const keys = Object.keys(value);\n return keys.length === 0;\n }\n return false;\n}\n\nfunction omitDefaults(\n obj: unknown,\n path: readonly string[],\n shouldPreserveEmpty: PreserveEmptyPredicate | undefined,\n): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => omitDefaults(item, path, shouldPreserveEmpty));\n }\n\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n const currentPath = [...path, key];\n\n if (key === '_generated') {\n continue;\n }\n\n if (key === 'generated' && value === false) {\n continue;\n }\n\n if ((key === 'onDelete' || key === 'onUpdate') && value === 'noAction') {\n continue;\n }\n\n if (isDefaultValue(value)) {\n const isRequiredDomainNamespaces = isArrayEqual(currentPath, ['domain', 'namespaces']);\n const isDomainNamespaceSlot = matchesPathPattern(currentPath, DOMAIN_NAMESPACE_SLOT_PATTERN);\n const isRequiredDomainModels = matchesPathPattern(\n currentPath,\n DOMAIN_MODELS_CONTAINER_PATTERN,\n );\n const isRequiredStorageNamespaces = isArrayEqual(currentPath, ['storage', 'namespaces']);\n const isStorageNamespaceSlot =\n currentPath.length === 3 &&\n isArrayEqual([currentPath[0], currentPath[1]], ['storage', 'namespaces']);\n const isRequiredRoots = isArrayEqual(currentPath, ['roots']);\n const isRequiredExtensionPacks = isArrayEqual(currentPath, ['extensionPacks']);\n const isRequiredCapabilities = isArrayEqual(currentPath, ['capabilities']);\n const isRequiredMeta = isArrayEqual(currentPath, ['meta']);\n const isRequiredExecutionDefaults = isArrayEqual(currentPath, [\n 'execution',\n 'mutations',\n 'defaults',\n ]);\n const isExtensionNamespace = currentPath.length === 2 && currentPath[0] === 'extensionPacks';\n const isModelRelations = matchesPathPattern(currentPath, DOMAIN_MODEL_RELATIONS_PATTERN);\n const isModelStorage = matchesPathPattern(currentPath, DOMAIN_MODEL_STORAGE_PATTERN);\n\n const isNullableField = key === 'nullable';\n\n const isFamilyPreserved = shouldPreserveEmpty?.(currentPath) ?? false;\n\n if (\n !isRequiredDomainNamespaces &&\n !isDomainNamespaceSlot &&\n !isRequiredDomainModels &&\n !isRequiredStorageNamespaces &&\n !isStorageNamespaceSlot &&\n !isRequiredRoots &&\n !isRequiredExtensionPacks &&\n !isRequiredCapabilities &&\n !isRequiredMeta &&\n !isRequiredExecutionDefaults &&\n !isExtensionNamespace &&\n !isModelRelations &&\n !isModelStorage &&\n !isNullableField &&\n !isFamilyPreserved\n ) {\n continue;\n }\n }\n\n result[key] = omitDefaults(value, currentPath, shouldPreserveEmpty);\n }\n\n return result;\n}\n\nfunction sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => sortObjectKeys(item));\n }\n\n const sorted: Record<string, unknown> = {};\n const keys = Object.keys(obj).sort();\n for (const key of keys) {\n sorted[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n\n return sorted;\n}\n\nexport function orderTopLevel(obj: Record<string, unknown>): Record<string, unknown> {\n const ordered: Record<string, unknown> = {};\n const remaining = new Set(Object.keys(obj));\n\n for (const key of TOP_LEVEL_ORDER) {\n if (remaining.has(key)) {\n ordered[key] = obj[key];\n remaining.delete(key);\n }\n }\n\n for (const key of Array.from(remaining).sort()) {\n ordered[key] = obj[key];\n }\n\n return ordered;\n}\n\nexport interface CanonicalizeContractOptions {\n readonly schemaVersion?: string;\n /**\n * Per-target hook that converts the in-memory contract (which may\n * carry class-instance IR nodes) into a plain JsonObject before the\n * family-agnostic canonicalization steps run.\n *\n * Routing through the hook is what lets each target decide which\n * fields appear in the on-disk envelope; runtime-only class API\n * fields stay invisible to the canonicalization walk by virtue of\n * the per-target serializer not putting them in the JSON shape.\n */\n readonly serializeContract: SerializeContract;\n /**\n * Family-contributed preserve-empty predicate. When the walk encounters a\n * default value (empty object/array or `false`) at `path`, calling this\n * with the full path allows the family to veto the omission. If absent,\n * only the framework's family-agnostic required-slot rules apply.\n */\n readonly shouldPreserveEmpty?: PreserveEmptyPredicate;\n /**\n * Family-contributed storage sort. Applied to the serialized `storage`\n * subtree after the default-omission walk, before the final key sort.\n * SQL family uses this to impose a deterministic order on `indexes` and\n * `uniques` arrays within each namespace table. Families that require no\n * special storage ordering omit this hook.\n */\n readonly sortStorage?: StorageSort;\n}\n\n/**\n * Object-form variant of {@link canonicalizeContract}. Exported because the\n * emitter writes the canonical contract through a separate JSON-stringify\n * pass and consumes the structured object directly.\n */\nexport function canonicalizeContractToObject(\n contract: Contract,\n options: CanonicalizeContractOptions,\n): Record<string, unknown> {\n const serialized = options.serializeContract(contract);\n const normalized: Record<string, unknown> = {\n ...ifDefined('schemaVersion', options.schemaVersion),\n targetFamily: serialized['targetFamily'],\n target: serialized['target'],\n profileHash: serialized['profileHash'],\n roots: serialized['roots'],\n domain: serialized['domain'],\n storage: serialized['storage'],\n ...ifDefined('execution', serialized['execution']),\n extensionPacks: serialized['extensionPacks'],\n capabilities: serialized['capabilities'],\n meta: serialized['meta'],\n };\n const withDefaultsOmitted = omitDefaults(normalized, [], options.shouldPreserveEmpty) as Record<\n string,\n unknown\n >;\n const withSortedStorage = options.sortStorage\n ? { ...withDefaultsOmitted, storage: options.sortStorage(withDefaultsOmitted['storage']) }\n : withDefaultsOmitted;\n const withSortedKeys = sortObjectKeys(withSortedStorage) as Record<string, unknown>;\n return orderTopLevel(withSortedKeys);\n}\n\nexport function canonicalizeContract(\n contract: Contract,\n options: CanonicalizeContractOptions,\n): string {\n return JSON.stringify(canonicalizeContractToObject(contract, options), null, 2);\n}\n","import { createHash } from 'node:crypto';\nimport { blindCast, castAs } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport {\n canonicalizeContract,\n type PreserveEmptyPredicate,\n type StorageSort,\n} from './canonicalization';\nimport type { Contract } from './contract-types';\nimport type { ExecutionHashBase, ProfileHashBase, StorageHashBase } from './types';\n\nconst SCHEMA_VERSION = '1';\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n// Storage hashes fingerprint table/column layout, not which target pack emitted a\n// namespace. Persisted contract.json carries namespace `kind` discriminators;\n// authoring-time hashes never included them (IR `kind` is non-enumerable).\nfunction omitNamespaceKindsForHash(storage: unknown): unknown {\n if (!isPlainRecord(storage)) {\n return storage;\n }\n const namespaces = storage['namespaces'];\n if (!isPlainRecord(namespaces)) {\n return storage;\n }\n const stripped: Record<string, unknown> = {};\n for (const [nsId, ns] of Object.entries(namespaces)) {\n if (isPlainRecord(ns)) {\n const { kind: _kind, ...rest } = ns;\n stripped[nsId] = rest;\n } else {\n stripped[nsId] = ns;\n }\n }\n return { ...storage, namespaces: stripped };\n}\n\nfunction sha256(content: string): string {\n const hash = createHash('sha256');\n hash.update(content);\n return `sha256:${hash.digest('hex')}`;\n}\n\ntype HashContractSection = Record<string, unknown> & {\n readonly shouldPreserveEmpty?: PreserveEmptyPredicate;\n readonly sortStorage?: StorageSort;\n};\n\nfunction hashContract(section: HashContractSection): string {\n const { shouldPreserveEmpty, sortStorage, ...sectionData } = section;\n const storageForHash = omitNamespaceKindsForHash(sectionData['storage'] ?? {});\n const contract = blindCast<Contract, 'hash-only partial contract for canonicalizeContract'>({\n targetFamily: sectionData['targetFamily'],\n target: sectionData['target'],\n roots: {},\n domain: { namespaces: {} },\n execution: sectionData['execution'],\n extensionPacks: {},\n capabilities: sectionData['capabilities'] ?? {},\n meta: {},\n profileHash: '',\n ...sectionData,\n storage: storageForHash,\n });\n return canonicalizeContract(contract, {\n schemaVersion: SCHEMA_VERSION,\n serializeContract: (c) => castAs<JsonObject>(JSON.parse(JSON.stringify(c))),\n ...ifDefined('shouldPreserveEmpty', shouldPreserveEmpty),\n ...ifDefined('sortStorage', sortStorage),\n });\n}\n\nexport type ComputeStorageHashArgs = {\n target: string;\n targetFamily: string;\n storage: Record<string, unknown>;\n readonly shouldPreserveEmpty?: PreserveEmptyPredicate;\n readonly sortStorage?: StorageSort;\n};\n\nexport function computeStorageHash(args: ComputeStorageHashArgs): StorageHashBase<string> {\n return blindCast<StorageHashBase<string>, 'sha256 digest of canonicalized storage'>(\n sha256(hashContract(args)),\n );\n}\n\nexport function computeExecutionHash(args: {\n target: string;\n targetFamily: string;\n execution: Record<string, unknown>;\n}): ExecutionHashBase<string> {\n return blindCast<ExecutionHashBase<string>, 'sha256 digest of canonicalized execution'>(\n sha256(hashContract(args)),\n );\n}\n\nexport function computeProfileHash(args: {\n target: string;\n targetFamily: string;\n capabilities: Record<string, Record<string, boolean>>;\n}): ProfileHashBase<string> {\n return blindCast<ProfileHashBase<string>, 'sha256 digest of canonicalized profile'>(\n sha256(hashContract(args)),\n );\n}\n"],"mappings":";;;;;;AAmCA,MAAM,gCAAgC;CAAC;CAAU;CAAc;AAAG;AAClE,MAAM,kCAAkC;CACtC;CACA;CACA;CACA;AACF;AACA,MAAM,iCAAiC;CACrC;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,+BAA+B;CACnC;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,eAAe,OAAyB;CAC/C,IAAI,UAAU,OAAO,OAAO;CAC5B,IAAI,UAAU,MAAM,OAAO;CAC3B,IAAI,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,GAAG,OAAO;CACvD,IAAI,OAAO,UAAU,YAAY,UAAU,MAEzC,OADa,OAAO,KAAK,KACf,EAAE,WAAW;CAEzB,OAAO;AACT;AAEA,SAAS,a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,MAAM,CAAC;EACP,aAAa;EACb,GAAG;EACH,SAAS;CACX,CACmC,GAAG;EACpC,eAAe;EACf,oBAAoB,MAAM,OAAmB,KAAK,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC;EAC1E,GAAG,UAAU,uBAAuB,mBAAmB;EACvD,GAAG,UAAU,eAAe,WAAW;CACzC,CAAC;AACH;AAUA,SAAgB,mBAAmB,MAAuD;CACxF,OAAO,UACL,OAAO,aAAa,IAAI,CAAC,CAC3B;AACF;AAEA,SAAgB,qBAAqB,MAIP;CAC5B,OAAO,UACL,OAAO,aAAa,IAAI,CAAC,CAC3B;AACF;AAEA,SAAgB,mBAAmB,MAIP;CAC1B,OAAO,UACL,OAAO,aAAa,IAAI,CAAC,CAC3B;AACF"}
|
package/package.json
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/contract",
|
|
3
|
-
"version": "0.12.0-dev.
|
|
3
|
+
"version": "0.12.0-dev.25",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"description": "Data contract type definitions and JSON schema for Prisma Next",
|
|
8
8
|
"dependencies": {
|
|
9
|
-
"@prisma-next/utils": "0.12.0-dev.
|
|
9
|
+
"@prisma-next/utils": "0.12.0-dev.25",
|
|
10
10
|
"@standard-schema/spec": "^1.1.0",
|
|
11
11
|
"arktype": "^2.2.0"
|
|
12
12
|
},
|
|
13
13
|
"devDependencies": {
|
|
14
|
-
"@prisma-next/tsconfig": "0.12.0-dev.
|
|
15
|
-
"@prisma-next/tsdown": "0.12.0-dev.
|
|
14
|
+
"@prisma-next/tsconfig": "0.12.0-dev.25",
|
|
15
|
+
"@prisma-next/tsdown": "0.12.0-dev.25",
|
|
16
16
|
"tsdown": "0.22.0",
|
|
17
17
|
"typescript": "5.9.3",
|
|
18
18
|
"vitest": "4.1.6"
|
package/src/hashing.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
+
import { blindCast, castAs } from '@prisma-next/utils/casts';
|
|
2
3
|
import { ifDefined } from '@prisma-next/utils/defined';
|
|
3
4
|
import type { JsonObject } from '@prisma-next/utils/json';
|
|
4
5
|
import {
|
|
@@ -11,6 +12,33 @@ import type { ExecutionHashBase, ProfileHashBase, StorageHashBase } from './type
|
|
|
11
12
|
|
|
12
13
|
const SCHEMA_VERSION = '1';
|
|
13
14
|
|
|
15
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
16
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Storage hashes fingerprint table/column layout, not which target pack emitted a
|
|
20
|
+
// namespace. Persisted contract.json carries namespace `kind` discriminators;
|
|
21
|
+
// authoring-time hashes never included them (IR `kind` is non-enumerable).
|
|
22
|
+
function omitNamespaceKindsForHash(storage: unknown): unknown {
|
|
23
|
+
if (!isPlainRecord(storage)) {
|
|
24
|
+
return storage;
|
|
25
|
+
}
|
|
26
|
+
const namespaces = storage['namespaces'];
|
|
27
|
+
if (!isPlainRecord(namespaces)) {
|
|
28
|
+
return storage;
|
|
29
|
+
}
|
|
30
|
+
const stripped: Record<string, unknown> = {};
|
|
31
|
+
for (const [nsId, ns] of Object.entries(namespaces)) {
|
|
32
|
+
if (isPlainRecord(ns)) {
|
|
33
|
+
const { kind: _kind, ...rest } = ns;
|
|
34
|
+
stripped[nsId] = rest;
|
|
35
|
+
} else {
|
|
36
|
+
stripped[nsId] = ns;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return { ...storage, namespaces: stripped };
|
|
40
|
+
}
|
|
41
|
+
|
|
14
42
|
function sha256(content: string): string {
|
|
15
43
|
const hash = createHash('sha256');
|
|
16
44
|
hash.update(content);
|
|
@@ -24,28 +52,23 @@ type HashContractSection = Record<string, unknown> & {
|
|
|
24
52
|
|
|
25
53
|
function hashContract(section: HashContractSection): string {
|
|
26
54
|
const { shouldPreserveEmpty, sortStorage, ...sectionData } = section;
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
// `canonicalizeContract` only walks the storage / execution /
|
|
30
|
-
// capabilities slices, all of which are populated above, so the
|
|
31
|
-
// missing precise Contract typing on the other slots is
|
|
32
|
-
// immaterial for the hash result.
|
|
33
|
-
const contract = {
|
|
55
|
+
const storageForHash = omitNamespaceKindsForHash(sectionData['storage'] ?? {});
|
|
56
|
+
const contract = blindCast<Contract, 'hash-only partial contract for canonicalizeContract'>({
|
|
34
57
|
targetFamily: sectionData['targetFamily'],
|
|
35
58
|
target: sectionData['target'],
|
|
36
59
|
roots: {},
|
|
37
60
|
domain: { namespaces: {} },
|
|
38
|
-
storage: sectionData['storage'] ?? {},
|
|
39
61
|
execution: sectionData['execution'],
|
|
40
62
|
extensionPacks: {},
|
|
41
63
|
capabilities: sectionData['capabilities'] ?? {},
|
|
42
64
|
meta: {},
|
|
43
65
|
profileHash: '',
|
|
44
66
|
...sectionData,
|
|
45
|
-
|
|
67
|
+
storage: storageForHash,
|
|
68
|
+
});
|
|
46
69
|
return canonicalizeContract(contract, {
|
|
47
70
|
schemaVersion: SCHEMA_VERSION,
|
|
48
|
-
serializeContract: (c) => JSON.parse(JSON.stringify(c))
|
|
71
|
+
serializeContract: (c) => castAs<JsonObject>(JSON.parse(JSON.stringify(c))),
|
|
49
72
|
...ifDefined('shouldPreserveEmpty', shouldPreserveEmpty),
|
|
50
73
|
...ifDefined('sortStorage', sortStorage),
|
|
51
74
|
});
|
|
@@ -60,7 +83,9 @@ export type ComputeStorageHashArgs = {
|
|
|
60
83
|
};
|
|
61
84
|
|
|
62
85
|
export function computeStorageHash(args: ComputeStorageHashArgs): StorageHashBase<string> {
|
|
63
|
-
return sha256
|
|
86
|
+
return blindCast<StorageHashBase<string>, 'sha256 digest of canonicalized storage'>(
|
|
87
|
+
sha256(hashContract(args)),
|
|
88
|
+
);
|
|
64
89
|
}
|
|
65
90
|
|
|
66
91
|
export function computeExecutionHash(args: {
|
|
@@ -68,7 +93,9 @@ export function computeExecutionHash(args: {
|
|
|
68
93
|
targetFamily: string;
|
|
69
94
|
execution: Record<string, unknown>;
|
|
70
95
|
}): ExecutionHashBase<string> {
|
|
71
|
-
return sha256
|
|
96
|
+
return blindCast<ExecutionHashBase<string>, 'sha256 digest of canonicalized execution'>(
|
|
97
|
+
sha256(hashContract(args)),
|
|
98
|
+
);
|
|
72
99
|
}
|
|
73
100
|
|
|
74
101
|
export function computeProfileHash(args: {
|
|
@@ -76,5 +103,7 @@ export function computeProfileHash(args: {
|
|
|
76
103
|
targetFamily: string;
|
|
77
104
|
capabilities: Record<string, Record<string, boolean>>;
|
|
78
105
|
}): ProfileHashBase<string> {
|
|
79
|
-
return sha256
|
|
106
|
+
return blindCast<ProfileHashBase<string>, 'sha256 digest of canonicalized profile'>(
|
|
107
|
+
sha256(hashContract(args)),
|
|
108
|
+
);
|
|
80
109
|
}
|