forked from rollup/plugins
-
Notifications
You must be signed in to change notification settings - Fork 3
/
worker.ts
55 lines (43 loc) 路 1.26 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
import process from 'process';
import { isMainThread, parentPort, workerData } from 'worker_threads';
import { hasOwnProperty, isObject } from 'smob';
import { minify } from 'terser';
import type { WorkerContextSerialized, WorkerOutput } from './type';
/**
* Duck typing worker context.
*
* @param input
*/
function isWorkerContextSerialized(input: unknown): input is WorkerContextSerialized {
return (
isObject(input) &&
hasOwnProperty(input, 'code') &&
typeof input.code === 'string' &&
hasOwnProperty(input, 'options') &&
typeof input.options === 'string'
);
}
export async function runWorker() {
if (isMainThread || !parentPort || !isWorkerContextSerialized(workerData)) {
return;
}
try {
// eslint-disable-next-line no-eval
const eval2 = eval;
const options = eval2(`(${workerData.options})`);
const result = await minify(workerData.code, options);
const output: WorkerOutput = {
code: result.code || workerData.code,
nameCache: options.nameCache
};
if (typeof result.map === 'string') {
output.sourceMap = JSON.parse(result.map);
}
if (isObject(result.map)) {
output.sourceMap = result.map;
}
parentPort.postMessage(output);
} catch (e) {
process.exit(1);
}
}