Open History to see the last commit
1import { createHash } from 'node:crypto'
2import { readFileSync } from 'node:fs'
3import { dirname, resolve } from 'node:path'
4import { fileURLToPath } from 'node:url'
5import { vi } from 'vitest'
6import { fc } from '@fast-check/vitest'
7import vitestPackage from 'vitest/package.json'
8import type * as HashModuleExports from '../src/hashing/hash'
9
10type HashModule = Pick<
11 typeof HashModuleExports,
12 `hash` | `registerOpaqueHash` | `equalHashValues`
13>
14
15const sourceDirectory = resolve(
16 dirname(fileURLToPath(import.meta.url)),
17 `../src/hashing`,
18)
19const sourceDigest = createHash(`sha256`)
20 .update(readFileSync(resolve(sourceDirectory, `hash.ts`)))
21 .update(readFileSync(resolve(sourceDirectory, `murmur.ts`)))
22 .digest(`hex`)
23
24export type HashSession = HashModule & {
25 readonly tape: ReadonlyArray<number>
26 readonly environment: Readonly<{
27 node: string
28 platform: string
29 arch: string
30 fastCheck: string
31 vitest: string
32 hashSources: string
33 }>
34}
35
36// Only module initialization is recorded/replayed. Hash calls and fast-check
37// generation run after the spy has been restored. Call serially within a file.
38export async function captureHashSession(
39 tape?: ReadonlyArray<number>,
40 load: () => Promise<HashModule> = () => import('../src/hashing/hash'),
41): Promise<HashSession> {
42 vi.resetModules()
43 const replayTape = tape?.slice()
44 const nativeRandom = Math.random
45 const draws: Array<number> = []
46 let cursor = 0
47 const random = vi.spyOn(Math, `random`).mockImplementation(() => {
48 if (replayTape && cursor >= replayTape.length)
49 throw new Error(`Hash replay tape exhausted`)
50 const value = replayTape ? replayTape[cursor++]! : nativeRandom()
51 if (!Number.isFinite(value) || value < 0 || value >= 1) {
52 throw new Error(`Invalid hash initialization draw`)
53 }
54 draws.push(value)
55 return value
56 })
57 try {
58 const module = await load()
59 if (replayTape && cursor !== replayTape.length)
60 throw new Error(`Unused hash replay draws`)
61 return {
62 ...module,
63 tape: Object.freeze(draws),
64 environment: Object.freeze({
65 node: process.version,
66 platform: process.platform,
67 arch: process.arch,
68 fastCheck: fc.__version,
69 vitest: vitestPackage.version,
70 hashSources: sourceDigest,
71 }),
72 }
73 } finally {
74 random.mockRestore()
75 }
76}