-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathhelpers.js
363 lines (340 loc) · 11.4 KB
/
helpers.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
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
const fs = require('fs');
const path = require('path');
const open = require('open');
const cliProgress = require('cli-progress');
const simpleCrawlerConfig = require('./config/simpleCrawler');
/**
* Determines the form factor of the given Lighthouse report
*
* @param {string} fileName
* @returns Can be either "desktop" or "mobile" form factor string
*/
const _determineFormFactorReport = (fileName) => {
let formFactor;
if (fileName.includes('.desktop')) {
formFactor = 'desktop';
} else if (fileName.includes('.mobile')) {
formFactor = 'mobile';
}
return formFactor;
};
/**
* Reads the CSV report directory and obtains a list of files
*
* @param {string} directoryPath
* @returns An array of files or false if the directory does not exist
*/
const _readReportDirectory = (directoryPath) => {
let files;
try {
files = fs.readdirSync(directoryPath);
} catch (e) {
console.error(e);
return false;
}
return files;
};
/**
* Creates write streams for the desktop and mobile aggregate reports
*
* @param {string} timestamp
* @param {string} directoryPath
* @param {string} formFactor
* @returns an array of write streams
*/
const _createWriteStreams = (timestamp, directoryPath, formFactor) => {
const desktopAggregateReportName = timestamp + '_desktop_aggregateReport.csv';
const mobileAggregateReportName = timestamp + '_mobile_aggregateReport.csv';
let desktopAggregatePath = path.join(directoryPath, desktopAggregateReportName);
let mobileAggregatePath = path.join(directoryPath, mobileAggregateReportName);
let desktopWriteStream;
let mobileWriteStream;
if (formFactor === 'desktop' || formFactor === 'all') {
desktopWriteStream = fs.createWriteStream(desktopAggregatePath, { flags: 'a', autoClose: false });
}
if (formFactor === 'mobile' || formFactor === 'all') {
mobileWriteStream = fs.createWriteStream(mobileAggregatePath, { flags: 'a', autoClose: false });
}
return [desktopWriteStream, mobileWriteStream];
};
/**
*
*
* @param {boolean} isFirstDesktopReport
* @param {fs.WriteStream} desktopWriteStream
* @param {String} fileContents
* @returns a boolean representing if the given report is the first of its kind
*/
const _writeDesktopCSVStream = (isFirstDesktopReport, desktopWriteStream, fileContents) => {
if (isFirstDesktopReport) {
desktopWriteStream.write(fileContents + '\n');
isFirstDesktopReport = false;
} else {
let newContents = fileContents.split('\n').slice(1).join('\n');
desktopWriteStream.write(newContents + '\n');
}
return isFirstDesktopReport;
};
/**
* Writes data to the mobile aggregate report
*
* @param {boolean} isFirstMobileReport
* @param {fs.WriteStream} mobileWriteStream
* @param {String} fileContents
* @returns a boolean representing if the given report is the first of its kind
*/
const _writeMobileCSVStream = (isFirstMobileReport, mobileWriteStream, fileContents) => {
if (isFirstMobileReport) {
mobileWriteStream.write(fileContents + '\n');
isFirstMobileReport = false;
} else {
let newContents = fileContents.split('\n').slice(1).join('\n');
mobileWriteStream.write(newContents + '\n');
}
return isFirstMobileReport;
};
/**
* Process the CSV reports and write their data to the respective write stream.
* @param {Object} processCSVObject
* @param {string[]} processCSVObject.files
* @param {string} processCSVObject.directoryPath
* @param {fs.WriteStream | undefined} processCSVObject.desktopWriteStream
* @param {fs.WriteStream | undefined} processCSVObject.mobileWriteStream
*/
const _processCSVFiles = (processCSVObject) => {
const {files, directoryPath, desktopWriteStream, mobileWriteStream, progressBar} = processCSVObject;
let isFirstDesktopReport = true;
let isFirstMobileReport = true;
files.forEach(fileName => {
let filePath = path.join(directoryPath, fileName);
let fileContents = fs.readFileSync(filePath, { encoding: 'utf-8' });
let formFactor = _determineFormFactorReport(fileName);
if (formFactor === 'desktop' && desktopWriteStream) {
isFirstDesktopReport = _writeDesktopCSVStream(isFirstDesktopReport, desktopWriteStream, fileContents);
progressBar.increment();
}
if (formFactor === 'mobile' && mobileWriteStream) {
isFirstMobileReport = _writeMobileCSVStream(isFirstMobileReport, mobileWriteStream, fileContents);
progressBar.increment();
}
});
};
/**
* Helper function to queue up async promises.
* Otherwise, Lighthouse is going to run a report on every URL in the URL list.
* This will bog down the CPU.
* @param {[function]} funcList A list of functions to be executed
* @param {number} [limit=4] The number of parallel processes to execute the funcList
*
*/
/* istanbul ignore next */
const parallelLimit = async (funcList, limit = 4) => {
let inFlight = new Set();
return funcList.map(async (func, i) => {
while (inFlight.size >= limit) {
await Promise.race(inFlight);
}
inFlight.add(func);
await func;
inFlight.delete(func);
});
};
const createFileTime = () => {
let fileTime = new Date().toLocaleString();
// Replacing characters that make OS sad
fileTime = fileTime.replace(/ /g, '__');
fileTime = fileTime.replace(/\//g, '_');
fileTime = fileTime.replace(/,/g, '_');
fileTime = fileTime.replace(/:/g, "_");
return fileTime;
};
const _determineURLs = (urls, domainRoot) => {
urls.forEach(url => {
if (!url.startsWith('https://') && !url.startsWith('http://')) {
url = 'https://' + url;
}
domainRoot.push(new URL(url));
});
};
const _parseProgramURLs = (options) => {
let domainRoot;
if (options.url === undefined) {
throw new Error('No URL given, quitting!');
}
if (Array.isArray(options.url)) {
domainRoot = [];
_determineURLs(options.url, domainRoot);
} else {
if (!options.url.startsWith('https://') && !options.url.startsWith('http://')) {
options.url = 'https://' + options.url;
}
domainRoot = new URL(options.url);
}
return domainRoot;
};
const _setupCrawlerConfig = (simpleCrawler, options) => {
for (let key in simpleCrawlerConfig) {
simpleCrawler[key] = simpleCrawlerConfig[key];
}
simpleCrawler.ignoreWWWDomain = true;
simpleCrawler.respectRobotsTxt = options.respect;
};
const _populateURLArray = (domainRoot, simpleCrawler, urlList) => {
if (domainRoot.length > 1) {
domainRoot.forEach(root => {
if (!simpleCrawler.queue.includes(root)) {
simpleCrawler.domainWhitelist.push(root.hostname);
simpleCrawler.queueURL(root.href);
}
});
} else {
urlList.push(domainRoot[0].href);
}
};
const _populateCrawledURLList = (isDomainRootAnArray, domainRoot, simpleCrawler, urlList) => {
if (isDomainRootAnArray) {
_populateURLArray(domainRoot, simpleCrawler, urlList);
} else {
urlList.push(domainRoot.href);
}
};
const _determineResultingFilePath = (opts, filePath, tempFilePath, replacedUrl) => {
if (opts.formFactor && opts.formFactor === 'desktop') {
filePath = path.join(tempFilePath, replacedUrl + '.desktop.report.' + opts.output);
} else {
filePath = path.join(tempFilePath, replacedUrl + '.mobile.report.' + opts.output);
}
return filePath;
};
const _writeReportResultFile = (filePath, report, opts, currentUrl, tempFilePath) => {
fs.writeFile(filePath, report, {
encoding: 'utf-8'
}, (err) => {
if (err)
throw err;
if (opts.formFactor && opts.formFactor === 'desktop') {
console.info('\n Wrote desktop report: ', currentUrl, 'at: ', tempFilePath);
} else {
console.info('\n Wrote mobile report: ', currentUrl, 'at: ', tempFilePath);
}
});
};
const _printNumberOfReports = (formFactor, urlList) => {
if (formFactor !== 'all') {
console.log(`Generating ${urlList.length} reports!`);
} else {
console.log(`Generating ${urlList.length * 2} reports!`);
}
}
const _getNumberOfReports = (formFactor, urlList) => {
if (formFactor !== 'all') {
return urlList.length;
} else {
return urlList.length * 2;
}
}
const _closeWriteStreams = (mobileWriteStream, desktopWriteStream) => {
if (desktopWriteStream) {
desktopWriteStream.close();
}
if (mobileWriteStream) {
mobileWriteStream.close();
}
}
const _waitForStreamsToClose = async (mobileWriteStream, desktopWriteStream) => {
if (desktopWriteStream) {
let desktopClosed = new Promise((resolve) => {
desktopWriteStream.on("close", () => resolve(true));
});
await desktopClosed;
}
if (mobileWriteStream) {
let mobileClosed = new Promise((resolve) => {
mobileWriteStream.on("close", () => resolve(true));
});
await mobileClosed;
}
}
const _setupProgressBarAggregateCsv = (desktopWriteStream, mobileWriteStream, files) => {
console.log('Aggregating reports!');
let progressBar = new cliProgress.SingleBar({
format: 'Aggregate progress {bar} {percentage}% | ETA: {eta}s | {value}/{total} | time elapsed: {duration}s',
forceRedraw: true
}, cliProgress.Presets.shades_classic);
if (desktopWriteStream && mobileWriteStream) {
progressBar.start(files.length, 0);
} else {
progressBar.start(files.length / 2, 0);
}
return progressBar;
};
const _setupProgressBarReportCreation = (formFactor, urlList) => {
let progressBar = new cliProgress.SingleBar({
format: 'Report creation progress {bar} {percentage}% | ETA: {eta}s | {value}/{total} | time elapsed: {duration}s',
forceRedraw: true
}, cliProgress.Presets.shades_classic);
let numberOfReports = _getNumberOfReports(formFactor, urlList);
console.log("Processing reports!");
progressBar.start(numberOfReports, 0);
return progressBar;
};
/**
* Opens generated reports in your preferred browser as an explorable list
* @param {Number} port Port used by Express
*/
const openReports = (port) => {
const express = require('express');
const serveIndex = require('serve-index');
const app = express();
try {
app.use(express.static('lighthouse'), serveIndex('lighthouse', { 'icons': true }));
app.listen(port);
open('http://localhost:' + port);
return true;
} catch (e) {
throw e;
}
};
/**
* Opens **all** generated reports in your preferred browser without a local server
*
* @param {string} tempFilePath
*/
const openReportsWithoutServer = (tempFilePath) => {
let filePath = tempFilePath;
/* istanbul ignore next */
if (fs.existsSync(filePath)) {
fs.readdirSync(filePath).forEach(file => {
console.log('Opening: ', file);
let tempPath = path.join(tempFilePath, file);
open(tempPath);
});
return true;
}
return false;
};
module.exports = {
_determineFormFactorReport,
_readReportDirectory,
_createWriteStreams,
_writeDesktopCSVStream,
_writeMobileCSVStream,
_processCSVFiles,
parallelLimit,
createFileTime,
_determineURLs,
_parseProgramURLs,
_setupCrawlerConfig,
_populateURLArray,
_populateCrawledURLList,
_determineResultingFilePath,
_writeReportResultFile,
_printNumberOfReports,
_waitForStreamsToClose,
_closeWriteStreams,
_getNumberOfReports,
_setupProgressBarAggregateCsv,
_setupProgressBarReportCreation,
openReports,
openReportsWithoutServer
};