-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathintercept-new-run-context.ts
More file actions
51 lines (37 loc) · 1.47 KB
/
intercept-new-run-context.ts
File metadata and controls
51 lines (37 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import type { ScriptCoverageWithOffset } from './provider'
import { WebSocket } from 'ws'
import provider from './index'
// eslint-disable-next-line antfu/no-top-level-await -- This should be blocking module loading
await initialize().catch((error) => {
console.error('[vitest-coverage] Error initializing process/thread intercepting:', error)
throw error
})
async function initialize() {
let reportedCoverage = false
const ws = new WebSocket(`ws://localhost:${Number(process.env.VITEST_WS_PORT)}`)
// @ts-expect-error -- untyped
ws.on('open', () => ws._socket?.unref?.())
await provider.startCoverage?.({
isolate: true,
// Environment options that were set by parent should inherit, no need to add more ws servers
trackProcessAndWorker: false,
})
onMessage(message => message === 'take-coverage' && takeCoverage())
process.on('beforeExit', takeCoverage)
async function takeCoverage() {
if (reportedCoverage) {
return
}
reportedCoverage = true
const coverage = await provider.takeCoverage?.({
// Start offset should be 0 as these run outside of Vite
moduleExecutionInfo: undefined,
}) as { result: ScriptCoverageWithOffset[] }
ws.send(JSON.stringify(coverage.result.map(entry => ({ ...entry, isExtendedContext: true }))))
await provider.stopCoverage?.({ isolate: true })
ws.close()
}
async function onMessage(callback: (message: unknown) => void) {
ws.on('message', raw => callback(raw.toString()))
}
}