diff --git a/lighthouse-cli/test/cli/run-test.js b/lighthouse-cli/test/cli/run-test.js index c60addf0835e..923bc42d9412 100644 --- a/lighthouse-cli/test/cli/run-test.js +++ b/lighthouse-cli/test/cli/run-test.js @@ -41,6 +41,7 @@ describe('CLI run', function() { Object.keys(results.audits).length, Object.keys(lhr.audits).length); assert.deepStrictEqual(results.timing, lhr.timing); + assert.ok(results.timing.total !== 0); fs.unlinkSync(filename); }); diff --git a/lighthouse-core/config/config.js b/lighthouse-core/config/config.js index aa5847b1bb2b..3d3e406761d7 100644 --- a/lighthouse-core/config/config.js +++ b/lighthouse-core/config/config.js @@ -312,6 +312,8 @@ class Config { * @param {LH.Flags=} flags */ constructor(configJSON, flags) { + const status = {msg: 'Create config', id: 'lh:init:config'}; + log.time(status, 'verbose'); let configPath = flags && flags.configPath; if (!configJSON) { @@ -364,6 +366,7 @@ class Config { // TODO(bckenny): until tsc adds @implements support, assert that Config is a ConfigJson. /** @type {LH.Config.Json} */ const configJson = this; // eslint-disable-line no-unused-vars + log.timeEnd(status); } /** @@ -748,6 +751,8 @@ class Config { * @return {Config['audits']} */ static requireAudits(audits, configPath) { + const status = {msg: 'Requiring audits', id: 'lh:config:requireAudits'}; + log.time(status, 'verbose'); const expandedAudits = Config.expandAuditShorthand(audits); if (!expandedAudits) { return null; @@ -779,6 +784,7 @@ class Config { const mergedAuditDefns = mergeOptionsOfItems(auditDefns); mergedAuditDefns.forEach(audit => assertValidAudit(audit.implementation, audit.path)); + log.timeEnd(status); return mergedAuditDefns; } @@ -820,6 +826,8 @@ class Config { if (!passes) { return null; } + const status = {msg: 'Requiring gatherers', id: 'lh:config:requireGatherers'}; + log.time(status, 'verbose'); const coreList = Runner.getGathererList(); const fullPasses = passes.map(pass => { @@ -853,7 +861,7 @@ class Config { return Object.assign(pass, {gatherers: mergedDefns}); }); - + log.timeEnd(status); return fullPasses; } } diff --git a/lighthouse-core/gather/computed/computed-artifact.js b/lighthouse-core/gather/computed/computed-artifact.js index 12b85ae3bb6f..7556bd9fb889 100644 --- a/lighthouse-core/gather/computed/computed-artifact.js +++ b/lighthouse-core/gather/computed/computed-artifact.js @@ -6,6 +6,7 @@ 'use strict'; const ArbitraryEqualityMap = require('../../lib/arbitrary-equality-map'); +const log = require('lighthouse-logger'); class ComputedArtifact { /** @@ -59,12 +60,15 @@ class ComputedArtifact { return computed; } + const status = {msg: `Computing artifact: ${this.name}`, id: `lh:computed:${this.name}`}; + log.time(status, 'verbose'); // Need to cast since `this.compute_(...)` returns the concrete return type // of the base class's compute_, not the called derived class's. const artifactPromise = /** @type {ReturnType} */ ( this.compute_(requiredArtifacts, this._allComputedArtifacts)); this._cache.set(requiredArtifacts, artifactPromise); + artifactPromise.then(() => log.timeEnd(status)); return artifactPromise; } } diff --git a/lighthouse-core/gather/driver.js b/lighthouse-core/gather/driver.js index 699371bcf178..771d80a20cad 100644 --- a/lighthouse-core/gather/driver.js +++ b/lighthouse-core/gather/driver.js @@ -136,9 +136,12 @@ class Driver { * @return {Promise} */ async getBrowserVersion() { + const status = {msg: 'Getting browser version', id: 'lh:gather:getVersion'}; + log.time(status, 'verbose'); const version = await this.sendCommand('Browser.getVersion'); const match = version.product.match(/\/(\d+)/); // eg 'Chrome/71.0.3577.0' const milestone = match ? parseInt(match[1]) : 0; + log.timeEnd(status); return Object.assign(version, {milestone}); } @@ -146,15 +149,22 @@ class Driver { * Computes the ULTRADUMB™ benchmark index to get a rough estimate of device class. * @return {Promise} */ - getBenchmarkIndex() { - return this.evaluateAsync(`(${pageFunctions.ultradumbBenchmarkString})()`); + async getBenchmarkIndex() { + const status = {msg: 'Benchmarking machine', id: 'lh:gather:getBenchmarkIndex'}; + log.time(status); + const indexVal = await this.evaluateAsync(`(${pageFunctions.ultradumbBenchmarkString})()`); + log.timeEnd(status); + return indexVal; } /** * @return {Promise} */ - connect() { - return this._connection.connect(); + async connect() { + const status = {msg: 'Connecting to browser', id: 'lh:init:connect'}; + log.time(status); + await this._connection.connect(); + log.timeEnd(status); } /** diff --git a/lighthouse-core/gather/gather-runner.js b/lighthouse-core/gather/gather-runner.js index bab5985c8440..d8d5463eb65f 100644 --- a/lighthouse-core/gather/gather-runner.js +++ b/lighthouse-core/gather/gather-runner.js @@ -76,8 +76,11 @@ class GatherRunner { url = constants.defaultPassConfig.blankPage, duration = constants.defaultPassConfig.blankDuration ) { + const status = {msg: 'Resetting state with about:blank', id: 'lh:gather:loadBlank'}; + log.time(status); await driver.gotoURL(url); await new Promise(resolve => setTimeout(resolve, duration)); + log.timeEnd(status); } /** @@ -103,7 +106,8 @@ class GatherRunner { * @return {Promise} */ static async setupDriver(driver, options) { - log.log('status', 'Initializing…'); + const status = {msg: 'Initializing…', id: 'lh:gather:setupDriver'}; + log.time(status); const resetStorage = !options.settings.disableStorageReset; // Enable emulation based on settings await driver.assertNoSameOriginServiceWorkerClients(options.requestedUrl); @@ -114,21 +118,27 @@ class GatherRunner { await driver.dismissJavaScriptDialogs(); await driver.listenForSecurityStateChanges(); if (resetStorage) await driver.clearDataForOrigin(options.requestedUrl); + log.timeEnd(status); } /** * @param {Driver} driver * @return {Promise} */ - static disposeDriver(driver) { - log.log('status', 'Disconnecting from browser...'); - return driver.disconnect().catch(err => { + static async disposeDriver(driver) { + const status = {msg: 'Disconnecting from browser...', id: 'lh:gather:disconnect'}; + + log.time(status); + try { + await driver.disconnect(); + } catch (err) { // Ignore disconnecting error if browser was already closed. // See https://github.com/GoogleChrome/lighthouse/issues/1583 if (!(/close\/.*status: 500$/.test(err.message))) { log.error('GatherRunner disconnect', err.message); } - }); + } + log.timeEnd(status); } /** @@ -183,6 +193,8 @@ class GatherRunner { * @return {Promise} */ static async beforePass(passContext, gathererResults) { + const bpStatus = {msg: `Running beforePass methods`, id: `lh:gather:beforePass`}; + log.time(bpStatus, 'verbose'); const blockedUrls = (passContext.passConfig.blockedUrlPatterns || []) .concat(passContext.settings.blockedUrlPatterns || []); const blankPage = passContext.passConfig.blankPage; @@ -198,10 +210,17 @@ class GatherRunner { const gatherer = gathererDefn.instance; // Abuse the passContext to pass through gatherer options passContext.options = gathererDefn.options || {}; + const status = { + msg: `Retrieving setup: ${gatherer.name}`, + id: `lh:gather:beforePass:${gatherer.name}`, + }; + log.time(status, 'verbose'); const artifactPromise = Promise.resolve().then(_ => gatherer.beforePass(passContext)); gathererResults[gatherer.name] = [artifactPromise]; await artifactPromise.catch(() => {}); + log.timeEnd(status); } + log.timeEnd(bpStatus); } /** @@ -220,9 +239,12 @@ class GatherRunner { const recordTrace = config.recordTrace; const isPerfRun = !settings.disableStorageReset && recordTrace && config.useThrottling; - const gatherernames = gatherers.map(g => g.instance.name).join(', '); - const status = 'Loading page & waiting for onload'; - log.log('status', status, gatherernames); + const status = { + msg: 'Loading page & waiting for onload', + id: 'lh:gather:loadPage', + args: [gatherers.map(g => g.instance.name).join(', ')], + }; + log.time(status); // Clear disk & memory cache if it's a perf run if (isPerfRun) await driver.cleanBrowserCaches(); @@ -233,19 +255,28 @@ class GatherRunner { // Navigate. await GatherRunner.loadPage(driver, passContext); - log.log('statusEnd', status); + log.timeEnd(status); + const pStatus = {msg: `Running pass methods`, id: `lh:gather:pass`}; + log.time(pStatus, 'verbose'); for (const gathererDefn of gatherers) { const gatherer = gathererDefn.instance; // Abuse the passContext to pass through gatherer options passContext.options = gathererDefn.options || {}; + const status = { + msg: `Retrieving in-page: ${gatherer.name}`, + id: `lh:gather:pass:${gatherer.name}`, + }; + log.time(status); const artifactPromise = Promise.resolve().then(_ => gatherer.pass(passContext)); const gathererResult = gathererResults[gatherer.name] || []; gathererResult.push(artifactPromise); gathererResults[gatherer.name] = gathererResult; await artifactPromise.catch(() => {}); + log.timeEnd(status); } + log.timeEnd(pStatus); } /** @@ -263,16 +294,20 @@ class GatherRunner { let trace; if (config.recordTrace) { - log.log('status', 'Retrieving trace'); + const status = {msg: 'Retrieving trace', id: `lh:gather:getTrace`}; + log.time(status); trace = await driver.endTrace(); - log.verbose('statusEnd', 'Retrieving trace'); + log.timeEnd(status); } - const status = 'Retrieving devtoolsLog and network records'; - log.log('status', status); + const status = { + msg: 'Retrieving devtoolsLog & network records', + id: `lh:gather:getDevtoolsLog`, + }; + log.time(status); const devtoolsLog = driver.endDevtoolsLog(); const networkRecords = NetworkRecorder.recordsFromLogs(devtoolsLog); - log.verbose('statusEnd', status); + log.timeEnd(status); let pageLoadError = GatherRunner.getPageLoadError(passContext.url, networkRecords); // If the driver was offline, a page load error is expected, so do not save it. @@ -293,13 +328,18 @@ class GatherRunner { trace, }; + const apStatus = {msg: `Running afterPass methods`, id: `lh:gather:afterPass`}; // Disable throttling so the afterPass analysis isn't throttled await driver.setThrottling(passContext.settings, {useThrottling: false}); + log.time(apStatus, 'verbose'); for (const gathererDefn of gatherers) { const gatherer = gathererDefn.instance; - const status = `Retrieving: ${gatherer.name}`; - log.log('status', status); + const status = { + msg: `Retrieving: ${gatherer.name}`, + id: `lh:gather:afterPass:${gatherer.name}`, + }; + log.time(status); // Add gatherer options to the passContext. passContext.options = gathererDefn.options || {}; @@ -314,8 +354,9 @@ class GatherRunner { gathererResult.push(artifactPromise); gathererResults[gatherer.name] = gathererResult; await artifactPromise.catch(() => {}); - log.verbose('statusEnd', status); + log.timeEnd(status); } + log.timeEnd(apStatus); // Resolve on tracing data using passName from config. return passData; @@ -358,6 +399,9 @@ class GatherRunner { // Take only unique LighthouseRunWarnings. baseArtifacts.LighthouseRunWarnings = Array.from(new Set(baseArtifacts.LighthouseRunWarnings)); + // Take the timing entries we've gathered so far. + baseArtifacts.Timing = log.getTimeEntries(); + // TODO(bckenny): correct Partial at this point to drop cast. return /** @type {LH.Artifacts} */ ({...baseArtifacts, ...gathererArtifacts}); } @@ -377,6 +421,7 @@ class GatherRunner { devtoolsLogs: {}, settings: options.settings, URL: {requestedUrl: options.requestedUrl, finalUrl: ''}, + Timing: [], }; } diff --git a/lighthouse-core/lib/asset-saver.js b/lighthouse-core/lib/asset-saver.js index 8fd2dbc4e142..2faa29b37c21 100644 --- a/lighthouse-core/lib/asset-saver.js +++ b/lighthouse-core/lib/asset-saver.js @@ -63,6 +63,11 @@ async function loadArtifacts(basePath) { artifacts.traces[passName] = Array.isArray(trace) ? {traceEvents: trace} : trace; }); + if (Array.isArray(artifacts.Timing)) { + // Any Timing entries in saved artifacts will have a different timeOrigin than the auditing phase + // The `gather` prop is read later in generate-timing-trace and they're added to a separate track of trace events + artifacts.Timing.forEach(entry => (entry.gather = true)); + } return artifacts; } @@ -74,6 +79,8 @@ async function loadArtifacts(basePath) { * @return {Promise} */ async function saveArtifacts(artifacts, basePath) { + const status = {msg: 'Saving artifacts', id: 'lh:assetSaver:saveArtifacts'}; + log.time(status); mkdirp.sync(basePath); rimraf.sync(`${basePath}/*${traceSuffix}`); rimraf.sync(`${basePath}/${artifactsFilename}`); @@ -95,6 +102,7 @@ async function saveArtifacts(artifacts, basePath) { const restArtifactsString = JSON.stringify(restArtifacts, null, 2); fs.writeFileSync(`${basePath}/${artifactsFilename}`, restArtifactsString, 'utf8'); log.log('Artifacts saved to disk in folder:', basePath); + log.timeEnd(status); } /** diff --git a/lighthouse-core/lib/timing-trace-saver.js b/lighthouse-core/lib/timing-trace-saver.js new file mode 100644 index 000000000000..078d4e2e3906 --- /dev/null +++ b/lighthouse-core/lib/timing-trace-saver.js @@ -0,0 +1,106 @@ +/** + * @license Copyright 2018 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. + */ +'use strict'; + +/** + * Technically, it's fine for usertiming measures to overlap, however non-async events make + * for a much clearer UI in traceviewer. We do this check to make sure we aren't passing off + * async-like measures as non-async. + * prevEntries are expected to be sorted by startTime + * @param {LH.Artifacts.MeasureEntry} entry user timing entry + * @param {LH.Artifacts.MeasureEntry[]} prevEntries user timing entries + */ +function checkEventOverlap(entry, prevEntries) { + for (const prevEntry of prevEntries) { + const prevEnd = prevEntry.startTime + prevEntry.duration; + const thisEnd = entry.startTime + entry.duration; + const isOverlap = prevEnd > entry.startTime && prevEnd < thisEnd; + if (isOverlap) { + // eslint-disable-next-line no-console + console.error(`Two measures overlap! ${prevEntry.name} & ${entry.name}`); + } + } +} + +/** + * Generates a chromium trace file from user timing measures + * Adapted from https://github.com/tdresser/performance-observer-tracing + * @param {LH.Artifacts.MeasureEntry[]} entries user timing entries + * @param {string=} trackName + */ +function generateTraceEvents(entries, trackName = 'measures') { + if (!Array.isArray(entries)) return []; + + /** @type {LH.TraceEvent[]} */ + const currentTrace = []; + let id = 0; + + entries.sort((a, b) => a.startTime - b.startTime); + entries.forEach((entry, i) => { + checkEventOverlap(entry, entries.slice(0, i)); + + /** @type {LH.TraceEvent} */ + const traceEvent = { + name: entry.name, + cat: entry.entryType, + ts: entry.startTime * 1000, + dur: entry.duration * 1000, + args: {}, + pid: 0, + tid: trackName === 'measures' ? 50 : 75, + ph: 'X', + id: '0x' + (id++).toString(16), + }; + + if (entry.entryType !== 'measure') throw new Error('Unexpected entryType!'); + if (entry.duration === 0) { + traceEvent.ph = 'n'; + traceEvent.s = 't'; + } + + currentTrace.push(traceEvent); + }); + + // Add labels + /** @type {LH.TraceEvent} */ + const metaEvtBase = { + pid: 0, + tid: trackName === 'measures' ? 50 : 75, + ts: 0, + dur: 0, + ph: 'M', + cat: '__metadata', + name: 'process_labels', + args: {labels: 'Default'}, + }; + currentTrace.push(Object.assign({}, metaEvtBase, {args: {labels: 'Lighthouse Timing'}})); + currentTrace.push(Object.assign({}, metaEvtBase, {name: 'thread_name', args: {name: trackName}})); + + return currentTrace; +} + +/** + * Writes a trace file to disk + * @param {LH.Result} lhr + * @return {string} + */ +function createTraceString(lhr) { + const gatherEntries = lhr.timing.entries.filter(entry => entry.gather); + const entries = lhr.timing.entries.filter(entry => !gatherEntries.includes(entry)); + + const auditEvents = generateTraceEvents(entries); + const gatherEvents = generateTraceEvents(gatherEntries, 'gather'); + const events = [...auditEvents, ...gatherEvents]; + + const jsonStr = ` + { "traceEvents": [ + ${events.map(evt => JSON.stringify(evt)).join(',\n')} + ]}`; + + return jsonStr; +} + +module.exports = {generateTraceEvents, createTraceString}; diff --git a/lighthouse-core/runner.js b/lighthouse-core/runner.js index 08e16b07d53e..a363974fd966 100644 --- a/lighthouse-core/runner.js +++ b/lighthouse-core/runner.js @@ -31,8 +31,9 @@ class Runner { */ static async run(connection, runOpts) { try { - const startTime = Date.now(); const settings = runOpts.config.settings; + const runnerStatus = {msg: 'Runner setup', id: 'lh:runner:run'}; + log.time(runnerStatus, 'verbose'); /** * List of top-level warnings for this Lighthouse run. @@ -98,7 +99,8 @@ class Runner { lighthouseRunWarnings); // LHR construction phase - log.log('status', 'Generating results...'); + const resultsStatus = {msg: 'Generating results...', id: 'lh:runner:generate'}; + log.time(resultsStatus); if (artifacts.LighthouseRunWarnings) { lighthouseRunWarnings.push(...artifacts.LighthouseRunWarnings); @@ -119,6 +121,9 @@ class Runner { categories = ReportScoring.scoreAllCategories(runOpts.config.categories, resultsById); } + log.timeEnd(resultsStatus); + log.timeEnd(runnerStatus); + /** @type {LH.Result} */ const lhr = { userAgent: artifacts.HostUserAgent, @@ -137,7 +142,7 @@ class Runner { configSettings: settings, categories, categoryGroups: runOpts.config.groups || undefined, - timing: {total: Date.now() - startTime}, + timing: this._getTiming(artifacts), i18n: { rendererFormattedStrings: i18n.getRendererFormattedStrings(settings.locale), icuMessagePaths: {}, @@ -147,7 +152,9 @@ class Runner { // Replace ICU message references with localized strings; save replaced paths in lhr. lhr.i18n.icuMessagePaths = i18n.replaceIcuMessageInstanceIds(lhr, settings.locale); + // Create the HTML, JSON, and/or CSV string const report = generateReport(lhr, settings.output); + return {lhr, artifacts, report}; } catch (err) { await Sentry.captureException(err, {level: 'fatal'}); @@ -155,6 +162,25 @@ class Runner { } } + /** + * This handles both the auditMode case where gatherer entries need to be merged in and + * the gather/audit case where timingEntriesFromRunner contains all entries from this run, + * including those also in timingEntriesFromArtifacts. + * @param {LH.Artifacts} artifacts + * @return {LH.Result.Timing} + */ + static _getTiming(artifacts) { + const timingEntriesFromArtifacts = artifacts.Timing || []; + const timingEntriesFromRunner = log.takeTimeEntries(); + const timingEntriesKeyValues = [ + ...timingEntriesFromArtifacts, + ...timingEntriesFromRunner, + ].map(entry => /** @type {[string, PerformanceEntry]} */ ([entry.name, entry])); + const timingEntries = Array.from(new Map(timingEntriesKeyValues).values()); + const runnerEntry = timingEntries.find(e => e.name === 'lh:runner:run'); + return {entries: timingEntries, total: runnerEntry && runnerEntry.duration || 0}; + } + /** * Establish connection, load page and collect all required artifacts * @param {string} requestedUrl @@ -186,7 +212,8 @@ class Runner { * @return {Promise>} */ static async _runAudits(settings, audits, artifacts, runWarnings) { - log.log('status', 'Analyzing and running audits...'); + const status = {msg: 'Analyzing and running audits...', id: 'lh:runner:auditing'}; + log.time(status); if (artifacts.settings) { const overrides = { @@ -218,6 +245,7 @@ class Runner { auditResults.push(auditResult); } + log.timeEnd(status); return auditResults; } @@ -232,9 +260,12 @@ class Runner { */ static async _runAudit(auditDefn, artifacts, sharedAuditContext) { const audit = auditDefn.implementation; - const status = `Evaluating: ${i18n.getFormatted(audit.meta.title, 'en-US')}`; + const status = { + msg: `Evaluating: ${i18n.getFormatted(audit.meta.title, 'en-US')}`, + id: `lh:audit:${audit.meta.id}`, + }; + log.time(status); - log.log('status', status); let auditResult; try { // Return an early error if an artifact required for the audit is missing or an error. @@ -294,7 +325,7 @@ class Runner { auditResult = Audit.generateErrorAuditResult(audit, errorMessage); } - log.verbose('statusEnd', status); + log.timeEnd(status); return auditResult; } diff --git a/lighthouse-core/scripts/generate-timing-trace.js b/lighthouse-core/scripts/generate-timing-trace.js new file mode 100644 index 000000000000..055311404d4c --- /dev/null +++ b/lighthouse-core/scripts/generate-timing-trace.js @@ -0,0 +1,57 @@ +/** + * @license Copyright 2018 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. + */ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const {createTraceString} = require('../lib/timing-trace-saver'); + +/** + * @fileoverview This script takes the timing entries saved during a Lighthouse run and generates + * a trace file that's readable in chrome://tracing. + * + * input = LHR.json + * output = LHR.timing.trace.json + */ + +/** + * @param {string} msg + */ +function printErrorAndQuit(msg) { + // eslint-disable-next-line no-console + console.error(`ERROR: + > ${msg} + > Example: + > yarn timing-trace results.json + `); + process.exit(1); +} + +/** + * Takes filename of LHR object. The primary entrypoint on CLI + */ +function saveTraceFromCLI() { + if (!process.argv[2]) { + printErrorAndQuit('Lighthouse JSON results path not provided'); + } + const filename = path.resolve(process.cwd(), process.argv[2]); + if (!fs.existsSync(filename)) { + printErrorAndQuit('Lighthouse JSON results not found.'); + } + + const lhrObject = JSON.parse(fs.readFileSync(filename, 'utf8')); + const jsonStr = createTraceString(lhrObject); + + const traceFilePath = `${filename}.timing.trace.json`; + fs.writeFileSync(traceFilePath, jsonStr, 'utf8'); + // eslint-disable-next-line no-console + console.log(` + > Timing trace file saved to: ${traceFilePath} + > Open this file in chrome://tracing +`); +} + +saveTraceFromCLI(); diff --git a/lighthouse-core/test/gather/computed/computed-artifact-test.js b/lighthouse-core/test/gather/computed/computed-artifact-test.js index 70a70293a28b..a6b535adf778 100644 --- a/lighthouse-core/test/gather/computed/computed-artifact-test.js +++ b/lighthouse-core/test/gather/computed/computed-artifact-test.js @@ -30,18 +30,20 @@ class TestComputedArtifact extends ComputedArtifact { } describe('ComputedArtifact base class', () => { - it('caches computed artifacts by strict equality', () => { + it('caches computed artifacts by strict equality', async () => { const computedArtifact = new TestComputedArtifact(); - return computedArtifact.request({x: 1}).then(result => { - assert.equal(result, 0); - }).then(_ => computedArtifact.request({x: 2})).then(result => { - assert.equal(result, 1); - }).then(_ => computedArtifact.request({x: 1})).then(result => { - assert.equal(result, 0); - }).then(_ => computedArtifact.request({x: 2})).then(result => { - assert.equal(result, 1); - assert.equal(computedArtifact.computeCounter, 2); - }); + let result = await computedArtifact.request({x: 1}); + assert.equal(result, 0); + + result = await computedArtifact.request({x: 2}); + assert.equal(result, 1); + + result = await computedArtifact.request({x: 1}); + assert.equal(result, 0); + + result = await computedArtifact.request({x: 2}); + assert.equal(result, 1); + assert.equal(computedArtifact.computeCounter, 2); }); }); diff --git a/lighthouse-core/test/index-test.js b/lighthouse-core/test/index-test.js index 99190946f006..3728566af8ac 100644 --- a/lighthouse-core/test/index-test.js +++ b/lighthouse-core/test/index-test.js @@ -128,7 +128,7 @@ describe('Module Tests', function() { assert.strictEqual(results.lhr.audits.viewport.score, 0); assert.ok(results.lhr.audits.viewport.explanation); assert.ok(results.lhr.timing); - assert.equal(typeof results.lhr.timing.total, 'number'); + assert.ok(results.lhr.timing.entries.length > 3, 'timing entries not populated'); }); }); diff --git a/lighthouse-core/test/lib/timing-trace-saver-test.js b/lighthouse-core/test/lib/timing-trace-saver-test.js new file mode 100644 index 000000000000..be3749e9df4b --- /dev/null +++ b/lighthouse-core/test/lib/timing-trace-saver-test.js @@ -0,0 +1,140 @@ +/** + * @license Copyright 2018 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. + */ +'use strict'; + +/* eslint-env jest */ + +/* eslint-disable no-console */ + +const assert = require('assert'); +const {generateTraceEvents, createTraceString} = require('../../lib/timing-trace-saver'); + +const mockEntries = [{ + startTime: 650, + name: 'lh:init:config', + duration: 210, + entryType: 'measure', +}, +{ + startTime: 870, + name: 'lh:runner:run', + duration: 120, + entryType: 'measure', +}, +{ + startTime: 990, + name: 'lh:runner:auditing', + duration: 750, + entryType: 'measure', +}, +{ + startTime: 1010, + name: 'lh:audit:is-on-https', + duration: 10, + entryType: 'measure', +}, +]; +const expectedTrace = { + traceEvents: [{ + name: 'lh:init:config', + cat: 'measure', + ts: 650000, + dur: 210000, + args: {}, + pid: 0, + tid: 50, + ph: 'X', + id: '0x0', + }, + { + name: 'lh:runner:run', + cat: 'measure', + ts: 870000, + dur: 120000, + args: {}, + pid: 0, + tid: 50, + ph: 'X', + id: '0x1', + }, + { + name: 'lh:runner:auditing', + cat: 'measure', + ts: 990000, + dur: 750000, + args: {}, + pid: 0, + tid: 50, + ph: 'X', + id: '0x2', + }, + { + name: 'lh:audit:is-on-https', + cat: 'measure', + ts: 1010000, + dur: 10000, + args: {}, + pid: 0, + tid: 50, + ph: 'X', + id: '0x3', + }, + ], +}; + + +describe('generateTraceEvents', () => { + let consoleError; + let origConsoleError; + + beforeEach(() => { + origConsoleError = console.error; + consoleError = jest.fn(); + console.error = consoleError; + }); + + afterEach(() => { + console.error = origConsoleError; + }); + + it('generates a single trace event', () => { + const event = generateTraceEvents(mockEntries); + assert.deepStrictEqual(event.slice(0, 1), expectedTrace.traceEvents.slice(0, 1)); + }); + + it('doesn\'t allow overlapping events', () => { + const overlappingEntries = [{ + startTime: 10, + name: 'overlap1', + duration: 100, + entryType: 'measure', + }, + { + startTime: 30, + name: 'overlap2', + duration: 100, + entryType: 'measure', + }, + ]; + + generateTraceEvents(overlappingEntries); + expect(consoleError).toHaveBeenCalled(); + expect(consoleError.mock.calls[0][0]).toContain('measures overlap'); + }); +}); + +describe('createTraceString', () => { + it('creates a real trace', () => { + const jsonStr = createTraceString({ + timing: { + entries: mockEntries, + }, + }); + const traceJson = JSON.parse(jsonStr); + const eventsWithoutMetadata = traceJson.traceEvents.filter(e => e.cat !== '__metadata'); + assert.deepStrictEqual(eventsWithoutMetadata, expectedTrace.traceEvents); + }); +}); diff --git a/lighthouse-core/test/results/artifacts/artifacts.json b/lighthouse-core/test/results/artifacts/artifacts.json index 1625f8caaba9..e9d1efa7d2fd 100644 --- a/lighthouse-core/test/results/artifacts/artifacts.json +++ b/lighthouse-core/test/results/artifacts/artifacts.json @@ -8,6 +8,7 @@ "requestedUrl": "http://localhost:10200/dobetterweb/dbw_tester.html", "finalUrl": "http://localhost:10200/dobetterweb/dbw_tester.html" }, + "Timing": [], "Scripts": { "75994.10": "/**\n * @license Copyright 2016 Google Inc. All Rights Reserved.\n * 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\n * 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.\n */\n\n/*eslint-disable*/\n\n(function() {\n\nconst params = new URLSearchParams(location.search);\n\nif (location.search === '' || params.has('dateNow')) {\n // FAIL - Date.now() usage in another file.\n const d = Date.now();\n}\n\nif (location.search === '' || params.has('mutationEvents')) {\n // FAIL - MutationEvent usage in another file.\n document.addEventListener('DOMNodeInserted', function(e) {\n console.log('DOMNodeInserted');\n });\n}\n\nif (location.search === '' || params.has('passiveEvents')) {\n // FAIL - non-passive listener usage in another file.\n document.addEventListener('wheel', e => {\n console.log('wheel: arrow function');\n });\n}\n\nif (location.search === '' || params.has('deprecations')) {\n const div = document.createElement('div');\n div.createShadowRoot();\n // FAIL(errors-in-console) - multiple shadow v0 roots.\n // TODO: disabled until m64 is stable (when moved from deprecation warning to error)\n // div.createShadowRoot();\n}\n\n})();\n", "75994.21": "/**\n* @license\n* Copyright Google Inc. All Rights Reserved.\n*\n* Use of this source code is governed by an MIT-style license that can be\n* found in the LICENSE file at https://angular.io/license\n*/\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (factory());\n}(this, (function () { 'use strict';\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\n\nvar Zone$1 = (function (global) {\n if (global['Zone']) {\n throw new Error('Zone already loaded.');\n }\n var Zone = (function () {\n function Zone(parent, zoneSpec) {\n this._properties = null;\n this._parent = parent;\n this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '';\n this._properties = zoneSpec && zoneSpec.properties || {};\n this._zoneDelegate =\n new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);\n }\n Zone.assertZonePatched = function () {\n if (global.Promise !== ZoneAwarePromise) {\n throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +\n 'has been overwritten.\\n' +\n 'Most likely cause is that a Promise polyfill has been loaded ' +\n 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +\n 'If you must load one, do so before loading zone.js.)');\n }\n };\n Object.defineProperty(Zone, \"current\", {\n get: function () {\n return _currentZoneFrame.zone;\n },\n enumerable: true,\n configurable: true\n });\n \n Object.defineProperty(Zone, \"currentTask\", {\n get: function () {\n return _currentTask;\n },\n enumerable: true,\n configurable: true\n });\n \n Object.defineProperty(Zone.prototype, \"parent\", {\n get: function () {\n return this._parent;\n },\n enumerable: true,\n configurable: true\n });\n \n Object.defineProperty(Zone.prototype, \"name\", {\n get: function () {\n return this._name;\n },\n enumerable: true,\n configurable: true\n });\n \n Zone.prototype.get = function (key) {\n var zone = this.getZoneWith(key);\n if (zone)\n return zone._properties[key];\n };\n Zone.prototype.getZoneWith = function (key) {\n var current = this;\n while (current) {\n if (current._properties.hasOwnProperty(key)) {\n return current;\n }\n current = current._parent;\n }\n return null;\n };\n Zone.prototype.fork = function (zoneSpec) {\n if (!zoneSpec)\n throw new Error('ZoneSpec required!');\n return this._zoneDelegate.fork(this, zoneSpec);\n };\n Zone.prototype.wrap = function (callback, source) {\n if (typeof callback !== 'function') {\n throw new Error('Expecting function got: ' + callback);\n }\n var _callback = this._zoneDelegate.intercept(this, callback, source);\n var zone = this;\n return function () {\n return zone.runGuarded(_callback, this, arguments, source);\n };\n };\n Zone.prototype.run = function (callback, applyThis, applyArgs, source) {\n if (applyThis === void 0) { applyThis = null; }\n if (applyArgs === void 0) { applyArgs = null; }\n if (source === void 0) { source = null; }\n _currentZoneFrame = new ZoneFrame(_currentZoneFrame, this);\n try {\n return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);\n }\n finally {\n _currentZoneFrame = _currentZoneFrame.parent;\n }\n };\n Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {\n if (applyThis === void 0) { applyThis = null; }\n if (applyArgs === void 0) { applyArgs = null; }\n if (source === void 0) { source = null; }\n _currentZoneFrame = new ZoneFrame(_currentZoneFrame, this);\n try {\n try {\n return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);\n }\n catch (error) {\n if (this._zoneDelegate.handleError(this, error)) {\n throw error;\n }\n }\n }\n finally {\n _currentZoneFrame = _currentZoneFrame.parent;\n }\n };\n Zone.prototype.runTask = function (task, applyThis, applyArgs) {\n task.runCount++;\n if (task.zone != this)\n throw new Error('A task can only be run in the zone which created it! (Creation: ' + task.zone.name +\n '; Execution: ' + this.name + ')');\n var previousTask = _currentTask;\n _currentTask = task;\n _currentZoneFrame = new ZoneFrame(_currentZoneFrame, this);\n try {\n if (task.type == 'macroTask' && task.data && !task.data.isPeriodic) {\n task.cancelFn = null;\n }\n try {\n return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);\n }\n catch (error) {\n if (this._zoneDelegate.handleError(this, error)) {\n throw error;\n }\n }\n }\n finally {\n _currentZoneFrame = _currentZoneFrame.parent;\n _currentTask = previousTask;\n }\n };\n Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {\n return this._zoneDelegate.scheduleTask(this, new ZoneTask('microTask', this, source, callback, data, customSchedule, null));\n };\n Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {\n return this._zoneDelegate.scheduleTask(this, new ZoneTask('macroTask', this, source, callback, data, customSchedule, customCancel));\n };\n Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) {\n return this._zoneDelegate.scheduleTask(this, new ZoneTask('eventTask', this, source, callback, data, customSchedule, customCancel));\n };\n Zone.prototype.cancelTask = function (task) {\n var value = this._zoneDelegate.cancelTask(this, task);\n task.runCount = -1;\n task.cancelFn = null;\n return value;\n };\n Zone.__symbol__ = __symbol__;\n return Zone;\n }());\n \n var ZoneDelegate = (function () {\n function ZoneDelegate(zone, parentDelegate, zoneSpec) {\n this._taskCounts = { microTask: 0, macroTask: 0, eventTask: 0 };\n this.zone = zone;\n this._parentDelegate = parentDelegate;\n this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);\n this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);\n this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate.zone);\n this._interceptZS =\n zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);\n this._interceptDlgt =\n zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);\n this._interceptCurrZone =\n zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate.zone);\n this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);\n this._invokeDlgt =\n zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);\n this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate.zone);\n this._handleErrorZS =\n zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);\n this._handleErrorDlgt =\n zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);\n this._handleErrorCurrZone =\n zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);\n this._scheduleTaskZS =\n zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);\n this._scheduleTaskDlgt =\n zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);\n this._scheduleTaskCurrZone =\n zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);\n this._invokeTaskZS =\n zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);\n this._invokeTaskDlgt =\n zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);\n this._invokeTaskCurrZone =\n zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate.zone);\n this._cancelTaskZS =\n zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);\n this._cancelTaskDlgt =\n zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);\n this._cancelTaskCurrZone =\n zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate.zone);\n this._hasTaskZS = zoneSpec && (zoneSpec.onHasTask ? zoneSpec : parentDelegate._hasTaskZS);\n this._hasTaskDlgt =\n zoneSpec && (zoneSpec.onHasTask ? parentDelegate : parentDelegate._hasTaskDlgt);\n this._hasTaskCurrZone = zoneSpec && (zoneSpec.onHasTask ? this.zone : parentDelegate.zone);\n }\n ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) {\n return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :\n new Zone(targetZone, zoneSpec);\n };\n ZoneDelegate.prototype.intercept = function (targetZone, callback, source) {\n return this._interceptZS ?\n this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :\n callback;\n };\n ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {\n return this._invokeZS ?\n this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :\n callback.apply(applyThis, applyArgs);\n };\n ZoneDelegate.prototype.handleError = function (targetZone, error) {\n return this._handleErrorZS ?\n this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :\n true;\n };\n ZoneDelegate.prototype.scheduleTask = function (targetZone, task) {\n try {\n if (this._scheduleTaskZS) {\n return this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);\n }\n else if (task.scheduleFn) {\n task.scheduleFn(task);\n }\n else if (task.type == 'microTask') {\n scheduleMicroTask(task);\n }\n else {\n throw new Error('Task is missing scheduleFn.');\n }\n return task;\n }\n finally {\n if (targetZone == this.zone) {\n this._updateTaskCount(task.type, 1);\n }\n }\n };\n ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {\n try {\n return this._invokeTaskZS ?\n this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :\n task.callback.apply(applyThis, applyArgs);\n }\n finally {\n if (targetZone == this.zone && (task.type != 'eventTask') &&\n !(task.data && task.data.isPeriodic)) {\n this._updateTaskCount(task.type, -1);\n }\n }\n };\n ZoneDelegate.prototype.cancelTask = function (targetZone, task) {\n var value;\n if (this._cancelTaskZS) {\n value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);\n }\n else if (!task.cancelFn) {\n throw new Error('Task does not support cancellation, or is already canceled.');\n }\n else {\n value = task.cancelFn(task);\n }\n if (targetZone == this.zone) {\n // this should not be in the finally block, because exceptions assume not canceled.\n this._updateTaskCount(task.type, -1);\n }\n return value;\n };\n ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) {\n return this._hasTaskZS &&\n this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);\n };\n ZoneDelegate.prototype._updateTaskCount = function (type, count) {\n var counts = this._taskCounts;\n var prev = counts[type];\n var next = counts[type] = prev + count;\n if (next < 0) {\n throw new Error('More tasks executed then were scheduled.');\n }\n if (prev == 0 || next == 0) {\n var isEmpty = {\n microTask: counts.microTask > 0,\n macroTask: counts.macroTask > 0,\n eventTask: counts.eventTask > 0,\n change: type\n };\n try {\n this.hasTask(this.zone, isEmpty);\n }\n finally {\n if (this._parentDelegate) {\n this._parentDelegate._updateTaskCount(type, count);\n }\n }\n }\n };\n return ZoneDelegate;\n }());\n var ZoneTask = (function () {\n function ZoneTask(type, zone, source, callback, options, scheduleFn, cancelFn) {\n this.runCount = 0;\n this.type = type;\n this.zone = zone;\n this.source = source;\n this.data = options;\n this.scheduleFn = scheduleFn;\n this.cancelFn = cancelFn;\n this.callback = callback;\n var self = this;\n this.invoke = function () {\n _numberOfNestedTaskFrames++;\n try {\n return zone.runTask(self, this, arguments);\n }\n finally {\n if (_numberOfNestedTaskFrames == 1) {\n drainMicroTaskQueue();\n }\n _numberOfNestedTaskFrames--;\n }\n };\n }\n ZoneTask.prototype.toString = function () {\n if (this.data && typeof this.data.handleId !== 'undefined') {\n return this.data.handleId;\n }\n else {\n return Object.prototype.toString.call(this);\n }\n };\n return ZoneTask;\n }());\n var ZoneFrame = (function () {\n function ZoneFrame(parent, zone) {\n this.parent = parent;\n this.zone = zone;\n }\n return ZoneFrame;\n }());\n function __symbol__(name) {\n return '__zone_symbol__' + name;\n }\n \n var symbolSetTimeout = __symbol__('setTimeout');\n var symbolPromise = __symbol__('Promise');\n var symbolThen = __symbol__('then');\n var _currentZoneFrame = new ZoneFrame(null, new Zone(null, null));\n var _currentTask = null;\n var _microTaskQueue = [];\n var _isDrainingMicrotaskQueue = false;\n var _uncaughtPromiseErrors = [];\n var _numberOfNestedTaskFrames = 0;\n function scheduleQueueDrain() {\n // if we are not running in any task, and there has not been anything scheduled\n // we must bootstrap the initial task creation by manually scheduling the drain\n if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {\n // We are not running in Task, so we need to kickstart the microtask queue.\n if (global[symbolPromise]) {\n global[symbolPromise].resolve(0)[symbolThen](drainMicroTaskQueue);\n }\n else {\n global[symbolSetTimeout](drainMicroTaskQueue, 0);\n }\n }\n }\n function scheduleMicroTask(task) {\n scheduleQueueDrain();\n _microTaskQueue.push(task);\n }\n function consoleError(e) {\n var rejection = e && e.rejection;\n if (rejection) {\n console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);\n }\n console.error(e);\n }\n function drainMicroTaskQueue() {\n if (!_isDrainingMicrotaskQueue) {\n _isDrainingMicrotaskQueue = true;\n while (_microTaskQueue.length) {\n var queue = _microTaskQueue;\n _microTaskQueue = [];\n for (var i = 0; i < queue.length; i++) {\n var task = queue[i];\n try {\n task.zone.runTask(task, null, null);\n }\n catch (e) {\n consoleError(e);\n }\n }\n }\n while (_uncaughtPromiseErrors.length) {\n var _loop_1 = function() {\n var uncaughtPromiseError = _uncaughtPromiseErrors.shift();\n try {\n uncaughtPromiseError.zone.runGuarded(function () {\n throw uncaughtPromiseError;\n });\n }\n catch (e) {\n consoleError(e);\n }\n };\n while (_uncaughtPromiseErrors.length) {\n _loop_1();\n }\n }\n _isDrainingMicrotaskQueue = false;\n }\n }\n function isThenable(value) {\n return value && value.then;\n }\n function forwardResolution(value) {\n return value;\n }\n function forwardRejection(rejection) {\n return ZoneAwarePromise.reject(rejection);\n }\n var symbolState = __symbol__('state');\n var symbolValue = __symbol__('value');\n var source = 'Promise.then';\n var UNRESOLVED = null;\n var RESOLVED = true;\n var REJECTED = false;\n var REJECTED_NO_CATCH = 0;\n function makeResolver(promise, state) {\n return function (v) {\n resolvePromise(promise, state, v);\n // Do not return value or you will break the Promise spec.\n };\n }\n function resolvePromise(promise, state, value) {\n if (promise[symbolState] === UNRESOLVED) {\n if (value instanceof ZoneAwarePromise && value.hasOwnProperty(symbolState) &&\n value.hasOwnProperty(symbolValue) && value[symbolState] !== UNRESOLVED) {\n clearRejectedNoCatch(value);\n resolvePromise(promise, value[symbolState], value[symbolValue]);\n }\n else if (isThenable(value)) {\n value.then(makeResolver(promise, state), makeResolver(promise, false));\n }\n else {\n promise[symbolState] = state;\n var queue = promise[symbolValue];\n promise[symbolValue] = value;\n for (var i = 0; i < queue.length;) {\n scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);\n }\n if (queue.length == 0 && state == REJECTED) {\n promise[symbolState] = REJECTED_NO_CATCH;\n try {\n throw new Error('Uncaught (in promise): ' + value +\n (value && value.stack ? '\\n' + value.stack : ''));\n }\n catch (e) {\n var error_1 = e;\n error_1.rejection = value;\n error_1.promise = promise;\n error_1.zone = Zone.current;\n error_1.task = Zone.currentTask;\n _uncaughtPromiseErrors.push(error_1);\n scheduleQueueDrain();\n }\n }\n }\n }\n // Resolving an already resolved promise is a noop.\n return promise;\n }\n function clearRejectedNoCatch(promise) {\n if (promise[symbolState] === REJECTED_NO_CATCH) {\n promise[symbolState] = REJECTED;\n for (var i = 0; i < _uncaughtPromiseErrors.length; i++) {\n if (promise === _uncaughtPromiseErrors[i].promise) {\n _uncaughtPromiseErrors.splice(i, 1);\n break;\n }\n }\n }\n }\n function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {\n clearRejectedNoCatch(promise);\n var delegate = promise[symbolState] ? onFulfilled || forwardResolution : onRejected || forwardRejection;\n zone.scheduleMicroTask(source, function () {\n try {\n resolvePromise(chainPromise, true, zone.run(delegate, null, [promise[symbolValue]]));\n }\n catch (error) {\n resolvePromise(chainPromise, false, error);\n }\n });\n }\n var ZoneAwarePromise = (function () {\n function ZoneAwarePromise(executor) {\n var promise = this;\n if (!(promise instanceof ZoneAwarePromise)) {\n throw new Error('Must be an instanceof Promise.');\n }\n promise[symbolState] = UNRESOLVED;\n promise[symbolValue] = []; // queue;\n try {\n executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));\n }\n catch (e) {\n resolvePromise(promise, false, e);\n }\n }\n ZoneAwarePromise.resolve = function (value) {\n return resolvePromise(new this(null), RESOLVED, value);\n };\n ZoneAwarePromise.reject = function (error) {\n return resolvePromise(new this(null), REJECTED, error);\n };\n ZoneAwarePromise.race = function (values) {\n var resolve;\n var reject;\n var promise = new this(function (res, rej) {\n _a = [res, rej], resolve = _a[0], reject = _a[1];\n var _a;\n });\n function onResolve(value) {\n promise && (promise = null || resolve(value));\n }\n function onReject(error) {\n promise && (promise = null || reject(error));\n }\n for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {\n var value = values_1[_i];\n if (!isThenable(value)) {\n value = this.resolve(value);\n }\n value.then(onResolve, onReject);\n }\n return promise;\n };\n ZoneAwarePromise.all = function (values) {\n var resolve;\n var reject;\n var promise = new this(function (res, rej) {\n resolve = res;\n reject = rej;\n });\n var count = 0;\n var resolvedValues = [];\n for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {\n var value = values_2[_i];\n if (!isThenable(value)) {\n value = this.resolve(value);\n }\n value.then((function (index) { return function (value) {\n resolvedValues[index] = value;\n count--;\n if (!count) {\n resolve(resolvedValues);\n }\n }; })(count), reject);\n count++;\n }\n if (!count)\n resolve(resolvedValues);\n return promise;\n };\n ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {\n var chainPromise = new this.constructor(null);\n var zone = Zone.current;\n if (this[symbolState] == UNRESOLVED) {\n this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);\n }\n else {\n scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);\n }\n return chainPromise;\n };\n ZoneAwarePromise.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n return ZoneAwarePromise;\n }());\n // Protect against aggressive optimizers dropping seemingly unused properties.\n // E.g. Closure Compiler in advanced mode.\n ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;\n ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;\n ZoneAwarePromise['race'] = ZoneAwarePromise.race;\n ZoneAwarePromise['all'] = ZoneAwarePromise.all;\n var NativePromise = global[__symbol__('Promise')] = global['Promise'];\n global['Promise'] = ZoneAwarePromise;\n function patchThen(NativePromise) {\n var NativePromiseProtototype = NativePromise.prototype;\n var NativePromiseThen = NativePromiseProtototype[__symbol__('then')] =\n NativePromiseProtototype.then;\n NativePromiseProtototype.then = function (onResolve, onReject) {\n var nativePromise = this;\n return new ZoneAwarePromise(function (resolve, reject) {\n NativePromiseThen.call(nativePromise, resolve, reject);\n })\n .then(onResolve, onReject);\n };\n }\n if (NativePromise) {\n patchThen(NativePromise);\n if (typeof global['fetch'] !== 'undefined') {\n var fetchPromise = void 0;\n try {\n // In MS Edge this throws\n fetchPromise = global['fetch']();\n }\n catch (e) {\n // In Chrome this throws instead.\n fetchPromise = global['fetch']('about:blank');\n }\n // ignore output to prevent error;\n fetchPromise.then(function () { return null; }, function () { return null; });\n if (fetchPromise.constructor != NativePromise &&\n fetchPromise.constructor != ZoneAwarePromise) {\n patchThen(fetchPromise.constructor);\n }\n }\n }\n // This is not part of public API, but it is usefull for tests, so we expose it.\n Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;\n /*\n * This code patches Error so that:\n * - It ignores un-needed stack frames.\n * - It Shows the associated Zone for reach frame.\n */\n var FrameType;\n (function (FrameType) {\n /// Skip this frame when printing out stack\n FrameType[FrameType[\"blackList\"] = 0] = \"blackList\";\n /// This frame marks zone transition\n FrameType[FrameType[\"transition\"] = 1] = \"transition\";\n })(FrameType || (FrameType = {}));\n var NativeError = global[__symbol__('Error')] = global.Error;\n // Store the frames which should be removed from the stack frames\n var blackListedStackFrames = {};\n // We must find the frame where Error was created, otherwise we assume we don't understand stack\n var zoneAwareFrame;\n global.Error = ZoneAwareError;\n // How should the stack frames be parsed.\n var frameParserStrategy = null;\n var stackRewrite = 'stackRewrite';\n /**\n * This is ZoneAwareError which processes the stack frame and cleans up extra frames as well as\n * adds zone information to it.\n */\n function ZoneAwareError() {\n // Create an Error.\n var error = NativeError.apply(this, arguments);\n this.message = error.message;\n // Save original stack trace\n this.originalStack = error.stack;\n // Process the stack trace and rewrite the frames.\n if (ZoneAwareError[stackRewrite] && this.originalStack) {\n var frames_1 = this.originalStack.split('\\n');\n var zoneFrame = _currentZoneFrame;\n var i = 0;\n // Find the first frame\n while (frames_1[i] !== zoneAwareFrame && i < frames_1.length) {\n i++;\n }\n for (; i < frames_1.length && zoneFrame; i++) {\n var frame = frames_1[i];\n if (frame.trim()) {\n var frameType = blackListedStackFrames.hasOwnProperty(frame) && blackListedStackFrames[frame];\n if (frameType === FrameType.blackList) {\n frames_1.splice(i, 1);\n i--;\n }\n else if (frameType === FrameType.transition) {\n if (zoneFrame.parent) {\n // This is the special frame where zone changed. Print and process it accordingly\n frames_1[i] += \" [\" + zoneFrame.parent.zone.name + \" => \" + zoneFrame.zone.name + \"]\";\n zoneFrame = zoneFrame.parent;\n }\n else {\n zoneFrame = null;\n }\n }\n else {\n frames_1[i] += \" [\" + zoneFrame.zone.name + \"]\";\n }\n }\n }\n this.stack = this.zoneAwareStack = frames_1.join('\\n');\n }\n }\n \n // Copy the prototype so that instanceof operator works as expected\n ZoneAwareError.prototype = Object.create(NativeError.prototype);\n ZoneAwareError[Zone.__symbol__('blacklistedStackFrames')] = blackListedStackFrames;\n ZoneAwareError[stackRewrite] = false;\n if (NativeError.hasOwnProperty('stackTraceLimit')) {\n // Extend default stack limit as we will be removing few frames.\n NativeError.stackTraceLimit = Math.max(NativeError.stackTraceLimit, 15);\n // make sure that ZoneAwareError has the same property which forwards to NativeError.\n Object.defineProperty(ZoneAwareError, 'stackTraceLimit', {\n get: function () {\n return NativeError.stackTraceLimit;\n },\n set: function (value) {\n return NativeError.stackTraceLimit = value;\n }\n });\n }\n if (NativeError.hasOwnProperty('captureStackTrace')) {\n Object.defineProperty(ZoneAwareError, 'captureStackTrace', {\n value: function (targetObject, constructorOpt) {\n NativeError.captureStackTrace(targetObject, constructorOpt);\n }\n });\n }\n Object.defineProperty(ZoneAwareError, 'prepareStackTrace', {\n get: function () {\n return NativeError.prepareStackTrace;\n },\n set: function (value) {\n return NativeError.prepareStackTrace = value;\n }\n });\n // Now we need to populet the `blacklistedStackFrames` as well as find the\n // Now we need to populet the `blacklistedStackFrames` as well as find the\n // run/runGuraded/runTask frames. This is done by creating a detect zone and then threading\n // the execution through all of the above methods so that we can look at the stack trace and\n // find the frames of interest.\n var detectZone = Zone.current.fork({\n name: 'detect',\n onInvoke: function (parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source) {\n // Here only so that it will show up in the stack frame so that it can be black listed.\n return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);\n },\n onHandleError: function (parentZD, current, target, error) {\n if (error.originalStack && Error === ZoneAwareError) {\n var frames_2 = error.originalStack.split(/\\n/);\n var runFrame = false, runGuardedFrame = false, runTaskFrame = false;\n while (frames_2.length) {\n var frame = frames_2.shift();\n // On safari it is possible to have stack frame with no line number.\n // This check makes sure that we don't filter frames on name only (must have\n // linenumber)\n if (/:\\d+:\\d+/.test(frame)) {\n // Get rid of the path so that we don't accidintely find function name in path.\n // In chrome the seperator is `(` and `@` in FF and safari\n // Chrome: at Zone.run (zone.js:100)\n // Chrome: at Zone.run (http://localhost:9876/base/build/lib/zone.js:100:24)\n // FireFox: Zone.prototype.run@http://localhost:9876/base/build/lib/zone.js:101:24\n // Safari: run@http://localhost:9876/base/build/lib/zone.js:101:24\n var fnName = frame.split('(')[0].split('@')[0];\n var frameType = FrameType.transition;\n if (fnName.indexOf('ZoneAwareError') !== -1) {\n zoneAwareFrame = frame;\n }\n if (fnName.indexOf('runGuarded') !== -1) {\n runGuardedFrame = true;\n }\n else if (fnName.indexOf('runTask') !== -1) {\n runTaskFrame = true;\n }\n else if (fnName.indexOf('run') !== -1) {\n runFrame = true;\n }\n else {\n frameType = FrameType.blackList;\n }\n blackListedStackFrames[frame] = frameType;\n // Once we find all of the frames we can stop looking.\n if (runFrame && runGuardedFrame && runTaskFrame) {\n ZoneAwareError[stackRewrite] = true;\n break;\n }\n }\n }\n }\n return false;\n }\n });\n // carefully constructor a stack frame which contains all of the frames of interest which\n // need to be detected and blacklisted.\n var detectRunFn = function () {\n detectZone.run(function () {\n detectZone.runGuarded(function () {\n throw new Error('blacklistStackFrames');\n });\n });\n };\n // Cause the error to extract the stack frames.\n detectZone.runTask(detectZone.scheduleMacroTask('detect', detectRunFn, null, function () { return null; }, null));\n return global['Zone'] = Zone;\n})(typeof window === 'object' && window || typeof self === 'object' && self || global);\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar zoneSymbol = function (n) { return (\"__zone_symbol__\" + n); };\nvar _global$1 = typeof window === 'object' && window || typeof self === 'object' && self || global;\nfunction bindArguments(args, source) {\n for (var i = args.length - 1; i >= 0; i--) {\n if (typeof args[i] === 'function') {\n args[i] = Zone.current.wrap(args[i], source + '_' + i);\n }\n }\n return args;\n}\nfunction patchPrototype(prototype, fnNames) {\n var source = prototype.constructor['name'];\n var _loop_1 = function(i) {\n var name_1 = fnNames[i];\n var delegate = prototype[name_1];\n if (delegate) {\n prototype[name_1] = (function (delegate) {\n return function () {\n return delegate.apply(this, bindArguments(arguments, source + '.' + name_1));\n };\n })(delegate);\n }\n };\n for (var i = 0; i < fnNames.length; i++) {\n _loop_1(i);\n }\n}\nvar isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);\nvar isNode = (!('nw' in _global$1) && typeof process !== 'undefined' &&\n {}.toString.call(process) === '[object process]');\nvar isBrowser = !isNode && !isWebWorker && !!(typeof window !== 'undefined' && window['HTMLElement']);\nfunction patchProperty(obj, prop) {\n var desc = Object.getOwnPropertyDescriptor(obj, prop) || { enumerable: true, configurable: true };\n var originalDesc = Object.getOwnPropertyDescriptor(obj, 'original' + prop);\n if (!originalDesc && desc.get) {\n Object.defineProperty(obj, 'original' + prop, { enumerable: false, configurable: true, get: desc.get });\n }\n // A property descriptor cannot have getter/setter and be writable\n // deleting the writable and value properties avoids this error:\n //\n // TypeError: property descriptors must not specify a value or be writable when a\n // getter or setter has been specified\n delete desc.writable;\n delete desc.value;\n // substr(2) cuz 'onclick' -> 'click', etc\n var eventName = prop.substr(2);\n var _prop = '_' + prop;\n desc.set = function (fn) {\n if (this[_prop]) {\n this.removeEventListener(eventName, this[_prop]);\n }\n if (typeof fn === 'function') {\n var wrapFn = function (event) {\n var result;\n result = fn.apply(this, arguments);\n if (result != undefined && !result)\n event.preventDefault();\n };\n this[_prop] = wrapFn;\n this.addEventListener(eventName, wrapFn, false);\n }\n else {\n this[_prop] = null;\n }\n };\n // The getter would return undefined for unassigned properties but the default value of an\n // unassigned property is null\n desc.get = function () {\n var r = this[_prop] || null;\n // result will be null when use inline event attribute,\n // such as \n // because the onclick function is internal raw uncompiled handler\n // the onclick will be evaluated when first time event was triggered or\n // the property is accessed, https://github.com/angular/zone.js/issues/525\n // so we should use original native get to retrive the handler\n if (r === null) {\n var oriDesc = Object.getOwnPropertyDescriptor(obj, 'original' + prop);\n if (oriDesc && oriDesc.get) {\n r = oriDesc.get.apply(this, arguments);\n if (r) {\n desc.set.apply(this, [r]);\n this.removeAttribute(prop);\n }\n }\n }\n return this[_prop] || null;\n };\n Object.defineProperty(obj, prop, desc);\n}\n\nfunction patchOnProperties(obj, properties) {\n var onProperties = [];\n for (var prop in obj) {\n if (prop.substr(0, 2) == 'on') {\n onProperties.push(prop);\n }\n }\n for (var j = 0; j < onProperties.length; j++) {\n patchProperty(obj, onProperties[j]);\n }\n if (properties) {\n for (var i = 0; i < properties.length; i++) {\n patchProperty(obj, 'on' + properties[i]);\n }\n }\n}\n\nvar EVENT_TASKS = zoneSymbol('eventTasks');\n// For EventTarget\nvar ADD_EVENT_LISTENER = 'addEventListener';\nvar REMOVE_EVENT_LISTENER = 'removeEventListener';\nfunction findExistingRegisteredTask(target, handler, name, capture, remove) {\n var eventTasks = target[EVENT_TASKS];\n if (eventTasks) {\n for (var i = 0; i < eventTasks.length; i++) {\n var eventTask = eventTasks[i];\n var data = eventTask.data;\n var listener = data.handler;\n if ((data.handler === handler || listener.listener === handler) &&\n data.useCapturing === capture && data.eventName === name) {\n if (remove) {\n eventTasks.splice(i, 1);\n }\n return eventTask;\n }\n }\n }\n return null;\n}\nfunction findAllExistingRegisteredTasks(target, name, capture, remove) {\n var eventTasks = target[EVENT_TASKS];\n if (eventTasks) {\n var result = [];\n for (var i = eventTasks.length - 1; i >= 0; i--) {\n var eventTask = eventTasks[i];\n var data = eventTask.data;\n if (data.eventName === name && data.useCapturing === capture) {\n result.push(eventTask);\n if (remove) {\n eventTasks.splice(i, 1);\n }\n }\n }\n return result;\n }\n return null;\n}\nfunction attachRegisteredEvent(target, eventTask, isPrepend) {\n var eventTasks = target[EVENT_TASKS];\n if (!eventTasks) {\n eventTasks = target[EVENT_TASKS] = [];\n }\n if (isPrepend) {\n eventTasks.unshift(eventTask);\n }\n else {\n eventTasks.push(eventTask);\n }\n}\nvar defaultListenerMetaCreator = function (self, args) {\n return {\n useCapturing: args[2],\n eventName: args[0],\n handler: args[1],\n target: self || _global$1,\n name: args[0],\n invokeAddFunc: function (addFnSymbol, delegate) {\n if (delegate && delegate.invoke) {\n return this.target[addFnSymbol](this.eventName, delegate.invoke, this.useCapturing);\n }\n else {\n return this.target[addFnSymbol](this.eventName, delegate, this.useCapturing);\n }\n },\n invokeRemoveFunc: function (removeFnSymbol, delegate) {\n if (delegate && delegate.invoke) {\n return this.target[removeFnSymbol](this.eventName, delegate.invoke, this.useCapturing);\n }\n else {\n return this.target[removeFnSymbol](this.eventName, delegate, this.useCapturing);\n }\n }\n };\n};\nfunction makeZoneAwareAddListener(addFnName, removeFnName, useCapturingParam, allowDuplicates, isPrepend, metaCreator) {\n if (useCapturingParam === void 0) { useCapturingParam = true; }\n if (allowDuplicates === void 0) { allowDuplicates = false; }\n if (isPrepend === void 0) { isPrepend = false; }\n if (metaCreator === void 0) { metaCreator = defaultListenerMetaCreator; }\n var addFnSymbol = zoneSymbol(addFnName);\n var removeFnSymbol = zoneSymbol(removeFnName);\n var defaultUseCapturing = useCapturingParam ? false : undefined;\n function scheduleEventListener(eventTask) {\n var meta = eventTask.data;\n attachRegisteredEvent(meta.target, eventTask, isPrepend);\n return meta.invokeAddFunc(addFnSymbol, eventTask);\n }\n function cancelEventListener(eventTask) {\n var meta = eventTask.data;\n findExistingRegisteredTask(meta.target, eventTask.invoke, meta.eventName, meta.useCapturing, true);\n return meta.invokeRemoveFunc(removeFnSymbol, eventTask);\n }\n return function zoneAwareAddListener(self, args) {\n var data = metaCreator(self, args);\n data.useCapturing = data.useCapturing || defaultUseCapturing;\n // - Inside a Web Worker, `this` is undefined, the context is `global`\n // - When `addEventListener` is called on the global context in strict mode, `this` is undefined\n // see https://github.com/angular/zone.js/issues/190\n var delegate = null;\n if (typeof data.handler == 'function') {\n delegate = data.handler;\n }\n else if (data.handler && data.handler.handleEvent) {\n delegate = function (event) { return data.handler.handleEvent(event); };\n }\n var validZoneHandler = false;\n try {\n // In cross site contexts (such as WebDriver frameworks like Selenium),\n // accessing the handler object here will cause an exception to be thrown which\n // will fail tests prematurely.\n validZoneHandler = data.handler && data.handler.toString() === '[object FunctionWrapper]';\n }\n catch (e) {\n // Returning nothing here is fine, because objects in a cross-site context are unusable\n return;\n }\n // Ignore special listeners of IE11 & Edge dev tools, see\n // https://github.com/angular/zone.js/issues/150\n if (!delegate || validZoneHandler) {\n return data.invokeAddFunc(addFnSymbol, data.handler);\n }\n if (!allowDuplicates) {\n var eventTask = findExistingRegisteredTask(data.target, data.handler, data.eventName, data.useCapturing, false);\n if (eventTask) {\n // we already registered, so this will have noop.\n return data.invokeAddFunc(addFnSymbol, eventTask);\n }\n }\n var zone = Zone.current;\n var source = data.target.constructor['name'] + '.' + addFnName + ':' + data.eventName;\n zone.scheduleEventTask(source, delegate, data, scheduleEventListener, cancelEventListener);\n };\n}\nfunction makeZoneAwareRemoveListener(fnName, useCapturingParam, metaCreator) {\n if (useCapturingParam === void 0) { useCapturingParam = true; }\n if (metaCreator === void 0) { metaCreator = defaultListenerMetaCreator; }\n var symbol = zoneSymbol(fnName);\n var defaultUseCapturing = useCapturingParam ? false : undefined;\n return function zoneAwareRemoveListener(self, args) {\n var data = metaCreator(self, args);\n data.useCapturing = data.useCapturing || defaultUseCapturing;\n // - Inside a Web Worker, `this` is undefined, the context is `global`\n // - When `addEventListener` is called on the global context in strict mode, `this` is undefined\n // see https://github.com/angular/zone.js/issues/190\n var eventTask = findExistingRegisteredTask(data.target, data.handler, data.eventName, data.useCapturing, true);\n if (eventTask) {\n eventTask.zone.cancelTask(eventTask);\n }\n else {\n data.invokeRemoveFunc(symbol, data.handler);\n }\n };\n}\n\n\nvar zoneAwareAddEventListener = makeZoneAwareAddListener(ADD_EVENT_LISTENER, REMOVE_EVENT_LISTENER);\nvar zoneAwareRemoveEventListener = makeZoneAwareRemoveListener(REMOVE_EVENT_LISTENER);\nfunction patchEventTargetMethods(obj, addFnName, removeFnName, metaCreator) {\n if (addFnName === void 0) { addFnName = ADD_EVENT_LISTENER; }\n if (removeFnName === void 0) { removeFnName = REMOVE_EVENT_LISTENER; }\n if (metaCreator === void 0) { metaCreator = defaultListenerMetaCreator; }\n if (obj && obj[addFnName]) {\n patchMethod(obj, addFnName, function () { return makeZoneAwareAddListener(addFnName, removeFnName, true, false, false, metaCreator); });\n patchMethod(obj, removeFnName, function () { return makeZoneAwareRemoveListener(removeFnName, true, metaCreator); });\n return true;\n }\n else {\n return false;\n }\n}\nvar originalInstanceKey = zoneSymbol('originalInstance');\n// wrap some native API on `window`\nfunction patchClass(className) {\n var OriginalClass = _global$1[className];\n if (!OriginalClass)\n return;\n _global$1[className] = function () {\n var a = bindArguments(arguments, className);\n switch (a.length) {\n case 0:\n this[originalInstanceKey] = new OriginalClass();\n break;\n case 1:\n this[originalInstanceKey] = new OriginalClass(a[0]);\n break;\n case 2:\n this[originalInstanceKey] = new OriginalClass(a[0], a[1]);\n break;\n case 3:\n this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);\n break;\n case 4:\n this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);\n break;\n default:\n throw new Error('Arg list too long.');\n }\n };\n var instance = new OriginalClass(function () { });\n var prop;\n for (prop in instance) {\n // https://bugs.webkit.org/show_bug.cgi?id=44721\n if (className === 'XMLHttpRequest' && prop === 'responseBlob')\n continue;\n (function (prop) {\n if (typeof instance[prop] === 'function') {\n _global$1[className].prototype[prop] = function () {\n return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);\n };\n }\n else {\n Object.defineProperty(_global$1[className].prototype, prop, {\n set: function (fn) {\n if (typeof fn === 'function') {\n this[originalInstanceKey][prop] = Zone.current.wrap(fn, className + '.' + prop);\n }\n else {\n this[originalInstanceKey][prop] = fn;\n }\n },\n get: function () {\n return this[originalInstanceKey][prop];\n }\n });\n }\n }(prop));\n }\n for (prop in OriginalClass) {\n if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {\n _global$1[className][prop] = OriginalClass[prop];\n }\n }\n}\n\nfunction createNamedFn(name, delegate) {\n try {\n return (Function('f', \"return function \" + name + \"(){return f(this, arguments)}\"))(delegate);\n }\n catch (e) {\n // if we fail, we must be CSP, just return delegate.\n return function () {\n return delegate(this, arguments);\n };\n }\n}\nfunction patchMethod(target, name, patchFn) {\n var proto = target;\n while (proto && Object.getOwnPropertyNames(proto).indexOf(name) === -1) {\n proto = Object.getPrototypeOf(proto);\n }\n if (!proto && target[name]) {\n // somehow we did not find it, but we can see it. This happens on IE for Window properties.\n proto = target;\n }\n var delegateName = zoneSymbol(name);\n var delegate;\n if (proto && !(delegate = proto[delegateName])) {\n delegate = proto[delegateName] = proto[name];\n proto[name] = createNamedFn(name, patchFn(delegate, delegateName, name));\n }\n return delegate;\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nfunction patchTimer(window, setName, cancelName, nameSuffix) {\n var setNative = null;\n var clearNative = null;\n setName += nameSuffix;\n cancelName += nameSuffix;\n var tasksByHandleId = {};\n function scheduleTask(task) {\n var data = task.data;\n data.args[0] = function () {\n task.invoke.apply(this, arguments);\n delete tasksByHandleId[data.handleId];\n };\n data.handleId = setNative.apply(window, data.args);\n tasksByHandleId[data.handleId] = task;\n return task;\n }\n function clearTask(task) {\n delete tasksByHandleId[task.data.handleId];\n return clearNative(task.data.handleId);\n }\n setNative =\n patchMethod(window, setName, function (delegate) { return function (self, args) {\n if (typeof args[0] === 'function') {\n var zone = Zone.current;\n var options = {\n handleId: null,\n isPeriodic: nameSuffix === 'Interval',\n delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,\n args: args\n };\n var task = zone.scheduleMacroTask(setName, args[0], options, scheduleTask, clearTask);\n if (!task) {\n return task;\n }\n // Node.js must additionally support the ref and unref functions.\n var handle = task.data.handleId;\n if (handle.ref && handle.unref) {\n task.ref = handle.ref.bind(handle);\n task.unref = handle.unref.bind(handle);\n }\n return task;\n }\n else {\n // cause an error by calling it directly.\n return delegate.apply(window, args);\n }\n }; });\n clearNative =\n patchMethod(window, cancelName, function (delegate) { return function (self, args) {\n var task = typeof args[0] === 'number' ? tasksByHandleId[args[0]] : args[0];\n if (task && typeof task.type === 'string') {\n if (task.cancelFn && task.data.isPeriodic || task.runCount === 0) {\n // Do not cancel already canceled functions\n task.zone.cancelTask(task);\n }\n }\n else {\n // cause an error by calling it directly.\n delegate.apply(window, args);\n }\n }; });\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n/*\n * This is necessary for Chrome and Chrome mobile, to enable\n * things like redefining `createdCallback` on an element.\n */\nvar _defineProperty = Object[zoneSymbol('defineProperty')] = Object.defineProperty;\nvar _getOwnPropertyDescriptor = Object[zoneSymbol('getOwnPropertyDescriptor')] =\n Object.getOwnPropertyDescriptor;\nvar _create = Object.create;\nvar unconfigurablesKey = zoneSymbol('unconfigurables');\nfunction propertyPatch() {\n Object.defineProperty = function (obj, prop, desc) {\n if (isUnconfigurable(obj, prop)) {\n throw new TypeError('Cannot assign to read only property \\'' + prop + '\\' of ' + obj);\n }\n var originalConfigurableFlag = desc.configurable;\n if (prop !== 'prototype') {\n desc = rewriteDescriptor(obj, prop, desc);\n }\n return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);\n };\n Object.defineProperties = function (obj, props) {\n Object.keys(props).forEach(function (prop) {\n Object.defineProperty(obj, prop, props[prop]);\n });\n return obj;\n };\n Object.create = function (obj, proto) {\n if (typeof proto === 'object' && !Object.isFrozen(proto)) {\n Object.keys(proto).forEach(function (prop) {\n proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);\n });\n }\n return _create(obj, proto);\n };\n Object.getOwnPropertyDescriptor = function (obj, prop) {\n var desc = _getOwnPropertyDescriptor(obj, prop);\n if (isUnconfigurable(obj, prop)) {\n desc.configurable = false;\n }\n return desc;\n };\n}\n\nfunction _redefineProperty(obj, prop, desc) {\n var originalConfigurableFlag = desc.configurable;\n desc = rewriteDescriptor(obj, prop, desc);\n return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);\n}\n\nfunction isUnconfigurable(obj, prop) {\n return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];\n}\nfunction rewriteDescriptor(obj, prop, desc) {\n desc.configurable = true;\n if (!desc.configurable) {\n if (!obj[unconfigurablesKey]) {\n _defineProperty(obj, unconfigurablesKey, { writable: true, value: {} });\n }\n obj[unconfigurablesKey][prop] = true;\n }\n return desc;\n}\nfunction _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) {\n try {\n return _defineProperty(obj, prop, desc);\n }\n catch (e) {\n if (desc.configurable) {\n // In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's\n // retry with the original flag value\n if (typeof originalConfigurableFlag == 'undefined') {\n delete desc.configurable;\n }\n else {\n desc.configurable = originalConfigurableFlag;\n }\n try {\n return _defineProperty(obj, prop, desc);\n }\n catch (e) {\n var descJson = null;\n try {\n descJson = JSON.stringify(desc);\n }\n catch (e) {\n descJson = descJson.toString();\n }\n console.log(\"Attempting to configure '\" + prop + \"' with descriptor '\" + descJson + \"' on object '\" + obj + \"' and got error, giving up: \" + e);\n }\n }\n else {\n throw e;\n }\n }\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';\nvar NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'\n .split(',');\nvar EVENT_TARGET = 'EventTarget';\nfunction eventTargetPatch(_global) {\n var apis = [];\n var isWtf = _global['wtf'];\n if (isWtf) {\n // Workaround for: https://github.com/google/tracing-framework/issues/555\n apis = WTF_ISSUE_555.split(',').map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET);\n }\n else if (_global[EVENT_TARGET]) {\n apis.push(EVENT_TARGET);\n }\n else {\n // Note: EventTarget is not available in all browsers,\n // if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget\n apis = NO_EVENT_TARGET;\n }\n for (var i = 0; i < apis.length; i++) {\n var type = _global[apis[i]];\n patchEventTargetMethods(type && type.prototype);\n }\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n// we have to patch the instance since the proto is non-configurable\nfunction apply(_global) {\n var WS = _global.WebSocket;\n // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener\n // On older Chrome, no need since EventTarget was already patched\n if (!_global.EventTarget) {\n patchEventTargetMethods(WS.prototype);\n }\n _global.WebSocket = function (a, b) {\n var socket = arguments.length > 1 ? new WS(a, b) : new WS(a);\n var proxySocket;\n // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance\n var onmessageDesc = Object.getOwnPropertyDescriptor(socket, 'onmessage');\n if (onmessageDesc && onmessageDesc.configurable === false) {\n proxySocket = Object.create(socket);\n ['addEventListener', 'removeEventListener', 'send', 'close'].forEach(function (propName) {\n proxySocket[propName] = function () {\n return socket[propName].apply(socket, arguments);\n };\n });\n }\n else {\n // we can patch the real socket\n proxySocket = socket;\n }\n patchOnProperties(proxySocket, ['close', 'error', 'message', 'open']);\n return proxySocket;\n };\n for (var prop in WS) {\n _global.WebSocket[prop] = WS[prop];\n }\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar eventNames = 'copy cut paste abort blur focus canplay canplaythrough change click contextmenu dblclick drag dragend dragenter dragleave dragover dragstart drop durationchange emptied ended input invalid keydown keypress keyup load loadeddata loadedmetadata loadstart message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup pause play playing progress ratechange reset scroll seeked seeking select show stalled submit suspend timeupdate volumechange waiting mozfullscreenchange mozfullscreenerror mozpointerlockchange mozpointerlockerror error webglcontextrestored webglcontextlost webglcontextcreationerror'\n .split(' ');\nfunction propertyDescriptorPatch(_global) {\n if (isNode) {\n return;\n }\n var supportsWebSocket = typeof WebSocket !== 'undefined';\n if (canPatchViaPropertyDescriptor()) {\n // for browsers that we can patch the descriptor: Chrome & Firefox\n if (isBrowser) {\n patchOnProperties(HTMLElement.prototype, eventNames);\n }\n patchOnProperties(XMLHttpRequest.prototype, null);\n if (typeof IDBIndex !== 'undefined') {\n patchOnProperties(IDBIndex.prototype, null);\n patchOnProperties(IDBRequest.prototype, null);\n patchOnProperties(IDBOpenDBRequest.prototype, null);\n patchOnProperties(IDBDatabase.prototype, null);\n patchOnProperties(IDBTransaction.prototype, null);\n patchOnProperties(IDBCursor.prototype, null);\n }\n if (supportsWebSocket) {\n patchOnProperties(WebSocket.prototype, null);\n }\n }\n else {\n // Safari, Android browsers (Jelly Bean)\n patchViaCapturingAllTheEvents();\n patchClass('XMLHttpRequest');\n if (supportsWebSocket) {\n apply(_global);\n }\n }\n}\nfunction canPatchViaPropertyDescriptor() {\n if (isBrowser && !Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') &&\n typeof Element !== 'undefined') {\n // WebKit https://bugs.webkit.org/show_bug.cgi?id=134364\n // IDL interface attributes are not configurable\n var desc = Object.getOwnPropertyDescriptor(Element.prototype, 'onclick');\n if (desc && !desc.configurable)\n return false;\n }\n Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {\n get: function () {\n return true;\n }\n });\n var req = new XMLHttpRequest();\n var result = !!req.onreadystatechange;\n Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {});\n return result;\n}\n\nvar unboundKey = zoneSymbol('unbound');\n// Whenever any eventListener fires, we check the eventListener target and all parents\n// for `onwhatever` properties and replace them with zone-bound functions\n// - Chrome (for now)\nfunction patchViaCapturingAllTheEvents() {\n var _loop_1 = function(i) {\n var property = eventNames[i];\n var onproperty = 'on' + property;\n self.addEventListener(property, function (event) {\n var elt = event.target, bound, source;\n if (elt) {\n source = elt.constructor['name'] + '.' + onproperty;\n }\n else {\n source = 'unknown.' + onproperty;\n }\n while (elt) {\n if (elt[onproperty] && !elt[onproperty][unboundKey]) {\n bound = Zone.current.wrap(elt[onproperty], source);\n bound[unboundKey] = elt[onproperty];\n elt[onproperty] = bound;\n }\n elt = elt.parentElement;\n }\n }, true);\n };\n for (var i = 0; i < eventNames.length; i++) {\n _loop_1(i);\n }\n \n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nfunction registerElementPatch(_global) {\n if (!isBrowser || !('registerElement' in _global.document)) {\n return;\n }\n var _registerElement = document.registerElement;\n var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];\n document.registerElement = function (name, opts) {\n if (opts && opts.prototype) {\n callbacks.forEach(function (callback) {\n var source = 'Document.registerElement::' + callback;\n if (opts.prototype.hasOwnProperty(callback)) {\n var descriptor = Object.getOwnPropertyDescriptor(opts.prototype, callback);\n if (descriptor && descriptor.value) {\n descriptor.value = Zone.current.wrap(descriptor.value, source);\n _redefineProperty(opts.prototype, callback, descriptor);\n }\n else {\n opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);\n }\n }\n else if (opts.prototype[callback]) {\n opts.prototype[callback] = Zone.current.wrap(opts.prototype[callback], source);\n }\n });\n }\n return _registerElement.apply(document, [name, opts]);\n };\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nvar set = 'set';\nvar clear = 'clear';\nvar blockingMethods = ['alert', 'prompt', 'confirm'];\nvar _global = typeof window === 'object' && window || typeof self === 'object' && self || global;\npatchTimer(_global, set, clear, 'Timeout');\npatchTimer(_global, set, clear, 'Interval');\npatchTimer(_global, set, clear, 'Immediate');\npatchTimer(_global, 'request', 'cancel', 'AnimationFrame');\npatchTimer(_global, 'mozRequest', 'mozCancel', 'AnimationFrame');\npatchTimer(_global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');\nfor (var i = 0; i < blockingMethods.length; i++) {\n var name = blockingMethods[i];\n patchMethod(_global, name, function (delegate, symbol, name) {\n return function (s, args) {\n return Zone.current.run(delegate, _global, args, name);\n };\n });\n}\neventTargetPatch(_global);\npropertyDescriptorPatch(_global);\npatchClass('MutationObserver');\npatchClass('WebKitMutationObserver');\npatchClass('FileReader');\npropertyPatch();\nregisterElementPatch(_global);\n// Treat XMLHTTPRequest as a macrotask.\npatchXHR(_global);\nvar XHR_TASK = zoneSymbol('xhrTask');\nvar XHR_SYNC = zoneSymbol('xhrSync');\nvar XHR_LISTENER = zoneSymbol('xhrListener');\nvar XHR_SCHEDULED = zoneSymbol('xhrScheduled');\nfunction patchXHR(window) {\n function findPendingTask(target) {\n var pendingTask = target[XHR_TASK];\n return pendingTask;\n }\n function scheduleTask(task) {\n self[XHR_SCHEDULED] = false;\n var data = task.data;\n // remove existing event listener\n var listener = data.target[XHR_LISTENER];\n if (listener) {\n data.target.removeEventListener('readystatechange', listener);\n }\n var newListener = data.target[XHR_LISTENER] = function () {\n if (data.target.readyState === data.target.DONE) {\n if (!data.aborted && self[XHR_SCHEDULED]) {\n task.invoke();\n }\n }\n };\n data.target.addEventListener('readystatechange', newListener);\n var storedTask = data.target[XHR_TASK];\n if (!storedTask) {\n data.target[XHR_TASK] = task;\n }\n sendNative.apply(data.target, data.args);\n self[XHR_SCHEDULED] = true;\n return task;\n }\n function placeholderCallback() { }\n function clearTask(task) {\n var data = task.data;\n // Note - ideally, we would call data.target.removeEventListener here, but it's too late\n // to prevent it from firing. So instead, we store info for the event listener.\n data.aborted = true;\n return abortNative.apply(data.target, data.args);\n }\n var openNative = patchMethod(window.XMLHttpRequest.prototype, 'open', function () { return function (self, args) {\n self[XHR_SYNC] = args[2] == false;\n return openNative.apply(self, args);\n }; });\n var sendNative = patchMethod(window.XMLHttpRequest.prototype, 'send', function () { return function (self, args) {\n var zone = Zone.current;\n if (self[XHR_SYNC]) {\n // if the XHR is sync there is no task to schedule, just execute the code.\n return sendNative.apply(self, args);\n }\n else {\n var options = { target: self, isPeriodic: false, delay: null, args: args, aborted: false };\n return zone.scheduleMacroTask('XMLHttpRequest.send', placeholderCallback, options, scheduleTask, clearTask);\n }\n }; });\n var abortNative = patchMethod(window.XMLHttpRequest.prototype, 'abort', function (delegate) { return function (self, args) {\n var task = findPendingTask(self);\n if (task && typeof task.type == 'string') {\n // If the XHR has already completed, do nothing.\n if (task.cancelFn == null) {\n return;\n }\n task.zone.cancelTask(task);\n }\n // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no task\n // to cancel. Do nothing.\n }; });\n}\n/// GEO_LOCATION\nif (_global['navigator'] && _global['navigator'].geolocation) {\n patchPrototype(_global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);\n}\n\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n\n})));\n", diff --git a/package.json b/package.json index 2ddc15dd7fc5..6a163f76bc72 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,8 @@ "fast": "yarn start --disable-device-emulation --throttlingMethod=provided", "deploy-viewer": "cd lighthouse-viewer && gulp deploy", "bundlesize": "bundlesize", + "plots-smoke": "bash plots/test/smoke.sh", + "timing-trace": "node lighthouse-core/scripts/generate-timing-trace.js", "changelog": "conventional-changelog --config ./build/changelog-generator/index.js --infile changelog.md --same-file", "type-check": "tsc -p . && cd ./lighthouse-viewer && yarn type-check", "i18n:checks": "./lighthouse-core/scripts/i18n/assert-strings-collected.sh", @@ -139,7 +141,7 @@ "intl-messageformat-parser": "^1.4.0", "jpeg-js": "0.1.2", "js-library-detector": "^5.1.0", - "lighthouse-logger": "^1.0.0", + "lighthouse-logger": "^1.2.0", "lodash.isequal": "^4.5.0", "lookup-closest-locale": "6.0.4", "metaviewport-parser": "0.2.0", diff --git a/typings/artifacts.d.ts b/typings/artifacts.d.ts index 9caaf9e99b9e..56e8e8337daa 100644 --- a/typings/artifacts.d.ts +++ b/typings/artifacts.d.ts @@ -37,6 +37,8 @@ declare global { settings: Config.Settings; /** The URL initially requested and the post-redirects URL that was actually loaded. */ URL: {requestedUrl: string, finalUrl: string}; + /** The timing instrumentation of the gather portion of a run. */ + Timing: Artifacts.MeasureEntry[]; } /** @@ -304,6 +306,11 @@ declare global { }[]; } + export interface MeasureEntry extends PerformanceEntry { + /** Whether timing entry was collected during artifact gathering. */ + gather?: boolean; + } + export interface MetricComputationDataInput { devtoolsLog: DevtoolsLog; trace: Trace; diff --git a/typings/externs.d.ts b/typings/externs.d.ts index e41a0192af3d..ea555850345f 100644 --- a/typings/externs.d.ts +++ b/typings/externs.d.ts @@ -222,6 +222,7 @@ declare global { }; frame?: string; name?: string; + labels?: string; }; pid: number; tid: number; @@ -229,6 +230,7 @@ declare global { dur: number; ph: 'B'|'b'|'D'|'E'|'e'|'F'|'I'|'M'|'N'|'n'|'O'|'R'|'S'|'T'|'X'; s?: 't'; + id?: string; } export interface DevToolsJsonTarget { diff --git a/typings/lhr.d.ts b/typings/lhr.d.ts index 4245aff3272a..8c1403f40cc0 100644 --- a/typings/lhr.d.ts +++ b/typings/lhr.d.ts @@ -59,13 +59,18 @@ declare global { /** Information about the environment in which Lighthouse was run. */ environment: Environment; /** Execution timings for the Lighthouse run */ - timing: {total: number, [t: string]: number}; + timing: Result.Timing; /** The record of all formatted string locations in the LHR and their corresponding source values. */ i18n: {rendererFormattedStrings: I18NRendererStrings, icuMessagePaths: I18NMessages}; } // Result namespace export module Result { + export interface Timing { + entries: Artifacts.MeasureEntry[]; + total: number; + } + export interface Category { /** The string identifier of the category. */ id: string; diff --git a/typings/lighthouse-logger/index.d.ts b/typings/lighthouse-logger/index.d.ts index 2863cda5ba40..f3f290a6c215 100644 --- a/typings/lighthouse-logger/index.d.ts +++ b/typings/lighthouse-logger/index.d.ts @@ -21,5 +21,6 @@ declare module 'lighthouse-logger' { export function reset(): string; /** Retrieves and clears all stored time entries */ export function takeTimeEntries(): PerformanceEntry[]; + export function getTimeEntries(): PerformanceEntry[]; export var events: import('events').EventEmitter; } diff --git a/yarn.lock b/yarn.lock index d983675d83de..bf7a8b2a1947 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5471,6 +5471,14 @@ lighthouse-logger@^1.0.0: dependencies: debug "^2.6.8" +lighthouse-logger@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/lighthouse-logger/-/lighthouse-logger-1.2.0.tgz#b76d56935e9c137e86a04741f6bb9b2776e886ca" + integrity sha512-wzUvdIeJZhRsG6gpZfmSCfysaxNEr43i+QT+Hie94wvHDKFLi4n7C2GqZ4sTC+PH5b5iktmXJvU87rWvhP3lHw== + dependencies: + debug "^2.6.8" + marky "^1.2.0" + load-json-file@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0" @@ -5849,6 +5857,11 @@ map-visit@^1.0.0: dependencies: object-visit "^1.0.0" +marky@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/marky/-/marky-1.2.0.tgz#9617ed647bbbea8f45d19526da33dec70606df42" + integrity sha1-lhftZHu76o9F0ZUm2jPexwYG30I= + md5-hex@^1.2.0: version "1.3.0" resolved "https://registry.yarnpkg.com/md5-hex/-/md5-hex-1.3.0.tgz#d2c4afe983c4370662179b8cad145219135046c4"