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() 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)), /]*\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