/
pure.ts
181 lines (151 loc) · 4.5 KB
/
pure.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/* eslint-disable no-restricted-imports */
import { VitestRunner } from 'vitest/node'
import type { WorkerGlobalState } from 'vitest'
import { toFilePath } from 'vite-node/utils'
function getWorkerState(): WorkerGlobalState {
// @ts-expect-error untyped global
return globalThis.__vitest_worker__
}
type Procedure = (...args: any[]) => void
class Bridge {
private callbacks: Record<string, Procedure[]> = {}
public on(event: string, fn: Procedure) {
this.callbacks[event] ??= []
this.callbacks[event].push(fn)
}
public off(event: string, fn: Procedure) {
if (this.callbacks[event])
this.callbacks[event] = this.callbacks[event].filter(f => f !== fn)
}
public removeEvents(event: string) {
this.callbacks[event] = []
}
public clear() {
this.callbacks = {}
}
public emit(event: string, ...data: any[]) {
return (this.callbacks[event] || []).map(fn => fn(...data))
}
}
interface InlineWorkerContext {
onmessage: Procedure | null
dispatchEvent: (e: Event) => void
addEventListener: (e: string, fn: Procedure) => void
removeEventListener: (e: string, fn: Procedure) => void
postMessage: (data: any) => void
self: InlineWorkerContext
global: InlineWorkerContext
invalidates: string[]
importScripts?: any
}
class InlineWorkerRunner extends VitestRunner {
constructor(options: any, private context: InlineWorkerContext) {
super(options)
}
prepareContext(context: Record<string, any>) {
const ctx = super.prepareContext(context)
// not supported for now
// need to be async
this.context.self.importScripts = () => {}
return Object.assign(ctx, this.context, {
importScripts: () => {},
})
}
}
export function defineWebWorker() {
if ('Worker' in globalThis)
return
const { config, rpc, mockMap, moduleCache } = getWorkerState()
const options = {
fetchModule(id: string) {
return rpc.fetch(id)
},
resolveId(id: string, importer?: string) {
return rpc.resolveId(id, importer)
},
moduleCache,
mockMap,
interopDefault: config.deps.interopDefault ?? true,
root: config.root,
base: config.base,
}
globalThis.Worker = class Worker {
private inside = new Bridge()
private outside = new Bridge()
private messageQueue: any[] | null = []
public onmessage: null | Procedure = null
public onmessageerror: null | Procedure = null
public onerror: null | Procedure = null
constructor(url: URL | string) {
const invalidates: string[] = []
const context: InlineWorkerContext = {
onmessage: null,
dispatchEvent: (event: Event) => {
this.inside.emit(event.type, event)
return true
},
addEventListener: this.inside.on.bind(this.inside),
removeEventListener: this.inside.off.bind(this.inside),
postMessage: (data) => {
this.outside.emit('message', { data })
},
get self() {
return context
},
get global() {
return context
},
invalidates,
}
this.inside.on('message', (e) => {
context.onmessage?.(e)
})
this.outside.on('message', (e) => {
this.onmessage?.(e)
})
const runner = new InlineWorkerRunner(options, context)
let id = url instanceof URL ? url.toString() : url
id = id
.replace('?worker_file', '')
.replace(/^file:\/+/, '/')
const fsPath = toFilePath(id, config.root)
invalidates.push(fsPath)
runner.executeFile(fsPath)
.then(() => {
invalidates.forEach((path) => {
// worker should be new every time
moduleCache.delete(path)
moduleCache.delete(`${path}__mock`)
})
const q = this.messageQueue
this.messageQueue = null
if (q)
q.forEach(this.postMessage, this)
}).catch((e) => {
this.outside.emit('error', e)
this.onerror?.(e)
console.error(e)
})
}
dispatchEvent(event: Event) {
this.outside.emit(event.type, event)
return true
}
addEventListener(event: string, fn: Procedure) {
this.outside.on(event, fn)
}
removeEventListener(event: string, fn: Procedure) {
this.outside.off(event, fn)
}
postMessage(data: any) {
if (this.messageQueue != null)
this.messageQueue.push(data)
else
this.inside.emit('message', { data })
}
terminate() {
this.outside.clear()
this.inside.clear()
}
}
}