lighthouse 9.5.0 → 9.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/report/bundle.esm.js +67 -384
  2. package/dist/report/flow.js +20 -25
  3. package/dist/report/standalone.js +18 -23
  4. package/lighthouse-cli/test/smokehouse/core-tests.js +2 -0
  5. package/lighthouse-cli/test/smokehouse/frontends/lib.js +1 -3
  6. package/lighthouse-cli/test/smokehouse/frontends/smokehouse-bin.js +1 -3
  7. package/lighthouse-cli/test/smokehouse/lighthouse-runners/cli.js +1 -0
  8. package/lighthouse-cli/test/smokehouse/readme.md +5 -4
  9. package/lighthouse-cli/test/smokehouse/report-assert.js +16 -13
  10. package/lighthouse-cli/test/smokehouse/version-check-test.js +46 -0
  11. package/lighthouse-cli/test/smokehouse/version-check.js +49 -0
  12. package/lighthouse-core/audits/bootup-time.js +2 -70
  13. package/lighthouse-core/audits/byte-efficiency/duplicated-javascript.js +3 -5
  14. package/lighthouse-core/audits/byte-efficiency/legacy-javascript.js +2 -5
  15. package/lighthouse-core/audits/byte-efficiency/unminified-javascript.js +4 -2
  16. package/lighthouse-core/audits/byte-efficiency/unused-javascript.js +3 -1
  17. package/lighthouse-core/audits/deprecations.js +603 -28
  18. package/lighthouse-core/audits/installable-manifest.js +27 -6
  19. package/lighthouse-core/audits/long-tasks.js +3 -3
  20. package/lighthouse-core/audits/metrics/experimental-interaction-to-next-paint.js +88 -0
  21. package/lighthouse-core/audits/network-requests.js +79 -62
  22. package/lighthouse-core/audits/preload-lcp-image.js +33 -7
  23. package/lighthouse-core/audits/third-party-summary.js +3 -3
  24. package/lighthouse-core/audits/work-during-interaction.js +280 -0
  25. package/lighthouse-core/computed/metrics/responsiveness.js +157 -0
  26. package/lighthouse-core/config/config-helpers.js +1 -1
  27. package/lighthouse-core/config/metrics-to-audits.js +5 -0
  28. package/lighthouse-core/fraggle-rock/config/default-config.js +9 -1
  29. package/lighthouse-core/fraggle-rock/gather/base-artifacts.js +2 -2
  30. package/lighthouse-core/fraggle-rock/gather/session.js +8 -2
  31. package/lighthouse-core/gather/driver.js +21 -14
  32. package/lighthouse-core/gather/gather-runner.js +2 -4
  33. package/lighthouse-core/gather/gatherers/css-usage.js +59 -34
  34. package/lighthouse-core/gather/gatherers/trace-elements.js +21 -2
  35. package/lighthouse-core/lib/arbitrary-equality-map.js +2 -2
  36. package/lighthouse-core/lib/dependency-graph/network-node.js +1 -1
  37. package/lighthouse-core/lib/i18n/i18n.js +2 -0
  38. package/lighthouse-core/lib/minify-trace.js +2 -0
  39. package/lighthouse-core/lib/script-helpers.js +24 -0
  40. package/lighthouse-core/lib/stack-packs.js +8 -5
  41. package/lighthouse-core/lib/tracehouse/task-groups.js +1 -0
  42. package/lighthouse-core/lib/tracehouse/task-summary.js +87 -0
  43. package/lighthouse-core/lib/tracehouse/trace-processor.js +39 -14
  44. package/lighthouse-core/runner.js +1 -1
  45. package/lighthouse-core/util-commonjs.js +20 -18
  46. package/package.json +10 -8
  47. package/report/assets/styles.css +5 -2
  48. package/report/clients/bundle.js +1 -0
  49. package/report/renderer/components.js +1 -1
  50. package/report/renderer/details-renderer.js +4 -4
  51. package/report/renderer/performance-category-renderer.js +15 -11
  52. package/report/renderer/util.js +20 -18
  53. package/report/test/renderer/__snapshots__/report-renderer-axe-test.js.snap +6 -98
  54. package/report/test/renderer/details-renderer-test.js +9 -9
  55. package/report/test/renderer/performance-category-renderer-test.js +31 -0
  56. package/report/test/renderer/report-renderer-axe-test.js +3 -15
  57. package/report/test-assets/faux-psi-template.html +3 -2
  58. package/report/test-assets/faux-psi.js +22 -1
  59. package/shared/localization/locales/en-US.json +244 -4
  60. package/shared/localization/locales/en-XL.json +244 -4
  61. package/shared/localization/swap-locale.js +2 -1
  62. package/third-party/chromium-synchronization/installability-errors-test.js +1 -0
  63. package/third-party/snyk/snapshot.json +2 -3
  64. package/tsconfig.json +1 -0
  65. package/types/artifacts.d.ts +40 -1
  66. package/types/lhr/audit-details.d.ts +3 -1
  67. package/types/smokehouse.d.ts +1 -1
  68. package/changelog.md +0 -5902
  69. package/lighthouse-core/scripts/package.json +0 -4
@@ -0,0 +1,280 @@
1
+ /**
2
+ * @license Copyright 2022 The Lighthouse Authors. All Rights Reserved.
3
+ * 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
4
+ * 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.
5
+ */
6
+ 'use strict';
7
+
8
+ const Audit = require('./audit.js');
9
+ const ComputedResponsivenes = require('../computed/metrics/responsiveness.js');
10
+ const ProcessedTrace = require('../computed/processed-trace.js');
11
+ const i18n = require('../lib/i18n/i18n.js');
12
+ const NetworkRecords = require('../computed/network-records.js');
13
+ const MainThreadTasks = require('../lib/tracehouse/main-thread-tasks.js');
14
+ const {taskGroups} = require('../lib/tracehouse/task-groups.js');
15
+ const TraceProcessor = require('../lib/tracehouse/trace-processor.js');
16
+ const {getExecutionTimingsByURL} = require('../lib/tracehouse/task-summary.js');
17
+ const inpThresholds = require('./metrics/experimental-interaction-to-next-paint.js').defaultOptions;
18
+ const LHError = require('../lib/lh-error.js');
19
+
20
+ /** @typedef {import('../computed/metrics/responsiveness.js').EventTimingEvent} EventTimingEvent */
21
+ /** @typedef {import('../lib/tracehouse/main-thread-tasks.js').TaskNode} TaskNode */
22
+
23
+ const TASK_THRESHOLD = 1;
24
+
25
+ const UIStrings = {
26
+ /** Title of a diagnostic audit that provides detail on the main thread work the browser did during a key user interaction. This descriptive title is shown to users when the amount is acceptable and no user action is required. */
27
+ title: 'Minimizes work during key interaction',
28
+ /** Title of a diagnostic audit that provides detail on the main thread work the browser did during a key user interaction. This imperative title is shown to users when there is a significant amount of execution time that could be reduced. */
29
+ failureTitle: 'Minimize work during key interaction',
30
+ /** Description of the work-during-interaction metric. This description is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */
31
+ description: 'This is the thread-blocking work occurring during the Interaction to Next Paint measurement. [Learn more](https://web.dev/inp/).',
32
+ /** Label for a column in a data table; entries will be information on the time that the browser is delayed before responding to user input. Ideally fits within a ~40 character limit. */
33
+ inputDelay: 'Input delay',
34
+ /** Label for a column in a data table; entries will be information on the time taken by code processing user input that delays a response to the user. Ideally fits within a ~40 character limit. */
35
+ processingDelay: 'Processing delay',
36
+ /** Label for a column in a data table; entries will be information on the time that the browser is delayed before presenting a response to user input on screen. Ideally fits within a ~40 character limit. */
37
+ presentationDelay: 'Presentation delay',
38
+ /**
39
+ * @description Summary text that identifies the time the browser took to process a user interaction.
40
+ * @example {mousedown} interactionType
41
+ */
42
+ displayValue: `{timeInMs, number, milliseconds}\xa0ms spent on event '{interactionType}'`,
43
+ /** Label for a column in a data table; entries will the UI element that was the target of a user interaction (for example, a button that was clicked on). Ideally fits within a ~40 character limit. */
44
+ eventTarget: 'Event target',
45
+ };
46
+
47
+ const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);
48
+
49
+ /**
50
+ * @fileoverview This metric gives a high-percentile measure of responsiveness to input.
51
+ */
52
+ class WorkDuringInteraction extends Audit {
53
+ /**
54
+ * @return {LH.Audit.Meta}
55
+ */
56
+ static get meta() {
57
+ return {
58
+ id: 'work-during-interaction',
59
+ title: str_(UIStrings.title),
60
+ failureTitle: str_(UIStrings.failureTitle),
61
+ description: str_(UIStrings.description),
62
+ scoreDisplayMode: Audit.SCORING_MODES.NUMERIC,
63
+ supportedModes: ['timespan'],
64
+ requiredArtifacts: ['traces', 'devtoolsLogs', 'TraceElements'],
65
+ };
66
+ }
67
+
68
+ /**
69
+ * @param {TaskNode} task
70
+ * @param {TaskNode|undefined} parent
71
+ * @param {number} startTs
72
+ * @param {number} endTs
73
+ * @return {number}
74
+ */
75
+ static recursivelyClipTasks(task, parent, startTs, endTs) {
76
+ const taskEventStart = task.event.ts;
77
+ const taskEventEnd = task.endEvent?.ts ?? task.event.ts + Number(task.event.dur || 0);
78
+
79
+ task.startTime = Math.max(startTs, Math.min(endTs, taskEventStart)) / 1000;
80
+ task.endTime = Math.max(startTs, Math.min(endTs, taskEventEnd)) / 1000;
81
+ task.duration = task.endTime - task.startTime;
82
+
83
+ const childTime = task.children
84
+ .map(child => WorkDuringInteraction.recursivelyClipTasks(child, task, startTs, endTs))
85
+ .reduce((sum, child) => sum + child, 0);
86
+ task.selfTime = task.duration - childTime;
87
+ return task.duration;
88
+ }
89
+
90
+ /**
91
+ * Clip the tasks by the start and end points. Take the easy route and drop
92
+ * to duration 0 if out of bounds, since only durations are needed in the
93
+ * end (for now).
94
+ * Assumes owned tasks, so modifies in place. Can be called multiple times on
95
+ * the same `tasks` because always computed from original event timing.
96
+ * @param {Array<TaskNode>} tasks
97
+ * @param {number} startTs
98
+ * @param {number} endTs
99
+ */
100
+ static clipTasksByTs(tasks, startTs, endTs) {
101
+ for (const task of tasks) {
102
+ if (task.parent) continue;
103
+ WorkDuringInteraction.recursivelyClipTasks(task, undefined, startTs, endTs);
104
+ }
105
+ }
106
+
107
+ /**
108
+ * @param {EventTimingEvent} interactionEvent
109
+ */
110
+ static getPhaseTimes(interactionEvent) {
111
+ const interactionData = interactionEvent.args.data;
112
+ const startTs = interactionEvent.ts;
113
+ const navStart = startTs - interactionData.timeStamp * 1000;
114
+ const processingStartTs = navStart + interactionData.processingStart * 1000;
115
+ const processingEndTs = navStart + interactionData.processingEnd * 1000;
116
+ const endTs = startTs + interactionData.duration * 1000;
117
+ return {
118
+ inputDelay: {startTs, endTs: processingStartTs},
119
+ processingDelay: {startTs: processingStartTs, endTs: processingEndTs},
120
+ presentationDelay: {startTs: processingEndTs, endTs},
121
+ };
122
+ }
123
+
124
+ /**
125
+ * @param {EventTimingEvent} interactionEvent
126
+ * @param {LH.Trace} trace
127
+ * @param {LH.Artifacts.ProcessedTrace} processedTrace
128
+ * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords
129
+ * @return {{table: LH.Audit.Details.Table, phases: Record<string, {startTs: number, endTs: number}>}}
130
+ */
131
+ static getThreadBreakdownTable(interactionEvent, trace, processedTrace, networkRecords) {
132
+ // Limit to interactionEvent's thread.
133
+ // TODO(bckenny): limit to interactionEvent's navigation.
134
+ const threadEvents = TraceProcessor.filteredTraceSort(trace.traceEvents, evt => {
135
+ return evt.pid === interactionEvent.pid && evt.tid === interactionEvent.tid;
136
+ });
137
+ const traceEndTs = threadEvents.reduce((endTs, evt) => {
138
+ return Math.max(evt.ts + (evt.dur || 0), endTs);
139
+ }, 0);
140
+ // frames is only used for URL attribution, so can include all frames, even if OOPIF.
141
+ const {frames} = processedTrace;
142
+ const threadTasks = MainThreadTasks.getMainThreadTasks(threadEvents, frames, traceEndTs);
143
+
144
+ const phases = WorkDuringInteraction.getPhaseTimes(interactionEvent);
145
+
146
+ /** @type {LH.Audit.Details.TableItem[]} */
147
+ const items = [];
148
+ for (const [phaseName, phaseTimes] of Object.entries(phases)) {
149
+ // Clip tasks to start and end time.
150
+ WorkDuringInteraction.clipTasksByTs(threadTasks, phaseTimes.startTs, phaseTimes.endTs);
151
+ const executionTimings = getExecutionTimingsByURL(threadTasks, networkRecords);
152
+
153
+ const results = [];
154
+ for (const [url, timingByGroupId] of executionTimings) {
155
+ const totalExecutionTimeForURL = Object.values(timingByGroupId)
156
+ .reduce((total, timespanMs) => total + timespanMs);
157
+
158
+ const scriptingTotal = timingByGroupId[taskGroups.scriptEvaluation.id] || 0;
159
+ const layoutTotal = timingByGroupId[taskGroups.styleLayout.id] || 0;
160
+ const renderTotal = timingByGroupId[taskGroups.paintCompositeRender.id] || 0;
161
+
162
+ results.push({
163
+ url: url,
164
+ total: totalExecutionTimeForURL,
165
+ scripting: scriptingTotal,
166
+ layout: layoutTotal,
167
+ render: renderTotal,
168
+ });
169
+ }
170
+
171
+ const filteredResults = results
172
+ .filter(result => result.total > TASK_THRESHOLD)
173
+ .sort((a, b) => b.total - a.total);
174
+
175
+ items.push({
176
+ phase: str_(UIStrings[/** @type {keyof UIStrings} */ (phaseName)]),
177
+ total: (phaseTimes.endTs - phaseTimes.startTs) / 1000,
178
+ subItems: {
179
+ type: 'subitems',
180
+ items: filteredResults,
181
+ },
182
+ });
183
+ }
184
+
185
+ /** @type {LH.Audit.Details.Table['headings']} */
186
+ const headings = [
187
+ /* eslint-disable max-len */
188
+ {key: 'phase', itemType: 'text', subItemsHeading: {key: 'url', itemType: 'url'}, text: 'Phase'},
189
+ {key: 'total', itemType: 'ms', subItemsHeading: {key: 'total', granularity: 1, itemType: 'ms'}, granularity: 1, text: 'Total time'},
190
+ {key: null, itemType: 'ms', subItemsHeading: {key: 'scripting', granularity: 1, itemType: 'ms'}, text: 'Script evaluation'},
191
+ {key: null, itemType: 'ms', subItemsHeading: {key: 'layout', granularity: 1, itemType: 'ms'}, text: taskGroups.styleLayout.label},
192
+ {key: null, itemType: 'ms', subItemsHeading: {key: 'render', granularity: 1, itemType: 'ms'}, text: taskGroups.paintCompositeRender.label},
193
+ /* eslint-enable max-len */
194
+ ];
195
+
196
+ return {
197
+ table: Audit.makeTableDetails(headings, items),
198
+ phases,
199
+ };
200
+ }
201
+
202
+ /**
203
+ * @param {LH.Artifacts['TraceElements']} traceElements
204
+ * @return {LH.Audit.Details.Table | undefined}
205
+ */
206
+ static getTraceElementTable(traceElements) {
207
+ const responsivenessElement = traceElements.find(el => el.traceEventType === 'responsiveness');
208
+ if (!responsivenessElement) return;
209
+
210
+ /** @type {LH.Audit.Details.Table['headings']} */
211
+ const headings = [
212
+ {key: 'node', itemType: 'node', text: str_(UIStrings.eventTarget)},
213
+ ];
214
+ const elementItems = [{node: Audit.makeNodeItem(responsivenessElement.node)}];
215
+
216
+ return Audit.makeTableDetails(headings, elementItems);
217
+ }
218
+
219
+ /**
220
+ * @param {LH.Artifacts} artifacts
221
+ * @param {LH.Audit.Context} context
222
+ * @return {Promise<LH.Audit.Product>}
223
+ */
224
+ static async audit(artifacts, context) {
225
+ const {settings} = context;
226
+ // TODO: responsiveness isn't yet supported by lantern.
227
+ if (settings.throttlingMethod === 'simulate') {
228
+ return {score: null, notApplicable: true};
229
+ }
230
+
231
+ const trace = artifacts.traces[WorkDuringInteraction.DEFAULT_PASS];
232
+ const metricData = {trace, settings};
233
+ const interactionEvent = await ComputedResponsivenes.request(metricData, context);
234
+ // If no interaction, diagnostic audit is n/a.
235
+ if (interactionEvent === null) {
236
+ return {score: null, notApplicable: true};
237
+ }
238
+ // TODO: remove workaround once 103.0.5052.0 is sufficiently released.
239
+ if (interactionEvent.name === 'FallbackTiming') {
240
+ throw new LHError(
241
+ LHError.errors.UNSUPPORTED_OLD_CHROME,
242
+ {featureName: 'detailed EventTiming trace events'}
243
+ );
244
+ }
245
+
246
+ const auditDetailsItems = [];
247
+
248
+ const traceElementItem = WorkDuringInteraction.getTraceElementTable(artifacts.TraceElements);
249
+ if (traceElementItem) auditDetailsItems.push(traceElementItem);
250
+
251
+ const devtoolsLog = artifacts.devtoolsLogs[WorkDuringInteraction.DEFAULT_PASS];
252
+ // Network records will usually be empty for timespans.
253
+ const networkRecords = await NetworkRecords.request(devtoolsLog, context);
254
+ const processedTrace = await ProcessedTrace.request(trace, context);
255
+ const {table: breakdownTable, phases} = WorkDuringInteraction.getThreadBreakdownTable(
256
+ interactionEvent, trace, processedTrace, networkRecords);
257
+ auditDetailsItems.push(breakdownTable);
258
+
259
+ const interactionType = interactionEvent.args.data.type;
260
+ auditDetailsItems.push({
261
+ type: /** @type {const} */ ('debugdata'),
262
+ interactionType,
263
+ phases,
264
+ });
265
+
266
+ const duration = interactionEvent.args.data.duration;
267
+ const displayValue = str_(UIStrings.displayValue, {timeInMs: duration, interactionType});
268
+ return {
269
+ score: duration < inpThresholds.p10 ? 1 : 0,
270
+ displayValue,
271
+ details: {
272
+ type: 'list',
273
+ items: auditDetailsItems,
274
+ },
275
+ };
276
+ }
277
+ }
278
+
279
+ module.exports = WorkDuringInteraction;
280
+ module.exports.UIStrings = UIStrings;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * @license Copyright 2022 The Lighthouse Authors. All Rights Reserved.
3
+ * 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
4
+ * 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.
5
+ */
6
+ 'use strict';
7
+
8
+ /**
9
+ * @fileoverview Returns a high-percentle (usually 98th) measure of how long it
10
+ * takes the page to visibly respond to user input (or null, if there was no
11
+ * user input in the provided trace).
12
+ */
13
+
14
+ /** @typedef {LH.Trace.CompleteEvent & {name: 'Responsiveness.Renderer.UserInteraction', args: {frame: string, data: {interactionType: 'drag'|'keyboard'|'tapOrClick', maxDuration: number}}}} ResponsivenessEvent */
15
+ /** @typedef {'keydown'|'keypress'|'keyup'|'mousedown'|'mouseup'|'pointerdown'|'pointerup'|'click'} EventTimingType */
16
+ /**
17
+ * @typedef EventTimingData
18
+ * @property {string} frame
19
+ * @property {number} timeStamp The time of user interaction (in ms from navStart).
20
+ * @property {number} processingStart The start of interaction handling (in ms from navStart).
21
+ * @property {number} processingEnd The end of interaction handling (in ms from navStart).
22
+ * @property {number} duration The time from user interaction to browser paint (in ms).
23
+ * @property {EventTimingType} type
24
+ * @property {number} nodeId
25
+ * @property {number} interactionId
26
+ */
27
+ /** @typedef {LH.Trace.AsyncEvent & {name: 'EventTiming', args: {data: EventTimingData}}} EventTimingEvent */
28
+ /**
29
+ * A fallback EventTiming placeholder, used if updated EventTiming events are not available.
30
+ * TODO: Remove once 103.0.5052.0 is sufficiently released.
31
+ * @typedef {{name: 'FallbackTiming', duration: number}} FallbackTimingEvent
32
+ */
33
+
34
+ const makeComputedArtifact = require('../computed-artifact.js');
35
+ const ProcessedTrace = require('../processed-trace.js');
36
+
37
+ const KEYBOARD_EVENTS = new Set(['keydown', 'keypress', 'keyup']);
38
+ const CLICK_TAP_DRAG_EVENTS = new Set([
39
+ 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'click']);
40
+ /** A map of Responsiveness `interactionType` to matching EventTiming `type`s. */
41
+ const interactionTypeToType = {
42
+ keyboard: KEYBOARD_EVENTS,
43
+ tapOrClick: CLICK_TAP_DRAG_EVENTS,
44
+ drag: CLICK_TAP_DRAG_EVENTS,
45
+ };
46
+
47
+ class Responsiveness {
48
+ /**
49
+ * @param {LH.Artifacts.ProcessedTrace} processedTrace
50
+ * @return {ResponsivenessEvent|null}
51
+ */
52
+ static getHighPercentileResponsiveness(processedTrace) {
53
+ const responsivenessEvents = processedTrace.frameTreeEvents
54
+ // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/timing/responsiveness_metrics.cc;l=146-150;drc=a1a2302f30b0a58f7669a41c80acdf1fa11958dd
55
+ .filter(/** @return {e is ResponsivenessEvent} */ e => {
56
+ return e.name === 'Responsiveness.Renderer.UserInteraction';
57
+ }).sort((a, b) => b.args.data.maxDuration - a.args.data.maxDuration);
58
+
59
+ // If there were no interactions with the page, the metric is N/A.
60
+ if (responsivenessEvents.length === 0) {
61
+ return null;
62
+ }
63
+
64
+ // INP is the "nearest-rank"/inverted_cdf 98th percentile, except Chrome only
65
+ // keeps the 10 worst events around, so it can never be more than the 10th from
66
+ // last array element. To keep things simpler, sort desc and pick from front.
67
+ // See https://source.chromium.org/chromium/chromium/src/+/main:components/page_load_metrics/browser/responsiveness_metrics_normalization.cc;l=45-59;drc=cb0f9c8b559d9c7c3cb4ca94fc1118cc015d38ad
68
+ const index = Math.min(9, Math.floor(responsivenessEvents.length / 50));
69
+
70
+ return responsivenessEvents[index];
71
+ }
72
+
73
+ /**
74
+ * Finds the interaction event that was probably the responsivenessEvent.maxDuration
75
+ * source.
76
+ * Note that (presumably due to rounding to ms), the interaction duration may not
77
+ * be the same value as `maxDuration`, just the closest value. Function will throw
78
+ * if the closest match is off by more than 4ms.
79
+ * TODO: this doesn't try to match inputs to interactions and break ties if more than
80
+ * one interaction had this duration by returning the first found.
81
+ * @param {ResponsivenessEvent} responsivenessEvent
82
+ * @param {LH.Trace} trace
83
+ * @return {EventTimingEvent|FallbackTimingEvent}
84
+ */
85
+ static findInteractionEvent(responsivenessEvent, {traceEvents}) {
86
+ const candidates = traceEvents.filter(/** @return {evt is EventTimingEvent} */ evt => {
87
+ // Examine only beginning/instant EventTiming events.
88
+ return evt.name === 'EventTiming' && evt.ph !== 'e';
89
+ });
90
+
91
+ if (candidates.length && !candidates.some(candidate => candidate.args.data?.frame)) {
92
+ // Full EventTiming data added in https://crrev.com/c/3632661
93
+ return {
94
+ name: 'FallbackTiming',
95
+ duration: responsivenessEvent.args.data.maxDuration,
96
+ };
97
+ }
98
+
99
+ const {maxDuration, interactionType} = responsivenessEvent.args.data;
100
+ let bestMatchEvent;
101
+ let minDurationDiff = Number.POSITIVE_INFINITY;
102
+ for (const candidate of candidates) {
103
+ // Must be from same frame.
104
+ if (candidate.args.data.frame !== responsivenessEvent.args.frame) continue;
105
+
106
+ // TODO(bckenny): must be in same navigation as well.
107
+
108
+ const {type, duration} = candidate.args.data;
109
+ // Discard if type is incompatible with responsiveness interactionType.
110
+ const matchingTypes = interactionTypeToType[interactionType];
111
+ if (!matchingTypes) {
112
+ throw new Error(`unexpected responsiveness interactionType '${interactionType}'`);
113
+ }
114
+ if (!matchingTypes.has(type)) continue;
115
+
116
+ const durationDiff = Math.abs(duration - maxDuration);
117
+ if (durationDiff < minDurationDiff) {
118
+ bestMatchEvent = candidate;
119
+ minDurationDiff = durationDiff;
120
+ }
121
+ }
122
+
123
+ if (!bestMatchEvent) {
124
+ throw new Error(`no interaction event found for responsiveness type '${interactionType}'`);
125
+ }
126
+ // TODO: seems to regularly happen up to 3ms and as high as 4. Allow for up to 5ms to be sure.
127
+ if (minDurationDiff > 5) {
128
+ throw new Error(`no interaction event found within 5ms of responsiveness maxDuration (max: ${maxDuration}, closest ${bestMatchEvent.args.data.duration})`); // eslint-disable-line max-len
129
+ }
130
+
131
+ return bestMatchEvent;
132
+ }
133
+
134
+ /**
135
+ * @param {{trace: LH.Trace, settings: Immutable<LH.Config.Settings>}} data
136
+ * @param {LH.Artifacts.ComputedContext} context
137
+ * @return {Promise<EventTimingEvent|FallbackTimingEvent|null>}
138
+ */
139
+ static async compute_(data, context) {
140
+ const {settings, trace} = data;
141
+ if (settings.throttlingMethod === 'simulate') {
142
+ throw new Error('Responsiveness currently unsupported by simulated throttling');
143
+ }
144
+
145
+ const processedTrace = await ProcessedTrace.request(trace, context);
146
+ const responsivenessEvent = Responsiveness.getHighPercentileResponsiveness(processedTrace);
147
+ if (!responsivenessEvent) return null;
148
+
149
+ const interactionEvent = Responsiveness.findInteractionEvent(responsivenessEvent, trace);
150
+ return JSON.parse(JSON.stringify(interactionEvent));
151
+ }
152
+ }
153
+
154
+ module.exports = makeComputedArtifact(Responsiveness, [
155
+ 'trace',
156
+ 'settings',
157
+ ]);
@@ -6,7 +6,7 @@
6
6
  'use strict';
7
7
 
8
8
  const path = require('path');
9
- const {isEqual: isDeepEqual} = require('lodash');
9
+ const isDeepEqual = require('lodash/isEqual.js');
10
10
  const constants = require('./constants.js');
11
11
  const Budget = require('./budget.js');
12
12
  const ConfigPlugin = require('./config-plugin.js');
@@ -48,9 +48,14 @@ const clsRelevantAudits = [
48
48
  // 'preload-fonts', // actually in BP, rather than perf
49
49
  ];
50
50
 
51
+ const inpRelevantAudits = [
52
+ 'work-during-interaction',
53
+ ];
54
+
51
55
  module.exports = {
52
56
  fcpRelevantAudits,
53
57
  lcpRelevantAudits,
54
58
  tbtRelevantAudits,
55
59
  clsRelevantAudits,
60
+ inpRelevantAudits,
56
61
  };
@@ -6,17 +6,23 @@
6
6
  'use strict';
7
7
 
8
8
  const legacyDefaultConfig = require('../../config/default-config.js');
9
+ const m2a = require('../../config/metrics-to-audits.js');
9
10
  const {deepClone} = require('../../config/config-helpers.js');
10
11
 
11
12
  /** @type {LH.Config.AuditJson[]} */
12
13
  const frAudits = [
13
14
  'byte-efficiency/uses-responsive-images-snapshot',
15
+ 'metrics/experimental-interaction-to-next-paint',
16
+ 'work-during-interaction',
14
17
  ];
15
18
 
16
19
  /** @type {Record<string, LH.Config.AuditRefJson[]>} */
17
20
  const frCategoryAuditRefExtensions = {
18
21
  'performance': [
19
22
  {id: 'uses-responsive-images-snapshot', weight: 0},
23
+ {id: 'experimental-interaction-to-next-paint', weight: 0, group: 'metrics', acronym: 'INP',
24
+ relevantAudits: m2a.inpRelevantAudits},
25
+ {id: 'work-during-interaction', weight: 0},
20
26
  ],
21
27
  };
22
28
 
@@ -97,7 +103,6 @@ const defaultConfig = {
97
103
  {id: artifacts.EmbeddedContent, gatherer: 'seo/embedded-content'},
98
104
  {id: artifacts.FontSize, gatherer: 'seo/font-size'},
99
105
  {id: artifacts.Inputs, gatherer: 'inputs'},
100
- {id: artifacts.FullPageScreenshot, gatherer: 'full-page-screenshot'},
101
106
  {id: artifacts.GlobalListeners, gatherer: 'global-listeners'},
102
107
  {id: artifacts.IFrameElements, gatherer: 'iframe-elements'},
103
108
  {id: artifacts.ImageElements, gatherer: 'image-elements'},
@@ -126,6 +131,9 @@ const defaultConfig = {
126
131
  // Artifact copies are renamed for compatibility with legacy artifacts.
127
132
  {id: artifacts.devtoolsLogs, gatherer: 'devtools-log-compat'},
128
133
  {id: artifacts.traces, gatherer: 'trace-compat'},
134
+
135
+ // FullPageScreenshot comes at the very end so all other node analysis is captured.
136
+ {id: artifacts.FullPageScreenshot, gatherer: 'full-page-screenshot'},
129
137
  ],
130
138
  navigations: [
131
139
  {
@@ -6,7 +6,7 @@
6
6
  'use strict';
7
7
 
8
8
  const log = require('lighthouse-logger');
9
- const {isEqual} = require('lodash');
9
+ const isDeepEqual = require('lodash/isEqual.js');
10
10
  const {
11
11
  getBrowserVersion,
12
12
  getBenchmarkIndex,
@@ -58,7 +58,7 @@ function deduplicateWarnings(warnings) {
58
58
  const unique = [];
59
59
 
60
60
  for (const warning of warnings) {
61
- if (unique.some(existing => isEqual(warning, existing))) continue;
61
+ if (unique.some(existing => isDeepEqual(warning, existing))) continue;
62
62
  unique.push(warning);
63
63
  }
64
64
 
@@ -96,7 +96,7 @@ class ProtocolSession {
96
96
  /** @param {import('puppeteer').CDPSession} session */
97
97
  const listener = session => callback(new ProtocolSession(session));
98
98
  this._callbackMap.set(callback, listener);
99
- this._session.connection().on('sessionattached', listener);
99
+ this._getConnection().on('sessionattached', listener);
100
100
  }
101
101
 
102
102
  /**
@@ -106,7 +106,7 @@ class ProtocolSession {
106
106
  removeSessionAttachedListener(callback) {
107
107
  const listener = this._callbackMap.get(callback);
108
108
  if (!listener) return;
109
- this._session.connection().off('sessionattached', listener);
109
+ this._getConnection().off('sessionattached', listener);
110
110
  }
111
111
 
112
112
  /**
@@ -171,6 +171,12 @@ class ProtocolSession {
171
171
  this._session.removeAllListeners();
172
172
  await this._session.detach();
173
173
  }
174
+
175
+ _getConnection() {
176
+ const connection = this._session.connection();
177
+ if (!connection) throw new Error('Connection has been closed.');
178
+ return connection;
179
+ }
174
180
  }
175
181
 
176
182
  module.exports = ProtocolSession;
@@ -304,20 +304,27 @@ class Driver {
304
304
  return;
305
305
  }
306
306
 
307
- // Events from subtargets will be stringified and sent back on `Target.receivedMessageFromTarget`.
308
- // We want to receive information about network requests from iframes, so enable the Network domain.
309
- await this.sendCommandToSession('Network.enable', event.sessionId);
310
-
311
- // We also want to receive information about subtargets of subtargets, so make sure we autoattach recursively.
312
- await this.sendCommandToSession('Target.setAutoAttach', event.sessionId, {
313
- autoAttach: true,
314
- flatten: true,
315
- // Pause targets on startup so we don't miss anything
316
- waitForDebuggerOnStart: true,
317
- });
318
-
319
- // We suspended the target when we auto-attached, so make sure it goes back to being normal.
320
- await this.sendCommandToSession('Runtime.runIfWaitingForDebugger', event.sessionId);
307
+ // Note: This is only reached for _out of process_ iframes (OOPIFs).
308
+ // If the iframe is in the same process as its embedding document, that means they
309
+ // share the same target.
310
+
311
+ // A target won't acknowledge/respond to protocol methods (or, at least for Network.enable)
312
+ // until it is resumed. But also we're paranoid about sending Network.enable _slightly_ too late,
313
+ // so we issue that method first. Therefore, we don't await on this serially, but await all at once.
314
+ await Promise.all([
315
+ // Events from subtargets will be stringified and sent back on `Target.receivedMessageFromTarget`.
316
+ // We want to receive information about network requests from iframes, so enable the Network domain.
317
+ this.sendCommandToSession('Network.enable', event.sessionId),
318
+ // We also want to receive information about subtargets of subtargets, so make sure we autoattach recursively.
319
+ this.sendCommandToSession('Target.setAutoAttach', event.sessionId, {
320
+ autoAttach: true,
321
+ flatten: true,
322
+ // Pause targets on startup so we don't miss anything
323
+ waitForDebuggerOnStart: true,
324
+ }),
325
+ // We suspended the target when we auto-attached, so make sure it goes back to being normal.
326
+ this.sendCommandToSession('Runtime.runIfWaitingForDebugger', event.sessionId),
327
+ ]);
321
328
  }
322
329
 
323
330
  /**
@@ -438,10 +438,8 @@ class GatherRunner {
438
438
  }
439
439
 
440
440
  try {
441
- if (baseArtifacts.WebAppManifest) {
442
- baseArtifacts.InstallabilityErrors = await InstallabilityErrors.getInstallabilityErrors(
443
- passContext.driver.defaultSession);
444
- }
441
+ baseArtifacts.InstallabilityErrors = await InstallabilityErrors.getInstallabilityErrors(
442
+ passContext.driver.defaultSession);
445
443
  } catch (err) {
446
444
  log.error('GatherRunner InstallabilityErrors', err);
447
445
  baseArtifacts.InstallabilityErrors = {