/
createFakeWorker.js
88 lines (83 loc) · 2.03 KB
/
createFakeWorker.js
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
const path = require("path");
module.exports = ({ outputDirectory }) =>
class Worker {
constructor(url, options = {}) {
expect(url).toBeInstanceOf(URL);
expect(url.origin).toBe("https://test.cases");
expect(url.pathname.startsWith("/path/")).toBe(true);
const file = url.pathname.slice(6);
const workerBootstrap = `
const { parentPort } = require("worker_threads");
const { URL } = require("url");
const path = require("path");
const fs = require("fs");
global.self = global;
self.URL = URL;
self.location = new URL(${JSON.stringify(url.toString())});
const urlToPath = url => {
if(url.startsWith("https://test.cases/path/")) url = url.slice(24);
return path.resolve(${JSON.stringify(outputDirectory)}, \`./\${url}\`);
};
self.importScripts = url => {
${
options.type === "module"
? `throw new Error("importScripts is not supported in module workers")`
: `require(urlToPath(url))`
};
};
self.fetch = async url => {
try {
const buffer = await new Promise((resolve, reject) =>
fs.readFile(urlToPath(url), (err, b) =>
err ? reject(err) : resolve(b)
)
);
return {
status: 200,
ok: true,
json: async () => JSON.parse(buffer.toString("utf-8"))
};
} catch(err) {
if(err.code === "ENOENT") {
return {
status: 404,
ok: false
};
}
throw err;
}
};
parentPort.on("message", data => {
if(self.onmessage) self.onmessage({
data
});
});
self.postMessage = data => {
parentPort.postMessage(data);
};
require(${JSON.stringify(path.resolve(outputDirectory, file))});
`;
// eslint-disable-next-line node/no-unsupported-features/node-builtins
this.worker = new (require("worker_threads").Worker)(workerBootstrap, {
eval: true
});
this._onmessage = undefined;
}
set onmessage(value) {
if (this._onmessage) this.worker.off("message", this._onmessage);
this.worker.on(
"message",
(this._onmessage = data => {
value({
data
});
})
);
}
postMessage(data) {
this.worker.postMessage(data);
}
terminate() {
return this.worker.terminate();
}
};