Repository navigation
Expand file tree
/
Copy pathrollup-plugin-inline-worker.js
More file actions
78 lines (73 loc) · 2.5 KB
/
Copy pathrollup-plugin-inline-worker.js
File metadata and controls
78 lines (73 loc) · 2.5 KB
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
import { rollup } from "rollup";
import { deflateRawSync } from "node:zlib";
import { readFileSync } from "node:fs";
import { Buffer } from "node:buffer";
import { inflateRaw } from "./lib/core/util/inflate.js";
const SPECIFIER_PREFIX = "inline-worker:";
const RESOLVED_SPECIFIER_PREFIX = "\0" + SPECIFIER_PREFIX;
const BINARY_SPECIFIER_PREFIX = "inline-binary:";
const RESOLVED_BINARY_SPECIFIER_PREFIX = "\0" + BINARY_SPECIFIER_PREFIX;
export { inlineWorker, inlineBinary, deflatePayload };
function inlineWorker({ intro, createPlugins, deflate = true }) {
return {
name: "inline-worker",
async resolveId(id, importer) {
if (id.startsWith(SPECIFIER_PREFIX)) {
const resolved = await this.resolve(id.slice(SPECIFIER_PREFIX.length), importer);
if (!resolved) {
this.error("cannot resolve " + JSON.stringify(id) + " from " + JSON.stringify(importer));
}
return RESOLVED_SPECIFIER_PREFIX + resolved.id;
}
},
async load(id) {
if (id.startsWith(RESOLVED_SPECIFIER_PREFIX)) {
const input = id.slice(RESOLVED_SPECIFIER_PREFIX.length);
const bundle = await rollup({ input });
try {
const { output } = await bundle.generate({
format: "umd",
intro,
plugins: createPlugins ? createPlugins() : []
});
const [chunk] = output;
for (const file of bundle.watchFiles) {
this.addWatchFile(file);
}
return "export default " + JSON.stringify(deflate ? deflatePayload(chunk.code) : chunk.code) + ";";
} finally {
await bundle.close();
}
}
}
};
}
function inlineBinary() {
return {
name: "inline-binary",
async resolveId(id, importer) {
if (id.startsWith(BINARY_SPECIFIER_PREFIX)) {
const resolved = await this.resolve(id.slice(BINARY_SPECIFIER_PREFIX.length), importer);
if (!resolved) {
this.error("cannot resolve " + JSON.stringify(id) + " from " + JSON.stringify(importer));
}
return RESOLVED_BINARY_SPECIFIER_PREFIX + resolved.id;
}
},
load(id) {
if (id.startsWith(RESOLVED_BINARY_SPECIFIER_PREFIX)) {
const file = id.slice(RESOLVED_BINARY_SPECIFIER_PREFIX.length);
this.addWatchFile(file);
return "export default " + JSON.stringify(deflatePayload(readFileSync(file))) + ";";
}
}
};
}
function deflatePayload(data) {
const deflated = deflateRawSync(data, { level: 9 });
const restored = Buffer.from(inflateRaw(new Uint8Array(deflated)));
if (Buffer.compare(restored, Buffer.from(data)) != 0) {
throw new Error("deflated payload round-trip failed");
}
return deflated.toString("base64");
}