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,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<typeof budgets.mobile>
|
||||
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<string, number> = { '/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<string, number> = {}
|
||||
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()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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'
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+2
-1
@@ -554,9 +554,10 @@ describe('security and deep status', () => {
|
||||
}
|
||||
const status = await collectDoctorStatus(payload as never)
|
||||
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
|
||||
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(Object.keys(status).sort()).toEqual(['mail', 'media', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
|
||||
expect(status.mail).toBeNull() // no Site integrations global in this config
|
||||
expect(status.media).toBeNull() // no upload collection in this config
|
||||
})
|
||||
test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => {
|
||||
const payload = {
|
||||
|
||||
@@ -304,10 +304,11 @@ describe('commands and skills', () => {
|
||||
expect(pkg.bin['ipal-kit']).toBe('bin/iapl.mjs')
|
||||
})
|
||||
|
||||
test('the package ships the 16 skills as iapl-*, and none under the old names', () => {
|
||||
test('the package ships the 16 skills as iapl-* (plus those new since, never with an old name), and none under the old names', () => {
|
||||
const shipped = readdirSync(path.join(packageRoot, 'docs/agent/skills'))
|
||||
const since117 = ['iapl-performance'] // 1.18.0
|
||||
expect(shipped.filter((n) => n.startsWith('ipal-'))).toEqual([])
|
||||
expect(shipped.filter((n) => n.startsWith('iapl-')).sort()).toEqual(LEGACY_SKILL_NAMES.map((n) => n.replace('ipal-', 'iapl-')).sort())
|
||||
expect(shipped.filter((n) => n.startsWith('iapl-')).sort()).toEqual([...LEGACY_SKILL_NAMES.map((n) => n.replace('ipal-', 'iapl-')), ...since117].sort())
|
||||
})
|
||||
|
||||
test('the installer and the doctor remove the same fixed list of old names', () => {
|
||||
@@ -331,7 +332,7 @@ describe('commands and skills', () => {
|
||||
const first = run('iapl-skills.mjs')
|
||||
expect(first.status, first.stderr).toBe(0)
|
||||
const skills = readdirSync(path.join(dir, '.agents/skills')).sort()
|
||||
expect(skills.filter((n) => n.startsWith('iapl-'))).toHaveLength(16)
|
||||
expect(skills.filter((n) => n.startsWith('iapl-'))).toHaveLength(17) // the 16 renamed + iapl-performance (1.18.0)
|
||||
expect(skills.filter((n) => n.startsWith('ipal-'))).toEqual(['ipal-custom'])
|
||||
expect(readFileSync(path.join(dir, '.agents/skills/ipal-custom/SKILL.md'), 'utf8')).toBe(own)
|
||||
expect(skills).toContain('our-skill')
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createServer, type Server } from 'node:http'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { gzipSync } from 'node:zlib'
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest'
|
||||
|
||||
import { runDoctor } from '../src/modules/doctor/run.js'
|
||||
import { IMAGE_RULES, overBudget, PERF_BUDGETS, perfBudgets } from '../src/modules/performance/budgets.js'
|
||||
|
||||
const packageRoot = path.resolve(import.meta.dirname, '..')
|
||||
const read = (rel: string) => readFileSync(path.join(packageRoot, rel), 'utf8')
|
||||
let dirs: string[] = []
|
||||
afterEach(() => {
|
||||
for (const d of dirs) {rmSync(d, { force: true, recursive: true })}
|
||||
dirs = []
|
||||
})
|
||||
|
||||
function project(files: Record<string, string>): string {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'iapl-perf-'))
|
||||
dirs.push(root)
|
||||
const all: Record<string, string> = {
|
||||
'node_modules/@intecion/ipal-kit/package.json': JSON.stringify({ name: '@intecion/ipal-kit', version: '1.18.0' }),
|
||||
'package.json': JSON.stringify({ name: 'examplepl-web', dependencies: { '@intecion/ipal-kit': '^1.18.0', next: '16.4.6' } }),
|
||||
...files,
|
||||
}
|
||||
for (const [rel, content] of Object.entries(all)) {
|
||||
mkdirSync(path.dirname(path.join(root, rel)), { recursive: true })
|
||||
writeFileSync(path.join(root, rel), content)
|
||||
}
|
||||
return root
|
||||
}
|
||||
const doctor = (root: string, only: string[], extra: { deepStatus?: object; url?: string } = {}) =>
|
||||
runDoctor({ offline: true, only, packageRoot, root, today: '2026-12-01', writeSeen: false, ...extra })
|
||||
/** Each line starts with the expected text, in order. */
|
||||
const startWith = (lines: string[], expected: string[]) => {
|
||||
expect(lines).toHaveLength(expected.length)
|
||||
expected.forEach((text, i) => expect(lines[i].startsWith(text), `${lines[i]}\n should start with: ${text}`).toBe(true))
|
||||
}
|
||||
const found = async (root: string, only: string[], extra = {}) => (await doctor(root, only, extra)).findings.map((f) => `${f.rule}: ${f.message}`)
|
||||
|
||||
describe('doctor: performance group (static)', () => {
|
||||
test('a clean site has no findings', async () => {
|
||||
const root = project({
|
||||
'e2e/performance.spec.ts': 'perfBudgets({})',
|
||||
'next.config.ts': 'images: buildImagesConfig()',
|
||||
'src/app/(frontend)/[locale]/layout.tsx': "import { Inter } from 'next/font/google'\nconst body = Inter({ display: 'swap' })\n<script type=\"application/ld+json\" />",
|
||||
'src/app/(frontend)/styles.css': '@import "@intecion/ipal-kit/tokens.css";\n.card { transition: transform 150ms, opacity 150ms }',
|
||||
})
|
||||
expect(await found(root, ['performance'])).toEqual([])
|
||||
})
|
||||
|
||||
test('images config, fonts, render-blocking, embeds, animations and a missing budget test are reported', async () => {
|
||||
const root = project({
|
||||
'next.config.ts': 'export default { images: { remotePatterns: [] } }',
|
||||
'src/app/(frontend)/[locale]/layout.tsx': [
|
||||
"import { Fraunces, Inter, Lora } from 'next/font/google'",
|
||||
"const a = Inter({ display: 'block' })",
|
||||
'<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter" />',
|
||||
'<script src="https://widget.example/chat.js"></script>',
|
||||
'<script async src="https://ok.example/a.js"></script>',
|
||||
].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': '<iframe src="https://www.google.com/maps/embed?pb=1" />\n<iframe loading="lazy" src="https://maps.example" />\n<iframe src="https://youtube.com/embed/x" />',
|
||||
'src/components/Sticky.tsx': "window.addEventListener('scroll', onScroll)\n<div className=\"transition-all\" />",
|
||||
})
|
||||
const out = await found(root, ['performance'])
|
||||
const by = (rule: string) => out.filter((l) => l.startsWith(`${rule}:`))
|
||||
expect(by('perf-images-config')).toHaveLength(1)
|
||||
startWith(by('perf-fonts'), [
|
||||
'perf-fonts: a font is loaded from a third-party host',
|
||||
'perf-fonts: font-display: block hides the text until',
|
||||
'perf-fonts: @font-face without font-display',
|
||||
'perf-fonts: 3 font families on the site (Fraunces, Inter, Lora)',
|
||||
])
|
||||
// the sync <script src>, the Google Fonts stylesheet <link> (also a font finding) and the remote @import
|
||||
expect(by('perf-render-blocking')).toHaveLength(3)
|
||||
expect(by('perf-embeds')).toHaveLength(1) // the map; the lazy one is fine, YouTube is iapl-audit's
|
||||
startWith(by('perf-animations'), [
|
||||
'perf-animations: a transition of a layout property',
|
||||
'perf-animations: transition-all or a transition',
|
||||
'perf-animations: a scroll listener runs on every scroll event',
|
||||
'perf-animations: the site animates (@keyframes',
|
||||
])
|
||||
expect(by('perf-budgets')).toHaveLength(1)
|
||||
// every finding is a warning (info for the budget test) in 1.18.0: reported, never failing CI
|
||||
const report = await doctor(root, ['performance'])
|
||||
expect(new Set(report.findings.map((f) => f.severity))).toEqual(new Set(['info', 'warning']))
|
||||
})
|
||||
|
||||
test('a remote stylesheet <link> is reported as render-blocking', async () => {
|
||||
const root = project({ 'e2e/perf.spec.ts': '', 'next.config.ts': 'buildImagesConfig()', 'src/app/layout.tsx': '<link href="https://cdn.example/a.css" rel="stylesheet" />' })
|
||||
expect(await found(root, ['perf-render-blocking'])).toEqual(['perf-render-blocking: a stylesheet from another host blocks the first paint on an extra connection'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('doctor: performance group (deep and live)', () => {
|
||||
test('perf-images: stored images over the limits', async () => {
|
||||
const root = project({})
|
||||
expect(await found(root, ['perf-images'], { deepStatus: { media: { images: 40, oversized: 3, tooWide: 1 } } })).toEqual([
|
||||
`perf-images: of 40 images, 3 are over ${(IMAGE_RULES.maxBytes / 1048576).toFixed(1)} MB and 1 wider than 2560 px`,
|
||||
])
|
||||
expect(await found(root, ['perf-images'], { deepStatus: { media: { images: 40, oversized: 0, tooWide: 0 } } })).toEqual([])
|
||||
})
|
||||
|
||||
let server: Server
|
||||
let url = ''
|
||||
let html = ''
|
||||
let compress = true
|
||||
beforeAll(async () => {
|
||||
server = createServer((_req, res) => {
|
||||
if (compress) {res.writeHead(200, { 'content-encoding': 'gzip', 'content-type': 'text/html' }).end(gzipSync(html))}
|
||||
else {res.writeHead(200, { 'content-type': 'text/html' }).end(html)}
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
url = `http://127.0.0.1:${(server.address() as { port: number }).port}`
|
||||
})
|
||||
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())))
|
||||
|
||||
test('perf-live: compression, blocking scripts, font preloads, a lazy first image, HTML size', async () => {
|
||||
const root = project({})
|
||||
html = '<html><head><script src="/_next/a.js" async=""></script><script src="/_next/p.js" noModule=""></script></head><body><main><img loading="eager" fetchpriority="high" src="/h.webp"></main></body></html>'
|
||||
expect(await found(root, ['perf-live'], { url })).toEqual([])
|
||||
compress = false
|
||||
const fonts = '<link rel="preload" href="/f.woff2" as="font" crossorigin="">'.repeat(5)
|
||||
html = `<html><head>${fonts}<script src="/legacy.js"></script></head><body><main><img loading="lazy" src="/h.webp"></main>${'x'.repeat(160 * 1024)}</body></html>`
|
||||
const out = await found(root, ['perf-live'], { url })
|
||||
compress = true
|
||||
startWith(out, [
|
||||
'perf-live: the HTML came back uncompressed',
|
||||
'perf-live: render-blocking scripts in <head>: /legacy.js',
|
||||
'perf-live: 5 font files preloaded',
|
||||
'perf-live: the first image of the page is lazy-loaded',
|
||||
'perf-live: the home page HTML is 160 KB (budget 150 KB)',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Site integrations: one read for callers that start together', () => {
|
||||
test('two reads in flight share one query; the next read queries again', async () => {
|
||||
const { getSiteIntegrations } = await import('../src/modules/payload/getSiteIntegrations.js')
|
||||
let calls = 0
|
||||
const payload = { findGlobal: async () => { calls++; await new Promise((r) => setTimeout(r, 5)); return { gtmContainerId: 'GTM-X' } } } as never
|
||||
const [a, b] = await Promise.all([getSiteIntegrations(payload), getSiteIntegrations(payload)])
|
||||
expect(a).toEqual({ gtmContainerId: 'GTM-X' })
|
||||
expect(b).toBe(a)
|
||||
expect(calls).toBe(1)
|
||||
await getSiteIntegrations(payload)
|
||||
expect(calls).toBe(2) // nothing kept after the read: a save in the panel is seen by the next request
|
||||
await getSiteIntegrations(payload, { depth: 0 })
|
||||
expect(calls).toBe(3) // reads with options are never shared
|
||||
})
|
||||
})
|
||||
|
||||
describe('budgets', () => {
|
||||
const measured = { bytes: { css: 11_000, font: 209_000, js: 188_000 }, cls: 0.03, inp: 40, lcp: 800, renderBlocking: ['/a.css'], requests: 26, tbt: 20, thirdParty: [] as string[] }
|
||||
test('the defaults are Core Web Vitals "good"; a site within them passes', () => {
|
||||
expect(PERF_BUDGETS.mobile).toMatchObject({ cls: 0.1, inp: 200, lcp: 2500 })
|
||||
expect(overBudget(measured, PERF_BUDGETS.mobile)).toEqual([])
|
||||
})
|
||||
test('a project tightens or loosens any number; every broken budget is named', () => {
|
||||
const tight = perfBudgets({ mobile: { jsBytes: 150_000, lcp: 700, thirdParty: ['https://challenges.cloudflare.com'] } }).mobile
|
||||
expect(tight.cls).toBe(0.1)
|
||||
expect(overBudget({ ...measured, renderBlocking: ['/a.css', '/b.js', '/c.js'], thirdParty: ['https://challenges.cloudflare.com', 'https://www.googletagmanager.com'] }, tight)).toEqual([
|
||||
'LCP 800 ms > 700 ms',
|
||||
'JS 188000 B > 150000 B',
|
||||
'render-blocking 3 > 2: /a.css, /b.js, /c.js',
|
||||
'third-party requests before consent: https://www.googletagmanager.com',
|
||||
])
|
||||
// the defaults are not changed by an override
|
||||
expect(PERF_BUDGETS.mobile.jsBytes).toBe(250_000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('what 1.18.0 changed for speed (source checks; measured in docs/performance.md)', () => {
|
||||
test('the /client barrels carry no "use client": a page ships only the components it uses', () => {
|
||||
for (const file of ['src/exports/client.ts', ...['accessibility', 'analytics', 'consent', 'lightbox', 'stats', 'turnstile'].map((m) => `src/modules/${m}/client.ts`)]) {
|
||||
expect(read(file), file).not.toMatch(/^\s*['"]use client['"]/m)
|
||||
}
|
||||
})
|
||||
test('the lightbox viewer is loaded on first open, not with the page', () => {
|
||||
const provider = read('src/modules/lightbox/LightboxProvider.tsx')
|
||||
expect(provider).toMatch(/lazy\(\(\) => import\('\.\/LightboxDialog\.js'\)/)
|
||||
expect(provider).not.toMatch(/^import \{ LightboxDialog \}/m)
|
||||
})
|
||||
test('route and metadata reads are cached per request by value, not by array identity', () => {
|
||||
const helpers = read('src/modules/frontend/createContentHelpers.ts')
|
||||
expect(helpers).toMatch(/resolveRouteCached\(locale, JSON\.stringify\(segments \?\? \[\]\), page\)/)
|
||||
expect(helpers).toMatch(/pageMetadataCached = cache\(/)
|
||||
})
|
||||
test('reads that need one field select it', () => {
|
||||
expect(read('src/modules/seo/slugsAcrossLocales.ts')).toMatch(/select: \{ slug: true \}/)
|
||||
expect(read('src/modules/seo/readSiteMetaConfig.ts')).toMatch(/select: \{ slug: true \}/)
|
||||
expect(read('src/modules/consent/getConsentTexts.ts')).toMatch(/select: \{ privacyPolicy: true \}/)
|
||||
})
|
||||
test('reduced motion: the banner and the cookie button stop their transitions', () => {
|
||||
expect(read('src/modules/consent/CookieBanner.tsx').match(/motion-reduce:transition-none/g)).toHaveLength(3)
|
||||
expect(read('src/modules/consent/CookieButton.tsx')).toContain('motion-reduce:transition-none')
|
||||
})
|
||||
test('the perf-lab helper the skill hands out is the one the reference gate runs', () => {
|
||||
expect(read('docs/agent/skills/iapl-performance/resources/perf-lab.mjs')).toBe(read('reference/e2e/perf-lab.mjs'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('deep status: images over the limits (counts only)', () => {
|
||||
test('counted per upload collection with the plugin\'s limits; a collection without the upload fields is skipped', async () => {
|
||||
const { countHeavyMedia } = await import('../src/modules/doctor/status.js')
|
||||
const calls: unknown[] = []
|
||||
const payload = {
|
||||
count: async ({ collection, where }: { collection: string; where: { and?: Array<Record<string, unknown>> } }) => {
|
||||
calls.push(where)
|
||||
if (collection === 'broken') {throw new Error('no width field')}
|
||||
const filter = JSON.stringify(where)
|
||||
return { totalDocs: filter.includes('filesize') ? 2 : filter.includes('width') ? 1 : 30 }
|
||||
},
|
||||
}
|
||||
expect(await countHeavyMedia(payload as never, [{ slug: 'pages' }, { slug: 'media', upload: true }, { slug: 'broken', upload: {} }])).toEqual({ images: 30, oversized: 2, tooWide: 1 })
|
||||
expect(JSON.stringify(calls)).toContain(`"greater_than":${IMAGE_RULES.maxBytes}`)
|
||||
expect(await countHeavyMedia(payload as never, [{ slug: 'pages' }])).toBeNull()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user