puppeteer/src/common/Coverage.ts

454 lines
14 KiB
TypeScript
Raw Normal View History

/**
* Copyright 2017 Google Inc. 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.
*/
import { assert } from './assert.js';
import { helper, debugError, PuppeteerEventListener } from './helper.js';
import { Protocol } from 'devtools-protocol';
import { CDPSession } from './Connection.js';
import { EVALUATION_SCRIPT_URL } from './ExecutionContext.js';
/**
* @internal
*/
export { PuppeteerEventListener };
/**
* The CoverageEntry class represents one entry of the coverage report.
* @public
*/
export interface CoverageEntry {
/**
* The URL of the style sheet or script.
*/
url: string;
/**
* The content of the style sheet or script.
*/
text: string;
/**
* The covered range as start and end positions.
*/
2020-05-07 10:54:55 +00:00
ranges: Array<{ start: number; end: number }>;
}
/**
* The CoverageEntry class for JavaScript
* @public
*/
export interface JSCoverageEntry extends CoverageEntry {
/**
* Raw V8 script coverage entry.
*/
rawScriptCoverage?: Protocol.Profiler.ScriptCoverage;
}
/**
* Set of configurable options for JS coverage.
* @public
*/
export interface JSCoverageOptions {
/**
* Whether to reset coverage on every navigation.
*/
resetOnNavigation?: boolean;
/**
* Whether anonymous scripts generated by the page should be reported.
*/
reportAnonymousScripts?: boolean;
/**
* Whether the result includes raw V8 script coverage entries.
*/
includeRawScriptCoverage?: boolean;
}
/**
* Set of configurable options for CSS coverage.
* @public
*/
export interface CSSCoverageOptions {
/**
* Whether to reset coverage on every navigation.
*/
resetOnNavigation?: boolean;
}
/**
* The Coverage class provides methods to gathers information about parts of
* JavaScript and CSS that were used by the page.
*
* @remarks
* To output coverage in a form consumable by {@link https://github.com/istanbuljs | Istanbul},
* see {@link https://github.com/istanbuljs/puppeteer-to-istanbul | puppeteer-to-istanbul}.
*
* @example
* An example of using JavaScript and CSS coverage to get percentage of initially
* executed code:
* ```js
* // Enable both JavaScript and CSS coverage
* await Promise.all([
* page.coverage.startJSCoverage(),
* page.coverage.startCSSCoverage()
* ]);
* // Navigate to page
* await page.goto('https://example.com');
* // Disable both JavaScript and CSS coverage
* const [jsCoverage, cssCoverage] = await Promise.all([
* page.coverage.stopJSCoverage(),
* page.coverage.stopCSSCoverage(),
* ]);
* let totalBytes = 0;
* let usedBytes = 0;
* const coverage = [...jsCoverage, ...cssCoverage];
* for (const entry of coverage) {
* totalBytes += entry.text.length;
* for (const range of entry.ranges)
* usedBytes += range.end - range.start - 1;
* }
* console.log(`Bytes used: ${usedBytes / totalBytes * 100}%`);
* ```
* @public
*/
export class Coverage {
2022-06-13 09:16:25 +00:00
#jsCoverage: JSCoverage;
#cssCoverage: CSSCoverage;
constructor(client: CDPSession) {
2022-06-13 09:16:25 +00:00
this.#jsCoverage = new JSCoverage(client);
this.#cssCoverage = new CSSCoverage(client);
}
/**
* @param options - Set of configurable options for coverage defaults to
* `resetOnNavigation : true, reportAnonymousScripts : false`
* @returns Promise that resolves when coverage is started.
*
* @remarks
* Anonymous scripts are ones that don't have an associated url. These are
* scripts that are dynamically created on the page using `eval` or
* `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous
* scripts will have `pptr://__puppeteer_evaluation_script__` as their URL.
*/
async startJSCoverage(options: JSCoverageOptions = {}): Promise<void> {
2022-06-13 09:16:25 +00:00
return await this.#jsCoverage.start(options);
}
/**
* @returns Promise that resolves to the array of coverage reports for
* all scripts.
*
* @remarks
* JavaScript Coverage doesn't include anonymous scripts by default.
* However, scripts with sourceURLs are reported.
*/
async stopJSCoverage(): Promise<JSCoverageEntry[]> {
2022-06-13 09:16:25 +00:00
return await this.#jsCoverage.stop();
}
/**
* @param options - Set of configurable options for coverage, defaults to
* `resetOnNavigation : true`
* @returns Promise that resolves when coverage is started.
*/
async startCSSCoverage(options: CSSCoverageOptions = {}): Promise<void> {
2022-06-13 09:16:25 +00:00
return await this.#cssCoverage.start(options);
}
/**
* @returns Promise that resolves to the array of coverage reports
* for all stylesheets.
* @remarks
* CSS Coverage doesn't include dynamically injected style tags
* without sourceURLs.
*/
async stopCSSCoverage(): Promise<CoverageEntry[]> {
2022-06-13 09:16:25 +00:00
return await this.#cssCoverage.stop();
}
}
/**
* @public
*/
export class JSCoverage {
2022-06-13 09:16:25 +00:00
#client: CDPSession;
#enabled = false;
#scriptURLs = new Map<string, string>();
#scriptSources = new Map<string, string>();
#eventListeners: PuppeteerEventListener[] = [];
#resetOnNavigation = false;
#reportAnonymousScripts = false;
#includeRawScriptCoverage = false;
constructor(client: CDPSession) {
2022-06-13 09:16:25 +00:00
this.#client = client;
}
2020-05-07 10:54:55 +00:00
async start(
options: {
resetOnNavigation?: boolean;
reportAnonymousScripts?: boolean;
includeRawScriptCoverage?: boolean;
2020-05-07 10:54:55 +00:00
} = {}
): Promise<void> {
2022-06-13 09:16:25 +00:00
assert(!this.#enabled, 'JSCoverage is already enabled');
const {
resetOnNavigation = true,
reportAnonymousScripts = false,
includeRawScriptCoverage = false,
} = options;
2022-06-13 09:16:25 +00:00
this.#resetOnNavigation = resetOnNavigation;
this.#reportAnonymousScripts = reportAnonymousScripts;
this.#includeRawScriptCoverage = includeRawScriptCoverage;
this.#enabled = true;
this.#scriptURLs.clear();
this.#scriptSources.clear();
this.#eventListeners = [
2020-05-07 10:54:55 +00:00
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#client,
2020-05-07 10:54:55 +00:00
'Debugger.scriptParsed',
2022-06-13 09:16:25 +00:00
this.#onScriptParsed.bind(this)
2020-05-07 10:54:55 +00:00
),
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#client,
2020-05-07 10:54:55 +00:00
'Runtime.executionContextsCleared',
2022-06-13 09:16:25 +00:00
this.#onExecutionContextsCleared.bind(this)
2020-05-07 10:54:55 +00:00
),
];
await Promise.all([
2022-06-13 09:16:25 +00:00
this.#client.send('Profiler.enable'),
this.#client.send('Profiler.startPreciseCoverage', {
callCount: this.#includeRawScriptCoverage,
2020-05-07 10:54:55 +00:00
detailed: true,
}),
2022-06-13 09:16:25 +00:00
this.#client.send('Debugger.enable'),
this.#client.send('Debugger.setSkipAllPauses', { skip: true }),
]);
}
2022-06-13 09:16:25 +00:00
#onExecutionContextsCleared(): void {
if (!this.#resetOnNavigation) return;
this.#scriptURLs.clear();
this.#scriptSources.clear();
}
2022-06-13 09:16:25 +00:00
async #onScriptParsed(
event: Protocol.Debugger.ScriptParsedEvent
2020-05-07 10:54:55 +00:00
): Promise<void> {
// Ignore puppeteer-injected scripts
2020-05-07 10:54:55 +00:00
if (event.url === EVALUATION_SCRIPT_URL) return;
// Ignore other anonymous scripts unless the reportAnonymousScripts option is true.
2022-06-13 09:16:25 +00:00
if (!event.url && !this.#reportAnonymousScripts) return;
try {
2022-06-13 09:16:25 +00:00
const response = await this.#client.send('Debugger.getScriptSource', {
2020-05-07 10:54:55 +00:00
scriptId: event.scriptId,
});
2022-06-13 09:16:25 +00:00
this.#scriptURLs.set(event.scriptId, event.url);
this.#scriptSources.set(event.scriptId, response.scriptSource);
} catch (error) {
// This might happen if the page has already navigated away.
debugError(error);
}
}
async stop(): Promise<JSCoverageEntry[]> {
2022-06-13 09:16:25 +00:00
assert(this.#enabled, 'JSCoverage is not enabled');
this.#enabled = false;
const result = await Promise.all([
2022-06-13 09:16:25 +00:00
this.#client.send('Profiler.takePreciseCoverage'),
this.#client.send('Profiler.stopPreciseCoverage'),
this.#client.send('Profiler.disable'),
this.#client.send('Debugger.disable'),
]);
2022-06-13 09:16:25 +00:00
helper.removeEventListeners(this.#eventListeners);
const coverage = [];
const profileResponse = result[0];
for (const entry of profileResponse.result) {
2022-06-13 09:16:25 +00:00
let url = this.#scriptURLs.get(entry.scriptId);
if (!url && this.#reportAnonymousScripts)
url = 'debugger://VM' + entry.scriptId;
2022-06-13 09:16:25 +00:00
const text = this.#scriptSources.get(entry.scriptId);
2020-05-07 10:54:55 +00:00
if (text === undefined || url === undefined) continue;
const flattenRanges = [];
2020-05-07 10:54:55 +00:00
for (const func of entry.functions) flattenRanges.push(...func.ranges);
const ranges = convertToDisjointRanges(flattenRanges);
2022-06-13 09:16:25 +00:00
if (!this.#includeRawScriptCoverage) {
coverage.push({ url, ranges, text });
} else {
coverage.push({ url, ranges, text, rawScriptCoverage: entry });
}
}
return coverage;
}
}
/**
* @public
*/
export class CSSCoverage {
2022-06-13 09:16:25 +00:00
#client: CDPSession;
#enabled = false;
#stylesheetURLs = new Map<string, string>();
#stylesheetSources = new Map<string, string>();
#eventListeners: PuppeteerEventListener[] = [];
#resetOnNavigation = false;
constructor(client: CDPSession) {
2022-06-13 09:16:25 +00:00
this.#client = client;
}
2020-05-07 10:54:55 +00:00
async start(options: { resetOnNavigation?: boolean } = {}): Promise<void> {
2022-06-13 09:16:25 +00:00
assert(!this.#enabled, 'CSSCoverage is already enabled');
2020-05-07 10:54:55 +00:00
const { resetOnNavigation = true } = options;
2022-06-13 09:16:25 +00:00
this.#resetOnNavigation = resetOnNavigation;
this.#enabled = true;
this.#stylesheetURLs.clear();
this.#stylesheetSources.clear();
this.#eventListeners = [
2020-05-07 10:54:55 +00:00
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#client,
2020-05-07 10:54:55 +00:00
'CSS.styleSheetAdded',
2022-06-13 09:16:25 +00:00
this.#onStyleSheet.bind(this)
2020-05-07 10:54:55 +00:00
),
helper.addEventListener(
2022-06-13 09:16:25 +00:00
this.#client,
2020-05-07 10:54:55 +00:00
'Runtime.executionContextsCleared',
2022-06-13 09:16:25 +00:00
this.#onExecutionContextsCleared.bind(this)
2020-05-07 10:54:55 +00:00
),
];
await Promise.all([
2022-06-13 09:16:25 +00:00
this.#client.send('DOM.enable'),
this.#client.send('CSS.enable'),
this.#client.send('CSS.startRuleUsageTracking'),
]);
}
2022-06-13 09:16:25 +00:00
#onExecutionContextsCleared(): void {
if (!this.#resetOnNavigation) return;
this.#stylesheetURLs.clear();
this.#stylesheetSources.clear();
}
2022-06-13 09:16:25 +00:00
async #onStyleSheet(event: Protocol.CSS.StyleSheetAddedEvent): Promise<void> {
const header = event.header;
// Ignore anonymous scripts
2020-05-07 10:54:55 +00:00
if (!header.sourceURL) return;
try {
2022-06-13 09:16:25 +00:00
const response = await this.#client.send('CSS.getStyleSheetText', {
2020-05-07 10:54:55 +00:00
styleSheetId: header.styleSheetId,
});
2022-06-13 09:16:25 +00:00
this.#stylesheetURLs.set(header.styleSheetId, header.sourceURL);
this.#stylesheetSources.set(header.styleSheetId, response.text);
} catch (error) {
// This might happen if the page has already navigated away.
debugError(error);
}
}
async stop(): Promise<CoverageEntry[]> {
2022-06-13 09:16:25 +00:00
assert(this.#enabled, 'CSSCoverage is not enabled');
this.#enabled = false;
const ruleTrackingResponse = await this.#client.send(
2020-05-07 10:54:55 +00:00
'CSS.stopRuleUsageTracking'
);
await Promise.all([
2022-06-13 09:16:25 +00:00
this.#client.send('CSS.disable'),
this.#client.send('DOM.disable'),
]);
2022-06-13 09:16:25 +00:00
helper.removeEventListeners(this.#eventListeners);
// aggregate by styleSheetId
const styleSheetIdToCoverage = new Map();
for (const entry of ruleTrackingResponse.ruleUsage) {
let ranges = styleSheetIdToCoverage.get(entry.styleSheetId);
if (!ranges) {
ranges = [];
styleSheetIdToCoverage.set(entry.styleSheetId, ranges);
}
ranges.push({
startOffset: entry.startOffset,
endOffset: entry.endOffset,
count: entry.used ? 1 : 0,
});
}
2022-05-31 14:34:16 +00:00
const coverage: CoverageEntry[] = [];
2022-06-13 09:16:25 +00:00
for (const styleSheetId of this.#stylesheetURLs.keys()) {
const url = this.#stylesheetURLs.get(styleSheetId);
2022-05-31 14:34:16 +00:00
assert(url);
2022-06-13 09:16:25 +00:00
const text = this.#stylesheetSources.get(styleSheetId);
2022-05-31 14:34:16 +00:00
assert(text);
2020-05-07 10:54:55 +00:00
const ranges = convertToDisjointRanges(
styleSheetIdToCoverage.get(styleSheetId) || []
);
coverage.push({ url, ranges, text });
}
return coverage;
}
}
2020-05-07 10:54:55 +00:00
function convertToDisjointRanges(
nestedRanges: Array<{ startOffset: number; endOffset: number; count: number }>
): Array<{ start: number; end: number }> {
const points = [];
for (const range of nestedRanges) {
2020-05-07 10:54:55 +00:00
points.push({ offset: range.startOffset, type: 0, range });
points.push({ offset: range.endOffset, type: 1, range });
}
// Sort points to form a valid parenthesis sequence.
points.sort((a, b) => {
// Sort with increasing offsets.
2020-05-07 10:54:55 +00:00
if (a.offset !== b.offset) return a.offset - b.offset;
// All "end" points should go before "start" points.
2020-05-07 10:54:55 +00:00
if (a.type !== b.type) return b.type - a.type;
const aLength = a.range.endOffset - a.range.startOffset;
const bLength = b.range.endOffset - b.range.startOffset;
// For two "start" points, the one with longer range goes first.
2020-05-07 10:54:55 +00:00
if (a.type === 0) return bLength - aLength;
// For two "end" points, the one with shorter range goes first.
return aLength - bLength;
});
const hitCountStack = [];
2022-05-31 14:34:16 +00:00
const results: Array<{
start: number;
end: number;
}> = [];
let lastOffset = 0;
// Run scanning line to intersect all ranges.
for (const point of points) {
2020-05-07 10:54:55 +00:00
if (
hitCountStack.length &&
lastOffset < point.offset &&
2022-05-31 14:34:16 +00:00
hitCountStack[hitCountStack.length - 1]! > 0
2020-05-07 10:54:55 +00:00
) {
2022-05-31 14:34:16 +00:00
const lastResult = results[results.length - 1];
if (lastResult && lastResult.end === lastOffset)
lastResult.end = point.offset;
2020-05-07 10:54:55 +00:00
else results.push({ start: lastOffset, end: point.offset });
}
lastOffset = point.offset;
2020-05-07 10:54:55 +00:00
if (point.type === 0) hitCountStack.push(point.range.count);
else hitCountStack.pop();
}
// Filter out empty ranges.
2020-05-07 10:54:55 +00:00
return results.filter((range) => range.end - range.start > 1);
}