Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: implement more insight audits, handle localization #16326

Merged
merged 5 commits into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 31 additions & 6 deletions core/audits/insights/image-delivery-insight.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable no-unused-vars */ // TODO: remove once implemented.

/**
* @license
* Copyright 2025 Google LLC
Expand All @@ -10,7 +8,7 @@ import {UIStrings} from '@paulirish/trace_engine/models/trace/insights/ImageDeli

import {Audit} from '../audit.js';
import * as i18n from '../../lib/i18n/i18n.js';
import {adaptInsightToAuditProduct, makeNodeItemForNodeId} from './insight-audit.js';
import {adaptInsightToAuditProduct} from './insight-audit.js';

// eslint-disable-next-line max-len
const str_ = i18n.createIcuMessageFn('node_modules/@paulirish/trace_engine/models/trace/insights/ImageDelivery.js', UIStrings);
Expand All @@ -36,14 +34,41 @@ class ImageDeliveryInsight extends Audit {
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
// TODO: implement.
return adaptInsightToAuditProduct(artifacts, context, 'ImageDelivery', (insight) => {
if (!insight.optimizableImages.length) {
// TODO: show UIStrings.noOptimizableImages?
return;
}

const relatedEventsMap = insight.relatedEvents && !Array.isArray(insight.relatedEvents) ?
insight.relatedEvents :
null;

/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
/* eslint-disable max-len */
{key: 'url', valueType: 'url', label: str_(i18n.UIStrings.columnURL), subItemsHeading: {key: 'reason', valueType: 'text'}},
{key: 'totalBytes', valueType: 'bytes', label: str_(i18n.UIStrings.columnResourceSize)},
{key: 'wastedBytes', valueType: 'bytes', label: str_(i18n.UIStrings.columnWastedBytes), subItemsHeading: {key: 'wastedBytes', valueType: 'bytes'}},
/* eslint-enable max-len */
];

/** @type {LH.Audit.Details.Table['items']} */
const items = [
];
const items = insight.optimizableImages.map(image => ({
url: image.request.args.data.url,
totalBytes: image.request.args.data.decodedBodyLength,
wastedBytes: image.byteSavings,
subItems: {
type: /** @type {const} */ ('subitems'),
// TODO: when strings update to remove number from "reason" uistrings, update this
// to use `image.optimizations.map(...)` and construct strings from the type.
items: (relatedEventsMap?.get(image.request) ?? []).map((reason, i) => ({
reason,
wastedBytes: image.optimizations[i].byteSavings,
connorjclark marked this conversation as resolved.
Show resolved Hide resolved
})),
},
}));

return Audit.makeTableDetails(headings, items);
});
}
Expand Down
36 changes: 35 additions & 1 deletion core/audits/insights/insight-audit.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ async function adaptInsightToAuditProduct(artifacts, context, insightName, creat
}

const insight = insights.model[insightName];
if (insight instanceof Error) {
return {
errorMessage: insight.message,
errorStack: insight.stack,
score: null,
};
}

const details = createDetails(insight);
if (!details || (details.type === 'table' && details.headings.length === 0)) {
return {
Expand All @@ -63,10 +71,18 @@ async function adaptInsightToAuditProduct(artifacts, context, insightName, creat
metricSavings = {...metricSavings, LCP: /** @type {any} */ (0)};
}

let score = insight.shouldShow ? 0 : 1;
// TODO: change insight model to denote passing/failing/informative. Until then... hack it.
if (insightName === 'LCPPhases') {
score = metricSavings?.LCP ?? 0 >= 1000 ? 0 : 1;
} else if (insightName === 'InteractionToNextPaint') {
score = metricSavings?.INP ?? 0 >= 500 ? 0 : 1;
}

return {
scoreDisplayMode:
insight.metricSavings ? Audit.SCORING_MODES.METRIC_SAVINGS : Audit.SCORING_MODES.NUMERIC,
score: insight.shouldShow ? 0 : 1,
score,
metricSavings,
warnings: insight.warnings,
details,
Expand All @@ -93,7 +109,25 @@ function makeNodeItemForNodeId(traceElements, nodeId) {
return Audit.makeNodeItem(node);
}

/**
* @param {LH.Artifacts.TraceElement[]} traceElements
* @param {number|null|undefined} nodeId
* @param {LH.IcuMessage|string} label
* @return {LH.Audit.Details.Table|undefined}
*/
function maybeMakeNodeElementTable(traceElements, nodeId, label) {
const node = makeNodeItemForNodeId(traceElements, nodeId);
if (!node) {
return;
}

return Audit.makeTableDetails([
{key: 'node', valueType: 'node', label},
], [{node}]);
}

export {
adaptInsightToAuditProduct,
makeNodeItemForNodeId,
maybeMakeNodeElementTable,
};
28 changes: 23 additions & 5 deletions core/audits/insights/interaction-to-next-paint-insight.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable no-unused-vars */ // TODO: remove once implemented.

/**
* @license
* Copyright 2025 Google LLC
Expand All @@ -10,7 +8,7 @@ import {UIStrings} from '@paulirish/trace_engine/models/trace/insights/Interacti

import {Audit} from '../audit.js';
import * as i18n from '../../lib/i18n/i18n.js';
import {adaptInsightToAuditProduct, makeNodeItemForNodeId} from './insight-audit.js';
import {adaptInsightToAuditProduct, maybeMakeNodeElementTable} from './insight-audit.js';

// eslint-disable-next-line max-len
const str_ = i18n.createIcuMessageFn('node_modules/@paulirish/trace_engine/models/trace/insights/InteractionToNextPaint.js', UIStrings);
Expand All @@ -36,15 +34,35 @@ class InteractionToNextPaintInsight extends Audit {
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
// TODO: implement.
return adaptInsightToAuditProduct(artifacts, context, 'InteractionToNextPaint', (insight) => {
const event = insight.longestInteractionEvent;
if (!event) {
connorjclark marked this conversation as resolved.
Show resolved Hide resolved
// TODO: show UIStrings.noInteractions?
return;
}

/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
{key: 'label', valueType: 'text', label: str_(UIStrings.phase)},
{key: 'duration', valueType: 'ms', label: str_(i18n.UIStrings.columnDuration)},
];

/** @type {LH.Audit.Details.Table['items']} */
const items = [
/* eslint-disable max-len */
{phase: 'inputDelay', label: str_(UIStrings.inputDelay), duration: event.inputDelay / 1000},
{phase: 'processingDuration', label: str_(UIStrings.processingDuration), duration: event.mainThreadHandling / 1000},
{phase: 'presentationDelay', label: str_(UIStrings.presentationDelay), duration: event.presentationDelay / 1000},
/* eslint-enable max-len */
];
return Audit.makeTableDetails(headings, items);

return Audit.makeListDetails([
maybeMakeNodeElementTable(
artifacts.TraceElements,
event.args.data.beginEvent.args.data.nodeId,
str_(i18n.UIStrings.columnElement)),
Audit.makeTableDetails(headings, items),
].filter(table => !!table));
});
}
}
Expand Down
56 changes: 45 additions & 11 deletions core/audits/insights/lcp-phases-insight.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable no-unused-vars */ // TODO: remove once implemented.

/**
* @license
* Copyright 2025 Google LLC
Expand All @@ -10,7 +8,7 @@ import {UIStrings} from '@paulirish/trace_engine/models/trace/insights/LCPPhases

import {Audit} from '../audit.js';
import * as i18n from '../../lib/i18n/i18n.js';
import {adaptInsightToAuditProduct, makeNodeItemForNodeId} from './insight-audit.js';
import {adaptInsightToAuditProduct, maybeMakeNodeElementTable} from './insight-audit.js';

// eslint-disable-next-line max-len
const str_ = i18n.createIcuMessageFn('node_modules/@paulirish/trace_engine/models/trace/insights/LCPPhases.js', UIStrings);
Expand All @@ -30,21 +28,57 @@ class LCPPhasesInsight extends Audit {
};
}

/**
* @param {Required<import('@paulirish/trace_engine/models/trace/insights/LCPPhases.js').LCPPhasesInsightModel>['phases']} phases
* @return {LH.Audit.Details.Table}
*/
static makePhaseTable(phases) {
const {ttfb, loadDelay, loadTime, renderDelay} = phases;

/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
{key: 'label', valueType: 'text', label: str_(UIStrings.phase)},
{key: 'duration', valueType: 'ms', label: str_(i18n.UIStrings.columnDuration)},
];

/** @type {LH.Audit.Details.Table['items']} */
let items = [
/* eslint-disable max-len */
{phase: 'timeToFirstByte', label: str_(UIStrings.timeToFirstByte), duration: ttfb},
{phase: 'resourceLoadDelay', label: str_(UIStrings.resourceLoadDelay), duration: loadDelay},
{phase: 'resourceLoadDuration', label: str_(UIStrings.resourceLoadDuration), duration: loadTime},
{phase: 'elementRenderDelay', label: str_(UIStrings.elementRenderDelay), duration: renderDelay},
/* eslint-enable max-len */
];

if (loadDelay === undefined) {
items = items.filter(item => item.phase !== 'resourceLoadDelay');
}
if (loadTime === undefined) {
items = items.filter(item => item.phase !== 'resourceLoadDuration');
}

return Audit.makeTableDetails(headings, items);
}

/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
// TODO: implement.
return adaptInsightToAuditProduct(artifacts, context, 'LCPPhases', (insight) => {
/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
];
/** @type {LH.Audit.Details.Table['items']} */
const items = [
];
return Audit.makeTableDetails(headings, items);
if (!insight.phases) {
return;
}

return Audit.makeListDetails([
maybeMakeNodeElementTable(
artifacts.TraceElements,
insight.lcpEvent?.args.data?.nodeId,
str_(i18n.UIStrings.columnElement)),
LCPPhasesInsight.makePhaseTable(insight.phases),
].filter(table => table !== undefined));
});
}
}
Expand Down
51 changes: 44 additions & 7 deletions core/audits/insights/third-parties-insight.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable no-unused-vars */ // TODO: remove once implemented.

/**
* @license
* Copyright 2025 Google LLC
Expand All @@ -10,11 +8,18 @@ import {UIStrings} from '@paulirish/trace_engine/models/trace/insights/ThirdPart

import {Audit} from '../audit.js';
import * as i18n from '../../lib/i18n/i18n.js';
import {adaptInsightToAuditProduct, makeNodeItemForNodeId} from './insight-audit.js';
import {adaptInsightToAuditProduct} from './insight-audit.js';

// eslint-disable-next-line max-len
const str_ = i18n.createIcuMessageFn('node_modules/@paulirish/trace_engine/models/trace/insights/ThirdParties.js', UIStrings);

/**
* @typedef URLSummary
* @property {number} transferSize
* @property {number} mainThreadTime
* @property {string | LH.IcuMessage} url
*/

class ThirdPartiesInsight extends Audit {
/**
* @return {LH.Audit.Meta}
Expand All @@ -30,21 +35,53 @@ class ThirdPartiesInsight extends Audit {
};
}

/**
* @param {LH.Artifacts.Entity} entity
* @param {import('@paulirish/trace_engine/models/trace/insights/ThirdParties.js').ThirdPartiesInsightModel} insight
* @return {Array<URLSummary>}
*/
static makeSubItems(entity, insight) {
const urls = [...insight.urlsByEntity.get(entity) ?? []];
return urls
.map(url => ({
url,
mainThreadTime: 0,
transferSize: 0,
...insight.summaryByUrl.get(url),
}))
// Sort by main thread time first, then transfer size to break ties.
.sort((a, b) => (b.mainThreadTime - a.mainThreadTime) || (b.transferSize - a.transferSize));
}

/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
// TODO: implement.
return adaptInsightToAuditProduct(artifacts, context, 'ThirdParties', (insight) => {
const thirdPartyEntities = [...insight.summaryByEntity.entries()]
.filter((([entity, _]) => entity !== insight.firstPartyEntity));

/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
/* eslint-disable max-len */
{key: 'entity', valueType: 'text', label: str_(UIStrings.columnThirdParty), subItemsHeading: {key: 'url', valueType: 'url'}},
{key: 'transferSize', granularity: 1, valueType: 'bytes', label: str_(UIStrings.columnTransferSize), subItemsHeading: {key: 'transferSize'}},
{key: 'mainThreadTime', granularity: 1, valueType: 'ms', label: str_(UIStrings.columnMainThreadTime), subItemsHeading: {key: 'mainThreadTime'}},
/* eslint-enable max-len */
];
/** @type {LH.Audit.Details.Table['items']} */
const items = [
];
return Audit.makeTableDetails(headings, items);
const items = thirdPartyEntities.map(([entity, summary]) => ({
entity: entity.name,
transferSize: summary.transferSize,
mainThreadTime: summary.mainThreadTime,
subItems: {
type: /** @type {const} */ ('subitems'),
items: ThirdPartiesInsight.makeSubItems(entity, insight),
},
}));
return Audit.makeTableDetails(headings, items, {isEntityGrouped: true});
});
}
}
Expand Down
Loading
Loading