lighthouse 9.5.0-dev.20220509 → 9.5.0-dev.20220510

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.
@@ -0,0 +1,246 @@
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
+
19
+ /** @typedef {import('../computed/metrics/responsiveness.js').EventTimingEvent} EventTimingEvent */
20
+ /** @typedef {import('../lib/tracehouse/main-thread-tasks.js').TaskNode} TaskNode */
21
+
22
+ const TASK_THRESHOLD = 1;
23
+
24
+ const UIStrings = {
25
+ /** 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. */
26
+ title: 'Minimizes work during key interaction',
27
+ /** 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. */
28
+ failureTitle: 'Minimize work during key interaction',
29
+ /** 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. */
30
+ description: 'This is the thread-blocking work occurring during the Interaction to Next Paint measurement. [Learn more](https://web.dev/inp/).',
31
+ /** 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. */
32
+ inputDelay: 'Input delay',
33
+ /** 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. */
34
+ processingDelay: 'Processing delay',
35
+ /** 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. */
36
+ presentationDelay: 'Presentation delay',
37
+ /**
38
+ * @description Summary text that identifies the time the browser took to process a user interaction.
39
+ * @example {mousedown} interactionType
40
+ */
41
+ displayValue: `{timeInMs, number, milliseconds}\xa0ms spent on event '{interactionType}'`,
42
+ };
43
+
44
+ const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);
45
+
46
+ /**
47
+ * @fileoverview This metric gives a high-percentile measure of responsiveness to input.
48
+ */
49
+ class WorkDuringInteraction extends Audit {
50
+ /**
51
+ * @return {LH.Audit.Meta}
52
+ */
53
+ static get meta() {
54
+ return {
55
+ id: 'work-during-interaction',
56
+ title: str_(UIStrings.title),
57
+ failureTitle: str_(UIStrings.failureTitle),
58
+ description: str_(UIStrings.description),
59
+ scoreDisplayMode: Audit.SCORING_MODES.NUMERIC,
60
+ supportedModes: ['timespan'],
61
+ requiredArtifacts: ['traces', 'devtoolsLogs'],
62
+ };
63
+ }
64
+
65
+ /**
66
+ * @param {TaskNode} task
67
+ * @param {TaskNode|undefined} parent
68
+ * @param {number} startTs
69
+ * @param {number} endTs
70
+ * @return {number}
71
+ */
72
+ static recursivelyClipTasks(task, parent, startTs, endTs) {
73
+ const taskEventStart = task.event.ts;
74
+ const taskEventEnd = task.endEvent?.ts ?? task.event.ts + Number(task.event.dur || 0);
75
+
76
+ task.startTime = Math.max(startTs, Math.min(endTs, taskEventStart)) / 1000;
77
+ task.endTime = Math.max(startTs, Math.min(endTs, taskEventEnd)) / 1000;
78
+ task.duration = task.endTime - task.startTime;
79
+
80
+ const childTime = task.children
81
+ .map(child => WorkDuringInteraction.recursivelyClipTasks(child, task, startTs, endTs))
82
+ .reduce((sum, child) => sum + child, 0);
83
+ task.selfTime = task.duration - childTime;
84
+ return task.duration;
85
+ }
86
+
87
+ /**
88
+ * Clip the tasks by the start and end points. Take the easy route and drop
89
+ * to duration 0 if out of bounds, since only durations are needed in the
90
+ * end (for now).
91
+ * Assumes owned tasks, so modifies in place. Can be called multiple times on
92
+ * the same `tasks` because always computed from original event timing.
93
+ * @param {Array<TaskNode>} tasks
94
+ * @param {number} startTs
95
+ * @param {number} endTs
96
+ */
97
+ static clipTasksByTs(tasks, startTs, endTs) {
98
+ for (const task of tasks) {
99
+ if (task.parent) continue;
100
+ WorkDuringInteraction.recursivelyClipTasks(task, undefined, startTs, endTs);
101
+ }
102
+ }
103
+
104
+ /**
105
+ * @param {EventTimingEvent} interactionEvent
106
+ */
107
+ static getPhaseTimes(interactionEvent) {
108
+ const interactionData = interactionEvent.args.data;
109
+ const startTs = interactionEvent.ts;
110
+ const navStart = startTs - interactionData.timeStamp * 1000;
111
+ const processingStartTs = navStart + interactionData.processingStart * 1000;
112
+ const processingEndTs = navStart + interactionData.processingEnd * 1000;
113
+ const endTs = startTs + interactionData.duration * 1000;
114
+ return {
115
+ inputDelay: {startTs, endTs: processingStartTs},
116
+ processingDelay: {startTs: processingStartTs, endTs: processingEndTs},
117
+ presentationDelay: {startTs: processingEndTs, endTs},
118
+ };
119
+ }
120
+
121
+ /**
122
+ * @param {EventTimingEvent} interactionEvent
123
+ * @param {LH.Trace} trace
124
+ * @param {LH.Artifacts.ProcessedTrace} processedTrace
125
+ * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords
126
+ * @return {{table: LH.Audit.Details.Table, phases: Record<string, {startTs: number, endTs: number}>}}
127
+ */
128
+ static eventThreadBreakdown(interactionEvent, trace, processedTrace, networkRecords) {
129
+ // Limit to interactionEvent's thread.
130
+ // TODO(bckenny): limit to interactionEvent's navigation.
131
+ const threadEvents = TraceProcessor.filteredTraceSort(trace.traceEvents, evt => {
132
+ return evt.pid === interactionEvent.pid && evt.tid === interactionEvent.tid;
133
+ });
134
+ const traceEndTs = threadEvents.reduce((endTs, evt) => {
135
+ return Math.max(evt.ts + (evt.dur || 0), endTs);
136
+ }, 0);
137
+ // frames is only used for URL attribution, so can include all frames, even if OOPIF.
138
+ const {frames} = processedTrace;
139
+ const threadTasks = MainThreadTasks.getMainThreadTasks(threadEvents, frames, traceEndTs);
140
+
141
+ const phases = WorkDuringInteraction.getPhaseTimes(interactionEvent);
142
+
143
+ /** @type {LH.Audit.Details.TableItem[]} */
144
+ const items = [];
145
+ for (const [phaseName, phaseTimes] of Object.entries(phases)) {
146
+ // Clip tasks to start and end time.
147
+ WorkDuringInteraction.clipTasksByTs(threadTasks, phaseTimes.startTs, phaseTimes.endTs);
148
+ const executionTimings = getExecutionTimingsByURL(threadTasks, networkRecords);
149
+
150
+ const results = [];
151
+ for (const [url, timingByGroupId] of executionTimings) {
152
+ const totalExecutionTimeForURL = Object.values(timingByGroupId)
153
+ .reduce((total, timespanMs) => total + timespanMs);
154
+
155
+ const scriptingTotal = timingByGroupId[taskGroups.scriptEvaluation.id] || 0;
156
+ const layoutTotal = timingByGroupId[taskGroups.styleLayout.id] || 0;
157
+ const renderTotal = timingByGroupId[taskGroups.paintCompositeRender.id] || 0;
158
+
159
+ results.push({
160
+ url: url,
161
+ total: totalExecutionTimeForURL,
162
+ scripting: scriptingTotal,
163
+ layout: layoutTotal,
164
+ render: renderTotal,
165
+ });
166
+ }
167
+
168
+ const filteredResults = results
169
+ .filter(result => result.total > TASK_THRESHOLD)
170
+ .sort((a, b) => b.total - a.total);
171
+
172
+ items.push({
173
+ phase: str_(UIStrings[/** @type {keyof UIStrings} */ (phaseName)]),
174
+ total: (phaseTimes.endTs - phaseTimes.startTs) / 1000,
175
+ subItems: {
176
+ type: 'subitems',
177
+ items: filteredResults,
178
+ },
179
+ });
180
+ }
181
+
182
+ /** @type {LH.Audit.Details.Table['headings']} */
183
+ const headings = [
184
+ /* eslint-disable max-len */
185
+ {key: 'phase', itemType: 'text', subItemsHeading: {key: 'url', itemType: 'url'}, text: 'Phase'},
186
+ {key: 'total', itemType: 'ms', subItemsHeading: {key: 'total', granularity: 1, itemType: 'ms'}, granularity: 1, text: 'Total time'},
187
+ {key: null, itemType: 'ms', subItemsHeading: {key: 'scripting', granularity: 1, itemType: 'ms'}, text: 'Script evaluation'},
188
+ {key: null, itemType: 'ms', subItemsHeading: {key: 'layout', granularity: 1, itemType: 'ms'}, text: taskGroups.styleLayout.label},
189
+ {key: null, itemType: 'ms', subItemsHeading: {key: 'render', granularity: 1, itemType: 'ms'}, text: taskGroups.paintCompositeRender.label},
190
+ /* eslint-enable max-len */
191
+ ];
192
+
193
+ return {
194
+ table: Audit.makeTableDetails(headings, items),
195
+ phases,
196
+ };
197
+ }
198
+
199
+ /**
200
+ * @param {LH.Artifacts} artifacts
201
+ * @param {LH.Audit.Context} context
202
+ * @return {Promise<LH.Audit.Product>}
203
+ */
204
+ static async audit(artifacts, context) {
205
+ const {settings} = context;
206
+ // TODO: responsiveness isn't yet supported by lantern.
207
+ if (settings.throttlingMethod === 'simulate') {
208
+ return {score: null, notApplicable: true};
209
+ }
210
+
211
+ const trace = artifacts.traces[WorkDuringInteraction.DEFAULT_PASS];
212
+ const metricData = {trace, settings};
213
+ const interactionEvent = await ComputedResponsivenes.request(metricData, context);
214
+ // If no interaction, diagnostic audit is n/a.
215
+ if (interactionEvent === null) {
216
+ return {score: null, notApplicable: true};
217
+ }
218
+
219
+ const devtoolsLog = artifacts.devtoolsLogs[WorkDuringInteraction.DEFAULT_PASS];
220
+ // Network records will usually be empty for timespans.
221
+ const networkRecords = await NetworkRecords.request(devtoolsLog, context);
222
+ const processedTrace = await ProcessedTrace.request(trace, context);
223
+ const {table, phases} = WorkDuringInteraction.eventThreadBreakdown(
224
+ interactionEvent, trace, processedTrace, networkRecords);
225
+
226
+ const duration = interactionEvent.args.data.duration;
227
+ const interactionType = interactionEvent.args.data.type;
228
+ const displayValue = str_(UIStrings.displayValue, {timeInMs: duration, interactionType});
229
+
230
+ return {
231
+ score: duration < inpThresholds.p10 ? 1 : 0,
232
+ displayValue,
233
+ details: {
234
+ ...table,
235
+ debugData: {
236
+ type: 'debugdata',
237
+ interactionType,
238
+ phases,
239
+ },
240
+ },
241
+ };
242
+ }
243
+ }
244
+
245
+ module.exports = WorkDuringInteraction;
246
+ module.exports.UIStrings = UIStrings;
@@ -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,19 +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',
14
15
  'metrics/experimental-interaction-to-next-paint',
16
+ 'work-during-interaction',
15
17
  ];
16
18
 
17
19
  /** @type {Record<string, LH.Config.AuditRefJson[]>} */
18
20
  const frCategoryAuditRefExtensions = {
19
21
  'performance': [
20
22
  {id: 'uses-responsive-images-snapshot', weight: 0},
21
- {id: 'experimental-interaction-to-next-paint', weight: 0, group: 'metrics', acronym: 'INP'},
23
+ {id: 'experimental-interaction-to-next-paint', weight: 0, group: 'metrics', acronym: 'INP',
24
+ relevantAudits: m2a.inpRelevantAudits},
25
+ {id: 'work-during-interaction', weight: 0},
22
26
  ],
23
27
  };
24
28
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lighthouse",
3
- "version": "9.5.0-dev.20220509",
3
+ "version": "9.5.0-dev.20220510",
4
4
  "description": "Automated auditing, performance metrics, and best practices for the web.",
5
5
  "main": "./lighthouse-core/index.js",
6
6
  "bin": {
@@ -1658,6 +1658,27 @@
1658
1658
  "lighthouse-core/audits/viewport.js | title": {
1659
1659
  "message": "Has a `<meta name=\"viewport\">` tag with `width` or `initial-scale`"
1660
1660
  },
1661
+ "lighthouse-core/audits/work-during-interaction.js | description": {
1662
+ "message": "This is the thread-blocking work occurring during the Interaction to Next Paint measurement. [Learn more](https://web.dev/inp/)."
1663
+ },
1664
+ "lighthouse-core/audits/work-during-interaction.js | displayValue": {
1665
+ "message": "{timeInMs, number, milliseconds} ms spent on event '{interactionType}'"
1666
+ },
1667
+ "lighthouse-core/audits/work-during-interaction.js | failureTitle": {
1668
+ "message": "Minimize work during key interaction"
1669
+ },
1670
+ "lighthouse-core/audits/work-during-interaction.js | inputDelay": {
1671
+ "message": "Input delay"
1672
+ },
1673
+ "lighthouse-core/audits/work-during-interaction.js | presentationDelay": {
1674
+ "message": "Presentation delay"
1675
+ },
1676
+ "lighthouse-core/audits/work-during-interaction.js | processingDelay": {
1677
+ "message": "Processing delay"
1678
+ },
1679
+ "lighthouse-core/audits/work-during-interaction.js | title": {
1680
+ "message": "Minimizes work during key interaction"
1681
+ },
1661
1682
  "lighthouse-core/config/default-config.js | a11yAriaGroupDescription": {
1662
1683
  "message": "These are opportunities to improve the usage of ARIA in your application which may enhance the experience for users of assistive technology, like a screen reader."
1663
1684
  },
@@ -1658,6 +1658,27 @@
1658
1658
  "lighthouse-core/audits/viewport.js | title": {
1659
1659
  "message": "Ĥáŝ á `<meta name=\"viewport\">` t̂áĝ ẃît́ĥ `width` ór̂ `initial-scale`"
1660
1660
  },
1661
+ "lighthouse-core/audits/work-during-interaction.js | description": {
1662
+ "message": "T̂h́îś îś t̂h́ê t́ĥŕêád̂-b́l̂óĉḱîńĝ ẃôŕk̂ óĉćûŕr̂ín̂ǵ d̂úr̂ín̂ǵ t̂h́ê Ín̂t́êŕâćt̂íôń t̂ó N̂éx̂t́ P̂áîńt̂ ḿêáŝúr̂ém̂én̂t́. [L̂éâŕn̂ ḿôŕê](https://web.dev/inp/)."
1663
+ },
1664
+ "lighthouse-core/audits/work-during-interaction.js | displayValue": {
1665
+ "message": "{timeInMs, number, milliseconds} m̂ś ŝṕêńt̂ ón̂ év̂én̂t́ '{interactionType}'"
1666
+ },
1667
+ "lighthouse-core/audits/work-during-interaction.js | failureTitle": {
1668
+ "message": "M̂ín̂ím̂íẑé ŵór̂ḱ d̂úr̂ín̂ǵ k̂éŷ ín̂t́êŕâćt̂íôń"
1669
+ },
1670
+ "lighthouse-core/audits/work-during-interaction.js | inputDelay": {
1671
+ "message": "Îńp̂út̂ d́êĺâý"
1672
+ },
1673
+ "lighthouse-core/audits/work-during-interaction.js | presentationDelay": {
1674
+ "message": "P̂ŕêśêńt̂át̂íôń d̂él̂áŷ"
1675
+ },
1676
+ "lighthouse-core/audits/work-during-interaction.js | processingDelay": {
1677
+ "message": "P̂ŕôćêśŝín̂ǵ d̂él̂áŷ"
1678
+ },
1679
+ "lighthouse-core/audits/work-during-interaction.js | title": {
1680
+ "message": "M̂ín̂ím̂íẑéŝ ẃôŕk̂ d́ûŕîńĝ ḱêý îńt̂ér̂áĉt́îón̂"
1681
+ },
1661
1682
  "lighthouse-core/config/default-config.js | a11yAriaGroupDescription": {
1662
1683
  "message": "T̂h́êśê ár̂é ôṕp̂ór̂t́ûńît́îéŝ t́ô ím̂ṕr̂óv̂é t̂h́ê úŝáĝé ôf́ ÂŔÎÁ îń ŷóûŕ âṕp̂ĺîćât́îón̂ ẃĥíĉh́ m̂áŷ én̂h́âńĉé t̂h́ê éx̂ṕêŕîén̂ćê f́ôŕ ûśêŕŝ óf̂ áŝśîśt̂ív̂é t̂éĉh́n̂ól̂óĝý, l̂ík̂é â śĉŕêén̂ ŕêád̂ér̂."
1663
1684
  },