-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
driver.js
474 lines (411 loc) · 15.3 KB
/
driver.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/**
* @license Copyright 2016 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const Fetcher = require('./fetcher.js');
const ExecutionContext = require('./driver/execution-context.js');
const LHError = require('../lib/lh-error.js');
const {fetchResponseBodyFromCache} = require('../gather/driver/network.js');
const EventEmitter = require('events').EventEmitter;
const log = require('lighthouse-logger');
const DevtoolsLog = require('./devtools-log.js');
const TraceGatherer = require('./gatherers/trace.js');
// Pulled in for Connection type checking.
// eslint-disable-next-line no-unused-vars
const Connection = require('./connections/connection.js');
const {getBrowserVersion} = require('./driver/environment.js');
// Controls how long to wait for a response after sending a DevTools protocol command.
const DEFAULT_PROTOCOL_TIMEOUT = 30000;
/**
* @typedef {LH.Protocol.StrictEventEmitter<LH.CrdpEvents>} CrdpEventEmitter
*/
/**
* @implements {LH.Gatherer.FRTransitionalDriver}
*/
class Driver {
/**
* @pri_vate (This should be private, but that makes our tests harder).
* An event emitter that enforces mapping between Crdp event names and payload types.
*/
_eventEmitter = /** @type {CrdpEventEmitter} */ (new EventEmitter());
/**
* @private
* Used to save network and lifecycle protocol traffic. Just Page and Network are needed.
*/
_devtoolsLog = new DevtoolsLog(/^(Page|Network)\./);
/**
* @private
* @type {Map<string, number>}
*/
_domainEnabledCounts = new Map();
/**
* @type {number}
* @private
*/
_nextProtocolTimeout = DEFAULT_PROTOCOL_TIMEOUT;
online = true;
// eslint-disable-next-line no-invalid-this
executionContext = new ExecutionContext(this);
// eslint-disable-next-line no-invalid-this
defaultSession = this;
// eslint-disable-next-line no-invalid-this
fetcher = new Fetcher(this.defaultSession, this.executionContext);
/**
* @param {Connection} connection
*/
constructor(connection) {
this._connection = connection;
this.on('Target.attachedToTarget', event => {
this._handleTargetAttached(event).catch(this._handleEventError);
});
this.on('Page.frameNavigated', event => {
// We're only interested in setting autoattach on the root via this method.
// `_handleTargetAttached` takes care of the recursive piece.
if (event.frame.parentId) return;
// Enable auto-attaching to subtargets so we receive iframe information.
this.sendCommand('Target.setAutoAttach', {
flatten: true,
autoAttach: true,
// Pause targets on startup so we don't miss anything
waitForDebuggerOnStart: true,
}).catch(this._handleEventError);
});
connection.on('protocolevent', this._handleProtocolEvent.bind(this));
/** @private @deprecated Only available for plugin backcompat. */
this.evaluate = this.executionContext.evaluate.bind(this.executionContext);
/** @private @deprecated Only available for plugin backcompat. */
this.evaluateAsync = this.executionContext.evaluateAsync.bind(this.executionContext);
}
/** @deprecated - Not available on Fraggle Rock driver. */
static get traceCategories() {
return TraceGatherer.getDefaultTraceCategories();
}
/**
* @return {Promise<LH.Crdp.Browser.GetVersionResponse & {milestone: number}>}
*/
async getBrowserVersion() {
return getBrowserVersion(this);
}
/**
* @return {Promise<void>}
*/
async connect() {
const status = {msg: 'Connecting to browser', id: 'lh:init:connect'};
log.time(status);
await this._connection.connect();
log.timeEnd(status);
}
/**
* @return {Promise<void>}
*/
disconnect() {
return this._connection.disconnect();
}
/**
* Get the browser WebSocket endpoint for devtools protocol clients like Puppeteer.
* Only works with WebSocket connection, not extension or devtools.
* @return {Promise<string>}
*/
wsEndpoint() {
return this._connection.wsEndpoint();
}
/**
* Bind listeners for protocol events.
* @template {keyof LH.CrdpEvents} E
* @param {E} eventName
* @param {(...args: LH.CrdpEvents[E]) => void} cb
*/
on(eventName, cb) {
if (this._eventEmitter === null) {
throw new Error('connect() must be called before attempting to listen to events.');
}
// log event listeners being bound
log.formatProtocol('listen for event =>', {method: eventName}, 'verbose');
this._eventEmitter.on(eventName, cb);
}
/**
* Bind a one-time listener for protocol events. Listener is removed once it
* has been called.
* @template {keyof LH.CrdpEvents} E
* @param {E} eventName
* @param {(...args: LH.CrdpEvents[E]) => void} cb
*/
once(eventName, cb) {
if (this._eventEmitter === null) {
throw new Error('connect() must be called before attempting to listen to events.');
}
// log event listeners being bound
log.formatProtocol('listen once for event =>', {method: eventName}, 'verbose');
this._eventEmitter.once(eventName, cb);
}
/**
* Unbind event listener.
* @template {keyof LH.CrdpEvents} E
* @param {E} eventName
* @param {Function} cb
*/
off(eventName, cb) {
if (this._eventEmitter === null) {
throw new Error('connect() must be called before attempting to remove an event listener.');
}
this._eventEmitter.removeListener(eventName, cb);
}
/**
* Bind to *any* protocol event.
* @param {(payload: LH.Protocol.RawEventMessage) => void} callback
*/
addProtocolMessageListener(callback) {
this._connection.on('protocolevent', callback);
}
/**
* Unbind to *any* protocol event.
* @param {(payload: LH.Protocol.RawEventMessage) => void} callback
*/
removeProtocolMessageListener(callback) {
this._connection.off('protocolevent', callback);
}
/** @param {LH.Crdp.Target.TargetInfo} targetInfo */
setTargetInfo(targetInfo) { // eslint-disable-line no-unused-vars
// OOPIF handling in legacy driver is implicit.
}
/** @param {(session: LH.Gatherer.FRProtocolSession) => void} callback */
addSessionAttachedListener(callback) { // eslint-disable-line no-unused-vars
// OOPIF handling in legacy driver is implicit.
}
/** @param {(session: LH.Gatherer.FRProtocolSession) => void} callback */
removeSessionAttachedListener(callback) { // eslint-disable-line no-unused-vars
// OOPIF handling in legacy driver is implicit.
}
/**
* Debounce enabling or disabling domains to prevent driver users from
* stomping on each other. Maintains an internal count of the times a domain
* has been enabled. Returns false if the command would have no effect (domain
* is already enabled or disabled), or if command would interfere with another
* user of that domain (e.g. two gatherers have enabled a domain, both need to
* disable it for it to be disabled). Returns true otherwise.
* @param {string} domain
* @param {string|undefined} sessionId
* @param {boolean} enable
* @return {boolean}
* @private
*/
_shouldToggleDomain(domain, sessionId, enable) {
const key = domain + (sessionId || '');
const enabledCount = this._domainEnabledCounts.get(key) || 0;
const newCount = enabledCount + (enable ? 1 : -1);
this._domainEnabledCounts.set(key, Math.max(0, newCount));
// Switching to enabled or disabled, respectively.
if ((enable && newCount === 1) || (!enable && newCount === 0)) {
log.verbose('Driver', `${domain}.${enable ? 'enable' : 'disable'}`);
return true;
} else {
if (newCount < 0) {
log.error('Driver', `Attempted to disable domain '${domain}' when already disabled.`);
}
return false;
}
}
/**
* @return {boolean}
*/
hasNextProtocolTimeout() {
return this._nextProtocolTimeout !== DEFAULT_PROTOCOL_TIMEOUT;
}
/**
* @return {number}
*/
getNextProtocolTimeout() {
return this._nextProtocolTimeout;
}
/**
* timeout is used for the next call to 'sendCommand'.
* NOTE: This can eventually be replaced when TypeScript
* resolves https://github.com/Microsoft/TypeScript/issues/5453.
* @param {number} timeout
*/
setNextProtocolTimeout(timeout) {
this._nextProtocolTimeout = timeout;
}
/**
* @param {LH.Protocol.RawEventMessage} event
*/
_handleProtocolEvent(event) {
this._devtoolsLog.record(event);
// @ts-expect-error TODO(bckenny): tsc can't type event.params correctly yet,
// typing as property of union instead of narrowing from union of
// properties. See https://github.com/Microsoft/TypeScript/pull/22348.
this._eventEmitter.emit(event.method, event.params);
}
/**
* @param {Error} error
*/
_handleEventError(error) {
log.error('Driver', 'Unhandled event error', error.message);
}
/**
* @param {LH.Crdp.Target.AttachedToTargetEvent} event
*/
async _handleTargetAttached(event) {
// We're only interested in network requests from iframes for now as those are "part of the page".
// If it's not an iframe, just resume it and move on.
if (event.targetInfo.type !== 'iframe') {
// We suspended the target when we auto-attached, so make sure it goes back to being normal.
await this.sendCommandToSession('Runtime.runIfWaitingForDebugger', event.sessionId);
return;
}
// Events from subtargets will be stringified and sent back on `Target.receivedMessageFromTarget`.
// We want to receive information about network requests from iframes, so enable the Network domain.
await this.sendCommandToSession('Network.enable', event.sessionId);
// We also want to receive information about subtargets of subtargets, so make sure we autoattach recursively.
await this.sendCommandToSession('Target.setAutoAttach', event.sessionId, {
autoAttach: true,
flatten: true,
// Pause targets on startup so we don't miss anything
waitForDebuggerOnStart: true,
});
// We suspended the target when we auto-attached, so make sure it goes back to being normal.
await this.sendCommandToSession('Runtime.runIfWaitingForDebugger', event.sessionId);
}
/**
* Call protocol methods, with a timeout.
* To configure the timeout for the next call, use 'setNextProtocolTimeout'.
* If 'sessionId' is undefined, the message is sent to the main session.
* @template {keyof LH.CrdpCommands} C
* @param {C} method
* @param {string|undefined} sessionId
* @param {LH.CrdpCommands[C]['paramsType']} params
* @return {Promise<LH.CrdpCommands[C]['returnType']>}
*/
sendCommandToSession(method, sessionId, ...params) {
const timeout = this._nextProtocolTimeout;
this._nextProtocolTimeout = DEFAULT_PROTOCOL_TIMEOUT;
/** @type {NodeJS.Timer|undefined} */
let asyncTimeout;
const timeoutPromise = new Promise((resolve, reject) => {
if (timeout === Infinity) return;
asyncTimeout = setTimeout((() => {
const err = new LHError(
LHError.errors.PROTOCOL_TIMEOUT,
{protocolMethod: method}
);
reject(err);
}), timeout);
});
return Promise.race([
this._innerSendCommand(method, sessionId, ...params),
timeoutPromise,
]).finally(() => {
asyncTimeout && clearTimeout(asyncTimeout);
});
}
/**
* Alias for 'sendCommandToSession(method, undefined, ...params)'
* @template {keyof LH.CrdpCommands} C
* @param {C} method
* @param {LH.CrdpCommands[C]['paramsType']} params
* @return {Promise<LH.CrdpCommands[C]['returnType']>}
*/
sendCommand(method, ...params) {
return this.sendCommandToSession(method, undefined, ...params);
}
/**
* Call protocol methods.
* @private
* @template {keyof LH.CrdpCommands} C
* @param {C} method
* @param {string|undefined} sessionId
* @param {LH.CrdpCommands[C]['paramsType']} params
* @return {Promise<LH.CrdpCommands[C]['returnType']>}
*/
_innerSendCommand(method, sessionId, ...params) {
const domainCommand = /^(\w+)\.(enable|disable)$/.exec(method);
if (domainCommand) {
const enable = domainCommand[2] === 'enable';
if (!this._shouldToggleDomain(domainCommand[1], sessionId, enable)) {
return Promise.resolve();
}
}
return this._connection.sendCommand(method, sessionId, ...params);
}
/**
* Returns whether a domain is currently enabled.
* @param {string} domain
* @return {boolean}
*/
isDomainEnabled(domain) {
// Defined, non-zero elements of the domains map are enabled.
return !!this._domainEnabledCounts.get(domain);
}
/**
* Return the body of the response with the given ID. Rejects if getting the
* body times out.
* @param {string} requestId
* @param {number} [timeout]
* @return {Promise<string>}
*/
async getRequestContent(requestId, timeout = 1000) {
return fetchResponseBodyFromCache(this.defaultSession, requestId, timeout);
}
/**
* @param {{x: number, y: number}} position
* @return {Promise<void>}
*/
scrollTo(position) {
const scrollExpression = `window.scrollTo(${position.x}, ${position.y})`;
return this.executionContext.evaluateAsync(scrollExpression, {useIsolation: true});
}
/**
* @return {Promise<{x: number, y: number}>}
*/
getScrollPosition() {
return this.executionContext.evaluateAsync(`({x: window.scrollX, y: window.scrollY})`,
{useIsolation: true});
}
/**
* @param {{additionalTraceCategories?: string|null}=} settings
* @return {Promise<void>}
*/
async beginTrace(settings) {
const additionalCategories = (settings && settings.additionalTraceCategories &&
settings.additionalTraceCategories.split(',')) || [];
const traceCategories = TraceGatherer.getDefaultTraceCategories().concat(additionalCategories);
const uniqueCategories = Array.from(new Set(traceCategories));
// Check any domains that could interfere with or add overhead to the trace.
if (this.isDomainEnabled('CSS')) {
throw new Error('CSS domain enabled when starting trace');
}
if (this.isDomainEnabled('DOM')) {
throw new Error('DOM domain enabled when starting trace');
}
// Enable Page domain to wait for Page.loadEventFired
return this.sendCommand('Page.enable')
.then(_ => this.sendCommand('Tracing.start', {
categories: uniqueCategories.join(','),
options: 'sampling-frequency=10000', // 1000 is default and too slow.
}));
}
/**
* @return {Promise<LH.Trace>}
*/
endTrace() {
return TraceGatherer.endTraceAndCollectEvents(this.defaultSession);
}
/**
* Begin recording devtools protocol messages.
*/
beginDevtoolsLog() {
this._devtoolsLog.reset();
this._devtoolsLog.beginRecording();
}
/**
* Stop recording to devtoolsLog and return log contents.
* @return {LH.DevtoolsLog}
*/
endDevtoolsLog() {
this._devtoolsLog.endRecording();
return this._devtoolsLog.messages;
}
}
module.exports = Driver;