From 801b897ea09ccc4701d039f6ed47a387261b4e47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 13:51:43 +0100 Subject: [PATCH] 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 --- reference/e2e/performance.spec.ts | 110 ++++++++++++ src/exports/doctor.ts | 4 + src/modules/doctor/rules/performance.ts | 196 +++++++++++++++++++++ src/modules/doctor/run.ts | 2 + src/modules/doctor/status.ts | 30 +++- src/modules/doctor/types.ts | 2 + src/modules/performance/budgets.ts | 105 +++++++++++ test/doctor.test.ts | 3 +- test/legacyNames.test.ts | 7 +- test/performance.test.ts | 221 ++++++++++++++++++++++++ 10 files changed, 674 insertions(+), 6 deletions(-) create mode 100644 reference/e2e/performance.spec.ts create mode 100644 src/modules/doctor/rules/performance.ts create mode 100644 src/modules/performance/budgets.ts create mode 100644 test/performance.test.ts diff --git a/reference/e2e/performance.spec.ts b/reference/e2e/performance.spec.ts new file mode 100644 index 0000000..089d950 --- /dev/null +++ b/reference/e2e/performance.spec.ts @@ -0,0 +1,110 @@ +import type { Browser } from '@playwright/test' + +import { overBudget, perfBudgets, SERVER_BUDGET } from '@intecion/ipal-kit/doctor' +import { chromium, expect, test } from '@playwright/test' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import path from 'node:path' + +// a plain ES module (JSDoc types), shared with scripts/perf-measure.mjs +import { measureMedian } from './perf-lab.mjs' + +/** + * Performance budgets — a BINDING gate (docs/performance.md): every page type, a phone on Slow 4G with a 4× slower CPU + * and a desktop, first visit. The numbers are this site's own, measured on 2026-12-01 (docs/dev/perf/*-after.json) + * with headroom for lab noise: a change that makes a page heavier or slower fails here, in `pnpm e2e:built`, with both + * bundlers. Loosen a number only with a reason in the comment next to it. + * PERF_RUNS (default 1) runs per page; the gate takes the median. + */ +const runs = Number(process.env.PERF_RUNS ?? 1) + +const budgets = perfBudgets({ + // measured 1.18.0: JS 184–188 kB, CSS 11–12 kB, fonts 209.5 kB (Inter + Fraunces, latin + latin-ext — four + // preloaded files: see "fonts" in docs/performance.md), LCP 0.8 s on the phone, 0.3 s on the desktop + desktop: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 200_000, lcp: 800, renderBlocking: 1, requests: 36, tbt: 50 }, + mobile: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 200_000, lcp: 1500, renderBlocking: 1, requests: 30, tbt: 100 }, +}) + +/** One of each template (AGENTS.md → Site map), with what differs for that page. */ +type Budget = Partial +const PAGES: Array<{ budget?: { desktop?: Budget; mobile?: Budget }; name: string; path: string; why?: string }> = [ + { name: 'home', path: '/pl' }, + { name: 'page', path: '/pl/o-nas' }, + { name: 'archive', path: '/pl/blog' }, + { name: 'post', path: '/pl/blog/zanim-kupisz-dzialke' }, + { name: 'case study', path: '/pl/realizacje/dom-pod-lasem' }, + { name: 'form', path: '/pl/wycena' }, + // every block × variant on one page, the contact form's Turnstile included (a necessary service, before consent) + { budget: { desktop: { jsBytes: 230_000, thirdParty: ['https://challenges.cloudflare.com'] }, mobile: { jsBytes: 230_000, thirdParty: ['https://challenges.cloudflare.com'] } }, name: 'showcase', path: '/pl/bloki' }, + // The 404 content loads after hydration (createNotFoundPage `load`, so it is not in every page's payload): it + // arrives late and moves the footer — measured CLS 0.32 and LCP 2.5 s on the phone. An owner decision in + // docs/performance.md; until then the gate holds it where it is (no worse). + { budget: { mobile: { cls: 0.35, lcp: 3000 } }, name: '404', path: '/pl/nie-ma-takiej-strony', why: 'lazy 404 (owner decision pending)' }, +] + +let browser: Browser +test.beforeAll(async () => { + browser = await chromium.launch() +}) +test.afterAll(async () => { + await browser?.close() +}) + +test.describe('performance budgets', () => { + test.describe.configure({ timeout: 180_000 }) + for (const page of PAGES) { + for (const profile of ['mobile', 'desktop'] as const) { + test(`${page.name} (${profile}) stays within its budget`, async ({ baseURL }) => { + const budget = { ...budgets[profile], ...page.budget?.[profile] } + const measured = await measureMedian(browser, `${baseURL}${page.path}`, profile, runs) + test.info().annotations.push({ description: JSON.stringify({ bytes: measured.bytes, cls: measured.cls, inp: measured.inp, lcp: measured.lcp, requests: measured.requests, tbt: measured.tbt }), type: 'measured' }) + expect(overBudget(measured, budget), `${page.path} ${profile}${page.why ? ` (${page.why})` : ''}`).toEqual([]) + // the LCP image is never lazy (web.dev/articles/lcp-lazy-loading) + if (measured.lcpElement?.tag === 'img') {expect(measured.lcpElement.loading, `${page.path}: the LCP image is lazy`).not.toBe('lazy')} + }) + } + } +}) + +/** + * Database queries for ONE render of a page outside the ISR cache (Next's own on-demand revalidation header), counted + * by MongoDB's profiler. Measured 1.18.0: 19–27 per page (1.17.2: 30–43); each budget is that plus ~15 %. Skipped when the profiler cannot be + * switched on (not MongoDB, or a user without the right). + */ +test.describe('queries per render', () => { + const QUERY_BUDGET: Record = { '/pl': 28, '/pl/bloki': 31, '/pl/blog/zanim-kupisz-dzialke': 30, '/pl/o-nas': 25, '/pl/wycena': 22 } + test('every page type stays within its query budget', async ({ baseURL }) => { + test.setTimeout(120_000) + const uri = process.env.DATABASE_URI + test.skip(!uri?.startsWith('mongodb'), 'not MongoDB') + const site = process.cwd() // Playwright runs in reference/ + const requireFromAdapter = createRequire(createRequire(path.join(site, 'package.json')).resolve('@payloadcms/db-mongodb')) + const mongoose = requireFromAdapter('mongoose') as typeof import('mongoose') + const conn = await mongoose.createConnection(uri!).asPromise() + const db = conn.db! + try { + try { + await db.command({ profile: 0 }) + } catch { + test.skip(true, 'the database user may not use the profiler') + } + const previewModeId = JSON.parse(readFileSync(path.join(site, '.next', 'prerender-manifest.json'), 'utf8')).preview?.previewModeId as string + const counts: Record = {} + for (const [p, limit] of Object.entries(QUERY_BUDGET)) { + await fetch(`${baseURL}${p}`, { headers: { 'x-prerender-revalidate': previewModeId } }) // warm: the first render compiles + await db.command({ profile: 0 }) + await db.collection('system.profile').drop().catch(() => {}) + await db.command({ profile: 2 }) + const res = await fetch(`${baseURL}${p}`, { headers: { 'x-prerender-revalidate': previewModeId } }) + expect(res.status).toBe(200) + await db.command({ profile: 0 }) + counts[p] = await db.collection('system.profile').countDocuments({ ns: { $not: /system\.profile$/ }, op: 'query' }) + expect(counts[p], `${p}: ${counts[p]} queries (budget ${limit}, plugin default ${SERVER_BUDGET.queriesPerRender})`).toBeLessThanOrEqual(limit) + } + test.info().annotations.push({ description: JSON.stringify(counts), type: 'queries' }) + } finally { + await db.command({ profile: 0 }).catch(() => {}) + await conn.close() + } + }) +}) diff --git a/src/exports/doctor.ts b/src/exports/doctor.ts index 5e12cde..783f7d1 100644 --- a/src/exports/doctor.ts +++ b/src/exports/doctor.ts @@ -13,6 +13,7 @@ export { planSkills } from '../modules/doctor/rules/agents.js' export { DEFAULT_SRC_ALLOW, findFrontend } from '../modules/doctor/rules/layout.js' export type { FrontendLayout } from '../modules/doctor/rules/layout.js' export { createLiveFetcher } from '../modules/doctor/rules/live.js' +export { performanceRules } from '../modules/doctor/rules/performance.js' export { AUDIT_RULE_MAP, parseToolOutput } from '../modules/doctor/rules/tooling.js' export { applySettings, AUDIT_SKIP_RULES, doctorRules, globToRegExp, runDeepProbe, runDoctor } from '../modules/doctor/run.js' export type { RunDoctorOptions } from '../modules/doctor/run.js' @@ -29,6 +30,9 @@ export type { DoctorStatus, RuleFinding, } from '../modules/doctor/types.js' +// Performance budgets (docs/performance.md): the defaults, a project's own on top, and the check the gate runs +export { IMAGE_RULES, overBudget, PERF_BUDGETS, perfBudgets, SERVER_BUDGET } from '../modules/performance/budgets.js' +export type { PerfBudget, PerfMeasurement, PerfProfile, ServerBudget } from '../modules/performance/budgets.js' // routes:check — the site's public routes against the judged snapshot (docs/security.md "Routes nobody has judged") export { runRouteCheck } from '../modules/security/routeCheck.js' export type { RunRouteCheckOptions } from '../modules/security/routeCheck.js' diff --git a/src/modules/doctor/rules/performance.ts b/src/modules/doctor/rules/performance.ts new file mode 100644 index 0000000..7262c34 --- /dev/null +++ b/src/modules/doctor/rules/performance.ts @@ -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() + 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 ', + '', + ].join('\n'), + 'src/app/(frontend)/styles.css': '@import url("https://cdn.example/x.css");\n@font-face { font-family: X; src: url(x.woff2) }\n.menu { transition: height 200ms }\n@keyframes spin { to { transform: rotate(1turn) } }', + 'src/components/Map.tsx': '