|
1 | | -const { isChromium } = require("../utils/node"); |
| 1 | +const { IS_CHROMIUM } = require("../utils/node"); |
| 2 | +const crypto = require("crypto"); |
2 | 3 |
|
3 | 4 | exports.WrapperCodePlugin = class WrapperCodePlugin { |
4 | 5 | constructor(options) { |
5 | 6 | this.options = options || {}; |
6 | 7 | } |
7 | 8 | apply(compiler) { |
8 | | - if (isChromium) return void 0; |
| 9 | + if (IS_CHROMIUM) return void 0; |
9 | 10 | compiler.hooks.emit.tapAsync("WrapperCodePlugin", (compilation, done) => { |
10 | | - Object.keys(compilation.assets).forEach(key => { |
11 | | - if (!isChromium && key === process.env.INJECT_FILE + ".js") { |
12 | | - try { |
13 | | - const buffer = compilation.assets[key].source(); |
14 | | - let code = buffer.toString("utf-8"); |
15 | | - code = `window.${process.env.INJECT_FILE}=function(){${code}}`; |
16 | | - compilation.assets[key] = { |
17 | | - source() { |
18 | | - return code; |
19 | | - }, |
20 | | - size() { |
21 | | - return this.source().length; |
22 | | - }, |
23 | | - }; |
24 | | - } catch (error) { |
25 | | - console.log("Parse Inject File Error", error); |
26 | | - } |
| 11 | + const injectKey = process.env.INJECT_FILE + ".js"; |
| 12 | + const injectFile = compilation.assets[injectKey]; |
| 13 | + const workerKey = "worker.js"; |
| 14 | + const workerFile = compilation.assets[workerKey]; |
| 15 | + if (injectFile) { |
| 16 | + // 处理 Inject Script |
| 17 | + const buffer = injectFile.source(); |
| 18 | + const code = buffer.toString("utf-8"); |
| 19 | + const source = `window.${process.env.INJECT_FILE}=function(){${code}}`; |
| 20 | + compilation.assets[injectKey] = { |
| 21 | + source() { |
| 22 | + return source; |
| 23 | + }, |
| 24 | + size() { |
| 25 | + return this.source().length; |
| 26 | + }, |
| 27 | + }; |
| 28 | + // 处理 Worker Script |
| 29 | + if (workerFile) { |
| 30 | + const workerBuffer = workerFile.source(); |
| 31 | + const workerCode = workerBuffer.toString("utf-8"); |
| 32 | + const hash = crypto.createHash("sha256"); |
| 33 | + hash.update(`;(function(){${code}})();`); |
| 34 | + const hashed = hash.digest("base64"); |
| 35 | + const nonCSP = workerCode.replace("${CSP-HASH}", hashed); |
| 36 | + compilation.assets[workerKey] = { |
| 37 | + source() { |
| 38 | + return nonCSP; |
| 39 | + }, |
| 40 | + size() { |
| 41 | + return this.source().length; |
| 42 | + }, |
| 43 | + }; |
27 | 44 | } |
28 | | - }); |
| 45 | + } |
29 | 46 | done(); |
30 | 47 | }); |
31 | 48 | } |
|
0 commit comments