/
worker.ts
294 lines (271 loc) · 8.7 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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import path from 'path'
import type Rollup from 'rollup'
import type { EmittedFile, TransformPluginContext } from 'rollup'
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import { cleanUrl, injectQuery, parseRequest } from '../utils'
import { ENV_PUBLIC_PATH } from '../constants'
import { onRollupWarning } from '../build'
import { fileToUrl, getAssetHash } from './asset'
interface WorkerCache {
// save worker bundle emitted files avoid overwrites the same file.
// <chunk_filename, hash>
assets: Map<string, string>
chunks: Map<string, string>
// worker bundle don't deps on any more worker runtime info an id only had an result.
// save worker bundled file id to avoid repeated execution of bundles
// <filename, hash>
bundle: Map<string, string>
// nested worker bundle context don't had file what emitted by outside bundle
// save the hash to id to rewrite truth id.
// <hash, id>
emitted: Map<string, string>
}
const WorkerFileId = 'worker_file'
const workerCache = new WeakMap<ResolvedConfig, WorkerCache>()
function emitWorkerFile(
ctx: Rollup.TransformPluginContext,
config: ResolvedConfig,
asset: EmittedFile,
type: 'assets' | 'chunks'
): string {
const fileName = asset.fileName!
const workerMap = workerCache.get(config)!
if (workerMap[type].has(fileName)) {
return workerMap[type].get(fileName)!
}
const hash = ctx.emitFile(asset)
workerMap[type].set(fileName, hash)
workerMap.emitted.set(hash, fileName)
return hash
}
function emitWorkerAssets(
ctx: Rollup.TransformPluginContext,
config: ResolvedConfig,
asset: EmittedFile
) {
const { format } = config.worker
return emitWorkerFile(
ctx,
config,
asset,
format === 'es' ? 'chunks' : 'assets'
)
}
function emitWorkerSourcemap(
ctx: Rollup.TransformPluginContext,
config: ResolvedConfig,
asset: EmittedFile
) {
return emitWorkerFile(ctx, config, asset, 'assets')
}
function emitWorkerChunks(
ctx: Rollup.TransformPluginContext,
config: ResolvedConfig,
asset: EmittedFile
) {
return emitWorkerFile(ctx, config, asset, 'chunks')
}
export async function bundleWorkerEntry(
ctx: Rollup.TransformPluginContext,
config: ResolvedConfig,
id: string,
query: Record<string, string> | null
): Promise<Buffer> {
// bundle the file as entry to support imports
const rollup = require('rollup') as typeof Rollup
const { plugins, rollupOptions, format } = config.worker
const bundle = await rollup.rollup({
...rollupOptions,
input: cleanUrl(id),
plugins,
onwarn(warning, warn) {
onRollupWarning(warning, warn, config)
},
preserveEntrySignatures: false
})
let chunk: Rollup.OutputChunk
try {
const {
output: [outputChunk, ...outputChunks]
} = await bundle.generate({
format,
sourcemap: config.build.sourcemap
})
chunk = outputChunk
outputChunks.forEach((outputChunk) => {
if (outputChunk.type === 'asset') {
emitWorkerAssets(ctx, config, outputChunk)
} else if (outputChunk.type === 'chunk') {
emitWorkerChunks(ctx, config, {
fileName: path.posix.join(
config.build.assetsDir,
outputChunk.fileName
),
source: outputChunk.code,
type: 'asset'
})
}
})
} finally {
await bundle.close()
}
return emitSourcemapForWorkerEntry(ctx, config, id, query, chunk)
}
function emitSourcemapForWorkerEntry(
context: TransformPluginContext,
config: ResolvedConfig,
id: string,
query: Record<string, string> | null,
chunk: Rollup.OutputChunk
): Buffer {
let { code, map: sourcemap } = chunk
if (sourcemap) {
if (config.build.sourcemap === 'inline') {
// Manually add the sourcemap to the code if configured for inline sourcemaps.
// TODO: Remove when https://github.com/rollup/rollup/issues/3913 is resolved
// Currently seems that it won't be resolved until Rollup 3
const dataUrl = sourcemap.toUrl()
code += `//# sourceMappingURL=${dataUrl}`
} else if (
config.build.sourcemap === 'hidden' ||
config.build.sourcemap === true
) {
const basename = path.parse(cleanUrl(id)).name
const data = sourcemap.toString()
const content = Buffer.from(data)
const contentHash = getAssetHash(content)
const fileName = `${basename}.${contentHash}.js.map`
const filePath = path.posix.join(config.build.assetsDir, fileName)
emitWorkerSourcemap(context, config, {
fileName: filePath,
type: 'asset',
source: data
})
// Emit the comment that tells the JS debugger where it can find the
// sourcemap file.
// 'hidden' causes the sourcemap file to be created but
// the comment in the file to be omitted.
if (config.build.sourcemap === true) {
// inline web workers need to use the full sourcemap path
// non-inline web workers can use a relative path
const sourceMapUrl =
query?.inline != null
? path.posix.join(config.base, filePath)
: fileName
code += `//# sourceMappingURL=${sourceMapUrl}`
}
}
}
return Buffer.from(code)
}
export async function workerFileToUrl(
ctx: Rollup.TransformPluginContext,
config: ResolvedConfig,
id: string,
query: Record<string, string> | null
): Promise<string> {
const workerMap = workerCache.get(config)!
let hash = workerMap.bundle.get(id)
if (hash) {
// rewrite truth id, no need to replace by asset plugin
return config.base + workerMap.emitted.get(hash)!
}
const code = await bundleWorkerEntry(ctx, config, id, query)
const basename = path.parse(cleanUrl(id)).name
const contentHash = getAssetHash(code)
const fileName = path.posix.join(
config.build.assetsDir,
`${basename}.${contentHash}.js`
)
hash = emitWorkerAssets(ctx, config, {
fileName,
type: 'asset',
source: code
})
workerMap.bundle.set(id, hash)
return `__VITE_ASSET__${hash}__`
}
export function webWorkerPlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'
return {
name: 'vite:worker',
buildStart() {
workerCache.set(config, {
assets: new Map(),
chunks: new Map(),
bundle: new Map(),
emitted: new Map()
})
},
load(id) {
if (isBuild) {
const parsedQuery = parseRequest(id)
if (
parsedQuery &&
(parsedQuery.worker ?? parsedQuery.sharedworker) != null
) {
return ''
}
}
},
async transform(_, id) {
const query = parseRequest(id)
if (query && query[WorkerFileId] != null) {
return {
code: `import '${ENV_PUBLIC_PATH}'\n` + _
}
}
if (
query == null ||
(query && (query.worker ?? query.sharedworker) == null)
) {
return
}
let url: string
if (isBuild) {
if (query.inline != null) {
const code = await bundleWorkerEntry(this, config, id, query)
const { format } = config.worker
const workerOptions = format === 'es' ? '{type: "module"}' : '{}'
// inline as blob data url
return {
code: `const encodedJs = "${code.toString('base64')}";
const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" });
export default function WorkerWrapper() {
const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob);
try {
return objURL ? new Worker(objURL, ${workerOptions}) : new Worker("data:application/javascript;base64," + encodedJs, {type: "module"});
} finally {
objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL);
}
}`,
// Empty sourcemap to supress Rollup warning
map: { mappings: '' }
}
} else {
url = await workerFileToUrl(this, config, id, query)
}
} else {
url = await fileToUrl(cleanUrl(id), config, this)
url = injectQuery(url, WorkerFileId)
}
const workerConstructor =
query.sharedworker != null ? 'SharedWorker' : 'Worker'
const workerOptions = { type: 'module' }
return {
code: `export default function WorkerWrapper() {
return new ${workerConstructor}(${JSON.stringify(
url
)}, ${JSON.stringify(workerOptions, null, 2)})
}`,
map: { mappings: '' } // Empty sourcemap to supress Rolup warning
}
},
renderChunk(code) {
if (config.isWorker && code.includes('import.meta.url')) {
return code.replace('import.meta.url', 'self.location.href')
}
}
}
}