Budgets and checks: PERF_BUDGETS / perfBudgets / overBudget, the reference gate (both bundlers), the doctor's performance group (static, live, deep)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
21073d98d0
commit
801b897ea0
@@ -0,0 +1,196 @@
|
||||
import type { DoctorContext } from '../project.js'
|
||||
import type { DoctorRule, RuleFinding } from '../types.js'
|
||||
|
||||
import { IMAGE_RULES } from '../../performance/budgets.js'
|
||||
import { stripComments } from '../util.js'
|
||||
|
||||
/**
|
||||
* The performance group (docs/performance.md): what makes a site slow and can be seen without a browser — images,
|
||||
* fonts, embeds, render-blocking resources, animations, a budget gate — plus the running site (`--url`) and the stored
|
||||
* media (`--deep`). Warnings in 1.18.0, as the owner decided for new rules: they report, they do not fail CI.
|
||||
*/
|
||||
|
||||
const DOCS = 'docs/performance.md'
|
||||
|
||||
/** The site's own code and styles: src/app (not the panel's route group) and src/components, comments stripped. */
|
||||
function siteFiles(ctx: DoctorContext, pattern = /\.(?:tsx?|jsx?|css|scss)$/): Array<{ code: string; file: string }> {
|
||||
const files: string[] = []
|
||||
const walk = (dir: string, depth: number) => {
|
||||
for (const name of ctx.list(dir)) {
|
||||
if (files.length >= 800 || name === 'node_modules' || name.startsWith('.') || name === '(payload)') {continue}
|
||||
const rel = `${dir}/${name}`
|
||||
if (pattern.test(name)) {files.push(rel)}
|
||||
else if (!/\.[a-z0-9]+$/i.test(name) || /^\(.*\)$|^\[.*\]$/.test(name)) {if (depth < 8) {walk(rel, depth + 1)}}
|
||||
}
|
||||
}
|
||||
for (const dir of ['app', 'components', 'blocks', 'design', 'styles']) {walk(`${ctx.src}${dir}`, 0)}
|
||||
return files.map((file) => ({ code: /\.s?css$/.test(file) ? ctx.read(file).replace(/\/\*[\s\S]*?\*\//g, '') : stripComments(ctx.read(file)), file }))
|
||||
}
|
||||
|
||||
const lineOf = (code: string, index: number) => code.slice(0, index).split('\n').length
|
||||
|
||||
/** Each match → one finding (at most `max` per rule, the rest summed up in the last one). */
|
||||
function findAll(files: Array<{ code: string; file: string }>, re: RegExp, make: (file: string, line: number, match: RegExpExecArray) => null | RuleFinding, max = 10): RuleFinding[] {
|
||||
const out: RuleFinding[] = []
|
||||
let more = 0
|
||||
for (const { code, file } of files) {
|
||||
const global = new RegExp(re.source, re.flags.includes('g') ? re.flags : `${re.flags}g`)
|
||||
for (let m = global.exec(code); m; m = global.exec(code)) {
|
||||
const finding = make(file, lineOf(code, m.index), m)
|
||||
if (!finding) {continue}
|
||||
if (out.length < max) {out.push(finding)} else {more++}
|
||||
}
|
||||
}
|
||||
if (more) {out[out.length - 1] = { ...out[out.length - 1], message: `${out[out.length - 1].message} (and ${more} more)` }}
|
||||
return out
|
||||
}
|
||||
|
||||
const nextConfig = (ctx: DoctorContext) => ['next.config.ts', 'next.config.mjs', 'next.config.js'].find((f) => ctx.exists(f))
|
||||
|
||||
/** Layout properties: animating them makes the browser lay the page out again on every frame. */
|
||||
const LAYOUT_PROPS = '(?:width|height|top|left|right|bottom|margin(?:-[a-z]+)?|padding(?:-[a-z]+)?|inset|max-height|min-height)'
|
||||
|
||||
export const performanceRules: DoctorRule[] = [
|
||||
{
|
||||
// next/image serves AVIF / WebP in the right width only for hosts it is allowed to optimise; buildImagesConfig sets
|
||||
// the formats, R2 and a long cache (web.dev/articles/serve-images-avif-webp — nextjs.org/docs/app/api-reference/components/image)
|
||||
id: 'perf-images-config',
|
||||
check: (ctx) => {
|
||||
const file = nextConfig(ctx)
|
||||
if (!file || /\bbuildImagesConfig\s*\(/.test(stripComments(ctx.read(file)))) {return []}
|
||||
return [{ file, fix: 'images: buildImagesConfig() in next.config (from @intecion/ipal-kit)', message: 'next.config does not use buildImagesConfig(): images may not be served as AVIF / WebP or with a long cache, and media on R2 may not be optimised at all', severity: 'warning' }]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// Fonts: self-hosted by next/font (no request to Google, no layout shift — nextjs.org/docs/app/getting-started/fonts);
|
||||
// at most two families; never font-display: block (invisible text — web.dev/articles/font-best-practices)
|
||||
id: 'perf-fonts',
|
||||
check: (ctx) => {
|
||||
const files = siteFiles(ctx)
|
||||
const out: RuleFinding[] = [
|
||||
...findAll(files, /fonts\.googleapis\.com|fonts\.gstatic\.com|use\.typekit\.net/, (file, line) => ({ file: `${file}:${line}`, fix: 'load the font with next/font (self-hosted, subset, no extra connection)', message: 'a font is loaded from a third-party host: an extra connection before text shows, and a request to Google before consent', severity: 'warning' })),
|
||||
...findAll(files, /display\s*:\s*['"]block['"]|font-display\s*:\s*block/, (file, line) => ({ file: `${file}:${line}`, fix: "display: 'swap' (next/font's default) or 'optional'", message: 'font-display: block hides the text until the font has loaded', severity: 'warning' })),
|
||||
...findAll(files.filter((f) => /\.s?css$/.test(f.file)), /@font-face\s*\{(?![^}]*font-display)[^}]*\}/, (file, line) => ({ file: `${file}:${line}`, fix: 'font-display: swap in the @font-face — or next/font/local, which sets it', message: '@font-face without font-display (the browser may hide the text for up to 3 s)', severity: 'warning' })),
|
||||
]
|
||||
const families = new Set<string>()
|
||||
for (const { code } of files) {
|
||||
const imports = /import\s*\{([^}]+)\}\s*from\s*['"]next\/font\/google['"]/.exec(code)
|
||||
for (const name of imports?.[1].split(',').map((n) => n.trim().split(/\s+as\s+/)[0]).filter(Boolean) ?? []) {families.add(name)}
|
||||
for (const m of code.matchAll(/\blocalFont\s*\(/g)) {families.add(`localFont#${m.index}`)}
|
||||
}
|
||||
if (families.size > 2) {
|
||||
out.push({ fix: 'two families at most (body + headings), variable fonts, the weights you use', message: `${families.size} font families on the site (${[...families].map((f) => f.replace(/#\d+$/, '')).join(', ')}): each one is more bytes before the text settles`, severity: 'warning' })
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// Nothing may hold the first paint except the one stylesheet (web.dev/articles/render-blocking-resources)
|
||||
id: 'perf-render-blocking',
|
||||
check: (ctx) => {
|
||||
const files = siteFiles(ctx)
|
||||
return [
|
||||
...findAll(files.filter((f) => /\.[jt]sx$/.test(f.file)), /<script(?![^>]*\s(?:async|defer|type=["']module["']|dangerouslySetInnerHTML|type=["']application\/(?:ld\+)?json["']))[^>]*\ssrc=/, (file, line) => ({ file: `${file}:${line}`, fix: 'next/script with strategy="afterInteractive" or "lazyOnload", or the plugin\'s ConsentScript / Analytics', message: 'a <script src> without async / defer blocks the page until it has downloaded and run', severity: 'warning' })),
|
||||
...findAll(files.filter((f) => /\.[jt]sx$/.test(f.file)), /<link(?=[^>]*\srel=["']stylesheet["'])[^>]*\shref=["']https?:/, (file, line) => ({ file: `${file}:${line}`, fix: 'import the CSS in the layout (bundled, one file) or self-host it', message: 'a stylesheet from another host blocks the first paint on an extra connection', severity: 'warning' })),
|
||||
...findAll(files.filter((f) => /\.s?css$/.test(f.file)), /@import\s+(?:url\()?["']?https?:/, (file, line) => ({ file: `${file}:${line}`, fix: 'self-host it (next/font for fonts) — an @import of a URL is fetched only after this file has loaded', message: 'CSS @import of a remote URL: a request chain before the first paint', severity: 'warning' })),
|
||||
]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// Embeds load a whole page each (YouTube ≈ 1 MB of JS): a facade until the click (web.dev/articles/third-party-facades)
|
||||
id: 'perf-embeds',
|
||||
check: (ctx) => findAll(siteFiles(ctx, /\.[jt]sx$/), /<iframe\b[^>]*>/, (file, line, m) => {
|
||||
if (/youtube/i.test(m[0])) {return null} // iapl-audit reports a raw YouTube iframe (audit:raw YouTube iframe)
|
||||
if (/loading=["']lazy["']/.test(m[0])) {return null}
|
||||
return { file: `${file}:${line}`, fix: 'load it on click (a facade: a picture and a button, like <YouTubeEmbed>), or at least loading="lazy" below the fold', message: 'an <iframe> (map, video, widget) loads with the page: its whole page, scripts and cookies come before the visitor asked', severity: 'warning' }
|
||||
}),
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// transform / opacity only, reduced motion honoured, no work per scroll event
|
||||
// (web.dev/articles/animations-guide, web.dev/articles/prefers-reduced-motion, web.dev/articles/optimize-inp)
|
||||
id: 'perf-animations',
|
||||
check: (ctx) => {
|
||||
const files = siteFiles(ctx)
|
||||
const css = files.filter((f) => /\.s?css$/.test(f.file))
|
||||
const tsx = files.filter((f) => /\.[jt]sx?$/.test(f.file))
|
||||
const out: RuleFinding[] = [
|
||||
...findAll(css, new RegExp(`transition(?:-property)?\\s*:[^;}]*\\b${LAYOUT_PROPS}\\b`), (file, line) => ({ file: `${file}:${line}`, fix: 'animate transform (translate, scale) and opacity instead', message: 'a transition of a layout property (width, height, top, margin…): the page is laid out again on every frame', severity: 'warning' })),
|
||||
...findAll(tsx, new RegExp(`\\btransition-(?:all|\\[[^\\]]*\\b${LAYOUT_PROPS}\\b[^\\]]*\\])`), (file, line) => ({ file: `${file}:${line}`, fix: 'transition-transform / transition-opacity / transition-colors', message: 'transition-all or a transition of a layout property animates layout on every frame', severity: 'warning' })),
|
||||
...findAll(tsx, /addEventListener\(\s*['"]scroll['"]/, (file, line) => ({ file: `${file}:${line}`, fix: 'IntersectionObserver for "is it on screen", or at most one update per frame (requestAnimationFrame) with { passive: true }', message: 'a scroll listener runs on every scroll event: work on the main thread delays the next tap (INP)', severity: 'warning' })),
|
||||
]
|
||||
const animates = files.some((f) => /@keyframes|\banimate-[a-z]|animation\s*:/.test(f.code))
|
||||
const reduces = files.some((f) => /prefers-reduced-motion|\bmotion-(?:reduce|safe):/.test(f.code)) || /ipal-kit\/(?:tokens|tailwind)\.css/.test(files.map((f) => f.code).join('\n'))
|
||||
if (animates && !reduces) {
|
||||
out.push({ fix: '@media (prefers-reduced-motion: reduce) { … } or motion-safe: / motion-reduce: classes — the plugin\'s tokens.css shortens its duration tokens for you', message: 'the site animates (@keyframes / animate-*) and nothing honours prefers-reduced-motion', severity: 'warning' })
|
||||
}
|
||||
return out
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// A budget nobody runs is a wish: the gate test fails when a change makes the site slower
|
||||
id: 'perf-budgets',
|
||||
check: (ctx) => {
|
||||
const dirs = ['e2e', 'tests', 'test'].filter((d) => ctx.exists(d))
|
||||
const has = dirs.some((d) => ctx.list(d).some((name) => /perf/i.test(name) || /\bperfBudgets\s*\(|\boverBudget\s*\(/.test(ctx.read(`${d}/${name}`))))
|
||||
return has ? [] : [{ fix: 'copy the iapl-performance skill\'s resources/performance.spec.template.ts to e2e/ (budgets from perfBudgets())', message: 'no performance budget test: nothing fails when a change makes the site slower', severity: 'info' }]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
source: 'static',
|
||||
},
|
||||
{
|
||||
// The first HTML as a visitor gets it: compression, render-blocking scripts, preloads, a lazy first image
|
||||
id: 'perf-live',
|
||||
check: async (ctx) => {
|
||||
const home = await ctx.live!.fetch('/')
|
||||
if (!home.status || home.status >= 400) {return []}
|
||||
const out: RuleFinding[] = []
|
||||
const html = home.text
|
||||
const head = html.slice(0, Math.max(0, html.indexOf('</head>')) || 0)
|
||||
if (!home.headers.get('content-encoding')) {
|
||||
out.push({ fix: 'let the proxy compress (Coolify: Traefik compress middleware) or Next (compress: true, the default)', message: 'the HTML came back uncompressed (no Content-Encoding)', severity: 'warning' })
|
||||
}
|
||||
const blocking = [...head.matchAll(/<script(?![^>]*\s(?:async|defer|type="module"|nomodule))[^>]*\ssrc="([^"]+)"/gi)].map((m) => m[1])
|
||||
if (blocking.length) {out.push({ message: `render-blocking scripts in <head>: ${blocking.slice(0, 3).join(', ')}`, severity: 'warning' })}
|
||||
const fonts = (head.match(/<link[^>]*\srel="preload"[^>]*\sas="font"/g) ?? []).length
|
||||
if (fonts > 4) {out.push({ fix: 'preload only the body font (next/font preload: false on the others) or fewer subsets', message: `${fonts} font files preloaded: they compete with the LCP image for the first round trips`, severity: 'warning' })}
|
||||
const main = html.indexOf('<main')
|
||||
const firstImg = main >= 0 ? /<img\b[^>]*>/.exec(html.slice(main))?.[0] : undefined
|
||||
if (firstImg && /loading="lazy"/.test(firstImg)) {out.push({ fix: '<Media priority> on the first image of the page (the hero) — exactly one', message: 'the first image of the page is lazy-loaded: when it is the LCP element it starts late (web.dev/articles/lcp-lazy-loading)', severity: 'warning' })}
|
||||
const kb = Math.round(Buffer.byteLength(html) / 1024)
|
||||
if (kb > 150) {out.push({ message: `the home page HTML is ${kb} KB (budget 150 KB): a big RSC payload is parsed twice — check depth, relations and what the layout passes to client components`, severity: 'warning' })}
|
||||
return out
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
source: 'live',
|
||||
},
|
||||
{
|
||||
// Images stored over the limits (an LCP image of 4 MB stays slow, whatever next/image does with it)
|
||||
id: 'perf-images',
|
||||
check: (ctx) => {
|
||||
const media = ctx.deep?.media
|
||||
if (!media || (!media.oversized && !media.tooWide)) {return []}
|
||||
const mb = (IMAGE_RULES.maxBytes / 1024 / 1024).toFixed(1)
|
||||
return [{ fix: `re-upload them prepared (≤ ${mb} MB, ≤ ${IMAGE_RULES.maxWidth} px) or tick "Optimise large image"; buildOptimizeUploadHook stops new ones`, message: `of ${media.images} images, ${media.oversized} are over ${mb} MB and ${media.tooWide} wider than ${IMAGE_RULES.maxWidth} px`, severity: 'warning' }]
|
||||
},
|
||||
docs: DOCS,
|
||||
group: 'performance',
|
||||
source: 'deep',
|
||||
},
|
||||
]
|
||||
@@ -14,6 +14,7 @@ import { layoutRules } from './rules/layout.js'
|
||||
import { legacyRules } from './rules/legacy.js'
|
||||
import { createLiveFetcher, liveRules } from './rules/live.js'
|
||||
import { mailRules } from './rules/mail.js'
|
||||
import { performanceRules } from './rules/performance.js'
|
||||
import { securityRules } from './rules/security.js'
|
||||
import { seedRules } from './rules/seeds.js'
|
||||
import { toolingRules } from './rules/tooling.js'
|
||||
@@ -41,6 +42,7 @@ export const doctorRules: DoctorRule[] = [
|
||||
...legacyRules,
|
||||
...seedRules,
|
||||
...blockRules,
|
||||
...performanceRules,
|
||||
...toolingRules,
|
||||
...liveRules,
|
||||
...deepRules,
|
||||
|
||||
@@ -10,6 +10,7 @@ import { countPendingCookies } from '../consent/scanner/approval.js'
|
||||
import { COOKIE_REVIEW_SLUG } from '../consent/scanner/collection.js'
|
||||
import { graphAvailable } from '../email/mailAdapter.js'
|
||||
import { mailPanelState } from '../email/relay/panel.js'
|
||||
import { IMAGE_RULES } from '../performance/budgets.js'
|
||||
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
|
||||
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
|
||||
import { readEnv } from '../shared/envName.js'
|
||||
@@ -22,7 +23,31 @@ export function pluginVersion(): string {
|
||||
return PLUGIN_VERSION
|
||||
}
|
||||
|
||||
type CollectionLike = { fields?: Array<{ name?: string }>; slug: string }
|
||||
type CollectionLike = { fields?: Array<{ name?: string }>; slug: string; upload?: unknown }
|
||||
|
||||
/**
|
||||
* Images stored over the plugin's limits (IMAGE_RULES): counts per upload collection, never file names. Uploads made
|
||||
* before `buildOptimizeUploadHook`, or let through by hand, are the usual cause of a slow LCP image.
|
||||
*/
|
||||
export async function countHeavyMedia(payload: BasePayload, collections: CollectionLike[]): Promise<DoctorStatus['media']> {
|
||||
const uploads = collections.filter((c) => c.upload)
|
||||
if (!uploads.length) {return null}
|
||||
let images = 0
|
||||
let oversized = 0
|
||||
let tooWide = 0
|
||||
for (const c of uploads) {
|
||||
const collection = c.slug as never
|
||||
const image = { mimeType: { like: 'image/' } }
|
||||
try {
|
||||
images += (await payload.count({ collection, overrideAccess: true, where: image })).totalDocs
|
||||
oversized += (await payload.count({ collection, overrideAccess: true, where: { and: [image, { filesize: { greater_than: IMAGE_RULES.maxBytes } }] } })).totalDocs
|
||||
tooWide += (await payload.count({ collection, overrideAccess: true, where: { and: [image, { width: { greater_than: IMAGE_RULES.maxWidth } }] } })).totalDocs
|
||||
} catch {
|
||||
// a collection without the standard upload fields: not counted
|
||||
}
|
||||
}
|
||||
return { images, oversized, tooWide }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only counts for iapl-doctor's deep rules: users without TOTP, cookies waiting for approval,
|
||||
@@ -46,6 +71,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
}
|
||||
}
|
||||
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
|
||||
const media = await countHeavyMedia(payload, collections)
|
||||
// Turnstile: the recorded state and where the secret comes from — never the keys themselves.
|
||||
let turnstile: DoctorStatus['turnstile'] = null
|
||||
let secretFromEnv: boolean | null = null
|
||||
@@ -120,7 +146,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
}
|
||||
const { csrf, serverURL } = payload.config as { csrf?: unknown; serverURL?: unknown }
|
||||
const originKnown = (typeof serverURL === 'string' && serverURL.trim() !== '') || (Array.isArray(csrf) && csrf.some((o) => typeof o === 'string' && o.trim() !== ''))
|
||||
return { mail, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites }
|
||||
return { mail, media, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, usersSetupClosed, usersWithout2fa, visitorWrites }
|
||||
}
|
||||
|
||||
export type DoctorEndpointOptions = {
|
||||
|
||||
@@ -96,6 +96,8 @@ export type DoctorStatus = {
|
||||
status?: { code?: null | string; since?: null | string; state?: null | string } | null
|
||||
transport: 'graph' | 'none' | 'relay' | 'smtp'
|
||||
} | null
|
||||
/** Images in the upload collections, and how many are over IMAGE_RULES (bytes, width). null = no upload collection. */
|
||||
media?: { images: number; oversized: number; tooWide: number } | null
|
||||
node?: string
|
||||
/** Auth collections whose `create` rule lets an anonymous request through (slugs only). */
|
||||
openSignUp?: null | string[]
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* Performance budgets — the numbers a site must stay within, measured in the lab (docs/performance.md).
|
||||
*
|
||||
* One set of defaults for every IAPL site (and shared with IAWL where the measurement is the same): Core Web Vitals
|
||||
* "good" (web.dev/articles/vitals) for LCP, CLS and INP, plus byte, request and query budgets that keep a brochure
|
||||
* site light. A project tightens or loosens any number with `perfBudgets({ … })`; the reference site's gate
|
||||
* (reference/e2e/performance.spec.ts) tightens them to its measured numbers, so a change that makes it slower fails.
|
||||
*
|
||||
* Node and browser safe: no imports.
|
||||
*/
|
||||
|
||||
/** What one page may cost on a first visit (empty cache), in Lighthouse's mobile or desktop lab profile. */
|
||||
export type PerfBudget = {
|
||||
/** Cumulative Layout Shift (session window). Good ≤ 0.1. */
|
||||
cls: number
|
||||
/** CSS bytes over the wire (compressed). */
|
||||
cssBytes: number
|
||||
/** Font bytes over the wire. */
|
||||
fontBytes: number
|
||||
/** The slowest response to one scripted tap (Event Timing), ms. A lab stand-in for INP. Good ≤ 200. */
|
||||
inp: number
|
||||
/** JavaScript bytes over the wire (compressed). */
|
||||
jsBytes: number
|
||||
/** Largest Contentful Paint, ms. Good ≤ 2500 (mobile). */
|
||||
lcp: number
|
||||
/** Render-blocking resources (resource timing `renderBlockingStatus`): the one stylesheet, nothing else. */
|
||||
renderBlocking: number
|
||||
/** Requests on load (HTML, CSS, JS, fonts, the images above the fold). */
|
||||
requests: number
|
||||
/** Total Blocking Time after first paint, ms: long main-thread tasks that would delay a tap. */
|
||||
tbt: number
|
||||
/** Origins other than the site that may be asked before the visitor chose in the consent banner. */
|
||||
thirdParty: string[]
|
||||
}
|
||||
|
||||
export type PerfProfile = 'desktop' | 'mobile'
|
||||
|
||||
/** Server budgets: one render of a page that is not in the ISR cache. */
|
||||
export type ServerBudget = {
|
||||
/** Database queries one render of a page may make (MongoDB profiler, docs/performance.md). */
|
||||
queriesPerRender: number
|
||||
}
|
||||
|
||||
/** The defaults: CWV "good" for the vitals, and sizes a brochure site needs no more than. */
|
||||
export const PERF_BUDGETS: Readonly<Record<PerfProfile, Readonly<PerfBudget>>> = {
|
||||
desktop: { cls: 0.1, cssBytes: 50_000, fontBytes: 250_000, inp: 100, jsBytes: 250_000, lcp: 1200, renderBlocking: 2, requests: 50, tbt: 100, thirdParty: [] },
|
||||
mobile: { cls: 0.1, cssBytes: 50_000, fontBytes: 250_000, inp: 200, jsBytes: 250_000, lcp: 2500, renderBlocking: 2, requests: 40, tbt: 200, thirdParty: [] },
|
||||
}
|
||||
|
||||
export const SERVER_BUDGET: Readonly<ServerBudget> = { queriesPerRender: 40 }
|
||||
|
||||
/**
|
||||
* Image rules every upload and every rendered image should meet — the doctor checks the stored media against them,
|
||||
* `buildOptimizeUploadHook` enforces the first two at upload. Shared with IAWL (WordPress) as the same numbers.
|
||||
*/
|
||||
export const IMAGE_RULES = {
|
||||
/** An image larger than this is stopped at upload (the editor may let the plugin shrink it). */
|
||||
maxBytes: 1.5 * 1024 * 1024,
|
||||
/** Wider than this is never needed on screen (a 1280 px wide slot at DPR 2). */
|
||||
maxWidth: 2560,
|
||||
/** Formats the site serves (next/image converts; buildImagesConfig sets them). */
|
||||
servedFormats: ['image/avif', 'image/webp'] as const,
|
||||
} as const
|
||||
|
||||
/** The defaults with a project's changes on top (per profile; `thirdParty` replaces, everything else merges). */
|
||||
export function perfBudgets(overrides: Partial<Record<PerfProfile, Partial<PerfBudget>>> = {}): Record<PerfProfile, PerfBudget> {
|
||||
return {
|
||||
desktop: { ...PERF_BUDGETS.desktop, thirdParty: [...PERF_BUDGETS.desktop.thirdParty], ...overrides.desktop },
|
||||
mobile: { ...PERF_BUDGETS.mobile, thirdParty: [...PERF_BUDGETS.mobile.thirdParty], ...overrides.mobile },
|
||||
}
|
||||
}
|
||||
|
||||
/** One lab measurement of a page (reference/e2e/perf-lab.mjs returns this shape). */
|
||||
export type PerfMeasurement = {
|
||||
bytes: { css: number; font: number; js: number }
|
||||
cls: null | number
|
||||
inp: null | number
|
||||
lcp: null | number
|
||||
renderBlocking: string[]
|
||||
requests: number
|
||||
tbt: null | number
|
||||
thirdParty: string[]
|
||||
}
|
||||
|
||||
/** Every budget a measurement breaks, as readable lines (empty = within budget). */
|
||||
export function overBudget(measured: PerfMeasurement, budget: PerfBudget): string[] {
|
||||
const out: string[] = []
|
||||
const over = (name: string, value: null | number | undefined, limit: number, unit = '') => {
|
||||
if (typeof value === 'number' && value > limit) {out.push(`${name} ${value}${unit} > ${limit}${unit}`)}
|
||||
}
|
||||
over('LCP', measured.lcp, budget.lcp, ' ms')
|
||||
over('CLS', measured.cls, budget.cls)
|
||||
over('TBT', measured.tbt, budget.tbt, ' ms')
|
||||
over('INP (scripted tap)', measured.inp, budget.inp, ' ms')
|
||||
over('JS', measured.bytes.js, budget.jsBytes, ' B')
|
||||
over('CSS', measured.bytes.css, budget.cssBytes, ' B')
|
||||
over('fonts', measured.bytes.font, budget.fontBytes, ' B')
|
||||
over('requests', measured.requests, budget.requests)
|
||||
if (measured.renderBlocking.length > budget.renderBlocking) {
|
||||
out.push(`render-blocking ${measured.renderBlocking.length} > ${budget.renderBlocking}: ${measured.renderBlocking.join(', ')}`)
|
||||
}
|
||||
const foreign = measured.thirdParty.filter((origin) => !budget.thirdParty.includes(origin))
|
||||
if (foreign.length) {out.push(`third-party requests before consent: ${foreign.join(', ')}`)}
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user