143 lines
8.2 KiB
TypeScript
143 lines
8.2 KiB
TypeScript
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. Third-party requests are recorded (none may come
|
||
* before consent) and aborted, so an external host's speed cannot fail or hang the gate.
|
||
*/
|
||
const runs = Number(process.env.PERF_RUNS ?? 1)
|
||
|
||
const budgets = perfBudgets({
|
||
// measured 1.18.0 (docs/dev/perf/*-1180-after.json): JS 175–180 kB on a page without a form, 184–188 kB with one
|
||
// (the form's code loads there only), CSS 11–12 kB, fonts 209.5 kB (Inter + Fraunces, latin + latin-ext; the
|
||
// heading font not preloaded), LCP 0.74–0.82 s on the phone, 0.28–0.30 s on the desktop
|
||
desktop: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 195_000, lcp: 800, renderBlocking: 1, requests: 36, tbt: 50 },
|
||
mobile: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 195_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 lazy 404: its content arrives after hydration; the placeholder in not-found.tsx keeps its height (CLS 0)
|
||
{ budget: { mobile: { lcp: 2200 } }, name: '404', path: '/pl/nie-ma-takiej-strony', why: 'the 404 content comes from a server action after hydration' },
|
||
]
|
||
|
||
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, { blockThirdParty: true })
|
||
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}: no query counted — the profiler did not record this database`).toBeGreaterThan(0)
|
||
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()
|
||
}
|
||
})
|
||
})
|
||
|
||
/**
|
||
* MongoDB TTL index of the consent log (1.18.0, shared/ttl.ts): the database deletes records older than the retention
|
||
* itself, also on a quiet site. The index exists with the retention's lifetime, and a new record carries the date it
|
||
* counts from. Skipped when not MongoDB.
|
||
*/
|
||
test('consent log: the TTL index is there and a new record carries its date', async ({ baseURL }) => {
|
||
const uri = process.env.DATABASE_URI
|
||
test.skip(!uri?.startsWith('mongodb'), 'not MongoDB')
|
||
const site = process.cwd()
|
||
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()
|
||
try {
|
||
const records = conn.db!.collection('consent-records')
|
||
const ttl = (await records.indexes()).find((i) => i.name === 'iapl_ttl')
|
||
expect(ttl, 'the TTL index').toMatchObject({ expireAfterSeconds: 1095 * 86_400, key: { iaplTtlFrom: 1 } })
|
||
const id = [...crypto.getRandomValues(new Uint8Array(12))].map((b) => b.toString(16).padStart(2, '0')).join('')
|
||
const res = await fetch(`${baseURL}/api/ipal/consent`, {
|
||
body: JSON.stringify({ id, state: { analytics: false, functional: false, marketing: false, necessary: true }, version: 1 }),
|
||
headers: { 'content-type': 'application/json', origin: baseURL! },
|
||
method: 'POST',
|
||
})
|
||
expect(res.status).toBe(201)
|
||
const record = await records.findOne({ consentId: id })
|
||
expect(record?.iaplTtlFrom, 'the date the TTL counts from').toBeInstanceOf(Date)
|
||
await records.deleteOne({ consentId: id })
|
||
} finally {
|
||
await conn.close()
|
||
}
|
||
})
|