/
child.ts
96 lines (86 loc) · 2.47 KB
/
child.ts
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import v8 from 'node:v8'
import { createBirpc } from 'birpc'
import { parseRegexp } from '@vitest/utils'
import type { ResolvedConfig } from '../types'
import type { RunnerRPC, RuntimeRPC } from '../types/rpc'
import type { ChildContext } from '../types/child'
import { getWorkerState } from '../utils'
import { mockMap, moduleCache, startViteNode } from './execute'
import { rpcDone } from './rpc'
import { setupInspect } from './inspector'
function init(ctx: ChildContext) {
const { config } = ctx
process.env.VITEST_WORKER_ID = '1'
process.env.VITEST_POOL_ID = '1'
// @ts-expect-error untyped global
globalThis.__vitest_environment__ = config.environment
// @ts-expect-error I know what I am doing :P
globalThis.__vitest_worker__ = {
ctx,
moduleCache,
config,
mockMap,
durations: {
environment: 0,
prepare: performance.now(),
},
rpc: createBirpc<RuntimeRPC, RunnerRPC>(
{
onCancel: () => {
getWorkerState().isCancelling = true
},
},
{
eventNames: ['onUserConsoleLog', 'onFinished', 'onCollected', 'onWorkerExit'],
serialize: v8.serialize,
deserialize: v => v8.deserialize(Buffer.from(v)),
post(v) {
process.send?.(v)
},
on(fn) { process.on('message', fn) },
},
),
}
if (ctx.invalidates) {
ctx.invalidates.forEach((fsPath) => {
moduleCache.delete(fsPath)
moduleCache.delete(`mock:${fsPath}`)
})
}
ctx.files.forEach(i => moduleCache.delete(i))
}
function parsePossibleRegexp(str: string | RegExp) {
const prefix = '$$vitest:'
if (typeof str === 'string' && str.startsWith(prefix))
return parseRegexp(str.slice(prefix.length))
return str
}
function unwrapConfig(config: ResolvedConfig) {
if (config.testNamePattern)
config.testNamePattern = parsePossibleRegexp(config.testNamePattern) as RegExp
return config
}
export async function run(ctx: ChildContext) {
const inspectorCleanup = setupInspect(ctx.config)
try {
init(ctx)
const { run, executor } = await startViteNode(ctx)
await run(ctx.files, ctx.config, ctx.environment, executor)
await rpcDone()
}
finally {
inspectorCleanup()
}
}
const procesExit = process.exit
process.on('message', async (message: any) => {
if (typeof message === 'object' && message.command === 'start') {
try {
message.config = unwrapConfig(message.config)
await run(message)
}
finally {
procesExit()
}
}
})