Merge claude/performance-2026-12-36a376: fewer queries per render, no 'use client' on the /client barrels, budgets, the doctor's performance and growth groups

Conflicts kept both sides: the doctor status (twoFactorConfirm with growth and media), its key test, e2e:built (the 2FA
enrolment spec and the performance budgets), the reference index (regenerated). Reference skill copies synced
(iapl-performance added, iapl-audit and iapl-reference updated).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 14:58:44 +01:00
co-authored by Claude Opus 5.5
77 changed files with 5841 additions and 80 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js'
export { A11Y_DEFAULT_TEXTS, AccessibilityWidget } from './AccessibilityWidget.js'
export type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js'
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { Analytics } from './Analytics.js'
export type { AnalyticsProps } from './Analytics.js'
// Low-level pixel loaders — exported for manual conversion events if a project
+4 -2
View File
@@ -12,6 +12,8 @@ export type MediaProps = {
/** Override the document's alt text — `''` for a decorative image. */
alt?: string
className?: string
/** Above the fold, not the LCP image (a logo): eager, without fetchPriority="high" or a preload. */
eager?: boolean
poster?: MediaValue
/** Only the first visible image of the page (the LCP image). */
priority?: boolean
@@ -25,14 +27,14 @@ export type MediaProps = {
* Every image or video of the library blocks. With `Image` (next/image, bound by createBlockRegistry)
* images are optimized with blur-up; without it a plain <img> with width, height, lazy loading and focal point.
*/
export function Media({ alt, className, Image, poster, priority = false, resource, sizes = MEDIA_SIZES.full, videoMode = 'player' }: { Image?: ImageComponent } & MediaProps) {
export function Media({ alt, className, eager = false, Image, poster, priority = false, resource, sizes = MEDIA_SIZES.full, videoMode = 'player' }: { Image?: ImageComponent } & MediaProps) {
const video = videoProps(resource, { mode: videoMode, poster })
if (video) {
// Captions are not stored with media uploads; a project that needs them swaps Media (ui option).
// eslint-disable-next-line jsx-a11y/media-has-caption
return <video {...video} aria-hidden={videoMode === 'background' ? true : undefined} className={className} />
}
const img = mediaImageProps(resource, { priority, sizes, ...(alt !== undefined ? { alt } : {}) })
const img = mediaImageProps(resource, { eager, priority, sizes, ...(alt !== undefined ? { alt } : {}) })
if (!img) {return null}
if (Image) {return <Image {...img} className={className} />}
const { blurDataURL: _blur, placeholder: _placeholder, preload: _preload, ...plain } = img
+3 -3
View File
@@ -136,7 +136,7 @@ const defaults: Required<CookieBannerClassNames> = {
closeButton: `shrink-0 ${radius} p-1 ${mutedText} hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]`,
content: 'flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between',
control: 'mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]',
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform motion-reduce:transition-none translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
cookie: `flex flex-col gap-1 border-t pt-2 first:border-t-0 first:pt-0 ${border}`,
cookieList: 'mt-3 flex flex-col gap-2',
cookieMeta: `grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs ${mutedText}`,
@@ -168,7 +168,7 @@ const defaults: Required<CookieBannerClassNames> = {
const DETAILED_DIALOG = `relative max-h-[90vh] w-full max-w-4xl overflow-y-auto ${radius} border p-6 shadow-2xl sm:p-8 ${surface} ${border}`
const SWITCH_TRACK =
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full bg-[var(--ipal-border,#d4d4d4)] transition-colors data-[checked=true]:bg-[var(--ipal-primary,#2563eb)] disabled:cursor-default disabled:opacity-60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ipal-primary,#2563eb)]'
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full bg-[var(--ipal-border,#d4d4d4)] transition-colors motion-reduce:transition-none data-[checked=true]:bg-[var(--ipal-primary,#2563eb)] disabled:cursor-default disabled:opacity-60 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ipal-primary,#2563eb)]'
type CookieBannerProps = {
classNames?: CookieBannerClassNames
@@ -358,7 +358,7 @@ export function CookieBanner({
return (
<details className={cn('cookies')} data-ipal="cookies">
<summary className={cn('cookiesToggle')}>
<svg aria-hidden="true" className="transition-transform group-open:rotate-90" fill="none" height="14" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="14">
<svg aria-hidden="true" className="transition-transform motion-reduce:transition-none group-open:rotate-90" fill="none" height="14" stroke="currentColor" strokeLinecap="round" strokeWidth="2" viewBox="0 0 24 24" width="14">
<path d="m9 18 6-6-6-6" />
</svg>
{labels.cookies} ({rows.length})
+1 -1
View File
@@ -79,7 +79,7 @@ export function CookieButton({ avoid, className, reserve = COOKIE_BUTTON_RESERVE
const cls =
className ??
'flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-[background-color,transform] ' +
'flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-[background-color,transform] motion-reduce:transition-none ' +
'bg-[var(--ipal-surface,light-dark(#fff,var(--ipal-surface-dark,#171717)))] border-[var(--ipal-border,light-dark(#e5e5e5,var(--ipal-border-dark,#262626)))] hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]'
const position: CSSProperties = className
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { ConsentProvider, useConsentContext } from './ConsentContext.js'
export { ConsentScript } from './ConsentScript.js'
export { readEffectiveConsent } from './consentStore.js'
+2
View File
@@ -141,6 +141,8 @@ async function readPrivacyPage(payload: BasePayload, settingsSlug: string): Prom
slug: settingsSlug as never,
depth: 1,
locale: 'all' as never,
// only the privacy page: without it depth 1 brought every page Site settings points at, in every language
select: { privacyPolicy: true } as never,
})) as { privacyPolicy?: unknown }
const page = settings.privacyPolicy
return page && typeof page === 'object' ? (page as PrivacyPage) : null
+140
View File
@@ -0,0 +1,140 @@
import type { BasePayload } from 'payload'
/**
* What grows in the database (docs/performance.md → "What grows"): read-only counts for the doctor's `growth` rules.
* Counts, sizes and dates only — never a value. Every read is capped, so the check stays cheap on a big site.
*/
export type GrowthStatus = {
/** Every collection (the plugin's, the project's and Payload's own): documents, bytes on MongoDB (null elsewhere), the oldest record. */
collections: Array<{ bytes: null | number; docs: number; oldest: null | string; slug: string }>
/** Key-value store entries (`payload-kv`): all of them, and those whose own expiry has passed (null = not readable). */
kv: { expired: null | number; total: number } | null
/** Media no document or global points at (by id), from the first `checked` documents. null = no upload collection. */
media: { capped: boolean; checked: number; orphaned: number; total: number } | null
/** Versioned collections and globals: the configured limit (0 = unlimited), all versions, and the documents. */
versions: Array<{ docs: number; kind: 'collection' | 'global'; max: number; slug: string; total: number }>
}
type CollectionLike = { slug: string; timestamps?: boolean; upload?: unknown; versions?: { maxPerDoc?: number } | false }
type GlobalLike = { slug: string; versions?: { max?: number } | false }
/** Documents read to find orphaned media (all collections and globals together). */
export const ORPHAN_SCAN_LIMIT = 5000
/** Key-value entries read to count expired ones. */
export const KV_SCAN_LIMIT = 5000
/** An expiry a plugin entry carries in its data (`resetAt`, `expiresAt`, `until`, epoch ms or ISO). */
function expiryOf(data: unknown): null | number {
if (!data || typeof data !== 'object') {return null}
for (const name of ['expiresAt', 'resetAt', 'until', 'exp']) {
const v = (data as Record<string, unknown>)[name]
const t = typeof v === 'number' ? v : typeof v === 'string' ? Date.parse(v) : Number.NaN
if (Number.isFinite(t)) {return t}
}
return null
}
async function mongoBytes(payload: BasePayload, slug: string): Promise<null | number> {
const db = payload.db as unknown as { collections?: Record<string, { collection?: { collectionName?: string } }>; connection?: { db?: { command: (c: object) => Promise<{ size?: number; totalIndexSize?: number }> } }; name?: string }
const name = db.collections?.[slug]?.collection?.collectionName
if (db.name !== 'mongoose' || !name || !db.connection?.db) {return null}
try {
const stats = await db.connection.db.command({ collStats: name })
return (stats.size ?? 0) + (stats.totalIndexSize ?? 0)
} catch {
return null
}
}
export async function collectGrowth(payload: BasePayload): Promise<GrowthStatus> {
const collections = (payload.config.collections ?? []) as unknown as CollectionLike[]
const globals = (payload.config.globals ?? []) as unknown as GlobalLike[]
const out: GrowthStatus = { collections: [], kv: null, media: null, versions: [] }
for (const c of collections) {
const collection = c.slug as never
try {
const docs = (await payload.count({ collection, overrideAccess: true })).totalDocs
let oldest: null | string = null
if (docs && c.timestamps !== false) {
const first = await payload.find({ collection, depth: 0, limit: 1, overrideAccess: true, pagination: false, select: { createdAt: true } as never, sort: 'createdAt' })
oldest = (first.docs[0] as { createdAt?: string } | undefined)?.createdAt ?? null
}
out.collections.push({ slug: c.slug, bytes: await mongoBytes(payload, c.slug), docs, oldest })
if (c.versions) {
const total = (await payload.countVersions({ collection, overrideAccess: true })).totalDocs
out.versions.push({ slug: c.slug, docs, kind: 'collection', max: c.versions.maxPerDoc ?? 100, total })
}
} catch {
// a collection the adapter cannot count (a virtual one): left out
}
}
for (const g of globals) {
if (!g.versions) {continue}
try {
const total = (await payload.countGlobalVersions({ global: g.slug as never, overrideAccess: true })).totalDocs
out.versions.push({ slug: g.slug, docs: 1, kind: 'global', max: g.versions.max ?? 100, total })
} catch {
// not countable on this adapter
}
}
// payload-kv: entries carry no expiry of their own in Payload; the plugin's carry one in their data
const kv = (payload as unknown as { kv?: { get: (k: string) => Promise<unknown>; keys: () => Promise<string[]> } }).kv
if (kv) {
try {
const keys = await kv.keys()
let expired = 0
const now = Date.now()
for (const key of keys.slice(0, KV_SCAN_LIMIT)) {
const t = expiryOf(await kv.get(key))
if (t !== null && t < now) {expired++}
}
out.kv = { expired: keys.length > KV_SCAN_LIMIT ? null : expired, total: keys.length }
} catch {
out.kv = null
}
}
// Orphaned media: ids of the upload collections that no other document or global mentions (any field, any depth)
const uploads = collections.filter((c) => c.upload)
if (uploads.length) {
const ids = new Set<string>()
for (const u of uploads) {
const res = await payload.find({ collection: u.slug as never, depth: 0, limit: ORPHAN_SCAN_LIMIT, overrideAccess: true, pagination: false, select: {} as never })
for (const d of res.docs as Array<{ id: number | string }>) {ids.add(String(d.id))}
}
const seen = new Set<string>()
let checked = 0
// every string and number anywhere in a document (relations, uploads, rich text, blocks) — ids are among them
const mark = (value: unknown, depth = 0): void => {
if (depth > 40 || value == null) {return}
if (typeof value === 'string' || typeof value === 'number') {
const key = String(value)
if (ids.has(key)) {seen.add(key)}
return
}
if (Array.isArray(value)) {for (const v of value) {mark(v, depth + 1)}}
else if (typeof value === 'object') {for (const v of Object.values(value)) {mark(v, depth + 1)}}
}
for (const c of collections) {
if (c.upload || c.slug.startsWith('payload-') || checked >= ORPHAN_SCAN_LIMIT) {continue}
try {
const res = await payload.find({ collection: c.slug as never, depth: 0, draft: true, limit: ORPHAN_SCAN_LIMIT - checked, locale: 'all' as never, overrideAccess: true, pagination: false })
checked += res.docs.length
for (const d of res.docs) {mark(d)}
} catch {
// not readable this way: its references are not counted (the orphan count can then be too high, never too low)
}
}
for (const g of globals) {
try {
mark(await payload.findGlobal({ slug: g.slug as never, depth: 0, draft: true, locale: 'all' as never, overrideAccess: true }))
} catch {
// not readable
}
}
out.media = { capped: checked >= ORPHAN_SCAN_LIMIT, checked, orphaned: [...ids].filter((id) => !seen.has(id)).length, total: ids.size }
}
return out
}
+180
View File
@@ -0,0 +1,180 @@
import { readdirSync, statSync } from 'node:fs'
import path from 'node:path'
import type { DoctorContext } from '../project.js'
import type { DoctorRule, GrowthThresholds, RuleFinding } from '../types.js'
/**
* The growth group (docs/performance.md → "What grows"): what makes a site and its database swell over the years.
* Deep rules read counts, sizes and dates (never values) from the status; the static one measures two folders on this
* machine. Warnings in 1.18.0, every threshold set in `iapl-doctor.json` → `growth`. Nothing here deletes anything.
*/
const DOCS = 'docs/performance.md'
const DAY = 86_400_000
export const GROWTH_DEFAULTS: Required<GrowthThresholds> = {
expiredKv: 1000,
imageCacheMB: 1024,
maxDocs: 200_000,
maxMB: 512,
maxVersions: 50_000,
orphanedMedia: 25,
submissionDays: 730,
uploadsMB: 2048,
}
const limits = (ctx: DoctorContext): Required<GrowthThresholds> => ({
...GROWTH_DEFAULTS,
// only numbers from iapl-doctor.json; anything else keeps the default
...Object.fromEntries(Object.entries(ctx.config.growth ?? {}).filter(([, v]) => typeof v === 'number' && Number.isFinite(v) && v >= 0)),
})
const days = (iso: null | string, today: string) => (iso ? Math.max(0, Math.floor((Date.parse(today) - Date.parse(iso)) / DAY)) : 0)
const mb = (bytes: number) => Math.round(bytes / 1024 / 1024)
/** Size of a folder on disk (bytes), capped at 200 000 files; 0 when it is not there. */
export function folderBytes(dir: string): number {
let total = 0
let files = 0
const walk = (d: string) => {
let names: string[]
try {
names = readdirSync(d)
} catch {
return
}
for (const name of names) {
if (++files > 200_000) {return}
const file = path.join(d, name)
try {
const s = statSync(file)
if (s.isDirectory()) {walk(file)} else {total += s.size}
} catch {
// gone meanwhile
}
}
}
walk(dir)
return total
}
export const growthRules: DoctorRule[] = [
{
// A collection past the thresholds: slower queries, backups and restores, a bigger bill on a managed database
id: 'growth-size',
check: (ctx) => {
const g = ctx.deep?.growth
if (!g) {return []}
const t = limits(ctx)
const big = g.collections.filter((c) => c.docs > t.maxDocs || (c.bytes ?? 0) > t.maxMB * 1024 * 1024)
return big.map((c) => ({
fix: 'a retention for logs (consentLog / stats retentionDays, forms.submissionRetentionDays), or raise growth.maxDocs / maxMB in iapl-doctor.json with a reason',
message: `${c.slug}: ${c.docs} documents${c.bytes === null ? '' : `, ${mb(c.bytes)} MB with indexes`}${c.oldest ? `, the oldest from ${c.oldest.slice(0, 10)}` : ''}`,
severity: 'warning' as const,
}))
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// Versions: Payload keeps 100 per document by default; 0 keeps every save forever
id: 'growth-versions',
check: (ctx) => {
const g = ctx.deep?.growth
if (!g) {return []}
const t = limits(ctx)
const out: RuleFinding[] = []
for (const v of g.versions) {
if (v.max === 0) {out.push({ fix: `versions: { ${v.kind === 'global' ? 'max' : 'maxPerDoc'}: 20 } (Payload's default is 100)`, message: `${v.kind} ${v.slug} keeps every version without a limit (${v.total} now)`, severity: 'warning' })}
else if (v.total > t.maxVersions) {out.push({ fix: `a lower ${v.kind === 'global' ? 'max' : 'maxPerDoc'} (now ${v.max}); Payload trims a document's oldest versions on its next save`, message: `${v.kind} ${v.slug}: ${v.total} versions for ${v.docs} document(s)`, severity: 'warning' })}
}
return out
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// A log with a retention whose oldest record is older than it: the purge is not running (it runs after a new
// record, at most once a day per process — a site without new records keeps the old ones)
id: 'growth-retention',
check: (ctx) => {
const g = ctx.deep?.growth
if (!g) {return []}
const out: RuleFinding[] = []
for (const [slug, keep] of Object.entries(g.retention)) {
const c = g.collections.find((x) => x.slug === slug)
if (!c || !keep || !c.oldest) {continue}
const age = days(c.oldest, ctx.today)
if (age > keep + 2) {out.push({ fix: 'check the server log for "retention purge failed"; the purge runs after the next new record', message: `${slug} keeps records for ${keep} days, but the oldest is ${age} days old`, severity: 'warning' })}
}
return out
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// Form submissions are personal data and the one plugin collection without a retention by default
id: 'growth-submissions',
check: (ctx) => {
const g = ctx.deep?.growth
const c = g?.collections.find((x) => x.slug === 'form-submissions')
if (!g || !c || !c.docs || g.retention['form-submissions']) {return []}
const age = days(c.oldest, ctx.today)
const t = limits(ctx)
return [{
fix: 'iapl({ forms: { submissionRetentionDays: 365 } }) — or delete old ones in the panel; a decision for the client (AGENTS.md → Project decisions)',
message: `${c.docs} form submissions kept without a retention, the oldest ${age} days old`,
severity: age > t.submissionDays ? 'warning' : 'info',
}]
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
id: 'growth-kv',
check: (ctx) => {
const kv = ctx.deep?.growth?.kv
if (!kv || kv.expired === null || kv.expired <= limits(ctx).expiredKv) {return []}
return [{ fix: 'expired entries are dead weight: the plugin sweeps its own mail-service nonces (1.18.0); entries of another package are its own', message: `payload-kv holds ${kv.total} entries, ${kv.expired} of them expired`, severity: 'warning' }]
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// Media nobody points at: storage, backups and the panel's media list grow for nothing
id: 'growth-media',
check: (ctx) => {
const m = ctx.deep?.growth?.media
if (!m || !m.orphaned) {return []}
return [{
fix: 'review them in the panel (Media) and delete what no page needs — the plugin never deletes media by itself',
message: `${m.orphaned} of ${m.total} media files are not used by any document or global${m.capped ? ` (from the first ${m.checked} documents: may be fewer)` : ''}`,
severity: m.orphaned > limits(ctx).orphanedMedia ? 'warning' : 'info',
}]
},
docs: DOCS,
group: 'growth',
source: 'deep',
},
{
// On this machine: Next's image cache has no size cap of its own; local uploads belong on R2 in production
id: 'growth-disk',
check: (ctx) => {
const t = limits(ctx)
const out: RuleFinding[] = []
const cache = folderBytes(path.join(ctx.root, '.next', 'cache', 'images'))
if (mb(cache) > t.imageCacheMB) {out.push({ file: '.next/cache/images', fix: 'it is rebuilt on demand: delete it, or let each Coolify deploy start with an empty one (no persistent volume on .next)', message: `the image cache is ${mb(cache)} MB (no size cap in Next; each image × width × format)`, severity: 'info' })}
const uploads = folderBytes(path.join(ctx.root, 'media'))
if (mb(uploads) > t.uploadsMB) {out.push({ file: 'media', fix: 'production media on R2 (buildR2Storage); locally, a copy of the database you no longer need can go', message: `the local upload folder is ${mb(uploads)} MB`, severity: 'info' })}
return out
},
docs: DOCS,
group: 'growth',
source: 'static',
},
]
+200
View File
@@ -0,0 +1,200 @@
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) => {
// only a project that already runs browser tests: there the budget test is one file to copy (a new site from the
// starter has none yet — AGENT.md §11 and the iapl-performance skill bring it in with the first e2e tests)
const playwright = !!ctx.installed('@playwright/test') || ['playwright.config.ts', 'playwright.config.js', 'playwright.config.mjs'].some((f) => ctx.exists(f))
if (!playwright) {return []}
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',
},
]
+4
View File
@@ -10,10 +10,12 @@ import { agentRules } from './rules/agents.js'
import { blockRules } from './rules/blocks.js'
import { consentRules } from './rules/consent.js'
import { envRules } from './rules/env.js'
import { growthRules } from './rules/growth.js'
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 +43,8 @@ export const doctorRules: DoctorRule[] = [
...legacyRules,
...seedRules,
...blockRules,
...performanceRules,
...growthRules,
...toolingRules,
...liveRules,
...deepRules,
+36 -2
View File
@@ -10,13 +10,16 @@ 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 { countPendingEnrolments, mailConfigured } from '../security/totp/enrolmentConfirm.js'
import { secondFactorPassed, SETUP_FROM_FIELD } from '../security/totp/secondFactor.js'
import { countAccountsWithoutTotp } from '../security/totp/setupRequired.js'
import { accessAllowed } from '../shared/accessAnswer.js'
import { readEnv } from '../shared/envName.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { retentionMap } from '../shared/retention.js'
import { turnstileSecretFromEnv } from '../turnstile/config.js'
import { collectGrowth } from './growth.js'
import { visitorWritableEntities } from './visitorWrites.js'
/** The plugin's own version — a constant (src/version.ts), never a file read at run time. */
@@ -24,7 +27,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,
@@ -56,6 +83,13 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
: { on: false }
}
const pendingCookies = collections.some((c) => c.slug === COOKIE_REVIEW_SLUG) ? await countPendingCookies(payload) : null
const media = await countHeavyMedia(payload, collections)
let growth: DoctorStatus['growth'] = null
try {
growth = { ...(await collectGrowth(payload)), retention: retentionMap(payload) }
} catch {
growth = null
}
// Turnstile: the recorded state and where the secret comes from — never the keys themselves.
let turnstile: DoctorStatus['turnstile'] = null
let secretFromEnv: boolean | null = null
@@ -130,7 +164,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, twoFactorConfirm, usersSetupClosed, usersWithout2fa, visitorWrites }
return { growth, mail, media, node: process.version, openSignUp, originKnown, pendingCookies, plugin: pluginVersion(), staffOnOwnRoles, staffOpenToOthers, turnstile, turnstileSecretFromEnv: secretFromEnv, twoFactorConfirm, usersSetupClosed, usersWithout2fa, visitorWrites }
}
export type DoctorEndpointOptions = {
+27
View File
@@ -1,3 +1,4 @@
import type { GrowthStatus } from './growth.js'
import type { DoctorContext } from './project.js'
/** How bad a finding is: error fails CI, warning is drift to fix, info is worth knowing. */
@@ -40,6 +41,8 @@ export type DoctorConfig = {
domain?: string
/** Paths of extra rule modules (relative to the project), each exporting `rules: DoctorRule[]`. */
extraRules?: string[]
/** Thresholds of the `growth` rules (docs/performance.md → "What grows"). */
growth?: GrowthThresholds
/** true once the site is live: seeds must then name their records. */
launched?: boolean
/**
@@ -58,6 +61,8 @@ export type DoctorStatus = {
envProblems?: string[]
/** Why the deep check could not finish (first line). */
error?: string
/** What grows (1.18.0, docs/performance.md): counts, sizes, oldest dates, versions, KV, orphaned media, retention in days. */
growth?: ({ retention: Partial<Record<string, number>> } & GrowthStatus) | null
/** null = not compared (the endpoint cannot read files). */
importMapCurrent?: boolean | null
/**
@@ -96,6 +101,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[]
@@ -164,3 +171,23 @@ export type DoctorReport = {
skipped: string[]
summary: { error: number; info: number; silenced: number; warning: number }
}
/** When the `growth` rules speak up — every number can be set in iapl-doctor.json `growth`. */
export type GrowthThresholds = {
/** Expired entries in payload-kv. Default 1000. */
expiredKv?: number
/** `.next/cache/images` on this machine, MB. Default 1024. */
imageCacheMB?: number
/** Documents in one collection. Default 200 000. */
maxDocs?: number
/** Size of one collection with its indexes (MongoDB), MB. Default 512. */
maxMB?: number
/** Versions of one collection or global. Default 50 000. */
maxVersions?: number
/** Media no document points at. Default 25. */
orphanedMedia?: number
/** Form submissions kept without a retention: older than this many days is a warning. Default 730. */
submissionDays?: number
/** Local upload folder (`media/`), MB. Default 2048. */
uploadsMB?: number
}
+34
View File
@@ -173,6 +173,7 @@ export const dropRelayCandidate = (payload: BasePayload, host: string = ownHost(
/** Remembers that the site at `host` started an enrolment with `nonce`. Only the nonce's hash is stored. */
export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number, host: string = ownHost(payload)): Promise<string> {
const nonceHash = sha256Hex(nonce)
await sweepExpiredNonces(payload)
await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash, host })
return nonceHash
}
@@ -194,3 +195,36 @@ export async function takeNonce(payload: BasePayload, nonce: string): Promise<{
}
export const releaseNonce = (payload: BasePayload, nonce: string) => kvOf(payload).delete(nonceKey(sha256Hex(nonce)))
/**
* Removes held nonces whose time has passed (1.18.0). A nonce whose call-back never came stayed in payload-kv for
* good: its expiry was only checked when read. An expired nonce can never be taken again (takeNonce refuses it) and
* a new enrolment uses a new key, so this changes nothing but the size of the store. At most once a day per process,
* started by the next enrolment; a failure is ignored (the next one tries again).
*/
let lastNonceSweep = 0
export async function sweepExpiredNonces(payload: BasePayload, now = Date.now()): Promise<number> {
if (now - lastNonceSweep < 86_400_000) {return 0}
lastNonceSweep = now
let removed = 0
try {
const kv = kvOf(payload)
const prefix = nonceKey('')
if (typeof kv.keys !== 'function') {return 0}
for (const key of (await kv.keys()).filter((k) => k.startsWith(prefix))) {
const held = (await kv.get(key)) as { expiresAt?: unknown } | null
if (held && typeof held.expiresAt === 'number' && held.expiresAt < now) {
await kv.delete(key)
removed++
}
}
} catch {
lastNonceSweep = 0
}
return removed
}
/** Tests: forget when the last sweep ran. */
export const resetNonceSweep = () => {
lastNonceSweep = 0
}
+7
View File
@@ -6,6 +6,8 @@ import type { AcceptedFormFile, FormFileFailure } from './attachments/fileGate.j
import type { FormValidationResult } from './validateSubmission.js'
import { mailAttachmentLimit } from '../email/attachmentLimit.js'
import { createDailyPurge } from '../shared/purge.js'
import { retentionOf } from '../shared/retention.js'
import { getTurnstileConfig } from '../turnstile/config.js'
import { verifyTurnstile } from '../turnstile/verify.js'
import { getFormAttachments } from './attachments/config.js'
@@ -15,6 +17,9 @@ import { formatFileSize } from './attachments/fileTypes.js'
import { consumeRateLimit } from './rateLimit.js'
import { validateSubmission } from './validateSubmission.js'
/** forms.submissionRetentionDays: old submissions deleted at most once a day, off the visitor's request. */
const purgeSubmissions = createDailyPurge('form-submissions')
export type SubmitFormArgs = {
/**
* A key the browser makes per submit attempt (16–64 letters, digits, `-`, `_`).
@@ -333,6 +338,8 @@ export async function storeSubmission({
...(delivery ? { filesDelivery: 'failed', submissionFiles: files.map((f) => ({ name: f.name, type: f.type, field: f.field, size: f.size })) } : {}),
} as never,
})
const keepDays = retentionOf(payload, 'form-submissions')
if (keepDays) {purgeSubmissions(payload, { createdAt: { less_than: new Date(Date.now() - keepDays * 86_400_000).toISOString() } })}
if (!delivery) {return { submissionId: submission.id, success: true }}
const result = delivery.result ?? { note: 'No e-mail was sent for this form.', state: 'failed' as const }
+6
View File
@@ -104,6 +104,12 @@ export type FormsOption = {
formSubmissionOverrides?: FormsCollectionOverrides
/** Collections a form can redirect to (e.g. ['pages']). */
redirectRelationships?: string[]
/**
* Keep form submissions this many days, then delete them (1.18.0; checked at most once a day, after a new
* submission). Default: kept until someone deletes them in the panel, as before. Submissions hold personal data
* (GDPR: no longer than needed) and are the one plugin collection that grows without end (docs/performance.md).
*/
submissionRetentionDays?: number
/**
* What a form does while Turnstile CANNOT check — the secret is missing or
* wrong, Cloudflare is down (the "degraded" state, shown in Site
+17 -4
View File
@@ -241,12 +241,18 @@ export function createContentHelpers({
})
/** What does this URL point at? Routing only — no listing data. */
const resolveRoute = cache(
// React cache() compares arguments by identity: the page passes the params' array, metadata and JSON-LD pass
// `segments ?? []` — a new array each time — so every caller missed and the homepage (no segments) was read in
// full four times per render. The segments travel as a string key instead (measured: docs/performance.md).
const resolveRoute = (locale: string, segments: string[] | undefined, page: number): Promise<null | ResolvedRoute> =>
resolveRouteCached(locale, JSON.stringify(segments ?? []), page)
const resolveRouteCached = cache(
async (
locale: string,
segments: string[] | undefined,
segmentsKey: string,
page: number,
): Promise<null | ResolvedRoute> => {
const segments = JSON.parse(segmentsKey) as string[]
const payload = await getCachedPayload()
const settings = (await getSettings(locale)) as Record<string, unknown>
return resolveRouteRaw({
@@ -275,10 +281,17 @@ export function createContentHelpers({
* }
*/
let pageMetadata: ReturnType<typeof createPageMetadata> | undefined
const generatePageMetadata = async (
// One build per request and URL: the page's generateMetadata, its render (alternate links) and getPageJsonLd all
// ask for it — uncached that was three times the homepage and document reads in every locale (measured: 43 → fewer
// MongoDB queries per render, docs/performance.md). The segments travel as a string so separate arrays still match.
const pageMetadataCached = cache(async (locale: string, segmentsKey: null | string, page: number): Promise<PageMetadata> =>
buildPageMetadata(locale, segmentsKey === null ? undefined : (JSON.parse(segmentsKey) as string[]), page))
const generatePageMetadata = (locale: string, segments: string[] | undefined, page = 1): Promise<PageMetadata> =>
pageMetadataCached(locale, segments === undefined ? null : JSON.stringify(segments), page)
const buildPageMetadata = async (
locale: string,
segments: string[] | undefined,
page = 1,
page: number,
): Promise<PageMetadata> => {
if (!i18n) {
throw new Error('[iapl] createContentHelpers: pass `i18n` to use generatePageMetadata.')
+6 -1
View File
@@ -174,6 +174,11 @@ export type NotFoundPageOptions =
* carries the whole 404 page in every locale.
*/
load: (locale: string) => Promise<ReactNode>
/**
* What the lazy 404 shows until its content arrives (default nothing). A block as tall as the site's 404
* content keeps the footer from moving when the content comes in (no layout shift, docs/performance.md).
*/
placeholder?: ReactNode
}
| ({ load?: undefined } & NotFoundViewOptions)
@@ -230,7 +235,7 @@ export function createNotFoundPage(helpers: NotFoundHelpers, options: NotFoundPa
const locales = await localesOf(helpers)
const defaultLocale = helpers.i18n?.defaultLocale ?? locales[0]
if (options.load) {
return <NotFoundLoader defaultLocale={defaultLocale} load={options.load} locales={locales} />
return <NotFoundLoader defaultLocale={defaultLocale} load={options.load} locales={locales} placeholder={options.placeholder} />
}
const eager = options
const views = Object.fromEntries(
+6 -3
View File
@@ -2,14 +2,17 @@
import type { CSSProperties, ReactNode } from 'react'
import { createContext, use, useCallback, useId, useMemo, useRef, useState } from 'react'
import { createContext, lazy, Suspense, use, useCallback, useId, useMemo, useRef, useState } from 'react'
import type { LightboxDialogProps } from './LightboxDialog.js'
import type { LightboxClassNames, LightboxImage, LightboxRenderImage, LightboxTexts } from './types.js'
import { LightboxDialog } from './LightboxDialog.js'
import { lightboxIndex, resolveLightboxTexts } from './texts.js'
// The viewer (dialog, swipe, keyboard, icons) is loaded the first time an image is opened, not with every page:
// most visitors never open one. The triggers and this provider stay small.
const LightboxDialog = lazy(() => import('./LightboxDialog.js').then((m) => ({ default: m.LightboxDialog })))
type Entry = { el: { current: HTMLElement | null }; group?: string; image: { current: LightboxImage } }
type OpenState = { images: readonly LightboxImage[]; index: number; returnFocus: HTMLElement | null }
@@ -152,7 +155,7 @@ export function LightboxProvider({ children, classNames, icons, loop = true, ren
<LightboxContext value={api}>
<TriggerContext value={triggerApi}>
{children}
{dialogProps ? (renderDialog ? renderDialog(dialogProps) : <LightboxDialog {...dialogProps} />) : null}
{dialogProps ? (renderDialog ? renderDialog(dialogProps) : <Suspense fallback={null}><LightboxDialog {...dialogProps} /></Suspense>) : null}
</TriggerContext>
</LightboxContext>
)
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { LightboxDialog, prefersReducedMotion } from './LightboxDialog.js'
export type { LightboxDialogProps } from './LightboxDialog.js'
export { LightboxProvider, LightboxTrigger, useLightbox, useOptionalLightbox } from './LightboxProvider.js'
+7 -2
View File
@@ -42,6 +42,11 @@ export const MEDIA_SIZES = {
export type MediaImageOptions = {
/** Alt override (decorative images: ''). Default: the document's alt. */
alt?: string
/**
* Above the fold but not the LCP image (a header logo): loads at once (`loading="eager"`) WITHOUT
* fetchPriority="high" or a preload, so it does not compete with the one `priority` image. Ignored with `priority`.
*/
eager?: boolean
/**
* Dominant colour as the <img> background while it loads. The style stays after
* load, so it would show through transparent pixels (white logo on a black box).
@@ -88,7 +93,7 @@ const asDoc = (resource: unknown): MediaDoc | null =>
*/
export function mediaImageProps(
resource: unknown,
{ alt, placeholderColor = 'auto', priority = false, sizes = '100vw' }: MediaImageOptions = {},
{ alt, eager = false, placeholderColor = 'auto', priority = false, sizes = '100vw' }: MediaImageOptions = {},
): MediaImageProps | null {
const doc = asDoc(resource)
if (!doc || doc.mimeType?.startsWith('video/')) {return null}
@@ -109,7 +114,7 @@ export function mediaImageProps(
width: doc.width,
...(priority
? { fetchPriority: 'high' as const, loading: 'eager' as const, preload: true }
: { loading: 'lazy' as const }),
: { loading: eager ? ('eager' as const) : ('lazy' as const) }),
...(blur ? { blurDataURL: blur, placeholder: 'blur' as const } : {}),
...(Object.keys(style).length ? { style } : {}),
}
+9 -11
View File
@@ -12,18 +12,16 @@ type NotFoundLoaderProps = {
/** The project's server action: `(locale) => renderNotFoundView(content, options, locale)`. */
load: (locale: string) => Promise<ReactNode>
locales: string[]
/**
* Shown until the content arrives (default nothing). The 404 content comes after hydration, so the footer moves
* when it arrives (a layout shift: measured CLS 0.32 on a phone for the reference site). A block as tall as the
* site's own 404 content keeps the footer still: `placeholder={<div style={{ minHeight: '36rem' }} />}`. A fixed
* one-screen block is no fix in general: shorter content then pulls the footer UP into view (measured 0.36).
*/
placeholder?: ReactNode
}
/**
* The 404 content, fetched only when the 404 is actually shown.
*
* Next puts the `not-found` tree of a layout into the RSC payload of EVERY page
* under it (the router needs it for a client-side 404). A 404 page with real
* content (often the homepage) rendered there in every locale multiplied the
* size of each page. Here only this small component is in the payload; the
* content comes from a server action on mount.
*/
export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderProps) {
export function NotFoundLoader({ defaultLocale, load, locales, placeholder = null }: NotFoundLoaderProps) {
const pathname = usePathname() ?? ''
const locale = localeFromPath(pathname, locales, defaultLocale)
const [view, setView] = useState<{ locale: string; node: ReactNode } | null>(null)
@@ -43,5 +41,5 @@ export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderP
}
}, [load, locale])
return <>{view?.locale === locale ? view.node : null}</>
return <>{view?.locale === locale ? view.node : placeholder}</>
}
+10 -1
View File
@@ -101,5 +101,14 @@ export function getSiteIntegrations<T = Record<string, unknown>>(
payload: BasePayload,
options?: GlobalQueryOptions,
): Promise<T> {
return findSiteIntegrations<T>(payload, options)
if (options && Object.keys(options).length) {return findSiteIntegrations<T>(payload, options)}
// Callers that start together (the layout reads analytics IDs and the Turnstile key side by side) share ONE read
// while it is in flight; the next call reads again, so nothing is cached between requests or after a save.
const pending = inFlight.get(payload)
if (pending) {return pending as Promise<T>}
const read = findSiteIntegrations<T>(payload).finally(() => inFlight.delete(payload))
inFlight.set(payload, read)
return read
}
const inFlight = new WeakMap<BasePayload, Promise<unknown>>()
+105
View File
@@ -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
}
+14 -4
View File
@@ -49,11 +49,21 @@ export function TableOfContents({ classNames: cn = {}, items, label, offset = 0.
setActive(current)
}
update()
window.addEventListener('scroll', update, { passive: true })
window.addEventListener('resize', update)
// At most one measurement per frame: a scroll fires many events between two paints, and each one read the
// position of every heading (forced layout on the main thread, which delays the next tap — INP).
let frame = 0
const schedule = () => {
if (!frame) {frame = requestAnimationFrame(() => {
frame = 0
update()
})}
}
window.addEventListener('scroll', schedule, { passive: true })
window.addEventListener('resize', schedule)
return () => {
window.removeEventListener('scroll', update)
window.removeEventListener('resize', update)
cancelAnimationFrame(frame)
window.removeEventListener('scroll', schedule)
window.removeEventListener('resize', schedule)
}
}, [items, offset])
+1
View File
@@ -82,6 +82,7 @@ export async function readSiteMetaConfig({
collection: pagesSlug as never,
depth: 0,
locale: 'all' as never,
select: { slug: true } as never, // only the slug map is used: not the layout in every language
})) as { slug?: unknown }
const slugField = homeDoc.slug
if (slugField && typeof slugField === 'object') {
+1
View File
@@ -30,6 +30,7 @@ export async function slugsAcrossLocales({
collection: collection as never,
depth: 0,
locale: 'all',
select: { slug: true } as never, // only the slug map is used: not the layout in every language
})) as { slug?: unknown }
return doc.slug && typeof doc.slug === 'object'
+22
View File
@@ -0,0 +1,22 @@
import type { BasePayload, Config } from 'payload'
/**
* How long each plugin log keeps its records, in days (`config.custom.iapl.retention`): written by iapl() for the
* consent log, the statistics and — when the project sets one — form submissions. The purge reads it; the doctor's
* `growth-retention` rule checks that the oldest record is not older (the purge runs), docs/performance.md.
*/
export type RetentionMap = Partial<Record<string, number>>
export function withRetention(config: Config, slug: string, days: number | undefined): Config {
if (typeof days !== 'number' || !(days > 0)) {return config}
const iapl = (config.custom?.iapl ?? {}) as { retention?: RetentionMap }
return { ...config, custom: { ...config.custom, iapl: { ...iapl, retention: { ...iapl.retention, [slug]: days } } } }
}
export function retentionOf(payload: Pick<BasePayload, 'config'>, slug: string): number | undefined {
const days = ((payload.config?.custom as { iapl?: { retention?: RetentionMap } } | undefined)?.iapl?.retention ?? {})[slug]
return typeof days === 'number' && days > 0 ? days : undefined
}
export const retentionMap = (payload: Pick<BasePayload, 'config'>): RetentionMap =>
({ ...((payload.config?.custom as { iapl?: { retention?: RetentionMap } } | undefined)?.iapl?.retention ?? {}) })
+2 -1
View File
@@ -1,3 +1,4 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
export { IAPL_VISITOR_COOKIE, PageStats, VISITOR_COOKIE } from './PageStats.js'
export type { PageStatsProps } from './PageStats.js'
+7 -3
View File
@@ -85,7 +85,11 @@ export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }:
ensureScript()
function render() {
if (!ref.current || !window.turnstile || widgetId.current) {return}
if (widgetId.current) {
clearInterval(interval) // rendered: stop polling (it used to tick every 300 ms for the life of the form)
return
}
if (!ref.current || !window.turnstile) {return}
widgetId.current = window.turnstile.render(ref.current, {
callback: (token: string) => onToken(token),
'error-callback': () => onToken(null),
@@ -95,9 +99,9 @@ export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }:
})
}
render()
// Script may load after mount — retry briefly until ready.
// Script may load after mount — retry until it is ready, then stop.
const interval = setInterval(render, 300)
render()
return () => clearInterval(interval)
}, [siteKey, widgetTheme, onToken])
+2 -1
View File
@@ -1,4 +1,5 @@
'use client'
// No 'use client' on this barrel (1.18.0): every component behind it carries its own. A barrel with the
// directive is one client boundary, so a page that imported one export shipped ALL of them (docs/performance.md).
// Client-only exports — the Turnstile widget. Kept separate from index.ts so
// the server-only verify never leaks into a browser bundle.
export { Turnstile } from './Turnstile.js'