Open History to see the last commit
1import assert from 'node:assert/strict'
2import { readFileSync } from 'node:fs'
3import { fileURLToPath } from 'node:url'
4import { Script } from 'node:vm'
5import { JSDOM, VirtualConsole } from 'jsdom'
6import { clientUrl, hashLinkCount, ordinaryLinkCount } from './fixture'
7import { settleHydration } from './settle'
8import type { FixtureArtifact } from './fixture'
9import type * as Client from './src/client'
10β
11type ClientApp = typeof Client
12type TaskHooks = {
13 opts: {
14 beforeEach?: () => void | Promise<void>
15 afterEach?: () => void | Promise<void>
16 }
17}
18β
19const turn = () => new Promise<void>((resolve) => setImmediate(resolve))
20β
21// React's scheduler ends a time slice once performance.now() has advanced 5 ms.
22// Under CodSpeed's CPU simulation the wall clock advances much further per
23// instruction, by a runner-dependent factor, so real time turned identical
24// samples into different numbers of yields, scheduler tasks and event-loop
25// turns. With a frozen clock React yields only to paint after a commit, as on
26// a fast host. 1 s is past React's initial 300 ms fallback throttle. Only the
27// window's performance clock is pinned: Date.now(), which the Router uses for
28// match timestamps, is unchanged.
29const schedulerTime = 1_000
30β
31export function setup({ countRenders = false } = {}) {
32 // Compile once, outside measurement. Evaluation below creates fresh objects
33 // in each window's realm; neither the payload nor module state is reused.
34 const artifact: FixtureArtifact = JSON.parse(
35 readFileSync(new URL('./dist/fixture.json', import.meta.url), 'utf8'),
36 )
37 const clientPath = new URL('./dist/client/client.js', import.meta.url)
38 const clientScript = new Script(readFileSync(clientPath, 'utf8'), {
39 filename: fileURLToPath(clientPath),
40 })
41 const bootstrapScripts = artifact.scripts.map(
42 (source, index) =>
43 new Script(source, {
44 filename: `hydration-bootstrap-${index}.js`,
45 }),
46 )
47 let current: Awaited<ReturnType<typeof prepare>> | undefined
48β
49 async function prepare() {
50 const errors: Array<string> = []
51 const virtualConsole = new VirtualConsole()
52 virtualConsole.on('jsdomError', (error) => errors.push(String(error)))
53 virtualConsole.on('error', (...args) =>
54 errors.push(args.map(String).join(' ')),
55 )
56 const dom = new JSDOM(artifact.html, {
57 url: `http://localhost${clientUrl}`,
58 runScripts: 'outside-only',
59 virtualConsole,
60 })
61 const immediates = new Set<NodeJS.Immediate>()
62 const scheduler = { tasks: 0 }
63 try {
64 Object.assign(dom.window, {
65 TextEncoder,
66 TextDecoder,
67 ReadableStream,
68 WritableStream,
69 TransformStream,
70 // Let React's production scheduler use the same task-turn primitive as
71 // the existing Node client benchmarks, without a real-delay timer.
72 setImmediate(
73 callback: (...args: Array<unknown>) => void,
74 ...args: Array<unknown>
75 ) {
76 scheduler.tasks++
77 const handle = setImmediate(() => {
78 immediates.delete(handle)
79 callback(...args)
80 })
81 immediates.add(handle)
82 return handle
83 },
84 clearImmediate(handle: NodeJS.Immediate) {
85 immediates.delete(handle)
86 clearImmediate(handle)
87 },
88 fetch() {
89 throw new Error('Hydration attempted a network request')
90 },
91 scrollTo() {},
92 })
93 dom.window.performance.now = () => schedulerTime
94 const context = dom.getInternalVMContext()
95 // jsdom has no layout/scroll implementation; only hydration CPU is measured.
96 dom.window.HTMLElement.prototype.scrollIntoView = () => {}
97 clientScript.runInContext(context)
98 const app = (dom.window as unknown as { HydrationBenchmark: ClientApp })
99 .HydrationBenchmark
100 assert.equal(app.serverEnvironment, false)
101 const anchors = Array.from(dom.window.document.querySelectorAll('a'))
102 const scriptElements = Array.from(
103 dom.window.document.querySelectorAll('script'),
104 )
105 const executingScript = { current: null as HTMLScriptElement | null }
106 Object.defineProperty(dom.window.document, 'currentScript', {
107 configurable: true,
108 get: () => executingScript.current,
109 })
110 assert.equal(anchors.length, ordinaryLinkCount + hashLinkCount)
111 const content = dom.window.document.getElementById('hydration-content')
112 assert.ok(content)
113 // Finish jsdom's initial document lifecycle before opening the measure.
114 await turn()
115 assert.equal(dom.window.document.readyState, 'complete')
116 assert.equal(app.ready(), false)
117 return {
118 dom,
119 context,
120 app,
121 anchors,
122 content,
123 scriptElements,
124 executingScript,
125 immediates,
126 scheduler,
127 errors,
128 started: false,
129 completed: false,
130 failed: false,
131 }
132 } catch (error) {
133 for (const handle of immediates) {
134 clearImmediate(handle)
135 }
136 dom.window.close()
137 throw error
138 }
139 }
140β
141 async function before() {
142 if (current) {
143 throw new Error('Previous hydration sample was not disposed')
144 }
145 current = await prepare()
146 }
147β
148 async function run() {
149 const sample = current
150 if (!sample || sample.started) {
151 throw new Error('Hydration requires a newly prepared sample')
152 }
153 sample.started = true
154 try {
155 // HTML parsing/module evaluation are already done. Payload execution,
156 // router initialization/restoration and React hydration are measured.
157 for (let index = 0; index < bootstrapScripts.length; index++) {
158 // SSR bootstrap scripts remove their own script element after running.
159 sample.executingScript.current = sample.scriptElements[index]!
160 try {
161 bootstrapScripts[index]!.runInContext(sample.context)
162 } finally {
163 sample.executingScript.current = null
164 }
165 }
166 await settleHydration(
167 sample.app.start(countRenders),
168 () => sample.immediates.size === 0,
169 () => {
170 const progress = sample.app.snapshot()
171 return JSON.stringify({
172 diagnostics: progress.diagnostics,
173 errors: [...sample.errors, ...progress.errors],
174 restoredMatches: progress.matches?.length,
175 pendingSchedulerCallbacks: sample.immediates.size,
176 })
177 },
178 )
179 if (sample.errors.length) {
180 throw new Error(sample.errors.join('\n'))
181 }
182 assert.ok(
183 sample.app.ready(),
184 'Hydration committed without the expected active links',
185 )
186 sample.completed = true
187 } catch (error) {
188 sample.failed = true
189 throw error
190 }
191 }
192β
193 function snapshot() {
194 if (!current) {
195 throw new Error('No hydration sample')
196 }
197 // Normalize realm prototypes only for untimed assertions.
198 return JSON.parse(JSON.stringify(current.app.snapshot())) as ReturnType<
199 ClientApp['snapshot']
200 >
201 }
202β
203 function schedulerTasks() {
204 if (!current) {
205 throw new Error('No hydration sample')
206 }
207 return current.scheduler.tasks
208 }
209β
210 function validate() {
211 assert.ok(current?.started)
212 const { dom, anchors, content, errors } = current
213 const doc = dom.window.document
214 const result = snapshot()
215 assert.deepEqual(errors, [])
216 assert.deepEqual(result.errors, [])
217 assert.equal(result.diagnostics.beforeLoads, 0)
218 assert.equal(result.diagnostics.loaders, 0)
219 assert.equal(result.diagnostics.mounted, true)
220 assert.equal(result.location, clientUrl)
221 assert.equal(result.matches?.length, 3)
222 for (const match of result.matches) {
223 assert.equal(match.status, 'success')
224 assert.deepEqual(match.context.viewer, {
225 id: 'viewer-3',
226 name: 'Ada',
227 role: 'editor',
228 })
229 }
230 assert.deepEqual(result.matches[1]!.context.team, {
231 id: 'team-7',
232 member: 'viewer-3',
233 })
234 assert.deepEqual(result.matches[2]!.context.permissions, { edit: true })
235 assert.deepEqual(result.matches[1]!.loaderData, {
236 title: 'Team team-7',
237 categories: ['open', 'closed'],
238 })
239 const data = result.matches[2]!.loaderData as {
240 owner: string
241 selected: string
242 rows: Array<{
243 id: string
244 label: string
245 details: { score: number; open: boolean }
246 }>
247 }
248 assert.equal(data.owner, 'viewer-3')
249 assert.equal(data.selected, 'item-42')
250 assert.equal(data.rows.length, ordinaryLinkCount)
251 assert.equal(doc.getElementById('hydration-content'), content)
252 assert.equal(doc.querySelectorAll('a').length, anchors.length)
253 assert.equal(doc.getElementById('viewer')?.textContent, 'Ada')
254 assert.equal(doc.getElementById('permission')?.textContent, 'Editable')
255 for (const anchor of anchors) {
256 assert.equal(doc.getElementById(anchor.id), anchor)
257 }
258 for (let index = 0; index < ordinaryLinkCount; index++) {
259 const anchor = doc.getElementById(`ordinary-item-${index}`)!
260 assert.equal(
261 anchor.getAttribute('href'),
262 `/teams/team-7/items/item-${index}?view=summary`,
263 )
264 assert.equal(anchor.textContent, `Item ${index}`)
265 assert.equal(
266 anchor.getAttribute('data-status'),
267 index === 42 ? 'active' : null,
268 )
269 assert.deepEqual(data.rows[index], {
270 id: `item-${index}`,
271 label: `Item ${index}`,
272 details: { score: index * 3, open: index % 2 === 0 },
273 })
274 }
275 for (let index = 0; index < hashLinkCount; index++) {
276 assert.equal(
277 doc.getElementById(`hash-${index}`)?.getAttribute('data-status'),
278 index % 2 === 0 ? 'active' : null,
279 )
280 }
281 doc
282 .getElementById('interactive')!
283 .dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }))
284 assert.equal(
285 current.app.snapshot().diagnostics.clicks,
286 result.diagnostics.clicks + 1,
287 )
288 }
289β
290 async function after() {
291 const sample = current
292 if (!sample) {
293 return
294 }
295 try {
296 if (!sample.failed) {
297 assert.ok(sample.completed, 'Hydration sample was not completed')
298 validate()
299 }
300 } finally {
301 current = undefined
302 try {
303 sample.app.dispose()
304 // Unmount work and its scheduled effects stay outside the measure.
305 await turn()
306 await turn()
307 } finally {
308 for (const handle of sample.immediates) {
309 clearImmediate(handle)
310 }
311 sample.dom.window.close()
312 }
313 }
314 }
315β
316 return {
317 before,
318 run,
319 after,
320 snapshot,
321 schedulerTasks,
322 // Vitest passes setup to the Tinybench Bench, where it runs once per
323 // warmup/run stage. Install the Task's public per-iteration hooks there.
324 installIterationHooks(task: TaskHooks) {
325 task.opts.beforeEach = before
326 task.opts.afterEach = after
327 },
328 }
329}