166 lines
9.2 KiB
JavaScript
166 lines
9.2 KiB
JavaScript
/**
|
||
* Lab measurements of one page in Chromium (Playwright + the DevTools protocol) — used by `pnpm perf:measure`
|
||
* (scripts/perf-measure.mjs, numbers for docs/performance.md) and by the budget gate (e2e/performance.spec.ts).
|
||
*
|
||
* Profiles follow Lighthouse's defaults so the numbers compare with PageSpeed Insights' lab data:
|
||
* - mobile: 412×823 at DPR 1.75, "Slow 4G" (150 ms RTT, 1.6 Mbit/s down, 750 kbit/s up), CPU 4× slower;
|
||
* - desktop: 1350×940, 40 ms RTT, 10 Mbit/s, CPU 1×.
|
||
* Every run is a fresh browser context (empty HTTP cache, no cookies): a first visit, the worst ordinary case.
|
||
*
|
||
* What is measured (all from the browser itself, web.dev/articles/vitals):
|
||
* ttfb, fcp, lcp (+ the LCP element: tag, src, loading, fetchpriority), cls (session windows, as web-vitals does),
|
||
* tbt (sum of long-task time over 50 ms between FCP and the end of the run: the lab stand-in for INP),
|
||
* inp (the longest Event Timing entry of one scripted interaction: a click on the page's first visible button),
|
||
* scriptMs (CDP Performance.ScriptDuration: parse, compile, run and hydrate), requests, bytes per type
|
||
* (transfer size, compressed), renderBlocking (resource timing renderBlockingStatus), thirdParty (requests to
|
||
* another origin before any consent is given).
|
||
*/
|
||
import { chromium } from '@playwright/test'
|
||
|
||
export const PROFILES = {
|
||
desktop: { cpu: 1, network: { downloadThroughput: (10 * 1024 * 1024) / 8, latency: 40, uploadThroughput: (10 * 1024 * 1024) / 8 }, viewport: { deviceScaleFactor: 1, height: 940, isMobile: false, width: 1350 } },
|
||
mobile: { cpu: 4, network: { downloadThroughput: (1.6 * 1024 * 1024) / 8, latency: 150, uploadThroughput: (750 * 1024) / 8 }, viewport: { deviceScaleFactor: 1.75, hasTouch: true, height: 823, isMobile: true, width: 412 } },
|
||
}
|
||
|
||
const OBSERVERS = `(() => {
|
||
const v = (window.__perf = { cls: 0, events: [], lcp: null, longTasks: [] })
|
||
let win = 0, winStart = 0, winLast = 0
|
||
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
|
||
const el = e.element
|
||
v.lcp = { at: e.startTime, size: e.size, tag: el ? el.tagName.toLowerCase() : null, src: e.url || null,
|
||
loading: el && el.getAttribute ? el.getAttribute('loading') : null,
|
||
fetchpriority: el && el.getAttribute ? el.getAttribute('fetchpriority') : null }
|
||
} }).observe({ buffered: true, type: 'largest-contentful-paint' })
|
||
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
|
||
if (e.hadRecentInput) continue
|
||
if (win && e.startTime - winLast < 1000 && e.startTime - winStart < 5000) { win += e.value } else { win = e.value; winStart = e.startTime }
|
||
winLast = e.startTime
|
||
v.cls = Math.max(v.cls, win)
|
||
} }).observe({ buffered: true, type: 'layout-shift' })
|
||
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.longTasks.push([e.startTime, e.duration]) }).observe({ buffered: true, type: 'longtask' })
|
||
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.events.push({ d: e.duration, n: e.name }) }).observe({ buffered: true, durationThreshold: 16, type: 'event' })
|
||
})()`
|
||
|
||
/**
|
||
* @typedef {{ bytes: { css: number, font: number, html: number, image: number, js: number, other: number }, cls: number,
|
||
* fcp: null | number, inp: null | number, interaction: null | string, lcp: null | number,
|
||
* lcpElement: null | { fetchpriority: null | string, loading: null | string, src: null | string, tag: null | string },
|
||
* load: null | number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number,
|
||
* status: null | number, tbt: null | number, thirdParty: string[], ttfb: null | number, url: string }} PageMeasurement
|
||
*/
|
||
|
||
const typeOf = (resourceType, mime = '') => {
|
||
if (resourceType === 'Document') {return 'html'}
|
||
if (resourceType === 'Script') {return 'js'}
|
||
if (resourceType === 'Stylesheet') {return 'css'}
|
||
if (resourceType === 'Font') {return 'font'}
|
||
if (resourceType === 'Image' || mime.startsWith('image/')) {return 'image'}
|
||
return 'other'
|
||
}
|
||
|
||
/**
|
||
* @param {import('@playwright/test').Browser} browser
|
||
* @param {string} url
|
||
* @param {'mobile'|'desktop'} profileName
|
||
* @param {{ interact?: boolean, settleMs?: number }} [options]
|
||
* @returns {Promise<PageMeasurement>}
|
||
*/
|
||
export async function measurePage(browser, url, profileName, options = {}) {
|
||
const profile = PROFILES[profileName]
|
||
const context = await browser.newContext({ ...profile.viewport, viewport: { height: profile.viewport.height, width: profile.viewport.width } })
|
||
const page = await context.newPage()
|
||
const cdp = await context.newCDPSession(page)
|
||
await cdp.send('Network.enable')
|
||
await cdp.send('Network.setCacheDisabled', { cacheDisabled: true })
|
||
await cdp.send('Network.emulateNetworkConditions', { offline: false, ...profile.network })
|
||
await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.cpu })
|
||
await cdp.send('Performance.enable')
|
||
await page.addInitScript(OBSERVERS)
|
||
|
||
const origin = new URL(url).origin
|
||
const requests = new Map()
|
||
cdp.on('Network.requestWillBeSent', (e) => { if (!e.request.url.startsWith('data:')) {requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url })} })
|
||
cdp.on('Network.responseReceived', (e) => { const r = requests.get(e.requestId); if (r) {r.type = typeOf(e.type, e.response.mimeType); r.status = e.response.status} })
|
||
cdp.on('Network.loadingFinished', (e) => { const r = requests.get(e.requestId); if (r) {r.bytes = e.encodedDataLength} })
|
||
|
||
const response = await page.goto(url, { waitUntil: 'load' })
|
||
await page.waitForLoadState('networkidle').catch(() => {})
|
||
await page.waitForTimeout(options.settleMs ?? 1000)
|
||
|
||
let interaction = null
|
||
if (options.interact !== false) {
|
||
// INP stand-in: one click on the first visible button (menu toggle, cookie settings, theme): a real handler runs
|
||
const button = page.locator('button:visible').first()
|
||
if (await button.count()) {
|
||
interaction = (await button.getAttribute('aria-label')) ?? (await button.innerText()).slice(0, 40)
|
||
await button.click({ timeout: 5000 }).catch(() => { interaction = null })
|
||
await page.waitForTimeout(500)
|
||
}
|
||
}
|
||
|
||
const nav = await page.evaluate(() => {
|
||
const n = performance.getEntriesByType('navigation')[0]
|
||
const fcp = performance.getEntriesByName('first-contentful-paint')[0]
|
||
const blocking = performance.getEntriesByType('resource').filter((r) => r.renderBlockingStatus === 'blocking').map((r) => r.name)
|
||
return { blocking, domContentLoaded: n.domContentLoadedEventEnd, fcp: fcp ? fcp.startTime : null, load: n.loadEventEnd, ttfb: n.responseStart }
|
||
})
|
||
const vitals = await page.evaluate(() => window.__perf)
|
||
const { metrics } = await cdp.send('Performance.getMetrics')
|
||
const metric = (name) => metrics.find((m) => m.name === name)?.value ?? 0
|
||
await context.close()
|
||
|
||
const list = [...requests.values()]
|
||
const bytes = { css: 0, font: 0, html: 0, image: 0, js: 0, other: 0 }
|
||
for (const r of list) {bytes[r.type] += r.bytes}
|
||
const fcp = nav.fcp ?? 0
|
||
const tbt = vitals.longTasks.filter(([start]) => start >= fcp).reduce((sum, [, d]) => sum + Math.max(0, d - 50), 0)
|
||
const round = (n) => (n == null ? null : Math.round(n))
|
||
return {
|
||
bytes: Object.fromEntries(Object.entries(bytes).map(([k, b]) => [k, Math.round(b)])),
|
||
cls: Math.round(vitals.cls * 1000) / 1000,
|
||
fcp: round(nav.fcp),
|
||
inp: vitals.events.length ? round(Math.max(...vitals.events.map((e) => e.d))) : interaction ? 0 : null,
|
||
interaction,
|
||
lcp: round(vitals.lcp?.at),
|
||
lcpElement: vitals.lcp ? { fetchpriority: vitals.lcp.fetchpriority, loading: vitals.lcp.loading, src: vitals.lcp.src ? vitals.lcp.src.replace(origin, '') : null, tag: vitals.lcp.tag } : null,
|
||
load: round(nav.load),
|
||
profile: profileName,
|
||
renderBlocking: nav.blocking.map((u) => u.replace(origin, '')),
|
||
requests: list.length,
|
||
scriptMs: round(metric('ScriptDuration') * 1000),
|
||
status: response?.status() ?? null,
|
||
tbt: round(tbt),
|
||
thirdParty: [...new Set(list.filter((r) => !r.url.startsWith(origin)).map((r) => new URL(r.url).origin))],
|
||
ttfb: round(nav.ttfb),
|
||
url: url.replace(origin, ''),
|
||
}
|
||
}
|
||
|
||
export const median = (values) => {
|
||
const sorted = values.filter((v) => typeof v === 'number').sort((a, b) => a - b)
|
||
if (!sorted.length) {return null}
|
||
const mid = Math.floor(sorted.length / 2)
|
||
return sorted.length % 2 ? sorted[mid] : Math.round(((sorted[mid - 1] + sorted[mid]) / 2) * 1000) / 1000
|
||
}
|
||
|
||
/**
|
||
* The median of `runs` measurements for every number; the rest from the last run.
|
||
* @param {import('@playwright/test').Browser} browser
|
||
* @param {string} url
|
||
* @param {'mobile'|'desktop'} profileName
|
||
* @param {number} [runs]
|
||
* @param {{ interact?: boolean, settleMs?: number }} [options]
|
||
* @returns {Promise<PageMeasurement>}
|
||
*/
|
||
export async function measureMedian(browser, url, profileName, runs = 3, options = {}) {
|
||
const all = []
|
||
for (let i = 0; i < runs; i++) {all.push(await measurePage(browser, url, profileName, options))}
|
||
const last = all.at(-1)
|
||
const out = { ...last, runs }
|
||
for (const key of ['cls', 'fcp', 'inp', 'lcp', 'load', 'requests', 'scriptMs', 'tbt', 'ttfb']) {out[key] = median(all.map((r) => r[key]))}
|
||
out.bytes = Object.fromEntries(Object.keys(last.bytes).map((k) => [k, median(all.map((r) => r.bytes[k]))]))
|
||
return out
|
||
}
|
||
|
||
export const launch = () => chromium.launch()
|