-
Notifications
You must be signed in to change notification settings - Fork 4
/
helpers.js
201 lines (166 loc) · 5.17 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
const { defaultsDeep, merge, isNull, mapValues, pick } = require("lodash");
const defaultOptions = {
headers: {},
pdfOptions: {
landscape: true,
printBackground: true
},
waitFor: [],
waitTimeout: 60000,
imageType: "png",
omitBackground: false,
imageQuality: 90,
scaleFactor: 2,
};
const log = (message) => {
if (process.env.MONITOR) return;
console.log(`[${new Date().toISOString()}] ${message}`);
};
const prepareOptions = reqBody => {
const body = mapValues(reqBody, val => (isNull(val) ? undefined : val));
const options = defaultsDeep(body, defaultOptions);
return options;
};
const wait = async (page, options) => {
for (let i = 0; i < options.waitFor.length; i++) {
const condition = options.waitFor[i];
// Uses either waitForTimeout or waitForSelector because options.waitFor[i]
// could only either be a String selector OR Integer time in milliseconds
if (parseInt(condition)) {
await page.waitForTimeout(parseInt(condition));
}else{
await page.waitForSelector(condition, { timeout: options.waitTimeout });
}
}
};
const prepareContent = async (page, options) => {
const waitUntil = options.waitForIdle ? "networkidle0" : "load";
const gotoOptions = { timeout: options.waitTimeout, waitUntil };
if (options.htmlContent) {
await page.setContent(options.htmlContent, gotoOptions);
} else {
log(`Navigating to ${options.url}`);
await page.goto(options.url, gotoOptions);
}
return await wait(page, options);
};
const measureContent = async (page) => {
const navigation = await page.evaluate(
'JSON.stringify(window.performance.getEntriesByType("navigation"))'
);
const resource = await page.evaluate(
'JSON.stringify(window.performance.getEntriesByType("resource"))'
);
return {navigation, resource};
}
const calculateDimensions = async (page, options) => {
const selector = options.viewportSelector || options.selector || "body";
/* istanbul ignore next */
const dimensions = await page.$$eval(
`${selector}, ${selector} *`,
elements => {
return elements.map(el => {
return ({
width: el.offsetWidth,
height: el.offsetHeight
})
});
}
);
const widths = dimensions
.map(el => el.width)
.filter(num => Number.isInteger(num));
const heights = dimensions
.map(el => el.height)
.filter(num => Number.isInteger(num));
const width = Math.max(...widths);
const height = Math.max(...heights);
if (!Number.isInteger(width) || !Number.isInteger(height)) {
throw new Error(
"Source was successfully loaded but no visible elements were rendered"
);
}
return { width, height };
};
const setViewport = async (page, options) => {
let dimensions;
if (options.width && options.height) {
dimensions = pick(options, ["width", "height"]);
} else {
calculatedDimensions = await calculateDimensions(page, options);
dimensions = {
width: options.width || calculatedDimensions.width,
height: options.height || calculatedDimensions.height,
}
}
Object.assign(dimensions, { deviceScaleFactor: options.scaleFactor });
return await page.setViewport(dimensions);
};
const captureImage = async (page, options) => {
log(`Starting Image capture of ${options.htmlContent ? 'provided HTML' : options.url}`);
await setViewport(page, options);
// save users that don't RTFM from themselves
// puppeteer requires `jpeg` instead of `jpg`
if (options.imageType == "jpg"){
options.imageType = "jpeg";
};
let imageOptions = {
clip: options.clipArea,
type: options.imageType,
omitBackground: options.omitBackground,
};
let jpgOptions = {
quality: options.imageQuality
};
let nonSelectorOptions = {
fullPage: !(options.width && options.height)
};
if (options.imageType == "jpeg"){
imageOptions = merge(imageOptions, jpgOptions);
}
if (options.selector) {
const element = await page.$(options.selector);
if (!options.clipArea) {
imageOptions.clip = await element.boundingBox();
}
return await element.screenshot(imageOptions);
}
imageOptions = merge(imageOptions, nonSelectorOptions);
return await page.screenshot(imageOptions);
};
const capturePdf = async (page, options) => {
log(`Starting PDF capture: ${options.url}`);
await setViewport(page, options);
if(options.emulateMediaType) {
await page.emulateMediaType(options.emulateMediaType);
}
return await page.pdf({ ...options.pdfOptions });
};
const captureContent = async (page, options) => {
log(`Starting Content capture: ${options.url}`);
if(options.userAgent) {
await page.setUserAgent(options.userAgent)
}
if(options.emulateMediaType) {
await page.emulateMediaType(options.emulateMediaType);
}
return await page.content();
};
const handleError = (error, res) => {
console.error(error.stack);
res.status(500);
res.send(error.message);
};
const isPrivateNetwork = input =>
input.match(/(^127\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)|(^169\.254\.)/);
module.exports = {
log,
measureContent,
prepareOptions,
prepareContent,
capturePdf,
captureImage,
captureContent,
handleError,
isPrivateNetwork,
};