Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { Temporal } from 'temporal-polyfill'
3import { compareKeys, serializeValue } from '../src/utils.js'
4import { hash } from '../src/hashing/index.js'
5import { equalHashValues } from '../src/hashing/hash.js'
6
7describe(`compareKeys`, () => {
8 it(`orders finite numeric keys before NaN`, () => {
9 expect(compareKeys(1, Number.NaN)).toBeLessThan(0)
10 expect(compareKeys(Number.NaN, 1)).toBeGreaterThan(0)
11 expect(compareKeys(Number.NaN, Number.NaN)).toBe(0)
12 })
13})
14
15describe(`serializeValue`, () => {
16 it(`preserves the established JSON form for ordinary keys`, () => {
17 expect(serializeValue(`user1`)).toBe(`"user1"`)
18 expect(serializeValue([1, `completed`])).toBe(`[1,"completed"]`)
19 })
20
21 it(`keeps distinct primitive types and special numbers distinct`, () => {
22 expect(serializeValue(1n)).not.toBe(serializeValue(`1`))
23 expect(serializeValue(Number.NaN)).not.toBe(serializeValue(null))
24 expect(serializeValue(undefined)).not.toBe(serializeValue(null))
25 expect(serializeValue(new Date(0))).not.toBe(
26 serializeValue(`1970-01-01T00:00:00.000Z`),
27 )
28 expect(serializeValue(new Date(Number.NaN))).not.toBe(
29 serializeValue(Number.NaN),
30 )
31 })
32
33 it(`canonicalizes plain-object property order`, () => {
34 expect(serializeValue({ a: 1, b: 2 })).toBe(serializeValue({ b: 2, a: 1 }))
35 })
36})
37
38const hashType = `number`
39describe(`hash`, () => {
40 describe(`primitive types`, () => {
41 it(`should hash null`, () => {
42 const result = hash(null)
43 expect(typeof result).toBe(hashType)
44 })
45
46 it(`should hash undefined`, () => {
47 const result = hash(undefined)
48 expect(typeof result).toBe(hashType)
49 })
50
51 it(`should hash strings`, () => {
52 const result1 = hash(`hello`)
53 const result2 = hash(``)
54 const result3 = hash(`test with spaces`)
55 const result4 = hash(`special\nchars\t"`)
56
57 expect(typeof result1).toBe(hashType)
58 expect(typeof result2).toBe(hashType)
59 expect(typeof result3).toBe(hashType)
60 expect(typeof result4).toBe(hashType)
61
62 // Same strings should have same hash
63 expect(hash(`hello`)).toBe(result1)
64 })
65
66 it(`should hash numbers`, () => {
67 const result1 = hash(42)
68 const result2 = hash(0)
69 const result3 = hash(-1)
70 const result4 = hash(3.14159)
71 const result5 = hash(Infinity)
72 const result6 = hash(-Infinity)
73 const result7 = hash(NaN)
74
75 expect(typeof result1).toBe(hashType)
76 expect(typeof result2).toBe(hashType)
77 expect(typeof result3).toBe(hashType)
78 expect(typeof result4).toBe(hashType)
79 expect(typeof result5).toBe(hashType)
80 expect(typeof result6).toBe(hashType)
81 expect(typeof result7).toBe(hashType)
82
83 // Same numbers should have same hash
84 expect(hash(42)).toBe(result1)
85 expect(equalHashValues(2.0, 2.5)).toBe(false)
86 expect(typeof hash(2.5)).toBe(hashType)
87 expect(hash(3.14159)).toBe(result4)
88 })
89
90 it(`should hash booleans`, () => {
91 const result1 = hash(true)
92 const result2 = hash(false)
93
94 expect(typeof result1).toBe(hashType)
95 expect(typeof result2).toBe(hashType)
96 expect(equalHashValues(true, false)).toBe(false)
97
98 // Same booleans should have same hash
99 expect(hash(true)).toBe(result1)
100 expect(hash(false)).toBe(result2)
101 })
102
103 it(`should hash bigint`, () => {
104 const result1 = hash(123n)
105 const result2 = hash(456n)
106 const result3 = hash(123n)
107
108 expect(typeof result1).toBe(hashType)
109 expect(typeof result2).toBe(hashType)
110 expect(typeof result3).toBe(hashType)
111 expect(result1).toBe(result3) // Same bigint should have same hash
112 expect(equalHashValues(123n, 456n)).toBe(false)
113 })
114
115 it(`should hash symbols`, () => {
116 const sym1 = Symbol(`test`)
117 const sym2 = Symbol(`test`)
118 const sym3 = Symbol(`different`)
119 const sym4 = Symbol()
120 const sym5 = Symbol()
121
122 const result1 = hash(sym1)
123 const result2 = hash(sym2)
124 const result3 = hash(sym3)
125 const result4 = hash(sym4)
126 const result5 = hash(sym5)
127
128 expect(typeof result1).toBe(hashType)
129 expect(typeof result2).toBe(hashType)
130 expect(typeof result3).toBe(hashType)
131 expect(typeof result4).toBe(hashType)
132 expect(typeof result5).toBe(hashType)
133 expect(equalHashValues(sym1, sym2)).toBe(false)
134 expect(equalHashValues(sym1, sym3)).toBe(false)
135 expect(equalHashValues(sym4, sym5)).toBe(false)
136 expect(equalHashValues(sym1, sym4)).toBe(false)
137 })
138
139 it(`should hash registered symbols`, () => {
140 const first = Symbol.for(`tanstack-db-ivm-hash-first`)
141 const same = Symbol.for(`tanstack-db-ivm-hash-first`)
142 const second = Symbol.for(`tanstack-db-ivm-hash-second`)
143
144 expect(hash(first)).toBe(hash(same))
145 expect(typeof hash(second)).toBe(hashType)
146 expect(equalHashValues(first, second)).toBe(false)
147 expect(typeof hash({ [second]: 1 })).toBe(hashType)
148 expect(equalHashValues({ [first]: 1 }, { [second]: 1 })).toBe(false)
149 })
150 })
151
152 describe(`object types`, () => {
153 it(`should hash plain objects`, () => {
154 const obj1 = { a: 1, b: 2 }
155 const obj2 = { b: 2, a: 1 } // Different key order
156
157 const hash1 = hash(obj1)
158 const hash2 = hash(obj2)
159
160 expect(typeof hash1).toBe(hashType)
161 expect(typeof hash2).toBe(hashType)
162 // Note: Different key orders might produce different hashes depending on JSON.stringify behavior
163 })
164
165 it(`includes enumerable symbol keys and values`, () => {
166 const key = Symbol(`key`)
167
168 expect(equalHashValues({ [key]: `before` }, { [key]: `after` })).toBe(
169 false,
170 )
171 expect(typeof hash({ [key]: `before` })).toBe(hashType)
172 expect(typeof hash({ [key]: `after` })).toBe(hashType)
173 const first = { [Symbol(`key`)]: `value` }
174 const second = { [Symbol(`key`)]: `value` }
175 expect(equalHashValues(first, second)).toBe(false)
176 expect(typeof hash(first)).toBe(hashType)
177 expect(typeof hash(second)).toBe(hashType)
178 })
179
180 it(`rejects self and mutual cycles through symbol keys`, () => {
181 const key = Symbol(`cycle`)
182 const first: Record<PropertyKey, unknown> = {}
183 const second: Record<PropertyKey, unknown> = {}
184 first[key] = first
185 second[key] = second
186
187 const firstPeer: Record<PropertyKey, unknown> = {}
188 const secondPeer: Record<PropertyKey, unknown> = {}
189 firstPeer[key] = secondPeer
190 secondPeer[key] = firstPeer
191
192 for (const input of [first, second, firstPeer, secondPeer]) {
193 expect(() => hash(input)).toThrow(
194 `Cannot hash cyclic structural values`,
195 )
196 expect(() => hash(input)).toThrow(
197 `Cannot hash cyclic structural values`,
198 )
199 }
200 })
201
202 it.each([`object`, `map`] as const)(
203 `rejects shared cyclic branches through %s with bounded work`,
204 (container) => {
205 const size = 14
206 let reads = 0
207 const nodes: Array<Record<string, unknown> | Map<string, unknown>> =
208 Array.from({ length: size }, (_, value) =>
209 container === `object`
210 ? { value }
211 : new Map<string, unknown>([[`value`, value]]),
212 )
213
214 for (let index = 0; index < size; index++) {
215 const node = nodes[index]!
216 const next = nodes[(index + 1) % size]!
217 for (const key of [`left`, `right`] as const) {
218 const wrapper = Object.defineProperty({}, `next`, {
219 enumerable: true,
220 get: () => {
221 reads++
222 return next
223 },
224 })
225 if (node instanceof Map) node.set(key, wrapper)
226 else node[key] = wrapper
227 }
228 }
229
230 expect(() => hash(nodes[0]!)).toThrow(
231 `Cannot hash cyclic structural values`,
232 )
233 const firstReads = reads
234 const copy = structuredClone(nodes[0]!)
235
236 expect(() => hash(copy)).toThrow(`Cannot hash cyclic structural values`)
237 expect(firstReads).toBeLessThanOrEqual(size * 2)
238 },
239 )
240
241 it(`rejects a shared child that cycles to either ancestor`, () => {
242 const createGraph = (backBranch: `left` | `right`) => {
243 const root: Record<string, unknown> = {}
244 const left: Record<string, unknown> = {}
245 const right: Record<string, unknown> = {}
246 const shared: Record<string, unknown> = {}
247 root.left = left
248 root.right = right
249 left.next = shared
250 right.next = shared
251 shared.back = backBranch === `left` ? left : right
252 return root
253 }
254
255 const left = createGraph(`left`)
256 const equalLeft = createGraph(`left`)
257 const right = createGraph(`right`)
258
259 for (const input of [left, equalLeft, right]) {
260 expect(() => hash(input)).toThrow(
261 `Cannot hash cyclic structural values`,
262 )
263 }
264 })
265
266 it(`rejects cyclic graphs with exponentially many ancestor contexts`, () => {
267 const depth = 11
268 const shared = Array.from(
269 { length: depth + 1 },
270 (_, level) => ({ level }) as Record<string, unknown>,
271 )
272 const left = Array.from({ length: depth }, (_, level) => ({
273 side: `left`,
274 level,
275 next: shared[level + 1],
276 }))
277 const right = Array.from({ length: depth }, (_, level) => ({
278 side: `right`,
279 level,
280 next: shared[level + 1],
281 }))
282 for (let level = 0; level < depth; level++) {
283 shared[level]!.left = left[level]
284 shared[level]!.right = right[level]
285 shared[depth]![`left${level}`] = left[level]
286 }
287
288 expect(() => hash(shared[0])).toThrow(TypeError)
289 expect(() => hash(shared[0])).toThrow(
290 `Cannot hash cyclic structural values`,
291 )
292
293 const ring = Array.from(
294 { length: 600 },
295 (_, value) => ({ value }) as { value: number; next?: unknown },
296 )
297 for (let index = 0; index < ring.length; index++) {
298 ring[index]!.next = ring[(index + 1) % ring.length]
299 }
300 expect(() => hash(structuredClone(ring[0]))).toThrow(
301 `Cannot hash cyclic structural values`,
302 )
303 expect(() => hash(ring[0])).toThrow(
304 `Cannot hash cyclic structural values`,
305 )
306
307 const independent: Record<string, { self?: unknown }> = {}
308 for (let index = 0; index < 600; index++) {
309 const cycle: { self?: unknown } = {}
310 cycle.self = cycle
311 independent[String(index)] = cycle
312 }
313 expect(() => hash(structuredClone(independent))).toThrow(
314 `Cannot hash cyclic structural values`,
315 )
316 expect(() => hash(independent)).toThrow(
317 `Cannot hash cyclic structural values`,
318 )
319
320 const independentDiamonds: Record<string, unknown> = {}
321 for (let index = 0; index < 600; index++) {
322 const diamondCenter: Record<string, unknown> = {}
323 const leftIngress = { next: diamondCenter }
324 const rightIngress = { next: diamondCenter }
325 diamondCenter.back = leftIngress
326 independentDiamonds[`left${index}`] = leftIngress
327 independentDiamonds[`right${index}`] = rightIngress
328 }
329 expect(() => hash(structuredClone(independentDiamonds))).toThrow(
330 `Cannot hash cyclic structural values`,
331 )
332 expect(() => hash(independentDiamonds)).toThrow(
333 `Cannot hash cyclic structural values`,
334 )
335
336 const small: { self?: unknown } = {}
337 small.self = small
338 expect(() => hash(structuredClone(small))).toThrow(
339 `Cannot hash cyclic structural values`,
340 )
341 expect(() => hash(small)).toThrow(`Cannot hash cyclic structural values`)
342 })
343
344 it(`rejects both small and large repeated cyclic traversals`, () => {
345 const createGraph = (size: number) => {
346 const nodes = Array.from(
347 { length: size },
348 (_, value) => ({ value }) as Record<string, unknown>,
349 )
350 for (let index = 0; index < size; index++) {
351 const next = nodes[(index + 1) % size]!
352 nodes[index]!.left = { next }
353 nodes[index]!.right = { next }
354 }
355 return nodes[0]
356 }
357
358 expect(() => hash(createGraph(20))).toThrow(
359 `Cannot hash cyclic structural values`,
360 )
361 expect(() => hash(createGraph(300))).toThrow(
362 `Cannot hash cyclic structural values`,
363 )
364 })
365
366 it(`does not warm structural caches when a hash is rejected`, () => {
367 let reads = 0
368 const sentinel = Object.defineProperty({}, `value`, {
369 enumerable: true,
370 get: () => ++reads,
371 })
372 const shared: Record<string, unknown> = {
373 payload: Array.from({ length: 66_000 }, (_, value) => ({ value })),
374 }
375 const left = { next: shared }
376 const right = { next: shared }
377 shared.back = left
378 const root = { aSentinel: sentinel, left, right }
379
380 expect(() => hash(root)).toThrow(`Cannot hash cyclic structural values`)
381 expect(() => hash(root)).toThrow(`Cannot hash cyclic structural values`)
382 expect(reads).toBe(2)
383 })
384
385 it.each([
386 [`Buffer`, () => Buffer.alloc(129)],
387 [`Uint8Array`, () => new Uint8Array(129)],
388 [`File`, () => new File([`opaque`], `opaque.bin`)],
389 ])(
390 `treats a large %s as an opaque leaf before structural work`,
391 (_name, createLeaf) => {
392 const leaves = Array.from({ length: 700 }, () => createLeaf())
393 for (const leaf of leaves) Object.assign(leaf, { self: leaf })
394 const createChain = () => {
395 const ring = leaves.map((leaf, value) => ({
396 value,
397 leaf,
398 next: undefined as unknown,
399 }))
400 for (let index = 0; index < ring.length; index++) {
401 ring[index]!.next = ring[index + 1]
402 }
403 return ring[0]
404 }
405
406 const first = createChain()
407 const expectedHash = hash(first)
408 expect(hash(first)).toBe(expectedHash)
409 expect(hash(createChain())).toBe(expectedHash)
410
411 let atDepthBoundary: unknown = createLeaf()
412 for (let index = 0; index < 768; index++) {
413 atDepthBoundary = { next: atDepthBoundary }
414 }
415 expect(() => hash(atDepthBoundary)).not.toThrow()
416
417 const adoptionLeaves = Array.from({ length: 20 }, () => createLeaf())
418 const createAdoptionGraph = () => {
419 const nodes = adoptionLeaves.map((leaf, value) => ({
420 value,
421 leaf,
422 })) as Array<Record<string, unknown>>
423 for (let index = 0; index < nodes.length; index++) {
424 const next = nodes[index + 1]
425 nodes[index]!.left = { next }
426 nodes[index]!.right = { next }
427 }
428 return nodes[0]
429 }
430 expect(hash(createAdoptionGraph())).toBe(hash(createAdoptionGraph()))
431 },
432 )
433
434 it(`rejects deep structural recursion before the JavaScript stack overflows`, () => {
435 let reads = 0
436 const sentinel = Object.defineProperty({}, `value`, {
437 enumerable: true,
438 get: () => ++reads,
439 })
440 const ring = Array.from(
441 { length: 800 },
442 (_, value) => ({ value }) as { value: number; next?: unknown },
443 )
444 for (let index = 0; index < ring.length; index++) {
445 ring[index]!.next = ring[(index + 1) % ring.length]
446 }
447 Object.defineProperty(ring[0]!, `aSentinel`, {
448 enumerable: true,
449 value: sentinel,
450 })
451
452 expect(() => hash(ring[0])).toThrow(
453 `Value is too complex to hash safely: structural depth`,
454 )
455 expect(() => hash(ring[0])).toThrow(
456 `Value is too complex to hash safely: structural depth`,
457 )
458 expect(reads).toBe(2)
459
460 const createChain = (size: number) => {
461 const root: { next?: unknown } = {}
462 let tail = root
463 for (let index = 0; index < size; index++) {
464 const next: { next?: unknown } = {}
465 tail.next = next
466 tail = next
467 }
468 return root
469 }
470 const accepted = createChain(600)
471 expect(hash(structuredClone(accepted))).toBe(hash(accepted))
472
473 const root = createChain(800)
474 expect(() => hash(root)).toThrow(
475 `Value is too complex to hash safely: structural depth`,
476 )
477 })
478
479 it(`rejects dense ancestor back-references without warming siblings`, () => {
480 const createGraph = (size: number) => {
481 const nodes: Array<Record<string, unknown>> = []
482 for (let index = 0; index < size; index++) {
483 const node: Record<string, unknown> = { index }
484 if (index > 0) nodes[index - 1]!.next = node
485 for (let ancestor = 0; ancestor < index; ancestor++) {
486 node[`ancestor${ancestor}`] = nodes[ancestor]
487 }
488 nodes.push(node)
489 }
490 return nodes[0]!
491 }
492 const accepted = createGraph(50)
493 expect(() => hash(structuredClone(accepted))).toThrow(
494 `Cannot hash cyclic structural values`,
495 )
496 expect(() => hash(accepted)).toThrow(
497 `Cannot hash cyclic structural values`,
498 )
499
500 let reads = 0
501 const sentinel = Object.defineProperty({}, `value`, {
502 enumerable: true,
503 get: () => ++reads,
504 })
505 const rejected = createGraph(450)
506 Object.defineProperty(rejected, `aSentinel`, {
507 enumerable: true,
508 value: sentinel,
509 })
510
511 expect(() => hash(rejected)).toThrow(
512 `Cannot hash cyclic structural values`,
513 )
514 expect(() => hash(rejected)).toThrow(
515 `Cannot hash cyclic structural values`,
516 )
517 expect(reads).toBe(2)
518 })
519
520 it(`should hash arrays`, () => {
521 const arr1 = [1, 2, 3]
522 const arr2 = [1, 2, 3]
523 const arr3 = [3, 2, 1]
524
525 const hash1 = hash(arr1)
526 const hash2 = hash(arr2)
527 const hash3 = hash(arr3)
528
529 expect(typeof hash1).toBe(hashType)
530 expect(typeof hash3).toBe(hashType)
531 expect(hash1).toBe(hash2) // Same content should have same hash
532 expect(equalHashValues(arr1, arr3)).toBe(false)
533 })
534
535 it(`should hash Date objects`, () => {
536 const date1 = new Date(`2023-01-01`)
537 const date2 = new Date(`2023-01-01`)
538 const date3 = new Date(`2023-01-02`)
539
540 const hash1 = hash(date1)
541 const hash2 = hash(date2)
542 const hash3 = hash(date3)
543
544 expect(typeof hash1).toBe(hashType)
545 expect(typeof hash3).toBe(hashType)
546 expect(hash1).toBe(hash2) // Same date should have same hash
547 expect(equalHashValues(date1, date3)).toBe(false)
548 })
549
550 it(`should hash Temporal objects by value`, () => {
551 const date1 = Temporal.PlainDate.from(`2024-01-15`)
552 const date2 = Temporal.PlainDate.from(`2024-01-15`)
553 const date3 = Temporal.PlainDate.from(`2024-06-15`)
554
555 const hash1 = hash(date1)
556 const hash2 = hash(date2)
557 const hash3 = hash(date3)
558
559 expect(typeof hash1).toBe(hashType)
560 expect(typeof hash3).toBe(hashType)
561 expect(hash1).toBe(hash2) // Same Temporal date should have same hash
562 expect(equalHashValues(date1, date3)).toBe(false)
563
564 // Different Temporal types with overlapping string representations should differ
565 const plainDate = Temporal.PlainDate.from(`2024-01-15`)
566 const plainDateTime = Temporal.PlainDateTime.from(`2024-01-15T00:00:00`)
567
568 expect(equalHashValues(plainDate, plainDateTime)).toBe(false)
569 expect(typeof hash(plainDate)).toBe(hashType)
570 expect(typeof hash(plainDateTime)).toBe(hashType)
571
572 // Other Temporal types should also hash correctly
573 const time1 = Temporal.PlainTime.from(`10:30:00`)
574 const time2 = Temporal.PlainTime.from(`10:30:00`)
575 const time3 = Temporal.PlainTime.from(`14:00:00`)
576
577 expect(hash(time1)).toBe(hash(time2))
578 expect(equalHashValues(time1, time3)).toBe(false)
579 expect(typeof hash(time3)).toBe(hashType)
580
581 const instant1 = Temporal.Instant.from(`2024-01-15T00:00:00Z`)
582 const instant2 = Temporal.Instant.from(`2024-01-15T00:00:00Z`)
583 const instant3 = Temporal.Instant.from(`2024-06-15T00:00:00Z`)
584
585 expect(hash(instant1)).toBe(hash(instant2))
586 expect(equalHashValues(instant1, instant3)).toBe(false)
587 expect(typeof hash(instant3)).toBe(hashType)
588 })
589
590 it(`should hash RegExp objects`, () => {
591 const regex1 = /test/g
592 const regex2 = /test/g
593 const regex3 = /different/i
594 const regex4 = /test/g
595 regex4.lastIndex = 1
596
597 const hash1 = hash(regex1)
598 const hash2 = hash(regex2)
599 const hash3 = hash(regex3)
600 const hash4 = hash(regex4)
601
602 expect(typeof hash1).toBe(hashType)
603 expect(typeof hash3).toBe(hashType)
604 expect(typeof hash4).toBe(hashType)
605 expect(hash1).toBe(hash2) // Same regex should have same hash
606 expect(equalHashValues(regex1, regex3)).toBe(false)
607 expect(equalHashValues(regex1, regex4)).toBe(false)
608 })
609
610 it(`should distinguish sparse arrays by length`, () => {
611 expect(equalHashValues([], Array(1))).toBe(false)
612 expect(equalHashValues(Array(1), Array(2))).toBe(false)
613 expect(typeof hash([])).toBe(hashType)
614 expect(typeof hash(Array(1))).toBe(hashType)
615 expect(typeof hash(Array(2))).toBe(hashType)
616 expect(hash(Array(2))).toBe(hash(Array(2)))
617 })
618
619 it(`should hash nested objects`, () => {
620 const nested1 = { a: { b: { c: 1 } } }
621 const nested2 = { a: { b: { c: 1 } } }
622 const nested3 = { a: { b: { c: 2 } } }
623
624 const hash1 = hash(nested1)
625 const hash2 = hash(nested2)
626 const hash3 = hash(nested3)
627
628 expect(typeof hash1).toBe(hashType)
629 expect(typeof hash3).toBe(hashType)
630 expect(hash1).toBe(hash2)
631 expect(equalHashValues(nested1, nested3)).toBe(false)
632 })
633
634 it(`should hash functions`, () => {
635 const func1 = function test() {
636 return 1
637 }
638 const func2 = function test() {
639 return 1
640 }
641 const func3 = function different() {
642 return 2
643 }
644
645 const hash1 = hash(func1)
646 const hash2 = hash(func2)
647 const hash3 = hash(func3)
648
649 expect(typeof hash1).toBe(hashType)
650 expect(typeof hash2).toBe(hashType)
651 expect(typeof hash3).toBe(hashType)
652 expect(equalHashValues(func1, func2)).toBe(false)
653 expect(equalHashValues(func1, func3)).toBe(false)
654 expect(hash1).toBe(hash(func1)) // hashing same function should return same hash
655 })
656
657 it(`should hash Set objects`, () => {
658 const set1 = new Set([1, 2, 3])
659 const set2 = new Set([1, 2, 3])
660 const set3 = new Set([1, 2, 3, 4])
661
662 const hash1 = hash(set1)
663 const hash2 = hash(set2)
664 const hash3 = hash(set3)
665
666 expect(typeof hash1).toBe(hashType)
667 expect(typeof hash3).toBe(hashType)
668 expect(hash1).toBe(hash2) // Same content should have same hash
669 expect(equalHashValues(set1, set3)).toBe(false)
670 })
671
672 it(`should hash Map objects`, () => {
673 const map1 = new Map([
674 [`a`, 1],
675 [`b`, 2],
676 ])
677 const map2 = new Map([
678 [`a`, 1],
679 [`b`, 2],
680 ])
681 const map3 = new Map([
682 [`a`, 1],
683 [`b`, 2],
684 [`c`, 3],
685 ])
686
687 const hash1 = hash(map1)
688 const hash2 = hash(map2)
689 const hash3 = hash(map3)
690
691 expect(typeof hash1).toBe(hashType)
692 expect(typeof hash3).toBe(hashType)
693 expect(hash1).toBe(hash2) // Same content should have same hash
694 expect(equalHashValues(map1, map3)).toBe(false)
695 })
696
697 it(`should hash Maps and Sets with unsupported types`, () => {
698 // Map with BigInt values
699 const mapWithBigInt1 = new Map([
700 [`a`, 123n],
701 [`b`, 456n],
702 ])
703 const mapWithBigInt2 = new Map([
704 [`a`, 123n],
705 [`b`, 456n],
706 ])
707 const mapWithBigInt3 = new Map([
708 [`a`, 123n],
709 [`b`, 789n],
710 ])
711
712 const hash1 = hash(mapWithBigInt1)
713 const hash2 = hash(mapWithBigInt2)
714 const hash3 = hash(mapWithBigInt3)
715
716 expect(typeof hash1).toBe(hashType)
717 expect(typeof hash3).toBe(hashType)
718 expect(hash1).toBe(hash2) // Same BigInt content should have same hash
719 expect(equalHashValues(mapWithBigInt1, mapWithBigInt3)).toBe(false)
720
721 // Set with Symbol values
722 const sym1 = Symbol(`test`)
723 const sym2 = Symbol(`different`)
724 const setWithSymbols1 = new Set([sym1, sym2])
725 const setWithSymbols2 = new Set([sym1, sym2])
726 const setWithSymbols3 = new Set([sym1])
727
728 const hash4 = hash(setWithSymbols1)
729 const hash5 = hash(setWithSymbols2)
730 const hash6 = hash(setWithSymbols3)
731
732 expect(typeof hash4).toBe(hashType)
733 expect(typeof hash6).toBe(hashType)
734 expect(hash4).toBe(hash5) // Same Symbol content should have same hash
735 expect(equalHashValues(setWithSymbols1, setWithSymbols3)).toBe(false)
736 })
737
738 it(`should hash small Buffers and Uint8Arrays by content`, () => {
739 // Small buffers (≤128 bytes) are hashed by content for proper equality comparisons
740 const buffer1 = Buffer.from([1, 2, 3])
741 const buffer2 = Buffer.from([1, 2, 3])
742 const buffer3 = Buffer.from([1, 2, 3, 4])
743
744 const hash1 = hash(buffer1)
745 const hash2 = hash(buffer2)
746 const hash3 = hash(buffer3)
747
748 expect(typeof hash1).toBe(hashType)
749 expect(typeof hash3).toBe(hashType)
750 expect(hash1).toBe(hash2) // Same content = same hash for small buffers
751 expect(equalHashValues(buffer1, buffer3)).toBe(false)
752 expect(hash1).toBe(hash(buffer1)) // Hashing same buffer should return same hash
753
754 const uint8Array1 = new Uint8Array([1, 2, 3])
755 const uint8Array2 = new Uint8Array([1, 2, 3])
756 const uint8Array3 = new Uint8Array([1, 2, 3, 4])
757
758 const hash4 = hash(uint8Array1)
759 const hash5 = hash(uint8Array2)
760 const hash6 = hash(uint8Array3)
761
762 expect(typeof hash4).toBe(hashType)
763 expect(typeof hash6).toBe(hashType)
764 expect(hash4).toBe(hash5) // Same content = same hash for small Uint8Arrays
765 expect(equalHashValues(uint8Array1, uint8Array3)).toBe(false)
766 expect(hash4).toBe(hash(uint8Array1)) // Hashing same uint8Array should return same hash
767 })
768
769 it(`should hash large Buffers, Uint8Arrays and File objects by reference`, () => {
770 // Large buffers (>128 bytes) are hashed by reference to avoid performance costs
771 const largeBuffer1 = Buffer.alloc(300)
772 const largeBuffer2 = Buffer.alloc(300)
773
774 // Fill with same content
775 for (let i = 0; i < 300; i++) {
776 largeBuffer1[i] = i % 256
777 largeBuffer2[i] = i % 256
778 }
779
780 const hash1 = hash(largeBuffer1)
781 const hash2 = hash(largeBuffer2)
782
783 expect(typeof hash1).toBe(hashType)
784 expect(typeof hash2).toBe(hashType)
785 expect(equalHashValues(largeBuffer1, largeBuffer2)).toBe(false)
786 expect(hash1).toBe(hash(largeBuffer1)) // Hashing same buffer should return same hash
787
788 const largeUint8Array1 = new Uint8Array(300)
789 const largeUint8Array2 = new Uint8Array(300)
790
791 // Fill with same content
792 for (let i = 0; i < 300; i++) {
793 largeUint8Array1[i] = i % 256
794 largeUint8Array2[i] = i % 256
795 }
796
797 const hash3 = hash(largeUint8Array1)
798 const hash4 = hash(largeUint8Array2)
799
800 expect(typeof hash3).toBe(hashType)
801 expect(typeof hash4).toBe(hashType)
802 expect(equalHashValues(largeUint8Array1, largeUint8Array2)).toBe(false)
803 expect(hash3).toBe(hash(largeUint8Array1)) // Hashing same uint8Array should return same hash
804
805 // Files are always hashed by reference regardless of size
806 const file1 = new File([`Hello, world!`], `test.txt`)
807 const file2 = new File([`Hello, world!`], `test.txt`)
808 const file3 = new File([`Hello, world!`], `test.txt`)
809
810 const hash7 = hash(file1)
811 const hash8 = hash(file2)
812 const hash9 = hash(file3)
813
814 expect(typeof hash7).toBe(hashType)
815 expect(typeof hash8).toBe(hashType)
816 expect(typeof hash9).toBe(hashType)
817 expect(equalHashValues(file1, file2)).toBe(false)
818 expect(equalHashValues(file1, file3)).toBe(false)
819 expect(hash7).toBe(hash(file1)) // Hashing same file should return same hash
820 })
821 })
822
823 describe(`caching behavior`, () => {
824 it(`should cache hash values for objects`, () => {
825 const obj = { test: `value` }
826
827 const hash1 = hash(obj)
828 const hash2 = hash(obj)
829
830 expect(hash1).toBe(hash2)
831 expect(typeof hash1).toBe(hashType)
832 })
833
834 it(`should return cached values on subsequent calls`, () => {
835 const obj = { complex: { nested: { data: [1, 2, 3] } } }
836
837 // First call should compute and cache
838 const hash1 = hash(obj)
839
840 // Second call should return cached value
841 const hash2 = hash(obj)
842
843 expect(hash1).toBe(hash2)
844 expect(typeof hash1).toBe(hashType)
845 })
846
847 it(`should not cache primitive values`, () => {
848 // Primitives should not be cached as they use JSON.stringify directly
849 const hash1 = hash(`test`)
850 const hash2 = hash(`test`)
851
852 expect(hash1).toBe(hash2)
853 expect(typeof hash1).toBe(hashType)
854 })
855 })
856
857 describe(`edge cases`, () => {
858 it(`should handle empty objects and arrays`, () => {
859 expect(typeof hash({})).toBe(hashType)
860 expect(typeof hash([])).toBe(hashType)
861 expect(equalHashValues({}, [])).toBe(false)
862 })
863
864 it(`should handle objects with null and undefined values`, () => {
865 const obj1 = { a: null, b: undefined }
866 const obj2 = { a: null, b: undefined }
867
868 const hash1 = hash(obj1)
869 const hash2 = hash(obj2)
870
871 expect(hash1).toBe(hash2)
872 expect(typeof hash1).toBe(hashType)
873 })
874
875 it(`should distinguish between arrays and maps`, () => {
876 const array = [
877 [1, 2],
878 [3, 4],
879 ] as const
880 const map = new Map(array)
881
882 const hash1 = hash(array)
883 const hash2 = hash(map)
884
885 expect(typeof hash1).toBe(hashType)
886 expect(typeof hash2).toBe(hashType)
887 expect(equalHashValues(array, map)).toBe(false)
888 })
889
890 it(`should handle mixed type arrays`, () => {
891 const mixedArray = [1, `string`, true, null, { key: `value` }]
892 const sameArray = [1, `string`, true, null, { key: `value` }]
893
894 const hash1 = hash(mixedArray)
895 const hash2 = hash(sameArray)
896
897 expect(hash1).toBe(hash2)
898 expect(typeof hash1).toBe(hashType)
899 })
900
901 it(`should produce consistent hashes for same content`, () => {
902 const obj = {
903 string: `test`,
904 number: 42,
905 boolean: true,
906 array: [1, 2, 3],
907 nested: { inner: `value` },
908 buffer: Buffer.from([1, 2, 3]),
909 uint8Array: new Uint8Array([1, 2, 3]),
910 file: new File([`Hello, world!`], `test.txt`),
911 }
912
913 // Multiple calls should return the same hash
914 const hashes = Array.from({ length: 5 }, () => hash(obj))
915 const firstHash = hashes[0]
916
917 expect(hashes.every((h) => h === firstHash)).toBe(true)
918 expect(typeof firstHash).toBe(hashType)
919 })
920 })
921})