Files
ipal-kit/src/modules/doctor/rules/performance.ts
T

197 lines
14 KiB
TypeScript

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',
},
]