Coverage.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /**
  2. * Copyright 2017 Google Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. const {helper, debugError, assert} = require('./helper');
  17. const {EVALUATION_SCRIPT_URL} = require('./ExecutionContext');
  18. /**
  19. * @typedef {Object} CoverageEntry
  20. * @property {string} url
  21. * @property {string} text
  22. * @property {!Array<!{start: number, end: number}>} ranges
  23. */
  24. class Coverage {
  25. /**
  26. * @param {!Puppeteer.CDPSession} client
  27. */
  28. constructor(client) {
  29. this._jsCoverage = new JSCoverage(client);
  30. this._cssCoverage = new CSSCoverage(client);
  31. }
  32. /**
  33. * @param {!{resetOnNavigation?: boolean, reportAnonymousScripts?: boolean}} options
  34. */
  35. async startJSCoverage(options) {
  36. return await this._jsCoverage.start(options);
  37. }
  38. /**
  39. * @return {!Promise<!Array<!CoverageEntry>>}
  40. */
  41. async stopJSCoverage() {
  42. return await this._jsCoverage.stop();
  43. }
  44. /**
  45. * @param {{resetOnNavigation?: boolean}=} options
  46. */
  47. async startCSSCoverage(options) {
  48. return await this._cssCoverage.start(options);
  49. }
  50. /**
  51. * @return {!Promise<!Array<!CoverageEntry>>}
  52. */
  53. async stopCSSCoverage() {
  54. return await this._cssCoverage.stop();
  55. }
  56. }
  57. module.exports = {Coverage};
  58. class JSCoverage {
  59. /**
  60. * @param {!Puppeteer.CDPSession} client
  61. */
  62. constructor(client) {
  63. this._client = client;
  64. this._enabled = false;
  65. this._scriptURLs = new Map();
  66. this._scriptSources = new Map();
  67. this._eventListeners = [];
  68. this._resetOnNavigation = false;
  69. }
  70. /**
  71. * @param {!{resetOnNavigation?: boolean, reportAnonymousScripts?: boolean}} options
  72. */
  73. async start(options = {}) {
  74. assert(!this._enabled, 'JSCoverage is already enabled');
  75. const {
  76. resetOnNavigation = true,
  77. reportAnonymousScripts = false
  78. } = options;
  79. this._resetOnNavigation = resetOnNavigation;
  80. this._reportAnonymousScripts = reportAnonymousScripts;
  81. this._enabled = true;
  82. this._scriptURLs.clear();
  83. this._scriptSources.clear();
  84. this._eventListeners = [
  85. helper.addEventListener(this._client, 'Debugger.scriptParsed', this._onScriptParsed.bind(this)),
  86. helper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),
  87. ];
  88. await Promise.all([
  89. this._client.send('Profiler.enable'),
  90. this._client.send('Profiler.startPreciseCoverage', {callCount: false, detailed: true}),
  91. this._client.send('Debugger.enable'),
  92. this._client.send('Debugger.setSkipAllPauses', {skip: true})
  93. ]);
  94. }
  95. _onExecutionContextsCleared() {
  96. if (!this._resetOnNavigation)
  97. return;
  98. this._scriptURLs.clear();
  99. this._scriptSources.clear();
  100. }
  101. /**
  102. * @param {!Protocol.Debugger.scriptParsedPayload} event
  103. */
  104. async _onScriptParsed(event) {
  105. // Ignore puppeteer-injected scripts
  106. if (event.url === EVALUATION_SCRIPT_URL)
  107. return;
  108. // Ignore other anonymous scripts unless the reportAnonymousScripts option is true.
  109. if (!event.url && !this._reportAnonymousScripts)
  110. return;
  111. try {
  112. const response = await this._client.send('Debugger.getScriptSource', {scriptId: event.scriptId});
  113. this._scriptURLs.set(event.scriptId, event.url);
  114. this._scriptSources.set(event.scriptId, response.scriptSource);
  115. } catch (e) {
  116. // This might happen if the page has already navigated away.
  117. debugError(e);
  118. }
  119. }
  120. /**
  121. * @return {!Promise<!Array<!CoverageEntry>>}
  122. */
  123. async stop() {
  124. assert(this._enabled, 'JSCoverage is not enabled');
  125. this._enabled = false;
  126. const [profileResponse] = await Promise.all([
  127. this._client.send('Profiler.takePreciseCoverage'),
  128. this._client.send('Profiler.stopPreciseCoverage'),
  129. this._client.send('Profiler.disable'),
  130. this._client.send('Debugger.disable'),
  131. ]);
  132. helper.removeEventListeners(this._eventListeners);
  133. const coverage = [];
  134. for (const entry of profileResponse.result) {
  135. let url = this._scriptURLs.get(entry.scriptId);
  136. if (!url && this._reportAnonymousScripts)
  137. url = 'debugger://VM' + entry.scriptId;
  138. const text = this._scriptSources.get(entry.scriptId);
  139. if (text === undefined || url === undefined)
  140. continue;
  141. const flattenRanges = [];
  142. for (const func of entry.functions)
  143. flattenRanges.push(...func.ranges);
  144. const ranges = convertToDisjointRanges(flattenRanges);
  145. coverage.push({url, ranges, text});
  146. }
  147. return coverage;
  148. }
  149. }
  150. class CSSCoverage {
  151. /**
  152. * @param {!Puppeteer.CDPSession} client
  153. */
  154. constructor(client) {
  155. this._client = client;
  156. this._enabled = false;
  157. this._stylesheetURLs = new Map();
  158. this._stylesheetSources = new Map();
  159. this._eventListeners = [];
  160. this._resetOnNavigation = false;
  161. }
  162. /**
  163. * @param {{resetOnNavigation?: boolean}=} options
  164. */
  165. async start(options = {}) {
  166. assert(!this._enabled, 'CSSCoverage is already enabled');
  167. const {resetOnNavigation = true} = options;
  168. this._resetOnNavigation = resetOnNavigation;
  169. this._enabled = true;
  170. this._stylesheetURLs.clear();
  171. this._stylesheetSources.clear();
  172. this._eventListeners = [
  173. helper.addEventListener(this._client, 'CSS.styleSheetAdded', this._onStyleSheet.bind(this)),
  174. helper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),
  175. ];
  176. await Promise.all([
  177. this._client.send('DOM.enable'),
  178. this._client.send('CSS.enable'),
  179. this._client.send('CSS.startRuleUsageTracking'),
  180. ]);
  181. }
  182. _onExecutionContextsCleared() {
  183. if (!this._resetOnNavigation)
  184. return;
  185. this._stylesheetURLs.clear();
  186. this._stylesheetSources.clear();
  187. }
  188. /**
  189. * @param {!Protocol.CSS.styleSheetAddedPayload} event
  190. */
  191. async _onStyleSheet(event) {
  192. const header = event.header;
  193. // Ignore anonymous scripts
  194. if (!header.sourceURL)
  195. return;
  196. try {
  197. const response = await this._client.send('CSS.getStyleSheetText', {styleSheetId: header.styleSheetId});
  198. this._stylesheetURLs.set(header.styleSheetId, header.sourceURL);
  199. this._stylesheetSources.set(header.styleSheetId, response.text);
  200. } catch (e) {
  201. // This might happen if the page has already navigated away.
  202. debugError(e);
  203. }
  204. }
  205. /**
  206. * @return {!Promise<!Array<!CoverageEntry>>}
  207. */
  208. async stop() {
  209. assert(this._enabled, 'CSSCoverage is not enabled');
  210. this._enabled = false;
  211. const ruleTrackingResponse = await this._client.send('CSS.stopRuleUsageTracking');
  212. await Promise.all([
  213. this._client.send('CSS.disable'),
  214. this._client.send('DOM.disable'),
  215. ]);
  216. helper.removeEventListeners(this._eventListeners);
  217. // aggregate by styleSheetId
  218. const styleSheetIdToCoverage = new Map();
  219. for (const entry of ruleTrackingResponse.ruleUsage) {
  220. let ranges = styleSheetIdToCoverage.get(entry.styleSheetId);
  221. if (!ranges) {
  222. ranges = [];
  223. styleSheetIdToCoverage.set(entry.styleSheetId, ranges);
  224. }
  225. ranges.push({
  226. startOffset: entry.startOffset,
  227. endOffset: entry.endOffset,
  228. count: entry.used ? 1 : 0,
  229. });
  230. }
  231. const coverage = [];
  232. for (const styleSheetId of this._stylesheetURLs.keys()) {
  233. const url = this._stylesheetURLs.get(styleSheetId);
  234. const text = this._stylesheetSources.get(styleSheetId);
  235. const ranges = convertToDisjointRanges(styleSheetIdToCoverage.get(styleSheetId) || []);
  236. coverage.push({url, ranges, text});
  237. }
  238. return coverage;
  239. }
  240. }
  241. /**
  242. * @param {!Array<!{startOffset:number, endOffset:number, count:number}>} nestedRanges
  243. * @return {!Array<!{start:number, end:number}>}
  244. */
  245. function convertToDisjointRanges(nestedRanges) {
  246. const points = [];
  247. for (const range of nestedRanges) {
  248. points.push({ offset: range.startOffset, type: 0, range });
  249. points.push({ offset: range.endOffset, type: 1, range });
  250. }
  251. // Sort points to form a valid parenthesis sequence.
  252. points.sort((a, b) => {
  253. // Sort with increasing offsets.
  254. if (a.offset !== b.offset)
  255. return a.offset - b.offset;
  256. // All "end" points should go before "start" points.
  257. if (a.type !== b.type)
  258. return b.type - a.type;
  259. const aLength = a.range.endOffset - a.range.startOffset;
  260. const bLength = b.range.endOffset - b.range.startOffset;
  261. // For two "start" points, the one with longer range goes first.
  262. if (a.type === 0)
  263. return bLength - aLength;
  264. // For two "end" points, the one with shorter range goes first.
  265. return aLength - bLength;
  266. });
  267. const hitCountStack = [];
  268. const results = [];
  269. let lastOffset = 0;
  270. // Run scanning line to intersect all ranges.
  271. for (const point of points) {
  272. if (hitCountStack.length && lastOffset < point.offset && hitCountStack[hitCountStack.length - 1] > 0) {
  273. const lastResult = results.length ? results[results.length - 1] : null;
  274. if (lastResult && lastResult.end === lastOffset)
  275. lastResult.end = point.offset;
  276. else
  277. results.push({start: lastOffset, end: point.offset});
  278. }
  279. lastOffset = point.offset;
  280. if (point.type === 0)
  281. hitCountStack.push(point.range.count);
  282. else
  283. hitCountStack.pop();
  284. }
  285. // Filter out empty ranges.
  286. return results.filter(range => range.end - range.start > 1);
  287. }