webpack-util.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const fs = require('fs');
  2. const babelCore = require('@babel/core');
  3. const WrapperWebpackPlugin = require('wrapper-webpack-plugin');
  4. // {entryName: path}
  5. const entryGlobals = {
  6. common: [
  7. './src/common/safe-globals.js',
  8. ],
  9. 'injected/content': [
  10. './src/injected/safe-globals-injected.js',
  11. './src/injected/content/safe-globals-content.js',
  12. ],
  13. 'injected/web': [
  14. './src/injected/safe-globals-injected.js',
  15. './src/injected/web/safe-globals-web.js',
  16. ],
  17. };
  18. /**
  19. * Adds a watcher for files in entryGlobals to properly recompile the project on changes.
  20. */
  21. function addWrapperWithGlobals(name, config, defsObj, callback) {
  22. config.module.rules.push({
  23. test: new RegExp(`/${name}/.*?\\.js$`.replace(/\//g, /[/\\]/.source)),
  24. use: [{
  25. loader: './scripts/fake-dep-loader.js',
  26. options: { files: entryGlobals[name] },
  27. }],
  28. });
  29. const defsRe = new RegExp(`\\b(${
  30. Object.keys(defsObj)
  31. .join('|')
  32. .replace(/\./g, '\\.')
  33. })\\b`, 'g');
  34. const reader = () => (
  35. entryGlobals[name]
  36. .map(path => readGlobalsFile(path))
  37. .join('\n')
  38. .replace(defsRe, s => defsObj[s])
  39. );
  40. config.plugins.push(new WrapperWebpackPlugin(callback(reader)));
  41. }
  42. function getUniqIdB64() {
  43. return Buffer.from(
  44. new Uint32Array(2)
  45. .map(() => Math.random() * (2 ** 32))
  46. .buffer,
  47. ).toString('base64');
  48. }
  49. function readGlobalsFile(filename, babelOpts = {}) {
  50. const { ast, code = !ast } = babelOpts;
  51. const src = fs.readFileSync(filename, { encoding: 'utf8' })
  52. .replace(/\bexport\s+(function\s+(\w+))/g, 'const $2 = $1')
  53. .replace(/\bexport\s+(?=(const|let)\s)/g, '');
  54. const res = babelCore.transformSync(src, {
  55. ...babelOpts,
  56. ast,
  57. code,
  58. filename,
  59. });
  60. return ast ? res : res.code;
  61. }
  62. exports.addWrapperWithGlobals = addWrapperWithGlobals;
  63. exports.getUniqIdB64 = getUniqIdB64;
  64. exports.readGlobalsFile = readGlobalsFile;