UNPKG

3.01 kBJavaScriptView Raw
1const path = require('path');
2const fs = require('fs');
3const webpack = require('webpack');
4const HTMLWebpackPlugin = require('html-webpack-plugin');
5const mode = process.env.NODE_ENV ?? 'production';
6const TerserPlugin = require('terser-webpack-plugin');
7
8function replaceUnsafeEval(file) {
9 const replacementRegex = /Function\("return this"\)\(\)/g;
10 const replaceWith = 'window';
11
12 if (!file) {
13 throw new Error('must specify webpack bundle file to replace unsafe evals');
14 }
15
16 // eslint-disable-next-line no-sync
17 if (!fs.existsSync(file)) {
18 throw new Error(`bundle file ${file} does not exist`);
19 }
20
21 let replacements = 0;
22
23 // eslint-disable-next-line no-sync
24 const bundle = fs.readFileSync(file).toString('utf8').replace(replacementRegex, () => {
25 replacements++;
26 return replaceWith;
27 });
28
29 // eslint-disable-next-line no-sync
30 fs.writeFileSync(file, bundle);
31
32 return replacements;
33}
34
35function getOutputFileName() {
36 return mode === 'production' ? 'BitGoJS.min.js' : 'BitGoJS.js';
37}
38
39module.exports = {
40 mode,
41 target: 'web',
42 entry: path.join(__dirname, '/dist/src/index.js'),
43 output: {
44 path: path.join(__dirname, '/dist/browser'),
45 filename: getOutputFileName(),
46 library: 'BitGoJS',
47 libraryTarget: 'umd',
48 },
49 resolve: {
50 alias: {
51 '@hashgraph/sdk': path.resolve('../../node_modules/@hashgraph/sdk/src/browser.js'),
52 },
53 fallback: {
54 constants: false,
55 crypto: require.resolve('crypto-browserify'),
56 dns: false,
57 fs: false,
58 http: require.resolve('stream-http'),
59 https: require.resolve('https-browserify'),
60 http2: require.resolve('stream-http'),
61 net: false,
62 os: false,
63 path: false,
64 stream: require.resolve('stream-browserify'),
65 tls: false,
66 url: require.resolve('url/'),
67 vm: false,
68 zlib: false,
69 },
70 },
71 externals: ['morgan', 'superagent-proxy'],
72 plugins: [
73 new webpack.ProvidePlugin({
74 Buffer: ['buffer', 'Buffer'],
75 process: 'process/browser',
76 }),
77 new HTMLWebpackPlugin({ filename: 'browser.html', title: 'BitGo SDK Sandbox' }),
78 // This plugin uses webpack's hooks to perform a post processing step to find + replace unsafe code.
79 // currently, hashgraph protobufs generated code will attempt resolve the global object with:
80 // Function("return this")()
81 // which is not permitted in strict CSP environments. This can safely just be replaced with the *actual* global
82 // object, i.e. window
83 {
84 apply: (compiler) => {
85 compiler.hooks.afterEmit.tap('AfterEmitPlugin', () => {
86 replaceUnsafeEval(`./dist/browser/${getOutputFileName()}`);
87 });
88 },
89 },
90 ],
91 node: {
92 global: true,
93 },
94 optimization: {
95 minimizer: [
96 new TerserPlugin({
97 parallel: true,
98 terserOptions: {
99 ecma: 6,
100 warnings: true,
101 mangle: false,
102 keep_classnames: true,
103 keep_fnames: true,
104 },
105 }),
106 ],
107 },
108};