/
worker.ts
58 lines (51 loc) · 1.75 KB
/
worker.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
import { createBirpc } from 'birpc'
import { workerId as poolId } from 'tinypool'
import type { RuntimeRPC, WorkerContext } from '../types'
import { getWorkerState } from '../utils/global'
import { mockMap, moduleCache, startViteNode } from './execute'
import { setupInspect } from './inspector'
import { rpcDone } from './rpc'
function init(ctx: WorkerContext) {
// @ts-expect-error untyped global
if (typeof __vitest_worker__ !== 'undefined' && ctx.config.threads && ctx.config.isolate)
throw new Error(`worker for ${ctx.files.join(',')} already initialized by ${getWorkerState().ctx.files.join(',')}. This is probably an internal bug of Vitest.`)
const { config, port, workerId } = ctx
process.env.VITEST_WORKER_ID = String(workerId)
process.env.VITEST_POOL_ID = String(poolId)
// @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,
rpc: createBirpc<RuntimeRPC>(
{},
{
eventNames: ['onUserConsoleLog', 'onFinished', 'onCollected', 'onWorkerExit'],
post(v) { port.postMessage(v) },
on(fn) { port.addListener('message', fn) },
},
),
}
if (ctx.invalidates) {
ctx.invalidates.forEach((fsPath) => {
moduleCache.delete(fsPath)
moduleCache.delete(`mock:${fsPath}`)
})
}
ctx.files.forEach(i => moduleCache.delete(i))
}
export async function run(ctx: WorkerContext) {
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()
}
}