-
-
Notifications
You must be signed in to change notification settings - Fork 879
/
build.js
206 lines (197 loc) · 7.23 KB
/
build.js
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
/* @noflow */
/* eslint import/no-nodejs-modules: 0, import/extensions: 0 */
import fs from 'node:fs';
import path from 'node:path';
import * as commander from 'commander';
import * as esbuild from 'esbuild';
import * as semver from 'semver';
import JSZip from 'jszip';
import flowRemoveTypes from 'flow-remove-types';
import { copy } from 'esbuild-plugin-copy';
import { sassPlugin } from 'esbuild-sass-plugin';
import isBetaVersion from './build/isBetaVersion.js';
import packageInfo from './package.json' with { type: 'json' };
const targets = {
chrome: {
browserName: 'chrome',
browserMinVersion: '114.0',
manifest: './chrome/manifest.json',
},
chromebeta: {
browserName: 'chrome',
browserMinVersion: '114.0',
manifest: './chrome/beta/manifest.json',
},
edge: {
browserName: 'edge',
browserMinVersion: '114.0',
manifest: './chrome/manifest.json',
},
opera: {
browserName: 'opera',
browserMinVersion: '114.0',
manifest: './chrome/manifest.json',
noSourcemap: true,
},
firefox: {
browserName: 'firefox',
browserMinVersion: '115.0',
browserMobileMinVersion: '120.0',
manifest: './firefox/manifest.json',
noSourcemap: true,
},
}
const options = commander.program
.option('--watch', 'Enable watch mode')
.option('--zip', 'Enable zipping')
.option('--mode <type>', 'Set the mode', 'development')
.option('--browsers <list>', 'Specify browsers to target', 'chrome')
.parse(process.argv)
.opts();
const isProduction = options.mode === 'production';
const devBuildToken = `${Math.random()}`.slice(2);
const announcementsSubreddit /*: string */ = 'RESAnnouncements';
const name /*: string */ = packageInfo.title;
const author /*: string */ = packageInfo.author;
const description /*: string */ = packageInfo.description;
const version /*: string */ = packageInfo.version;
const isBeta /*: boolean */ = isBetaVersion(version);
const isPatch /*: boolean */ = semver.patch(version) !== 0;
const isMinor /*: boolean */ = !isPatch && semver.minor(version) !== 0;
const isMajor /*: boolean */ = !isPatch && !isMinor && semver.major(version) !== 0;
const updatedURL /*: string */ = isBeta ?
// link to the release listing page instead of a specific release page
// so if someone goes from the previous version to a hotfix (e.g. 5.10.3 -> 5.12.1)
// they see the big release notes for the minor release in addition to the changes in the hotfix
`https://redditenhancementsuite.com/releases/beta/#v${version}` :
`https://redditenhancementsuite.com/releases/#v${version}`;
const homepageURL /*: string */ = packageInfo.homepage;
// used for invalidating caches on each build (executed at build time)
// production builds uses version number to keep the build reproducible
const buildToken = isProduction ? version : devBuildToken;
async function buildForBrowser(targetName, { manifest, noSourceMap, browserName, browserMinVersion, browserMobileMinVersion }) {
const context = {
entryPoints: {
'foreground.entry': './lib/foreground.entry.js',
'background.entry': './lib/background.entry.js',
'options.entry': './lib/options/options.entry.js',
'prompt.entry': './lib/environment/background/permissions/prompt.entry.js',
manifest,
options: './lib/options/options.scss',
res: './lib/css/res.scss',
},
sourcemap: !isProduction || !noSourceMap,
outdir: `./dist/${targetName}/`,
bundle: true,
format: 'iife',
treeShaking: true,
metafile: true,
target: [`${browserName}${browserMinVersion}`],
loader: {
'.svg': 'dataurl',
'.gif': 'dataurl',
'.png': 'dataurl',
'.woff': 'dataurl',
},
define: {
'process.env.BUILD_TARGET': `"${browserName}"`,
'process.env.NODE_ENV': `"${options.mode}"`,
'process.env.buildToken': `"${buildToken}"`,
'process.env.announcementsSubreddit': `"${announcementsSubreddit}"`,
'process.env.name': `"${name}"`,
'process.env.author': `"${author}"`,
'process.env.description': `"${description}"`,
'process.env.version': `"${version}"`,
'process.env.isBeta': `"${isBeta.toString()}"`,
'process.env.isPatch': `"${isPatch.toString()}"`,
'process.env.isMinor': `"${isMinor.toString()}"`,
'process.env.isMajor': `"${isMajor.toString()}"`,
'process.env.updatedURL': `"${updatedURL}"`,
'process.env.homepageURL': `"${homepageURL}"`,
},
plugins: [
{
name: 'remove-flow-types',
setup(build) {
build.onLoad({ filter: /\.m?js$/ }, async args => {
const text = await fs.promises.readFile(args.path, 'utf8')
const contents = flowRemoveTypes(text, { pretty: true }).toString();
return {
contents,
loader: 'js',
}
})
},
},
sassPlugin(),
copy({
assets: [
{ from: ['./LICENSE'], to: ['./'] },
{ from: ['./images/css-off-small.png'], to: ['./'] },
{ from: ['./images/css-off.png'], to: ['./'] },
{ from: ['./images/css-on-small.png'], to: ['./'] },
{ from: ['./images/css-on.png'], to: ['./'] },
{ from: ['./images/icon128.png'], to: ['./'] },
{ from: ['./images/icon48.png'], to: ['./'] },
{ from: ['./lib/environment/background/permissions/prompt.html'], to: ['./'] },
{ from: ['./lib/options/options.html'], to: ['./'] },
{ from: ['./node_modules/dashjs/dist/dash.mediaplayer.min.js'], to: ['./'] },
],
}),
{
name: 'build-manifest',
setup(build) {
build.onLoad({ filter: /manifest\.json$/ }, async args => {
let text = await fs.promises.readFile(args.path, 'utf8')
const replace = {
__version__: version,
__name__: name,
__description__: description,
__homepage__: homepageURL,
__author__: author,
__browser_min_version__: browserMinVersion,
__browser_mobile_min_version__: browserMobileMinVersion,
}
Object.keys(replace).forEach(v => {
text = text.replaceAll(v, replace[v]);
});
JSON.parse(text); // Check if resulting JSON is valid
return { contents: text, loader: 'copy' };
});
},
}, options.zip ? {
name: 'zip-build',
setup(build) {
const sourceDir = `./dist/${targetName}/`;
const outPath = './dist/zip';
build.onEnd(async () => {
const zip = new JSZip();
const files = await fs.promises.readdir(sourceDir);
await Promise.all(files.map(async file => {
const filePath = path.join(sourceDir, file);
const content = await fs.promises.readFile(filePath);
zip.file(file, content);
}));
const zipContent = await zip.generateAsync({ compression: 'DEFLATE', type: 'nodebuffer' });
await fs.promises.mkdir(outPath, { recursive: true })
await fs.promises.writeFile(`${outPath}/${targetName}.zip`, zipContent);
console.log(`emitted zip file for ${targetName}`);
})
},
} : undefined,
].filter(Boolean),
};
if (options.watch) {
console.log(`Watching ${targetName}; break to exit`);
const ctx = await esbuild.context(context);
await ctx.watch();
} else {
console.log(`building ${targetName}`);
const result = await esbuild.build(context)
fs.writeFileSync(`dist/esbuild-meta-${targetName}.json`, JSON.stringify(result.metafile))
}
}
let buildTargets = options.browsers;
// browser option `all` converts to all available targets
buildTargets = [...new Set(buildTargets.replace('all', Object.keys(targets).join(',')).split(','))];
buildTargets.map(v => buildForBrowser(v, targets[v]));