forked from mytonwalletorg/mytonwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webpack.config.ts
427 lines (390 loc) · 12.9 KB
/
webpack.config.ts
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import 'webpack-dev-server';
import StatoscopeWebpackPlugin from '@statoscope/webpack-plugin';
// @ts-ignore
import PreloadWebpackPlugin from '@vue/preload-webpack-plugin';
// @ts-ignore
import WebpackBeforeBuildPlugin from 'before-build-webpack';
import CopyWebpackPlugin from 'copy-webpack-plugin';
import dotenv from 'dotenv';
import fs from 'fs';
import { GitRevisionPlugin } from 'git-revision-webpack-plugin';
import HtmlPlugin from 'html-webpack-plugin';
import yaml from 'js-yaml';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import path from 'path';
import type { Compiler, Configuration } from 'webpack';
import {
DefinePlugin, EnvironmentPlugin, NormalModuleReplacementPlugin, ProvidePlugin,
} from 'webpack';
import { PRODUCTION_URL } from './src/config';
dotenv.config();
// GitHub workflow uses an empty string as the default value if it's not in repository variables, so we cannot define a default value here
process.env.BASE_URL = process.env.BASE_URL || PRODUCTION_URL;
const {
APP_ENV = 'production',
BASE_URL,
HEAD,
} = process.env;
const IS_CAPACITOR = process.env.IS_CAPACITOR === '1';
const IS_EXTENSION = process.env.IS_EXTENSION === '1';
const IS_PACKAGED_ELECTRON = process.env.IS_PACKAGED_ELECTRON === '1';
const IS_FIREFOX_EXTENSION = process.env.IS_FIREFOX_EXTENSION === '1';
const IS_OPERA_EXTENSION = process.env.IS_OPERA_EXTENSION === '1';
const gitRevisionPlugin = new GitRevisionPlugin();
const branch = HEAD || gitRevisionPlugin.branch();
const appRevision = !branch || branch === 'HEAD' ? gitRevisionPlugin.commithash()?.substring(0, 7) : branch;
const canUseStatoscope = !IS_EXTENSION && !IS_PACKAGED_ELECTRON && !IS_CAPACITOR;
const cspConnectSrcExtra = APP_ENV === 'development'
? `http://localhost:3000 ${process.env.CSP_CONNECT_SRC_EXTRA_URL}`
: '';
const cspFrameSrcExtra = [
'https://widget.changelly.com/',
'https://dreamwalkers.io/',
'https://avanchange.com/',
'https://pay.wata.pro/',
'https://royalpay.cc/',
].join(' ');
// The `connect-src` rule contains `https:` due to arbitrary requests are needed for jetton JSON configs.
// The `img-src` rule contains `https:` due to arbitrary image URLs being used as jetton logos.
// The `media-src` rule contains `data:` because of iOS sound initialization.
const CSP = `
default-src 'none';
manifest-src 'self';
connect-src 'self' https: ${cspConnectSrcExtra};
script-src 'self' 'wasm-unsafe-eval';
style-src 'self' https://fonts.googleapis.com/;
img-src 'self' data: https:;
media-src 'self' data:;
object-src 'none';
base-uri 'none';
font-src 'self' https://fonts.gstatic.com/;
form-action 'none';
frame-src 'self' ${cspFrameSrcExtra};`
.replace(/\s+/g, ' ').trim();
const appVersion = require('./package.json').version;
const defaultI18nFilename = path.resolve(__dirname, './src/i18n/en.json');
export default function createConfig(
_: any,
{ mode = 'production' }: { mode: 'none' | 'development' | 'production' },
): Configuration {
return {
mode,
target: 'web',
optimization: {
usedExports: true,
...(APP_ENV === 'staging' && {
chunkIds: 'named',
}),
...(IS_EXTENSION && {
minimize: false,
}),
...(IS_CAPACITOR && {
splitChunks: false,
}),
},
entry: {
main: './src/index.tsx',
extensionServiceWorker: './src/extension/serviceWorker.ts',
extensionContentScript: './src/extension/contentScript.ts',
extensionPageScript: './src/extension/pageScript/index.ts',
},
devServer: {
port: 4321,
host: '0.0.0.0',
allowedHosts: 'all',
hot: false,
static: [
{
directory: path.resolve(__dirname, 'public'),
},
{
directory: path.resolve(__dirname, 'src/lib/rlottie'),
},
],
devMiddleware: {
stats: 'minimal',
},
headers: {
'Content-Security-Policy': CSP,
},
},
watchOptions: { ignored: defaultI18nFilename },
output: {
filename: (pathData) => (pathData.chunk?.name?.startsWith('extension') ? '[name].js' : '[name].[contenthash].js'),
chunkFilename: '[id].[chunkhash].js',
assetModuleFilename: '[name].[contenthash][ext]',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
module: {
rules: [
{
test: /\.(ts|tsx|js)$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
'postcss-loader',
],
},
{
test: /\.module\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: {
exportLocalsConvention: 'camelCase',
auto: true,
localIdentName: APP_ENV === 'production' ? '[sha1:hash:base64:8]' : '[name]__[local]',
},
},
},
'postcss-loader',
'sass-loader',
],
},
{
test: /\.scss$/,
exclude: /\.module\.scss$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader'],
},
{
test: /\.(woff(2)?|ttf|eot|svg|png|jpg|tgs|webp|mp3)(\?v=\d+\.\d+\.\d+)?$/,
type: 'asset/resource',
},
{
test: /\.wasm$/,
type: 'asset/resource',
},
{
test: /\.(txt|tl)$/i,
type: 'asset/source',
},
],
},
resolve: {
extensions: ['.js', '.ts', '.tsx'],
fallback: {
crypto: false,
},
alias: {
// It is used to remove duplicate dependencies
'bn.js': path.join(__dirname, 'node_modules/bn.js/lib/bn.js'),
},
},
plugins: [
...(IS_OPERA_EXTENSION ? [{
apply: (compiler: Compiler) => {
compiler.hooks.afterDone.tap('After Compilation', async () => {
const dir = './dist/';
for (const filename of await fs.promises.readdir(dir)) {
const file = path.join(dir, filename);
if (file.endsWith('.tgs')) {
await fs.promises.rename(file, file.replace('.tgs', '.json'));
} else if (filename.includes('main') && filename.endsWith('.js')) {
const content = (await fs.promises.readFile(file))
.toString('utf-8')
.replace(/\.tgs"/g, '.json"');
await fs.promises.writeFile(file, content);
}
}
});
},
}] : []),
new WebpackBeforeBuildPlugin((stats: any, callback: VoidFunction) => {
const defaultI18nYaml = fs.readFileSync('./src/i18n/en.yaml', 'utf8');
const defaultI18nJson = convertI18nYamlToJson(defaultI18nYaml, mode === 'production');
if (!defaultI18nJson) {
return;
}
fs.writeFile(defaultI18nFilename, defaultI18nJson, 'utf-8', () => {
callback();
});
}),
new HtmlPlugin({
template: 'src/index.html',
chunks: ['main'],
csp: CSP,
}),
new PreloadWebpackPlugin({
include: 'allAssets',
fileWhitelist: [
/duck_.*?\.png/, // Lottie thumbs
/coin_.*?\.png/, // Coin icons
/theme_.*?\.png/, // Theme icons
/chain_.*?\.png/, // Chain icons
/settings_.*?\.svg/, // Settings icons (svg)
],
as(entry: string) {
if (/\.png$/.test(entry)) return 'image';
if (/\.svg$/.test(entry)) return 'image';
return 'script';
},
}),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
chunkFilename: '[name].[chunkhash].css',
ignoreOrder: true,
}),
/* eslint-disable no-null/no-null */
new EnvironmentPlugin({
APP_ENV: 'production',
APP_NAME: null,
APP_VERSION: appVersion,
APP_REVISION: appRevision,
TEST_SESSION: null,
TONHTTPAPI_MAINNET_URL: null,
TONHTTPAPI_MAINNET_API_KEY: null,
TONHTTPAPI_TESTNET_URL: null,
TONHTTPAPI_TESTNET_API_KEY: null,
TONAPIIO_MAINNET_URL: null,
TONAPIIO_TESTNET_URL: null,
TONHTTPAPI_V3_MAINNET_API_KEY: null,
TONHTTPAPI_V3_TESTNET_API_KEY: null,
BRILLIANT_API_BASE_URL: null,
PROXY_HOSTS: null,
STAKING_POOLS: null,
LIQUID_POOL: null,
LIQUID_JETTON: null,
IS_PACKAGED_ELECTRON: false,
IS_ANDROID_DIRECT: false,
ELECTRON_TONHTTPAPI_MAINNET_API_KEY: null,
ELECTRON_TONHTTPAPI_TESTNET_API_KEY: null,
BASE_URL,
BOT_USERNAME: null,
IS_EXTENSION: false,
IS_FIREFOX_EXTENSION: false,
IS_CAPACITOR: false,
SWAP_FEE_ADDRESS: null,
DIESEL_ADDRESS: null,
}),
/* eslint-enable no-null/no-null */
new DefinePlugin({
APP_REVISION: DefinePlugin.runtimeValue(
() => {
const { gitBranch, commit } = getGitMetadata();
return JSON.stringify(!gitBranch || gitBranch === 'HEAD' ? commit : gitBranch);
},
mode === 'development' ? true : [],
),
}),
new ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
}),
new CopyWebpackPlugin({
patterns: [
{
from: 'src/extension/manifest.json',
transform: (content) => {
const manifest = JSON.parse(content.toString());
manifest.version = appVersion;
manifest.content_security_policy = {
extension_pages: CSP,
};
if (IS_FIREFOX_EXTENSION) {
manifest.background = {
scripts: [manifest.background.service_worker],
};
manifest.host_permissions = ['<all_urls>'];
manifest.permissions = manifest.permissions.filter((value: string) => value !== 'system.display');
manifest.browser_specific_settings = {
gecko: {
id: '{98fcdaee-2b58-4f71-8a3c-f0c66f24dede}',
strict_min_version: '91.1.0', // Minimum version for using a proxy
},
};
}
return JSON.stringify(manifest, undefined, 2);
},
},
{
from: 'src/i18n/*.yaml',
to: 'i18n/[name].json',
transform: (content: Buffer) => convertI18nYamlToJson(
content as unknown as string, mode === 'production',
) as any,
},
{
from: 'src/_headers',
transform: (content: Buffer) => content.toString().replace('{{CSP}}', CSP),
},
],
}),
...(canUseStatoscope ? [new StatoscopeWebpackPlugin({
statsOptions: {
context: __dirname,
},
saveReportTo: path.resolve('./public/statoscope-report.html'),
saveStatsTo: path.resolve('./public/statoscope-build-statistics.json'),
normalizeStats: true,
open: false,
extensions: [new WebpackContextExtension()], // eslint-disable-line @typescript-eslint/no-use-before-define
})] : []),
...(IS_EXTENSION
? [
new NormalModuleReplacementPlugin(
/src\/api\/providers\/worker\/connector\.ts/,
'../extension/connectorForPopup.ts',
),
]
: []),
],
devtool:
IS_EXTENSION ? 'cheap-source-map' : APP_ENV === 'production' && IS_PACKAGED_ELECTRON ? undefined : 'source-map',
};
}
function getGitMetadata() {
const revisionPlugin = new GitRevisionPlugin();
const commit = revisionPlugin.commithash()?.substring(0, 7);
return {
gitBranch: HEAD || gitRevisionPlugin.branch(),
commit,
};
}
function convertI18nYamlToJson(content: string, shouldThrowException: boolean): string | undefined {
try {
const i18n = yaml.load(content) as AnyLiteral;
const json: AnyLiteral = Object.entries(i18n).reduce((acc: AnyLiteral, [key, value]) => {
if (typeof value === 'string') {
acc[key] = value;
}
if (typeof value === 'object') {
acc[key] = { ...value };
}
return acc;
}, {});
return JSON.stringify(json, undefined, 2);
} catch (err: any) {
console.error(err.message); // eslint-disable-line no-console
if (shouldThrowException) {
throw err;
}
}
return undefined;
}
class WebpackContextExtension {
context: string;
constructor() {
this.context = '';
}
handleCompiler(compiler: Compiler) {
this.context = compiler.context;
}
getExtension() {
return {
descriptor: { name: 'custom-webpack-extension-context', version: '1.0.0' },
payload: { context: this.context },
};
}
}