forked from GoogleChrome/lighthouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
js-usage.js
74 lines (63 loc) · 2.19 KB
/
js-usage.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
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import BaseGatherer from '../base-gatherer.js';
/**
* @fileoverview Tracks unused JavaScript
*/
class JsUsage extends BaseGatherer {
/** @type {LH.Gatherer.GathererMeta} */
meta = {
supportedModes: ['snapshot', 'timespan', 'navigation'],
};
constructor() {
super();
/** @type {LH.Crdp.Profiler.ScriptCoverage[]} */
this._scriptUsages = [];
}
/**
* @param {LH.Gatherer.Context} context
*/
async startInstrumentation(context) {
const session = context.driver.defaultSession;
await session.sendCommand('Profiler.enable');
await session.sendCommand('Profiler.startPreciseCoverage', {detailed: false});
}
/**
* @param {LH.Gatherer.Context} context
*/
async stopInstrumentation(context) {
const session = context.driver.defaultSession;
const coverageResponse = await session.sendCommand('Profiler.takePreciseCoverage');
this._scriptUsages = coverageResponse.result;
await session.sendCommand('Profiler.stopPreciseCoverage');
await session.sendCommand('Profiler.disable');
}
/**
* @return {Promise<LH.Artifacts['JsUsage']>}
*/
async getArtifact() {
/** @type {Record<string, LH.Crdp.Profiler.ScriptCoverage>} */
const usageByScriptId = {};
for (const scriptUsage of this._scriptUsages) {
// If `url` is blank, that means the script was dynamically
// created (eval, new Function, onload, ...)
if (scriptUsage.url === '' || scriptUsage.url === '_lighthouse-eval.js') {
// We currently don't consider coverage of dynamic scripts, and we definitely don't want
// coverage of code Lighthouse ran to inspect the page, so we ignore this ScriptCoverage.
// Audits would work the same without this, it is only an optimization (not tracking coverage
// for scripts we don't care about).
continue;
}
// Scripts run via puppeteer's evaluate interface will have this url.
if (scriptUsage.url === '__puppeteer_evaluation_script__') {
continue;
}
usageByScriptId[scriptUsage.scriptId] = scriptUsage;
}
return usageByScriptId;
}
}
export default JsUsage;