Open History to see the last commit
1import { MurmurHashStream, getSymbolIdentity, randomHash } from './murmur.js'
2import { isTemporal } from './temporal.js'
3import type { Hasher } from './murmur.js'
4import type { TemporalLike } from './temporal.js'
5
6/*
7 * Implementation of structural hashing based on the Composites polyfill implementation:
8 * https://github.com/tc39/proposal-composites
9 */
10
11const TRUE = randomHash()
12const FALSE = randomHash()
13const NULL = randomHash()
14const UNDEFINED = randomHash()
15const KEY = randomHash()
16const FUNCTIONS = randomHash()
17const DATE_MARKER = randomHash()
18const REGEXP_MARKER = randomHash()
19const STRUCTURAL_MARKERS = {
20 object: randomHash(),
21 array: randomHash(),
22 map: randomHash(),
23 set: randomHash(),
24}
25const UINT8ARRAY_MARKER = randomHash()
26const TEMPORAL_MARKER = randomHash()
27// Bound structural recursion and value visits. Shared acyclic subtrees are
28// cached; cycles are rejected rather than given context-dependent hashes.
29const MAX_STRUCTURAL_HASH_WORK = 1_000_000
30const MAX_STRUCTURAL_HASH_DEPTH = 768
31
32// Maximum byte length for Uint8Arrays to hash by content instead of reference
33// Arrays smaller than this will be hashed by content, allowing proper equality comparisons
34// for small arrays like ULIDs (16 bytes) while still avoiding performance costs for large arrays
35const UINT8ARRAY_CONTENT_HASH_THRESHOLD = 128
36
37const hashCache = new WeakMap<object, number>()
38const referenceValues = new WeakSet<object>()
39
40/** @internal Register a mutable handle before it enters a structural value. */
41export function registerOpaqueHash(value: object): void {
42 cachedReferenceHash(value)
43}
44
45type HashContext = {
46 activeObjects: Set<object>
47 work: number
48 pendingHashes: Map<object, number>
49}
50
51export function hash(input: any): number {
52 const hasher = new MurmurHashStream()
53 updateHasher(hasher, input)
54 return hasher.digest()
55}
56
57function hashObject(input: object, context: HashContext): number {
58 if (context.activeObjects.size >= MAX_STRUCTURAL_HASH_DEPTH) {
59 throw new RangeError(
60 `Value is too complex to hash safely: structural depth`,
61 )
62 }
63
64 context.activeObjects.add(input)
65
66 let valueHash: number | undefined
67 try {
68 if (input instanceof Date) {
69 valueHash = hashDate(input)
70 } else if (isBinaryValue(input)) {
71 valueHash = hashUint8Array(input)
72 } else if (isTemporal(input)) {
73 valueHash = hashTemporal(input)
74 } else if (input instanceof RegExp) {
75 valueHash = hashPlainObject(input, REGEXP_MARKER, context, [
76 input.source,
77 input.flags,
78 input.lastIndex,
79 ])
80 } else {
81 const [kind, plainObjectInput] = structuralShape(input)
82 valueHash = hashPlainObject(
83 plainObjectInput,
84 STRUCTURAL_MARKERS[kind],
85 context,
86 kind === `array` ? [input instanceof Array ? input.length : 0] : [],
87 )
88 }
89 } finally {
90 context.activeObjects.delete(input)
91 }
92
93 context.pendingHashes.set(input, valueHash)
94 return valueHash
95}
96
97function hashDate(input: Date): number {
98 const hasher = new MurmurHashStream()
99 hasher.update(DATE_MARKER)
100 hasher.update(input.getTime())
101 return hasher.digest()
102}
103
104function hashUint8Array(input: Uint8Array): number {
105 const hasher = new MurmurHashStream()
106 hasher.update(UINT8ARRAY_MARKER)
107 // Hash the byte length first to differentiate arrays of different sizes
108 hasher.update(input.byteLength)
109 // Hash each byte in the array
110 for (let i = 0; i < input.byteLength; i++) {
111 hasher.writeByte(input[i]!)
112 }
113 return hasher.digest()
114}
115
116function hashTemporal(input: TemporalLike): number {
117 const hasher = new MurmurHashStream()
118 hasher.update(TEMPORAL_MARKER)
119 hasher.update(input[Symbol.toStringTag])
120 hasher.update(input.toString())
121 return hasher.digest()
122}
123
124function hashPlainObject(
125 input: object,
126 marker: number,
127 context: HashContext,
128 headerValues: ReadonlyArray<unknown> = [],
129): number {
130 const hasher = new MurmurHashStream()
131
132 // Mark the type of the input
133 hasher.update(marker)
134 for (const value of headerValues) updateHasher(hasher, value, context)
135 const keys = Object.keys(input)
136 keys.sort(keySort)
137 for (const key of keys) {
138 hasher.update(KEY)
139 hasher.update(key)
140 updateHasher(hasher, input[key as keyof typeof input], context)
141 }
142 const symbolKeys = Object.getOwnPropertySymbols(input)
143 .filter((key) => Object.prototype.propertyIsEnumerable.call(input, key))
144 .sort((left, right) => getSymbolIdentity(left) - getSymbolIdentity(right))
145 for (const key of symbolKeys) {
146 hasher.update(KEY)
147 hasher.update(key)
148 updateHasher(hasher, input[key as keyof typeof input], context)
149 }
150
151 return hasher.digest()
152}
153
154function updateHasher(
155 hasher: Hasher,
156 input: unknown,
157 context?: HashContext,
158): void {
159 if (context && ++context.work > MAX_STRUCTURAL_HASH_WORK) {
160 throw new RangeError(`Value is too complex to hash safely: structural work`)
161 }
162 if (input === null) {
163 hasher.update(NULL)
164 return
165 }
166 switch (typeof input) {
167 case `undefined`:
168 hasher.update(UNDEFINED)
169 return
170 case `boolean`:
171 hasher.update(input ? TRUE : FALSE)
172 return
173 case `number`:
174 // Normalize NaNs and -0
175 hasher.update(isNaN(input) ? NaN : input === 0 ? 0 : input)
176 return
177 case `bigint`:
178 case `string`:
179 case `symbol`:
180 hasher.update(input)
181 return
182 case `object`:
183 hasher.update(getCachedHash(input, context))
184 return
185 case `function`:
186 // Functions are assigned a globally unique ID
187 // and that ID is cached in the weak map
188 hasher.update(cachedReferenceHash(input))
189 return
190 default:
191 console.warn(
192 `Ignored input during hashing because it is of type ${typeof input} which is not supported`,
193 )
194 }
195}
196
197function getCachedHash(input: object, context?: HashContext): number {
198 if (!context) {
199 const cached = hashCache.get(input)
200 if (cached !== undefined) return cached
201 if (isReferenceHashedObject(input)) return cachedReferenceHash(input)
202
203 // Only an uncached structural root needs graph traversal state. Commit its
204 // cache entries after success so a failed traversal cannot poison retries.
205 context = {
206 activeObjects: new Set(),
207 work: 0,
208 pendingHashes: new Map(),
209 }
210 const result = hashObject(input, context)
211 for (const [object, valueHash] of context.pendingHashes) {
212 hashCache.set(object, valueHash)
213 }
214 return result
215 }
216
217 if (context.activeObjects.has(input)) {
218 throw new TypeError(`Cannot hash cyclic structural values`)
219 }
220
221 // Opaque leaves cannot contain structural back-references. Resolve them
222 // before entering structural recursion, even when they have user properties.
223 if (isReferenceHashedObject(input)) return cachedReferenceHash(input)
224
225 const valueHash = hashCache.get(input) ?? context.pendingHashes.get(input)
226 if (valueHash !== undefined) return valueHash
227
228 return hashObject(input, context)
229}
230
231function isReferenceHashedObject(input: object): boolean {
232 return (
233 (typeof File !== `undefined` && input instanceof File) ||
234 (isBinaryValue(input) &&
235 input.byteLength > UINT8ARRAY_CONTENT_HASH_THRESHOLD)
236 )
237}
238
239function isBinaryValue(input: object): input is Uint8Array {
240 return (
241 (typeof Buffer !== `undefined` && input instanceof Buffer) ||
242 input instanceof Uint8Array
243 )
244}
245
246function structuralShape(
247 input: object,
248): [keyof typeof STRUCTURAL_MARKERS, object] {
249 if (input instanceof Map) return [`map`, [...input.entries()]]
250 if (input instanceof Set) return [`set`, [...input.values()]]
251 return [input instanceof Array ? `array` : `object`, input]
252}
253
254/** @internal Compare immutable structural values without computing a digest.
255 * Pair memoization also permits cyclic values that structural hashing rejects.
256 * Reference-valued leaves remain opaque, including registered mutable handles.
257 */
258export function equalHashValues(left: unknown, right: unknown): boolean {
259 const compared = new Map<object, Set<object>>()
260 function equal(a: unknown, b: unknown): boolean {
261 if (a === b || (Number.isNaN(a) && Number.isNaN(b))) return true
262 if (
263 a === null ||
264 b === null ||
265 typeof a !== `object` ||
266 typeof b !== `object`
267 )
268 return false
269 if (
270 referenceValues.has(a) ||
271 referenceValues.has(b) ||
272 isReferenceHashedObject(a) ||
273 isReferenceHashedObject(b)
274 )
275 return false
276 if (a instanceof Date || b instanceof Date)
277 return (
278 a instanceof Date &&
279 b instanceof Date &&
280 equal(a.getTime(), b.getTime())
281 )
282 if (isBinaryValue(a) || isBinaryValue(b))
283 return (
284 isBinaryValue(a) &&
285 isBinaryValue(b) &&
286 a.byteLength === b.byteLength &&
287 a.every((value, index) => value === b[index])
288 )
289 if (isTemporal(a) || isTemporal(b))
290 return (
291 isTemporal(a) &&
292 isTemporal(b) &&
293 a[Symbol.toStringTag] === b[Symbol.toStringTag] &&
294 a.toString() === b.toString()
295 )
296 if (a instanceof RegExp || b instanceof RegExp) {
297 if (
298 !(a instanceof RegExp && b instanceof RegExp) ||
299 a.source !== b.source ||
300 a.flags !== b.flags ||
301 a.lastIndex !== b.lastIndex
302 )
303 return false
304 }
305 if (Array.isArray(a) && Array.isArray(b) && a.length !== b.length)
306 return false
307
308 // Revisited pairs close cycles and avoid expanding shared subtrees.
309 const peers = compared.get(a)
310 if (peers?.has(b)) return true
311 if (peers) peers.add(b)
312 else compared.set(a, new Set([b]))
313 const [aKind, aShape] = structuralShape(a)
314 const [bKind, bShape] = structuralShape(b)
315 if (aKind !== bKind) return false
316 const keys = (value: object) =>
317 Reflect.ownKeys(value).filter((key) =>
318 Object.prototype.propertyIsEnumerable.call(value, key),
319 )
320 const aKeys = keys(aShape)
321 if (aKeys.length !== keys(bShape).length) return false
322 return aKeys.every(
323 (key) =>
324 Object.prototype.propertyIsEnumerable.call(bShape, key) &&
325 equal(aShape[key as keyof object], bShape[key as keyof object]),
326 )
327 }
328 return equal(left, right)
329}
330
331let nextRefId = 1
332function cachedReferenceHash(fn: object): number {
333 let valueHash = hashCache.get(fn)
334 if (valueHash === undefined) {
335 valueHash = nextRefId ^ FUNCTIONS
336 nextRefId++
337 hashCache.set(fn, valueHash)
338 referenceValues.add(fn)
339 }
340 return valueHash
341}
342
343/**
344 * Strings sorted lexicographically.
345 */
346function keySort(a: string, b: string): number {
347 return a.localeCompare(b)
348}