generated from Mechanika-Design/repo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
101 lines (81 loc) · 2.16 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
const puppeteer = require('puppeteer');
const ora = require('ora');
const runMetricsExtracter = require('./src/runner');
const {
DEFAULT_REPEAT_TIMES,
DEFAULT_VIEWPORT_SIZE,
DEFAULT_OUTPUT_FORMAT,
OUTPUT_FORMATS,
URL_REGEX,
} = require('./src/constants');
const output = require('./src/output');
module.exports = async function start(
{
url,
repeat = DEFAULT_REPEAT_TIMES,
height = DEFAULT_VIEWPORT_SIZE.HEIGHT,
width = DEFAULT_VIEWPORT_SIZE.WIDTH,
outputFormat = DEFAULT_OUTPUT_FORMAT.DEFAULT,
withRedirects = false,
outputFile = false,
customPath,
waitUntil,
headless = true,
sandbox = true,
},
errorHandler,
) {
// TODO: Create function to check options.
if (url === undefined || !URL_REGEX.test(url)) {
errorHandler(Error('Invalid URL'));
}
if (!OUTPUT_FORMATS.includes(outputFormat)) {
errorHandler(Error('Unsupported output format'));
}
const spinner = ora('Launching Browser').start();
const logStep = (step, repeat) => {
spinner.text = `Extracting metrics ${step}/${repeat}`;
};
const logInfo = (log) => {
spinner.text = log;
};
const browser = await puppeteer.launch({
headless,
args: sandbox ? undefined : ['--no-sandbox'],
});
const page = await browser.newPage();
// Set the viewport.
await page.setViewport({
width: parseInt(width, 10),
height: parseInt(height, 10),
});
try {
let client;
if (customPath) {
const customPathFunction = require(customPath);
await customPathFunction(page, logInfo);
}
// If we want tu use a custom url, reach it before making metrics.
logInfo(`Testing ${url}...`);
await page.goto(url).catch(errorHandler);
if (!client) {
client = await page.target().createCDPSession();
await client.send('Performance.enable');
}
const aggregatedData = await runMetricsExtracter({
page,
client,
url,
withRedirects,
repeat,
waitUntil,
logStep,
});
spinner.stop();
await browser.close();
return output(aggregatedData, outputFormat, outputFile);
} catch (error) {
await browser.close();
errorHandler(error);
}
};