-
Notifications
You must be signed in to change notification settings - Fork 772
/
build.mjs
357 lines (338 loc) · 9.43 KB
/
build.mjs
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
import archiver from 'archiver'
import fs from 'fs-extra'
import path from 'path'
import webpack from 'webpack'
import ProgressBarPlugin from 'progress-bar-webpack-plugin'
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import TerserPlugin from 'terser-webpack-plugin'
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
const outdir = 'build'
const __dirname = path.resolve()
const isProduction = process.argv[2] !== '--development' // --production and --analyze are both production
const isAnalyzing = process.argv[2] === '--analyze'
async function deleteOldDir() {
await fs.rm(outdir, { recursive: true, force: true })
}
async function runWebpack(isWithoutKatex, isWithoutTiktoken, minimal, callback) {
const shared = [
'preact',
'webextension-polyfill',
'@primer/octicons-react',
'react-bootstrap-icons',
'countries-list',
'i18next',
'react-i18next',
'react-tabs',
'./src/utils',
'./src/_locales/i18n-react',
]
if (isWithoutKatex) shared.push('./src/components')
const compiler = webpack({
entry: {
'content-script': {
import: './src/content-script/index.jsx',
dependOn: 'shared',
},
background: {
import: './src/background/index.mjs',
},
popup: {
import: './src/popup/index.jsx',
dependOn: 'shared',
},
IndependentPanel: {
import: './src/pages/IndependentPanel/index.jsx',
dependOn: 'shared',
},
shared: shared,
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, outdir),
},
mode: isProduction ? 'production' : 'development',
devtool: isProduction ? false : 'inline-source-map',
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
output: { ascii_only: true },
},
}),
new CssMinimizerPlugin(),
],
concatenateModules: !isAnalyzing,
},
plugins: [
minimal
? new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
})
: new webpack.ProvidePlugin({
process: 'process/browser.js',
Buffer: ['buffer', 'Buffer'],
}),
new ProgressBarPlugin({
format: ' build [:bar] :percent (:elapsed seconds)',
clear: false,
}),
new MiniCssExtractPlugin({
filename: '[name].css',
}),
new BundleAnalyzerPlugin({
analyzerMode: isAnalyzing ? 'static' : 'disable',
}),
...(isWithoutKatex
? [
new webpack.NormalModuleReplacementPlugin(/markdown\.jsx/, (result) => {
if (result.request) {
result.request = result.request.replace(
'markdown.jsx',
'markdown-without-katex.jsx',
)
}
}),
]
: []),
],
resolve: {
extensions: ['.jsx', '.mjs', '.js'],
alias: {
parse5: path.resolve(__dirname, 'node_modules/parse5'),
...(minimal
? { buffer: path.resolve(__dirname, 'node_modules/buffer') }
: {
util: path.resolve(__dirname, 'node_modules/util'),
buffer: path.resolve(__dirname, 'node_modules/buffer'),
stream: 'stream-browserify',
crypto: 'crypto-browserify',
}),
},
},
module: {
rules: [
{
test: /\.m?jsx?$/,
exclude: /(node_modules)/,
resolve: {
fullySpecified: false,
},
use: [
{
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
{
plugins: ['@babel/plugin-transform-runtime'],
},
],
plugins: [
[
'@babel/plugin-transform-react-jsx',
{
runtime: 'automatic',
importSource: 'preact',
},
],
],
},
},
],
},
{
test: /\.s[ac]ss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
{
loader: 'sass-loader',
},
],
},
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 1,
},
},
{
loader: 'less-loader',
},
],
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
},
],
},
{
test: /\.(woff|ttf)$/,
type: 'asset/resource',
generator: {
emit: false,
},
},
{
test: /\.woff2$/,
type: 'asset/inline',
},
{
test: /\.(jpg|png|svg)$/,
type: 'asset/inline',
},
{
test: /\.(graphql|gql)$/,
loader: 'graphql-tag/loader',
},
isWithoutTiktoken
? {
test: /crop-text\.mjs$/,
loader: 'string-replace-loader',
options: {
multiple: [
{
search: "import { encode } from '@nem035/gpt-3-encoder'",
replace: '',
},
{
search: 'encode(',
replace: 'String(',
},
],
},
}
: {},
minimal
? {
test: /styles\.scss$/,
loader: 'string-replace-loader',
options: {
multiple: [
{
search: "@import '../fonts/styles.css';",
replace: '',
},
],
},
}
: {},
minimal
? {
test: /index\.mjs$/,
loader: 'string-replace-loader',
options: {
multiple: [
{
search: 'import { generateAnswersWithChatGLMApi }',
replace: '//',
},
{
search: 'await generateAnswersWithChatGLMApi',
replace: '//',
},
],
},
}
: {},
],
},
})
if (isProduction) compiler.run(callback)
else compiler.watch({}, callback)
}
async function zipFolder(dir) {
const output = fs.createWriteStream(`${dir}.zip`)
const archive = archiver('zip', {
zlib: { level: 9 },
})
archive.pipe(output)
archive.directory(dir, false)
await archive.finalize()
}
async function copyFiles(entryPoints, targetDir) {
if (!fs.existsSync(targetDir)) await fs.mkdir(targetDir)
await Promise.all(
entryPoints.map(async (entryPoint) => {
await fs.copy(entryPoint.src, `${targetDir}/${entryPoint.dst}`)
}),
)
}
async function finishOutput(outputDirSuffix) {
const commonFiles = [
{ src: 'src/logo.png', dst: 'logo.png' },
{ src: 'src/rules.json', dst: 'rules.json' },
{ src: 'build/shared.js', dst: 'shared.js' },
{ src: 'build/content-script.css', dst: 'content-script.css' }, // shared
{ src: 'build/content-script.js', dst: 'content-script.js' },
{ src: 'build/background.js', dst: 'background.js' },
{ src: 'build/popup.js', dst: 'popup.js' },
{ src: 'build/popup.css', dst: 'popup.css' },
{ src: 'src/popup/index.html', dst: 'popup.html' },
{ src: 'build/IndependentPanel.js', dst: 'IndependentPanel.js' },
{ src: 'src/pages/IndependentPanel/index.html', dst: 'IndependentPanel.html' },
]
// chromium
const chromiumOutputDir = `./${outdir}/chromium${outputDirSuffix}`
await copyFiles(
[...commonFiles, { src: 'src/manifest.json', dst: 'manifest.json' }],
chromiumOutputDir,
)
if (isProduction) await zipFolder(chromiumOutputDir)
// firefox
const firefoxOutputDir = `./${outdir}/firefox${outputDirSuffix}`
await copyFiles(
[...commonFiles, { src: 'src/manifest.v2.json', dst: 'manifest.json' }],
firefoxOutputDir,
)
if (isProduction) await zipFolder(firefoxOutputDir)
}
function generateWebpackCallback(finishOutputFunc) {
return async function webpackCallback(err, stats) {
if (err || stats.hasErrors()) {
console.error(err || stats.toString())
return
}
// console.log(stats.toString())
await finishOutputFunc()
}
}
async function build() {
await deleteOldDir()
if (isProduction && !isAnalyzing) {
// await runWebpack(
// true,
// false,
// generateWebpackCallback(() => finishOutput('-without-katex')),
// )
// await new Promise((r) => setTimeout(r, 5000))
await runWebpack(
true,
true,
true,
generateWebpackCallback(() => finishOutput('-without-katex-and-tiktoken')),
)
await new Promise((r) => setTimeout(r, 10000))
}
await runWebpack(
false,
false,
false,
generateWebpackCallback(() => finishOutput('')),
)
}
build()