-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
navigation-runner.js
316 lines (263 loc) · 10.9 KB
/
navigation-runner.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
/**
* @license
* Copyright 2021 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import puppeteer from 'puppeteer-core';
import log from 'lighthouse-logger';
import {Driver} from './driver.js';
import {Runner} from '../runner.js';
import {getEmptyArtifactState, collectPhaseArtifacts, awaitArtifacts} from './runner-helpers.js';
import * as prepare from './driver/prepare.js';
import {gotoURL} from './driver/navigation.js';
import * as storage from './driver/storage.js';
import * as emulation from '../lib/emulation.js';
import {initializeConfig} from '../config/config.js';
import {getBaseArtifacts, finalizeArtifacts} from './base-artifacts.js';
import * as format from '../../shared/localization/format.js';
import {LighthouseError} from '../lib/lh-error.js';
import UrlUtils from '../lib/url-utils.js';
import {getPageLoadError} from '../lib/navigation-error.js';
import Trace from './gatherers/trace.js';
import DevtoolsLog from './gatherers/devtools-log.js';
import {NetworkRecords} from '../computed/network-records.js';
/**
* @typedef NavigationContext
* @property {Driver} driver
* @property {LH.Puppeteer.Page} page
* @property {LH.Config.ResolvedConfig} resolvedConfig
* @property {LH.NavigationRequestor} requestor
* @property {LH.BaseArtifacts} baseArtifacts
* @property {Map<string, LH.ArbitraryEqualityMap>} computedCache
*/
/** @typedef {Omit<Parameters<typeof collectPhaseArtifacts>[0], 'phase'>} PhaseState */
const DEFAULT_HOSTNAME = '127.0.0.1';
const DEFAULT_PORT = 9222;
/**
* @param {{driver: Driver, resolvedConfig: LH.Config.ResolvedConfig, requestor: LH.NavigationRequestor}} args
* @return {Promise<{baseArtifacts: LH.BaseArtifacts}>}
*/
async function _setup({driver, resolvedConfig, requestor}) {
await driver.connect();
// We can't trigger the navigation through user interaction if we reset the page before starting.
if (typeof requestor === 'string' && !resolvedConfig.settings.skipAboutBlank) {
// Disable network monitor on the blank page to prevent it from picking up network requests and
// frame navigated events before the run starts.
await driver._networkMonitor?.disable();
await gotoURL(driver, resolvedConfig.settings.blankPage, {waitUntil: ['navigated']});
await driver._networkMonitor?.enable();
}
const baseArtifacts = await getBaseArtifacts(resolvedConfig, driver, {gatherMode: 'navigation'});
const {warnings} =
await prepare.prepareTargetForNavigationMode(driver, resolvedConfig.settings, requestor);
baseArtifacts.LighthouseRunWarnings.push(...warnings);
return {baseArtifacts};
}
/**
* @param {NavigationContext} navigationContext
*/
async function _cleanupNavigation({driver}) {
await emulation.clearThrottling(driver.defaultSession);
}
/**
* @param {NavigationContext} navigationContext
* @return {Promise<{requestedUrl: string, mainDocumentUrl: string, navigationError: LH.LighthouseError | undefined}>}
*/
async function _navigate(navigationContext) {
const {driver, resolvedConfig, requestor} = navigationContext;
try {
const {requestedUrl, mainDocumentUrl, warnings} = await gotoURL(driver, requestor, {
...resolvedConfig.settings,
waitUntil: resolvedConfig.settings.pauseAfterFcpMs ? ['fcp', 'load'] : ['load'],
});
navigationContext.baseArtifacts.LighthouseRunWarnings.push(...warnings);
return {requestedUrl, mainDocumentUrl, navigationError: undefined};
} catch (err) {
if (!(err instanceof LighthouseError)) throw err;
if (err.code !== 'NO_FCP' && err.code !== 'PAGE_HUNG' && err.code !== 'TARGET_CRASHED') {
throw err;
}
if (typeof requestor !== 'string') throw err;
// TODO: Make the urls optional here so we don't need to throw an error with a callback requestor.
return {
requestedUrl: requestor,
mainDocumentUrl: requestor,
navigationError: err,
};
}
}
/**
* @param {NavigationContext} navigationContext
* @param {PhaseState} phaseState
* @return {Promise<{devtoolsLog?: LH.DevtoolsLog, records?: Array<LH.Artifacts.NetworkRequest>, trace?: LH.Trace}>}
*/
async function _collectDebugData(navigationContext, phaseState) {
let devtoolsLog;
let trace;
for (const definition of phaseState.artifactDefinitions) {
const {instance} = definition.gatherer;
if (instance instanceof DevtoolsLog) {
devtoolsLog = instance.getDebugData();
} else if (instance instanceof Trace) {
trace = instance.getDebugData();
}
}
const records = devtoolsLog && (await NetworkRecords.request(devtoolsLog, navigationContext));
return {devtoolsLog, records, trace};
}
/**
* @param {NavigationContext} navigationContext
* @param {PhaseState} phaseState
* @param {Awaited<ReturnType<typeof _navigate>>} navigateResult
* @return {Promise<Partial<LH.GathererArtifacts>>}
*/
async function _computeNavigationResult(
navigationContext,
phaseState,
navigateResult
) {
const {navigationError, requestedUrl, mainDocumentUrl} = navigateResult;
const debugData = await _collectDebugData(navigationContext, phaseState);
const pageLoadError = debugData.records
? getPageLoadError(navigationError, {
url: mainDocumentUrl,
ignoreStatusCode: navigationContext.resolvedConfig.settings.ignoreStatusCode,
networkRecords: debugData.records,
warnings: navigationContext.baseArtifacts.LighthouseRunWarnings,
})
: navigationError;
if (pageLoadError) {
const locale = navigationContext.resolvedConfig.settings.locale;
const localizedMessage = format.getFormatted(pageLoadError.friendlyMessage, locale);
log.error('NavigationRunner', localizedMessage, requestedUrl);
/** @type {Partial<LH.GathererArtifacts>} */
const artifacts = {};
const pageLoadErrorId = 'pageLoadError-defaultPass';
if (debugData.devtoolsLog) {
artifacts.DevtoolsLogError = debugData.devtoolsLog;
artifacts.devtoolsLogs = {[pageLoadErrorId]: debugData.devtoolsLog};
}
if (debugData.trace) {
artifacts.TraceError = debugData.trace;
artifacts.traces = {[pageLoadErrorId]: debugData.trace};
}
navigationContext.baseArtifacts.LighthouseRunWarnings.push(pageLoadError.friendlyMessage);
navigationContext.baseArtifacts.PageLoadError = pageLoadError;
return artifacts;
} else {
await collectPhaseArtifacts({phase: 'getArtifact', ...phaseState});
return await awaitArtifacts(phaseState.artifactState);
}
}
/**
* @param {NavigationContext} navigationContext
* @return {ReturnType<typeof _computeNavigationResult>}
*/
async function _navigation(navigationContext) {
if (!navigationContext.resolvedConfig.artifacts) {
throw new Error('No artifacts were defined on the config');
}
const artifactState = getEmptyArtifactState();
const phaseState = {
url: await navigationContext.driver.url(),
gatherMode: /** @type {const} */ ('navigation'),
driver: navigationContext.driver,
page: navigationContext.page,
computedCache: navigationContext.computedCache,
artifactDefinitions: navigationContext.resolvedConfig.artifacts,
artifactState,
baseArtifacts: navigationContext.baseArtifacts,
settings: navigationContext.resolvedConfig.settings,
};
const disableAsyncStacks =
await prepare.enableAsyncStacks(navigationContext.driver.defaultSession);
await collectPhaseArtifacts({phase: 'startInstrumentation', ...phaseState});
await collectPhaseArtifacts({phase: 'startSensitiveInstrumentation', ...phaseState});
const navigateResult = await _navigate(navigationContext);
// Every required url is initialized to an empty string in `getBaseArtifacts`.
// If we haven't set all the required urls yet, set them here.
if (!Object.values(phaseState.baseArtifacts.URL).every(Boolean)) {
phaseState.baseArtifacts.URL = {
requestedUrl: navigateResult.requestedUrl,
mainDocumentUrl: navigateResult.mainDocumentUrl,
finalDisplayedUrl: await navigationContext.driver.url(),
};
}
phaseState.url = navigateResult.mainDocumentUrl;
await collectPhaseArtifacts({phase: 'stopSensitiveInstrumentation', ...phaseState});
await collectPhaseArtifacts({phase: 'stopInstrumentation', ...phaseState});
// bf-cache-failures can emit `Page.frameNavigated` at the end of the run.
// This can cause us to issue protocol commands after the target closes.
// We should disable our `Page.frameNavigated` handlers before that.
await disableAsyncStacks();
await _cleanupNavigation(navigationContext);
return _computeNavigationResult(navigationContext, phaseState, navigateResult);
}
/**
* @param {{requestedUrl?: string, driver: Driver, resolvedConfig: LH.Config.ResolvedConfig, lhBrowser?: LH.Puppeteer.Browser, lhPage?: LH.Puppeteer.Page}} args
*/
async function _cleanup({requestedUrl, driver, resolvedConfig, lhBrowser, lhPage}) {
const didResetStorage = !resolvedConfig.settings.disableStorageReset && requestedUrl;
if (didResetStorage) {
await storage.clearDataForOrigin(driver.defaultSession,
requestedUrl,
resolvedConfig.settings.clearStorageTypes
);
}
await driver.disconnect();
// If Lighthouse started the Puppeteer instance then we are responsible for closing it.
await lhPage?.close();
await lhBrowser?.disconnect();
}
/**
* @param {LH.Puppeteer.Page|undefined} page
* @param {LH.NavigationRequestor|undefined} requestor
* @param {{config?: LH.Config, flags?: LH.Flags}} [options]
* @return {Promise<LH.Gatherer.GatherResult>}
*/
async function navigationGather(page, requestor, options = {}) {
const {flags = {}, config} = options;
log.setLevel(flags.logLevel || 'error');
const {resolvedConfig} = await initializeConfig('navigation', config, flags);
const computedCache = new Map();
const isCallback = typeof requestor === 'function';
const runnerOptions = {resolvedConfig, computedCache};
const gatherFn = async () => {
const normalizedRequestor = isCallback ? requestor : UrlUtils.normalizeUrl(requestor);
/** @type {LH.Puppeteer.Browser|undefined} */
let lhBrowser = undefined;
/** @type {LH.Puppeteer.Page|undefined} */
let lhPage = undefined;
// For navigation mode, we shouldn't connect to a browser in audit mode,
// therefore we connect to the browser in the gatherFn callback.
if (!page) {
const {hostname = DEFAULT_HOSTNAME, port = DEFAULT_PORT} = flags;
lhBrowser = await puppeteer.connect({browserURL: `http://${hostname}:${port}`, defaultViewport: null});
lhPage = await lhBrowser.newPage();
page = lhPage;
}
const driver = new Driver(page);
const context = {
driver,
lhBrowser,
lhPage,
page,
resolvedConfig,
requestor: normalizedRequestor,
computedCache,
};
const {baseArtifacts} = await _setup(context);
const artifacts = await _navigation({...context, baseArtifacts});
await _cleanup(context);
return finalizeArtifacts(baseArtifacts, artifacts);
};
const artifacts = await Runner.gather(gatherFn, runnerOptions);
return {artifacts, runnerOptions};
}
export {
navigationGather,
_setup,
_navigate,
_navigation,
_cleanup,
};