/
worker.ts
201 lines (186 loc) · 6.07 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
import type { ResolvedConfig } from '../config'
import type { Plugin } from '../plugin'
import { fileToUrl, getAssetHash } from './asset'
import { cleanUrl, injectQuery, parseRequest } from '../utils'
import type Rollup from 'rollup'
import { ENV_PUBLIC_PATH } from '../constants'
import path from 'path'
import { onRollupWarning } from '../build'
import type { TransformPluginContext } from 'rollup'
const WorkerFileId = 'worker_file'
export interface BundleWorkerEntryOutput {
code: string
sourcemap: Rollup.SourceMap | undefined
}
export async function bundleWorkerEntry(
config: ResolvedConfig,
id: string
): Promise<BundleWorkerEntryOutput> {
// 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 code: string
let sourcemap: Rollup.SourceMap | undefined
try {
const { output } = await bundle.generate({
format,
sourcemap: config.build.sourcemap
})
code = output[0].code
sourcemap = output[0].map
} finally {
await bundle.close()
}
return {
code: code,
sourcemap
}
}
export interface EmitResult {
code: Buffer
}
export function emitSourcemapForWorkerEntry(
context: TransformPluginContext,
config: ResolvedConfig,
id: string,
query: Record<string, string> | null,
workerEntry: BundleWorkerEntryOutput
): EmitResult {
let { code, sourcemap } = workerEntry
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)
if (!context.cache.has(contentHash)) {
context.cache.set(contentHash, true)
context.emitFile({
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 ? filePath : fileName
code += `//# sourceMappingURL=${sourceMapUrl}`
}
}
}
return {
code: Buffer.from(code)
}
}
export function webWorkerPlugin(config: ResolvedConfig): Plugin {
const isBuild = config.command === 'build'
return {
name: 'vite:worker',
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) {
const bundled = await bundleWorkerEntry(config, id)
const { code } = emitSourcemapForWorkerEntry(
this,
config,
id,
query,
bundled
)
if (query.inline != null) {
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 {
const basename = path.parse(cleanUrl(id)).name
const contentHash = getAssetHash(code)
const fileName = path.posix.join(
config.build.assetsDir,
`${basename}.${contentHash}.js`
)
url = `__VITE_ASSET__${this.emitFile({
fileName,
type: 'asset',
source: code
})}__`
}
} 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
}
}
}
}