-
Notifications
You must be signed in to change notification settings - Fork 40
/
page.js
258 lines (215 loc) · 8.67 KB
/
page.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
import fs from 'fs';
import logger from '@percy/logger';
import Network from './network.js';
import { PERCY_DOM } from './api.js';
import {
hostname,
waitFor,
waitForTimeout as sleep,
serializeFunction
} from './utils.js';
export class Page {
static TIMEOUT = undefined;
log = logger('core:page');
constructor(session, options) {
this.session = session;
this.browser = session.browser;
this.enableJavaScript = options.enableJavaScript ?? true;
this.network = new Network(this, options);
this.meta = options.meta;
this._initializeLoadTimeout();
session.on('Runtime.executionContextCreated', this._handleExecutionContextCreated);
session.on('Runtime.executionContextDestroyed', this._handleExecutionContextDestroyed);
session.on('Runtime.executionContextsCleared', this._handleExecutionContextsCleared);
session.send('Runtime.enable').catch(session._handleClosedError);
this.log.debug('Page created');
}
// Close the page
async close() {
await this.session.close();
this.log.debug('Page closed', this.meta);
}
// Resize the page to the specified width and height
async resize({ width, height, deviceScaleFactor = 1, mobile = false }) {
this.log.debug(`Resize page to ${width}x${height} @${deviceScaleFactor}x`);
await this.session.send('Emulation.setDeviceMetricsOverride', {
deviceScaleFactor,
mobile,
height,
width
});
}
// Go to a URL and wait for navigation to occur
async goto(url, { waitUntil = 'load' } = {}) {
this.log.debug(`Navigate to: ${url}`, this.meta);
let navigate = async () => {
// set cookies before navigation so we can default the domain to this hostname
if (this.session.browser.cookies.length) {
let defaultDomain = hostname(url);
await this.session.send('Network.setCookies', {
// spread is used to make a shallow copy of the cookie
cookies: this.session.browser.cookies.map(({ ...cookie }) => {
if (!cookie.url) cookie.domain ||= defaultDomain;
return cookie;
})
});
}
// handle navigation errors
let res = await this.session.send('Page.navigate', { url });
if (res.errorText) throw new Error(res.errorText);
};
let handlers = [
// wait until navigation and the correct lifecycle
['Page.frameNavigated', e => this.session.targetId === e.frame.id],
['Page.lifecycleEvent', e => this.session.targetId === e.frameId && e.name === waitUntil]
].map(([name, cond]) => {
let handler = e => cond(e) && (handler.finished = true) && handler.off();
handler.off = () => this.session.off(name, handler);
this.session.on(name, handler);
return handler;
});
try {
// trigger navigation and poll for handlers to have finished
await Promise.all([navigate(), waitFor(() => {
if (this.session.closedReason) throw new Error(this.session.closedReason);
return handlers.every(handler => handler.finished);
}, Page.TIMEOUT)]);
} catch (error) {
// remove any unused handlers
for (let handler of handlers) handler.off();
// assign context to unknown errors
if (!error.message.startsWith('Timeout')) {
throw Object.assign(error, { message: `Navigation failed: ${error.message}` });
}
// throw a network error to show active requests
this.network._throwTimeoutError(
`Navigation failed: Timed out waiting for the page ${waitUntil} event`
);
}
this.log.debug('Page navigated', this.meta);
}
// Evaluate JS functions within the page's execution context
async eval(fn, ...args) {
let { result, exceptionDetails } =
await this.session.send('Runtime.callFunctionOn', {
functionDeclaration: serializeFunction(fn),
arguments: args.map(value => ({ value })),
executionContextId: this.contextId,
returnByValue: true,
awaitPromise: true,
userGesture: true
});
if (exceptionDetails) {
throw exceptionDetails.exception.description;
} else {
return result.value;
}
}
// Evaluate one or more scripts in succession
async evaluate(scripts) {
if (!(scripts &&= [].concat(scripts))?.length) return;
this.log.debug('Evaluate JavaScript', { ...this.meta, scripts });
for (let script of scripts) await this.eval(script);
}
async insertPercyDom() {
// inject @percy/dom for serialization by evaluating the file contents which adds a global
// PercyDOM object that we can later check against
/* istanbul ignore next: no instrumenting injected code */
if (await this.eval(() => !window.PercyDOM)) {
this.log.debug('Inject @percy/dom', this.meta);
let script = await fs.promises.readFile(PERCY_DOM, 'utf-8');
await this.eval(new Function(script)); /* eslint-disable-line no-new-func */
}
}
// Takes a snapshot after waiting for any timeout, waiting for any selector, executing any
// scripts, and waiting for the network idle. Returns all other provided snapshot options along
// with the captured URL and DOM snapshot.
async snapshot({
waitForTimeout,
waitForSelector,
execute,
...snapshot
}) {
let { name, width, enableJavaScript, disableShadowDOM, domTransformation, reshuffleInvalidTags } = snapshot;
this.log.debug(`Taking snapshot: ${name}${width ? ` @${width}px` : ''}`, this.meta);
// wait for any specified timeout
if (waitForTimeout) {
this.log.debug(`Wait for ${waitForTimeout}ms timeout`, this.meta);
await sleep(waitForTimeout);
}
// wait for any specified selector
if (waitForSelector) {
this.log.debug(`Wait for selector: ${waitForSelector}`, this.meta);
await this.eval(`await waitForSelector(${JSON.stringify(waitForSelector)}, ${Page.TIMEOUT})`);
}
// execute any javascript
if (execute) {
let execBefore = typeof execute === 'object' && !Array.isArray(execute);
await this.evaluate(execBefore ? execute.beforeSnapshot : execute);
}
// wait for any final network activity before capturing the dom snapshot
await this.network.idle();
await this.insertPercyDom();
// serialize and capture a DOM snapshot
this.log.debug('Serialize DOM', this.meta);
/* istanbul ignore next: no instrumenting injected code */
let capture = await this.eval((_, options) => ({
/* eslint-disable-next-line no-undef */
domSnapshot: PercyDOM.serialize(options),
url: document.URL
}), { enableJavaScript, disableShadowDOM, domTransformation, reshuffleInvalidTags });
return { ...snapshot, ...capture };
}
// Initialize newly attached pages and iframes with page options
_handleAttachedToTarget = event => {
let session = !event ? this.session
: this.session.children.get(event.sessionId);
/* istanbul ignore if: sanity check */
if (!session) return;
let commands = [this.network.watch(session)];
if (session.isDocument) {
session.on('Target.attachedToTarget', this._handleAttachedToTarget);
commands.push(
session.send('Page.enable'),
session.send('Page.setLifecycleEventsEnabled', { enabled: true }),
session.send('Security.setIgnoreCertificateErrors', { ignore: true }),
session.send('Emulation.setScriptExecutionDisabled', { value: !this.enableJavaScript }),
session.send('Target.setAutoAttach', {
waitForDebuggerOnStart: false,
autoAttach: true,
flatten: true
}));
}
return Promise.all(commands)
.catch(session._handleClosedError);
}
// Keep track of the page's execution context id
_handleExecutionContextCreated = event => {
if (this.session.targetId === event.context.auxData.frameId) {
this.contextId = event.context.id;
// inject global percy config as soon as possible
this.eval(`window.__PERCY__ = ${
JSON.stringify({ config: this.browser.percy.config })
};`).catch(this.session._handleClosedError);
}
}
_handleExecutionContextDestroyed = event => {
/* istanbul ignore next: context cleared is usually called first */
if (this.contextId === event.executionContextId) {
this.contextId = null;
}
}
_handleExecutionContextsCleared = () => {
this.contextId = null;
}
_initializeLoadTimeout() {
if (Page.TIMEOUT) return;
Page.TIMEOUT = parseInt(process.env.PERCY_PAGE_LOAD_TIMEOUT) || 30000;
if (Page.TIMEOUT > 60000) {
this.log.warn('Setting PERCY_PAGE_LOAD_TIMEOUT over 60000ms is not recommended. ' +
'If your page needs more than 60000ms to load due to CPU/Network load, ' +
'its recommended to increase CI resources where this cli is running.');
}
}
}
export default Page;