-
Notifications
You must be signed in to change notification settings - Fork 44
/
index.js
307 lines (274 loc) · 8.22 KB
/
index.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
"use strict";
require("shelljs/global");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const OUT = "./report/lighthouse";
const REPORT_SUMMARY = "summary.json";
const JSON_EXT = ".report.json";
const CSV_EXT = ".report.csv";
const HTML_EXT = ".report.html";
execute.OUT = OUT;
module.exports = execute;
function execute(options) {
log = log.bind(log, options.verbose || false);
const out = options.out || OUT;
const lhScript = lighthouseScript(options, log);
const summaryPath = path.join(out, REPORT_SUMMARY);
try {
const files = fs.readdirSync(out);
files.forEach((f) => {
if (
f.endsWith(JSON_EXT) ||
f.endsWith(HTML_EXT) ||
f.endsWith(CSV_EXT) ||
f == REPORT_SUMMARY
) {
const oldFile = path.join(out, f);
log(`Removing old report file: ${oldFile}`);
rm("-f", oldFile);
}
});
} catch (e) {}
mkdir("-p", out);
let budgetErrors = [];
const count = options.sites.length;
log(`Lighthouse batch run begin for ${count} site${count > 1 ? "s" : ""}`);
const reports = sitesInfo(options)
.map((site, i) => {
if (budgetErrors.length && options.failFast) {
return undefined;
}
const prefix = `${i + 1}/${count}: `;
const htmlOut = options.html ? " --output html" : "";
const csvOut = options.csv ? " --output csv" : "";
const filePath = path.join(out, site.file);
const customParams = options.params || "";
const chromeFlags =
customParams.indexOf("--chrome-flags=") === -1
? `--chrome-flags="--no-sandbox --headless --disable-gpu"`
: "";
// if gen'ing (html|csv)+json reports, ext '.report.json' is added by lighthouse cli automatically,
// so here we try and keep the file names consistent by stripping to avoid duplication
const outputPath =
options.html || options.csv
? filePath.slice(0, -JSON_EXT.length)
: filePath;
const cmd = `"${site.url}" --output json${
htmlOut + csvOut
} --output-path "${outputPath}" ${chromeFlags} ${customParams}`;
log(`${prefix}Lighthouse analyzing '${site.url}'`);
log(cmd);
const outcome = exec(`${lhScript} ${cmd}`);
const summary = updateSummary(filePath, site, outcome, options);
if (summary.error)
console.warn(`${prefix}Lighthouse analysis FAILED for ${summary.url}`);
else
log(
`${prefix}Lighthouse analysis of '${summary.url}' complete with score ${summary.score}`
);
if (options.report === false) {
log(`Removing generated report file '${filePath}'`);
rm(filePath);
}
const errors = checkBudgets(summary, options);
if (errors) {
const other = summary.errors;
summary.errors = {
budget: errors,
};
if (other) {
summary.errors.other = other;
}
budgetErrors = budgetErrors.concat(errors);
}
return summary;
})
.filter((summary) => !!summary);
console.log(`Lighthouse batch run end`);
console.log(`Writing reports summary to ${summaryPath}`);
fs.writeFileSync(summaryPath, JSON.stringify(reports), "utf8");
if (options.print) {
console.log(`Printing reports summary`);
console.log(JSON.stringify(reports, null, 2));
}
if (budgetErrors.length) {
console.error(`Error: failed to meet budget thresholds`);
for (let err of budgetErrors) {
console.error(` - ${err}`);
}
log("Exiting with code 1");
process.exit(1);
}
}
function sitesInfo(options) {
let sites = [];
if (options.file) {
try {
const contents = fs.readFileSync(options.file, "utf8");
sites = contents.trim().split("\n");
} catch (e) {
console.error(`Failed to read file ${options.file}, aborting.\n`, e);
log("Exiting with code 1");
process.exit(1);
}
}
if (options.sites) {
sites = sites.concat(options.sites);
}
const existingNames = {};
return sites.map((url) => {
url = url.trim();
if (!url.match(/^https?:/)) {
if (!url.startsWith("//")) url = `//${url}`;
url = `https:${url}`;
}
const origName = siteName(url);
let name = origName;
// if the same page is being tested multiple times then
// give each one an incremented name to avoid collisions
let j = 1;
while (existingNames[name]) {
name = `${origName}_${j}`;
j++;
}
existingNames[name] = true;
const info = {
url,
name,
file: `${name}${JSON_EXT}`,
};
if (options.html) info.html = `${name}${HTML_EXT}`;
if (options.csv) info.csv = `${name}${CSV_EXT}`;
return info;
});
}
function lighthouseScript(options, log) {
if (options.useGlobal) {
if (exec("lighthouse --version").code === 0) {
log("Targeting global install of Lighthouse cli");
return "lighthouse";
} else {
console.warn(
"Global Lighthouse install not found, falling back to local one"
);
}
}
let cliPath = path.resolve(
`${__dirname}/node_modules/lighthouse/lighthouse-cli/index.js`
);
if (!fs.existsSync(cliPath)) {
cliPath = path.resolve(
`${__dirname}/../lighthouse/lighthouse-cli/index.js`
);
if (!fs.existsSync(cliPath)) {
console.error(`Failed to find Lighthouse CLI, aborting.`);
process.exit(1);
}
}
log(`Targeting local Lighthouse cli at '${cliPath}'`);
return `node ${cliPath}`;
}
function siteName(site) {
const maxLength = 100;
let name = site
.replace(/^https?:\/\//, "")
.replace(/[\/\?#:\*\$@\!\.]/g, "_");
if (name.length > maxLength) {
const hash = crypto
.createHash("sha1")
.update(name)
.digest("hex")
.slice(0, 7);
name = name.slice(0, maxLength).replace(/_+$/g, ""); // trim any `_` suffix
name = `${name}_${hash}`;
}
return name;
}
function updateSummary(filePath, summary, outcome, options) {
if (outcome.code !== 0) {
summary.score = 0;
summary.error = outcome.stderr;
return summary;
}
const report = JSON.parse(fs.readFileSync(filePath));
return {
...summary,
...getAverageScore(report),
};
}
function getAverageScore(report) {
let categories = report.reportCategories; // lighthouse v1,2
if (report.categories) {
// lighthouse v3
categories = Object.values(report.categories);
}
let total = 0;
const detail = categories.reduce((acc, cat) => {
if (cat.id) acc[cat.id] = cat.score;
total += cat.score;
return acc;
}, {});
return {
score: Number((total / categories.length).toFixed(2)),
detail,
};
}
function checkBudgets(summary, options) {
const errors = [];
if (options.score > 0) {
const score = toScore(summary.score);
if (score < options.score) {
errors.push(
`average score ${score} < ${options.score} for ${summary.url}`
);
}
}
if (options.accessibility > 0 && summary.detail) {
const score = toScore(summary.detail.accessibility);
if (score < options.accessibility) {
errors.push(
`accessibility score ${score} < ${options.accessibility} for ${summary.url}`
);
}
}
if (options.performance > 0 && summary.detail) {
const score = toScore(summary.detail.performance);
if (score < options.performance) {
errors.push(
`performance score ${score} < ${options.performance} for ${summary.url}`
);
}
}
if (options.bestPractices > 0 && summary.detail) {
const score = toScore(summary.detail["best-practices"]);
if (score < options.bestPractices) {
errors.push(
`best practices score ${score} < ${options.bestPractices} for ${summary.url}`
);
}
}
if (options.seo > 0 && summary.detail) {
const score = toScore(summary.detail.seo);
if (score < options.seo) {
errors.push(
`seo score ${score} < ${options.seo} for site ${summary.url}`
);
}
}
if (options.pwa > 0 && summary.detail) {
const score = toScore(summary.detail.pwa);
if (score < options.pwa) {
errors.push(
`pwa score ${score} < ${options.pwa} for site ${summary.url}`
);
}
}
return errors.length ? errors : undefined;
}
function log(v, msg) {
if (v) console.log(msg);
}
function toScore(score) {
return Number(score) * 100;
}