-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathbuild-bundle.js
283 lines (256 loc) · 9.9 KB
/
build-bundle.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
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
/**
* @license Copyright 2018 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
/**
* @fileoverview Script to bundle lighthouse entry points so that they can be run
* in the browser (as long as they have access to a debugger protocol Connection).
*/
import fs from 'fs';
import path from 'path';
import {execSync} from 'child_process';
import {createRequire} from 'module';
import esMain from 'es-main';
import esbuild from 'esbuild';
// @ts-expect-error: plugin has no types.
import PubAdsPlugin from 'lighthouse-plugin-publisher-ads';
// @ts-expect-error: plugin has no types.
import SoftNavPlugin from 'lighthouse-plugin-soft-navigation';
import * as plugins from './esbuild-plugins.js';
import {Runner} from '../core/runner.js';
import {LH_ROOT} from '../root.js';
import {readJson} from '../core/test/test-utils.js';
import {nodeModulesPolyfillPlugin} from '../third-party/esbuild-plugins-polyfills/esbuild-polyfills.js';
const require = createRequire(import.meta.url);
/**
* The git tag for the current HEAD (if HEAD is itself a tag),
* otherwise a combination of latest tag + #commits since + sha.
* Note: can't do this in CI because it is a shallow checkout.
*/
const GIT_READABLE_REF =
execSync(process.env.CI ? 'git rev-parse HEAD' : 'git describe').toString().trim();
// HACK: manually include the lighthouse-plugin-publisher-ads audits.
/** @type {Array<string>} */
// @ts-expect-error
const pubAdsAudits = PubAdsPlugin.audits.map(a => a.path);
/** @type {Array<string>} */
// @ts-expect-error
const softNavAudits = SoftNavPlugin.audits.map(a => a.path);
/** @param {string} file */
const isDevtools = file =>
path.basename(file).includes('devtools') || path.basename(file).endsWith('dt-bundle.js');
/** @param {string} file */
const isLightrider = file => path.basename(file).includes('lightrider');
const today = (() => {
const date = new Date();
const year = new Intl.DateTimeFormat('en', {year: 'numeric'}).format(date);
const month = new Intl.DateTimeFormat('en', {month: 'short'}).format(date);
const day = new Intl.DateTimeFormat('en', {day: '2-digit'}).format(date);
return `${month} ${day} ${year}`;
})();
const pkg = readJson(`${LH_ROOT}/package.json`);
const banner = `
/**
* Lighthouse ${GIT_READABLE_REF} (${today})
*
* ${pkg.description}
*
* @homepage ${pkg.homepage}
* @author ${pkg.author}
* @license ${pkg.license}
*/
`.trim();
/**
* Bundle starting at entryPath, writing the minified result to distPath.
* @param {string} entryPath
* @param {string} distPath
* @param {{minify: boolean}=} opts
* @return {Promise<void>}
*/
async function buildBundle(entryPath, distPath, opts = {minify: true}) {
// List of paths (absolute / relative to config-helpers.js) to include
// in bundle and make accessible via config-helpers.js `requireWrapper`.
const dynamicModulePaths = [
...Runner.getGathererList().map(gatherer => `../gather/gatherers/${gatherer}`),
...Runner.getAuditList().map(gatherer => `../audits/${gatherer}`),
];
// Include plugins.
if (isDevtools(entryPath) || isLightrider(entryPath)) {
dynamicModulePaths.push('lighthouse-plugin-publisher-ads');
pubAdsAudits.forEach(pubAdAudit => {
dynamicModulePaths.push(pubAdAudit);
});
dynamicModulePaths.push('lighthouse-plugin-soft-navigation');
softNavAudits.forEach(softNavAudit => {
dynamicModulePaths.push(softNavAudit);
});
}
const bundledMapEntriesCode = dynamicModulePaths.map(modulePath => {
const pathNoExt = modulePath.replace('.js', '');
return `['${pathNoExt}', import('${modulePath}')]`;
}).join(',\n');
/** @type {Record<string, string>} */
const shimsObj = {
// zlib's decompression code is very large and we don't need it.
// We export empty functions, instead of an empty module, simply to silence warnings
// about no exports.
'__zlib-lib/inflate': `
export function inflateInit2() {};
export function inflate() {};
export function inflateEnd() {};
export function inflateReset() {};
`,
};
const modulesToIgnore = [
'puppeteer-core',
'pako/lib/zlib/inflate.js',
'@sentry/node',
'source-map',
'ws',
];
// Don't include the stringified report in DevTools - see devtools-report-assets.js
// Don't include in Lightrider - HTML generation isn't supported, so report assets aren't needed.
if (isDevtools(entryPath) || isLightrider(entryPath)) {
shimsObj[`${LH_ROOT}/report/generator/report-assets.js`] =
'export const reportAssets = {}';
}
// Don't include locales in DevTools.
if (isDevtools(entryPath)) {
shimsObj[`${LH_ROOT}/shared/localization/locales.js`] = 'export const locales = {};';
}
for (const modulePath of modulesToIgnore) {
shimsObj[modulePath] = 'export default {}';
}
await esbuild.build({
entryPoints: [entryPath],
outfile: distPath,
write: false,
format: 'iife',
charset: 'utf8',
bundle: true,
minify: opts.minify,
treeShaking: true,
sourcemap: 'linked',
banner: {js: banner},
// Because of page-functions!
keepNames: true,
inject: ['./build/process-global.js'],
/** @type {esbuild.Plugin[]} */
plugins: [
plugins.replaceModules({
...shimsObj,
'url': `
export const URL = globalThis.URL;
export const fileURLToPath = url => url;
export default {URL, fileURLToPath};
`,
'module': `
export const createRequire = () => {
return {
resolve() {
throw new Error('createRequire.resolve is not supported in bundled Lighthouse');
},
};
};
`,
}, {
// buildBundle is used in a lot of different contexts. Some share the same modules
// that need to be replaced, but others don't use those modules at all.
disableUnusedError: true,
}),
nodeModulesPolyfillPlugin(),
plugins.bulkLoader([
// TODO: when we used rollup, various things were tree-shaken out before inlineFs did its
// thing. Now treeshaking only happens at the end, so the plugin sees more cases than it
// did before. Some of those new cases emit warnings. Safe to ignore, but should be
// resolved eventually.
plugins.partialLoaders.inlineFs({
verbose: Boolean(process.env.DEBUG),
ignorePaths: [require.resolve('puppeteer-core/lib/esm/puppeteer/common/Page.js')],
}),
plugins.partialLoaders.rmGetModuleDirectory,
plugins.partialLoaders.replaceText({
'/* BUILD_REPLACE_BUNDLED_MODULES */': `[\n${bundledMapEntriesCode},\n]`,
// TODO: Use globalThis directly.
'global.isLightrider': 'globalThis.isLightrider',
'global.isDevtools': 'globalThis.isDevtools',
// By default esbuild converts `import.meta` to an empty object.
// We need at least the url property for i18n things.
/** @param {string} id */
'import.meta': (id) => `{url: '${path.relative(LH_ROOT, id)}'}`,
}),
]),
{
name: 'alias',
setup({onResolve}) {
onResolve({filter: /\.*/}, (args) => {
/** @type {Record<string, string>} */
const entries = {
'debug': require.resolve('debug/src/browser.js'),
'lighthouse-logger': require.resolve('../lighthouse-logger/index.js'),
};
if (args.path in entries) {
return {path: entries[args.path]};
}
});
},
},
{
name: 'postprocess',
setup({onEnd}) {
onEnd(async (result) => {
if (result.errors.length) {
return;
}
const codeFile = result.outputFiles?.find(file => file.path.endsWith('.js'));
const mapFile = result.outputFiles?.find(file => file.path.endsWith('.js.map'));
if (!codeFile) {
throw new Error('missing output');
}
// Just make sure the above shimming worked.
let code = codeFile.text;
if (code.includes('inflate_fast')) {
throw new Error('Expected zlib inflate code to have been removed');
}
// Get rid of our extra license comments.
// All comments would have been moved to the end of the file, so removing some will not break
// source maps.
// https://stackoverflow.com/a/35923766
const re = /\/\*\*\s*\n([^*]|(\*(?!\/)))*\*\/\n/g;
let hasSeenFirst = false;
code = code.replace(re, (match) => {
if (match.includes('@license') && match.match(/Lighthouse Authors|Google/)) {
if (hasSeenFirst) {
return '';
}
hasSeenFirst = true;
}
return match;
});
await fs.promises.writeFile(codeFile.path, code);
if (mapFile) {
await fs.promises.writeFile(mapFile.path, mapFile.text);
}
});
},
},
],
});
}
/**
* @param {Array<string>} argv
*/
async function cli(argv) {
// Take paths relative to cwd and build.
const [entryPath, distPath] = argv.slice(2)
.map(filePath => path.resolve(process.cwd(), filePath));
await buildBundle(entryPath, distPath, {minify: !process.env.DEBUG});
}
// Test if called from the CLI or as a module.
if (esMain(import.meta)) {
await cli(process.argv);
}
export {
buildBundle,
};