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:
+22
-10
@@ -1041,22 +1041,30 @@ Example `styles.css`: [section-code.md](./skills/iapl-block/resources/section-co
|
||||
125 % and 150 % zoom at 1366 (common on Windows). No horizontal scroll, no clipped text,
|
||||
the menu works, the hero CTA is visible.
|
||||
|
||||
### 6.11b Speed (Core Web Vitals)
|
||||
### 6.11b Speed (Core Web Vitals) — the handbook is [performance.md](../performance.md), the skill `iapl-performance`
|
||||
| What | How | Forbidden |
|
||||
|---|---|---|
|
||||
| LCP image (the first visible one, usually the hero) | `<Media priority>` — exactly one per page | `priority` on many images, the hero as a CSS `background-image` |
|
||||
| every other image | `<Media sizes={MEDIA_SIZES.third}>` — `sizes` = the width on screen | no `sizes` (downloads the full width), `<img>` |
|
||||
| LCP image (the first visible one, usually the hero) | `<Media priority>` — exactly one per page (preload + `fetchpriority="high"`) | `priority` on many images, the hero as a CSS `background-image`, a lazy hero |
|
||||
| above the fold, not the LCP (header logo) | `<Media eager>` — loads at once, no high priority, no preload | `priority` on the logo (it competes with the hero) |
|
||||
| every other image | `<Media sizes={MEDIA_SIZES.third}>` — `sizes` = the width on screen; lazy by default | no `sizes` (downloads the full width), `<img>` |
|
||||
| placeholder | `buildMediaPlaceholderHook` + a field in Media (blur + color) | empty boxes that "jump in" while loading |
|
||||
| uploads | `buildOptimizeUploadHook` (stops images over 1.5 MB / 2560 px, converts on request); `iapl-doctor --deep` counts stored images over the limits | 8 MB phone photos in the library |
|
||||
| background video | `videoMode="background"`, MP4 H.264 ≤ 20 MB, no sound, with a poster | a video as the hero without a poster, `autoplay` with sound |
|
||||
| video with content | `videoMode="player"` (loads after a click) | `preload="auto"` |
|
||||
| YouTube | `<YouTubeEmbed>` from `/client` (the iframe only after a click) | a bare `<iframe src="youtube.com/embed…">` |
|
||||
| next.config | `images: { ...buildImagesConfig() }` (AVIF/WebP, R2) | no `remotePatterns` → images from R2 without optimization |
|
||||
| fonts | `next/font`, max 2 families × 2–3 weights, `subsets: ['latin', 'latin-ext']` (PL), `display: 'swap'` | a `<link>` to Google Fonts, 6 weights "just in case" |
|
||||
| third-party scripts | `Analytics` (via `SiteProviders`, `analytics={{ defer: true }}`) / `ConsentScript` from the plugin | chat/map widgets loaded at start |
|
||||
| client components | small, interaction only (§6.9) | a whole section `'use client'` |
|
||||
| YouTube, maps, widgets | `<YouTubeEmbed>` from `/client` (the iframe only after a click); a map behind a click (a picture + a button) | a bare `<iframe>` that loads with the page |
|
||||
| next.config | `images: buildImagesConfig()` (AVIF/WebP, R2, 31-day cache) | no `remotePatterns` → images from R2 without optimization |
|
||||
| fonts | `next/font`, max 2 families, variable, `subsets: ['latin', 'latin-ext']` (PL), `display: 'swap'` | a `<link>` to Google Fonts, `display: 'block'`, 6 weights "just in case" |
|
||||
| third-party scripts | `Analytics` (via `SiteProviders`, `analytics={{ defer: true }}`) / `ConsentScript` from the plugin; `next/script` for anything else | `<script src>` without `async` in the layout, chat/map widgets loaded at start |
|
||||
| animations | `transform` / `opacity` only, the token durations (`duration-fast`, reduced motion built in) or `motion-reduce:`; IntersectionObserver for "is it on screen" | animating `height` / `top` / `margin`, `transition-all`, a `scroll` listener doing work per event |
|
||||
| client components | small, interaction only (§6.9); import from `@intecion/ipal-kit/client` freely — a page ships only what it renders (1.18.0) | a whole section `'use client'` |
|
||||
| data | the cached helpers of `lib/content` (`getSettings`, `resolveRoute`, `getSiteShell`…), `depth` as low as the page needs, `select` when you need one field, `cache()` around your own getters | `findGlobal` in a component without `cache()`, `depth: 2` "to be safe", a query per list item |
|
||||
| what grows | logs with a retention (consent log 1095 days, statistics 90; `forms: { submissionRetentionDays }` on the client's decision), `versions: { maxPerDoc: 20 }` where you turn versions on, unused media reviewed; `iapl-doctor --deep --only growth` ([performance.md](../performance.md) §6) | `maxPerDoc: 0`, submissions kept forever without a decision, a persistent volume on `.next` |
|
||||
| budgets | `e2e/performance.spec.ts` from the `iapl-performance` skill (`perfBudgets()` from `/doctor`): fails when a page gets slower | "it felt fast on my machine" |
|
||||
|
||||
Target on the built site (mobile, Lighthouse/PageSpeed): LCP < 2.5 s, CLS < 0.1, INP < 200 ms.
|
||||
Checks: `iapl-audit` (img/video outside Media, many `priority`, `h-screen`, fixed widths,
|
||||
Target on the built site (mobile, Lighthouse/PageSpeed): LCP < 2.5 s, CLS < 0.1, INP < 200 ms — the plugin's default
|
||||
budgets (`PERF_BUDGETS`). Checks: `iapl-doctor --only performance` (images config, fonts, render-blocking, embeds,
|
||||
animations, a budget test; `--url`: compression, blocking scripts, preloads, a lazy first image, HTML size; `--deep`:
|
||||
stored images over the limits), `iapl-audit` (img/video outside Media, many `priority`, `h-screen`, fixed widths,
|
||||
YouTube `<iframe>`) and `iapl-seo-check` (images without dimensions, LCP image without priority).
|
||||
|
||||
### 6.12 Exports and imports
|
||||
@@ -1561,6 +1569,8 @@ block library — [doctor.md](../doctor.md)):
|
||||
bash .agents/skills/iapl-audit/scripts/audit.sh
|
||||
pnpm exec iapl-doctor # + --deep --url http://localhost:3000 on the built site
|
||||
node .agents/skills/iapl-seo-check/scripts/seo-check.mjs http://localhost:3000
|
||||
pnpm test:e2e e2e/performance.spec # the budget gate (iapl-performance) on the built site
|
||||
pnpm exec iapl-doctor --deep --only growth # what grows: sizes, versions, retention, old submissions, unused media
|
||||
pnpm generate:types && pnpm tsc --noEmit
|
||||
pnpm build # --webpack in the script; locally, not only dev
|
||||
# hardcoding and the field zoo in blocks
|
||||
@@ -1621,6 +1631,7 @@ Anything that needs a developer → move it to the panel.
|
||||
| Rich text | [richtext.md](../richtext.md) |
|
||||
| Headers, CSP, 2FA, panel path | [security.md](../security.md) |
|
||||
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](../seo.md) |
|
||||
| Speed: what the plugin does, what the project does, budgets, measuring, the doctor's performance group | [performance.md](../performance.md) |
|
||||
| Auto-slug | [slug.md](../slug.md) |
|
||||
| Media: collection, file names, optimization, placeholders | [media.md](../media.md) |
|
||||
| Image lightbox (enlarge, galleries, rich text images) | [lightbox.md](../lightbox.md) |
|
||||
@@ -1702,6 +1713,7 @@ the task matches — manually: `/<name>`.
|
||||
| `iapl-debug` | anything does not work — procedure + a symptom → cause → fix table |
|
||||
| `iapl-audit` | before every "done" — the §0b set + the §11 checks + panel (§6.5a) + hardcoding in JSX + tsc + build |
|
||||
| `iapl-seo-check` | the running site through the eyes of Googlebot and AI agents (head, canonical, hreflang, sitemap, 404, JSON-LD, llms, Markdown, MCP) |
|
||||
| `iapl-performance` | speed: the doctor's performance group, measuring the built site (phone and desktop), the budget gate `e2e/performance.spec.ts` (`resources/`), reading LCP / CLS / INP / bytes / queries — when building pages or blocks, before handing over, whenever "slow" or PageSpeed comes up |
|
||||
| `iapl-consent-check` | browser: no tracking pixels or cookies before consent; the Google tag may load before consent only in Consent Mode `advanced` (all signals `denied`) — a client who wants zero requests gets `consentMode: 'basic'` |
|
||||
| `iapl-doctor` | the whole site against the team standard in one command (`pnpm exec iapl-doctor`): versions, Node 22, layout, database names, env, headers, CSP, 2FA, cookie scanner, adminMeta, AGENTS.md, skills, seeds, block library, pnpm audit; `--url` / `--deep` for the running site and the database; `--strict` in the CI of a new site |
|
||||
| `iapl-plugin-gap` | IAPL has a bug or is missing a feature — report to the owner, wait for the decision; a marked workaround only after approval |
|
||||
|
||||
@@ -374,7 +374,7 @@ export const Pages: CollectionConfig = {
|
||||
{ name: 'layout', type: 'blocks', blocks: pageBlocks, minRows: 1 },
|
||||
buildSummaryField(), // aiSummary — GEO (llms.txt, MCP)
|
||||
buildNoindexField(),
|
||||
{ name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text' }], labels: { plural: 'Old addresses', singular: 'Old address' } },
|
||||
{ name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text', index: true }], labels: { plural: 'Old addresses', singular: 'Old address' } },
|
||||
],
|
||||
hooks: {
|
||||
afterChange: [revalidate.afterChange],
|
||||
@@ -1138,6 +1138,8 @@ Rules: AGENT.md §8a.
|
||||
| `e2e/mail-relay-setup.ts` | for the mail-service spec: empties the SMTP fields and the stored token, so the next e-mail enrols and goes through the mail service (local database only) (below) |
|
||||
| `e2e/mail-relay.spec.ts` | the mail service on a built site: the state block in the panel, the first e-mail through the public confirm route, no token in anything the browser receives |
|
||||
| `e2e/own-account.spec.ts` | built-site test (pnpm e2e:built, 1.18.0): the account page asks for the current password before a new e-mail is saved (accounts.confirmOwnChanges); five failed staff sign-ins from one place answer 429 there, not elsewhere (accounts.signInLimit); a staff sign-in from another origin gets 403 (accounts.signInSameOrigin) |
|
||||
| `e2e/perf-lab.mjs` | the lab measurement of one page (Lighthouse's phone and desktop profiles, Web Vitals observers, bytes per type) — used by the performance spec and `pnpm perf:measure`; the iapl-performance skill ships the same file |
|
||||
| `e2e/performance.spec.ts` | the performance budgets (run by `pnpm e2e:built` in both bundlers): every page type on a throttled phone and a desktop — LCP, CLS, TBT, the response to a tap, JS / CSS / font bytes, requests, render-blocking, third parties before consent — and the MongoDB queries of one render (docs/performance.md) |
|
||||
| `e2e/routes.snapshot.json` | every public route of the site (REST, GraphQL, Next route files) with one line saying who may use it and why — the judged list `routes:check` compares with |
|
||||
| `e2e/routes.ts` | `routes:check`: the site's public routes against e2e/routes.snapshot.json (`pnpm payload run e2e/routes.ts [update]`; from the repository `pnpm routes:check`) (below) |
|
||||
| `e2e/sign-in-answers.spec.ts` | built-site test (pnpm e2e:built, 1.17.2): a locked staff account gets the wrong-password answer over REST and GraphQL (accounts.lockedAnswer); the plugin's panel actions refuse another origin and take the site's own (adminSameOrigin) |
|
||||
|
||||
@@ -42,6 +42,13 @@ classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warnin
|
||||
next/font in `--font-body` with the preset (warning), and with `src/design/tokens.ts`: no `DESIGN.md` (warning) and
|
||||
`iapl-tokens --check` — a stale `src/design/tokens.css` or a WCAG AA contrast failure is an error.
|
||||
|
||||
## Speed (AGENT.md §6.11b, docs/performance.md)
|
||||
The full run (not `--quick`) lists the doctor's `performance` group as warnings: `next.config` without
|
||||
`buildImagesConfig()`, fonts from Google or with `display: 'block'`, more than two families, a blocking `<script src>`
|
||||
or a remote stylesheet, an `<iframe>` that loads with the page, transitions of layout properties, `transition-all`,
|
||||
`scroll` listeners, animations with nothing for reduced motion. The `iapl-performance` skill measures the built site and
|
||||
adds the budget test.
|
||||
|
||||
## iapl-audit and iapl-doctor
|
||||
`iapl-audit` checks the **code** inside the edit loop (and tsc + build). `pnpm exec iapl-doctor` checks the **site**
|
||||
against the team standard: it runs this script (`--quick`) from the installed package, reports its findings under its
|
||||
|
||||
@@ -362,6 +362,14 @@ if [ -n "$UI" ]; then
|
||||
done
|
||||
fi
|
||||
|
||||
# --- Speed (§6.11b, performance.md) — the doctor's performance group: images config, fonts, render-blocking,
|
||||
# embeds, animations, a budget test. Full mode only: the doctor itself runs this audit with --quick.
|
||||
if [ "$QUICK" -eq 0 ] && [ -x node_modules/.bin/iapl-doctor ]; then
|
||||
PERF=$(node_modules/.bin/iapl-doctor --only performance --offline --json 2>/dev/null \
|
||||
| node -e 'let s="";process.stdin.on("data",(d)=>(s+=d)).on("end",()=>{try{for(const f of JSON.parse(s).findings){if(!f.silenced&&f.severity!=="info"){console.log(`${f.file??"(site)"} [${f.rule}] ${f.message}`)}}}catch{}})')
|
||||
report WARNING "speed (iapl-doctor --only performance)" "§6.11b / performance.md — each line names the rule; iapl-performance skill" "$PERF"
|
||||
fi
|
||||
|
||||
# --- Compile & build ---
|
||||
if [ "$QUICK" -eq 0 ]; then
|
||||
echo
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
name: iapl-performance
|
||||
description: Makes and keeps an IAPL site fast — page loading (LCP image, fonts, nothing render-blocking, static rendering), elements (lazy below the fold, reserved space, click-to-load embeds), animations (transform/opacity, reduced motion, no scroll handlers), resources (only the JS a page uses, compression, no third-party request before consent), images (AVIF/WebP, sizes, upload limits) and the server (queries per render, depth, select, caching); what grows in the database and on disk over the years (logs and their retention, form submissions, versions, KV, unused media, the image cache). Measures the built site, runs the doctor's performance group, and adds the budget gate that fails when a change makes the site slower. Use when building pages or blocks, before handing over, after an IAPL upgrade, and whenever "slow", PageSpeed, Lighthouse, Core Web Vitals, LCP, CLS, INP, a growing database or disk come up.
|
||||
---
|
||||
|
||||
# iapl-performance
|
||||
|
||||
The handbook is `node_modules/@intecion/ipal-kit/docs/performance.md`: what the plugin does for you, what the project
|
||||
must do, how to measure, how to read the findings. This skill is the order of work.
|
||||
|
||||
## 1. Check what the plugin cannot do for you (code)
|
||||
```bash
|
||||
pnpm exec iapl-doctor --only performance # images config, fonts, render-blocking, embeds, animations, budget test
|
||||
bash .agents/skills/iapl-audit/scripts/audit.sh --quick # <img>/<video> outside Media, priority outside the hero, YouTube iframe, h-screen
|
||||
```
|
||||
Fix every warning — each names the file, the fix and the doc. The rules that matter most:
|
||||
|
||||
| Area | Do | Never |
|
||||
|---|---|---|
|
||||
| LCP image | `<Media priority>` on the first image of the page — **one** per page; a header logo gets `eager` | `priority` on many images; a lazy hero; the hero as a CSS background |
|
||||
| other images | `<Media sizes={MEDIA_SIZES.third}>` — the width on screen; lazy by default | no `sizes`; a plain `<img>` |
|
||||
| fonts | `next/font` (self-hosted), ≤ 2 families, variable, `display: 'swap'` | a `<link>` to Google Fonts; `display: 'block'` |
|
||||
| scripts | the plugin's `Analytics` / `ConsentScript`; `next/script` for anything else | a `<script src>` without `async` in the layout |
|
||||
| embeds | `<YouTubeEmbed>`; a map or widget behind a click (a picture + a button) | an `<iframe>` that loads with the page |
|
||||
| animations | `transform` / `opacity` only; the token durations (`duration-fast`) or `motion-reduce:` | animating `height`, `top`, `margin`; `transition-all`; a `scroll` listener (use IntersectionObserver) |
|
||||
| client code | small `'use client'` leaves; server components by default | a whole section `'use client'` |
|
||||
| server | the plugin's cached helpers (`lib/content`), `depth` as low as the page needs, `select` for one field | `findGlobal` without `cache()`; `depth: 2` "to be safe"; a query per list item |
|
||||
|
||||
## 2. Measure the built site
|
||||
```bash
|
||||
pnpm build && pnpm start # dev numbers mean nothing
|
||||
pnpm exec iapl-doctor --url http://localhost:3000 --only perf-live # compression, blocking scripts, preloads, lazy hero, HTML size
|
||||
pnpm exec iapl-doctor --deep --only perf-images # stored images over 1.5 MB / 2560 px
|
||||
```
|
||||
Lab numbers per page (phone on Slow 4G with a 4× slower CPU, and desktop): copy `resources/perf-lab.mjs` and
|
||||
`resources/performance.spec.template.ts` (→ `e2e/performance.spec.ts`), list one page of each template, run
|
||||
`pnpm test:e2e e2e/performance.spec`, then set each budget to what you measured plus ~20 %. From then on the test fails when
|
||||
a change makes a page slower. PageSpeed Insights on the deployed site shows the field data (real visitors).
|
||||
|
||||
## 3. Read the result
|
||||
- **LCP** > 2.5 s on the phone: the LCP element is named in the measurement (`lcpElement`). An image → `priority`,
|
||||
`sizes`, a smaller upload; text → a font that arrives late (fewer preloaded files).
|
||||
- **CLS** > 0.1: an image without dimensions (use `Media`), content that arrives after hydration (the lazy 404 —
|
||||
`createNotFoundPage({ load, placeholder })`), a font swap (next/font sets fallback metrics).
|
||||
- **TBT / INP**: long tasks — a big client component, a scroll handler, a third-party widget at start.
|
||||
- **JS bytes**: what the page ships; import client components from `@intecion/ipal-kit/client` freely — since
|
||||
1.18.0 a page carries only the ones it renders.
|
||||
- **Queries per render** (the reference gate counts them): over 30 for an ordinary page → a missing `cache()`, a
|
||||
`depth` too high, or a loop of `findByID`.
|
||||
|
||||
## 4. What grows (performance.md §6)
|
||||
```bash
|
||||
pnpm exec iapl-doctor --deep --only growth # counts and sizes per collection, oldest records, versions, expired KV, unused media, disk
|
||||
```
|
||||
- Logs purge themselves (consent log 1095 days, statistics 90). Form submissions are kept unless
|
||||
`iapl({ forms: { submissionRetentionDays } })` — ask the client (personal data) and record it in AGENTS.md.
|
||||
- Versions: where you turn them on, `versions: { maxPerDoc: 20 }` (globals `max`); never `0`.
|
||||
- Unused media (`growth-media`): list them for the client; the plugin never deletes media or submissions by itself.
|
||||
- Coolify: no persistent volume on `.next` (the image cache starts empty on each deploy); database backups on the
|
||||
MongoDB resource.
|
||||
- Thresholds of the findings: `iapl-doctor.json` → `growth`.
|
||||
|
||||
## 5. Before "done"
|
||||
`iapl-doctor --only performance` without warnings (or each one silenced with a reason in `iapl-doctor.json`),
|
||||
the budget test green, and the numbers in `AGENTS.md` → "Project decisions" when the client accepted an exception
|
||||
(a heavy font, a third-party widget).
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Lab measurements of one page in Chromium (Playwright + the DevTools protocol) — used by `pnpm perf:measure`
|
||||
* (scripts/perf-measure.mjs, numbers for docs/performance.md) and by the budget gate (e2e/performance.spec.ts).
|
||||
*
|
||||
* Profiles follow Lighthouse's defaults so the numbers compare with PageSpeed Insights' lab data:
|
||||
* - mobile: 412×823 at DPR 1.75, "Slow 4G" (150 ms RTT, 1.6 Mbit/s down, 750 kbit/s up), CPU 4× slower;
|
||||
* - desktop: 1350×940, 40 ms RTT, 10 Mbit/s, CPU 1×.
|
||||
* Every run is a fresh browser context (empty HTTP cache, no cookies): a first visit, the worst ordinary case.
|
||||
*
|
||||
* What is measured (all from the browser itself, web.dev/articles/vitals):
|
||||
* ttfb, fcp, lcp (+ the LCP element: tag, src, loading, fetchpriority), cls (session windows, as web-vitals does),
|
||||
* tbt (sum of long-task time over 50 ms between FCP and the end of the run: the lab stand-in for INP),
|
||||
* inp (the longest Event Timing entry of one scripted interaction: a click on the page's first visible button),
|
||||
* scriptMs (CDP Performance.ScriptDuration: parse, compile, run and hydrate), requests, bytes per type
|
||||
* (transfer size, compressed), renderBlocking (resource timing renderBlockingStatus), thirdParty (requests to
|
||||
* another origin before any consent is given). Next's link prefetches (`?_rsc=`, made when the browser is idle) are
|
||||
* counted apart (`prefetches`): they are not part of the page's load and come at a different moment each run.
|
||||
* Option `blockThirdParty` (the gate): requests to another origin are recorded, then aborted — a slow external host
|
||||
* cannot hold the page's load event, and the numbers are the site's own.
|
||||
*/
|
||||
import { chromium } from '@playwright/test'
|
||||
|
||||
export const PROFILES = {
|
||||
desktop: { cpu: 1, network: { downloadThroughput: (10 * 1024 * 1024) / 8, latency: 40, uploadThroughput: (10 * 1024 * 1024) / 8 }, viewport: { deviceScaleFactor: 1, height: 940, isMobile: false, width: 1350 } },
|
||||
mobile: { cpu: 4, network: { downloadThroughput: (1.6 * 1024 * 1024) / 8, latency: 150, uploadThroughput: (750 * 1024) / 8 }, viewport: { deviceScaleFactor: 1.75, hasTouch: true, height: 823, isMobile: true, width: 412 } },
|
||||
}
|
||||
|
||||
const OBSERVERS = `(() => {
|
||||
const v = (window.__perf = { cls: 0, events: [], lcp: null, longTasks: [] })
|
||||
let win = 0, winStart = 0, winLast = 0
|
||||
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
|
||||
const el = e.element
|
||||
v.lcp = { at: e.startTime, size: e.size, tag: el ? el.tagName.toLowerCase() : null, src: e.url || null,
|
||||
loading: el && el.getAttribute ? el.getAttribute('loading') : null,
|
||||
fetchpriority: el && el.getAttribute ? el.getAttribute('fetchpriority') : null }
|
||||
} }).observe({ buffered: true, type: 'largest-contentful-paint' })
|
||||
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
|
||||
if (e.hadRecentInput) continue
|
||||
if (win && e.startTime - winLast < 1000 && e.startTime - winStart < 5000) { win += e.value } else { win = e.value; winStart = e.startTime }
|
||||
winLast = e.startTime
|
||||
v.cls = Math.max(v.cls, win)
|
||||
} }).observe({ buffered: true, type: 'layout-shift' })
|
||||
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.longTasks.push([e.startTime, e.duration]) }).observe({ buffered: true, type: 'longtask' })
|
||||
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.events.push({ d: e.duration, n: e.name }) }).observe({ buffered: true, durationThreshold: 16, type: 'event' })
|
||||
})()`
|
||||
|
||||
/**
|
||||
* @typedef {{ bytes: { css: number, font: number, html: number, image: number, js: number, other: number }, cls: number,
|
||||
* fcp: null | number, inp: null | number, interaction: null | string, lcp: null | number,
|
||||
* lcpElement: null | { fetchpriority: null | string, loading: null | string, src: null | string, tag: null | string },
|
||||
* load: null | number, prefetches: number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number,
|
||||
* status: null | number, tbt: null | number, thirdParty: string[], ttfb: null | number, url: string }} PageMeasurement
|
||||
*/
|
||||
|
||||
const typeOf = (resourceType, mime = '') => {
|
||||
if (resourceType === 'Document') {return 'html'}
|
||||
if (resourceType === 'Script') {return 'js'}
|
||||
if (resourceType === 'Stylesheet') {return 'css'}
|
||||
if (resourceType === 'Font') {return 'font'}
|
||||
if (resourceType === 'Image' || mime.startsWith('image/')) {return 'image'}
|
||||
return 'other'
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('@playwright/test').Browser} browser
|
||||
* @param {string} url
|
||||
* @param {'mobile'|'desktop'} profileName
|
||||
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
|
||||
* @returns {Promise<PageMeasurement>}
|
||||
*/
|
||||
export async function measurePage(browser, url, profileName, options = {}) {
|
||||
const profile = PROFILES[profileName]
|
||||
const context = await browser.newContext({ ...profile.viewport, viewport: { height: profile.viewport.height, width: profile.viewport.width } })
|
||||
const page = await context.newPage()
|
||||
const cdp = await context.newCDPSession(page)
|
||||
await cdp.send('Network.enable')
|
||||
await cdp.send('Network.setCacheDisabled', { cacheDisabled: true })
|
||||
await cdp.send('Network.emulateNetworkConditions', { offline: false, ...profile.network })
|
||||
await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.cpu })
|
||||
await cdp.send('Performance.enable')
|
||||
await page.addInitScript(OBSERVERS)
|
||||
|
||||
const origin = new URL(url).origin
|
||||
if (options.blockThirdParty) {await context.route((u) => u.origin !== origin, (route) => route.abort())}
|
||||
const requests = new Map()
|
||||
let prefetches = 0
|
||||
cdp.on('Network.requestWillBeSent', (e) => {
|
||||
if (e.request.url.startsWith('data:')) {return}
|
||||
if (/[?&]_rsc=/.test(e.request.url)) {prefetches++; return}
|
||||
requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url })
|
||||
})
|
||||
cdp.on('Network.responseReceived', (e) => { const r = requests.get(e.requestId); if (r) {r.type = typeOf(e.type, e.response.mimeType); r.status = e.response.status} })
|
||||
cdp.on('Network.loadingFinished', (e) => { const r = requests.get(e.requestId); if (r) {r.bytes = e.encodedDataLength} })
|
||||
|
||||
const response = await page.goto(url, { timeout: 60_000, waitUntil: 'load' })
|
||||
await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => {})
|
||||
await page.waitForTimeout(options.settleMs ?? 1000)
|
||||
|
||||
let interaction = null
|
||||
if (options.interact !== false) {
|
||||
// INP stand-in: one click on the first visible button (menu toggle, cookie settings, theme): a real handler runs
|
||||
const button = page.locator('button:visible').first()
|
||||
if (await button.count()) {
|
||||
interaction = (await button.getAttribute('aria-label')) ?? (await button.innerText()).slice(0, 40)
|
||||
await button.click({ timeout: 5000 }).catch(() => { interaction = null })
|
||||
await page.waitForTimeout(500)
|
||||
}
|
||||
}
|
||||
|
||||
const nav = await page.evaluate(() => {
|
||||
const n = performance.getEntriesByType('navigation')[0]
|
||||
const fcp = performance.getEntriesByName('first-contentful-paint')[0]
|
||||
const blocking = performance.getEntriesByType('resource').filter((r) => r.renderBlockingStatus === 'blocking').map((r) => r.name)
|
||||
return { blocking, domContentLoaded: n.domContentLoadedEventEnd, fcp: fcp ? fcp.startTime : null, load: n.loadEventEnd, ttfb: n.responseStart }
|
||||
})
|
||||
const vitals = await page.evaluate(() => window.__perf)
|
||||
const { metrics } = await cdp.send('Performance.getMetrics')
|
||||
const metric = (name) => metrics.find((m) => m.name === name)?.value ?? 0
|
||||
await context.close()
|
||||
|
||||
const list = [...requests.values()]
|
||||
const bytes = { css: 0, font: 0, html: 0, image: 0, js: 0, other: 0 }
|
||||
for (const r of list) {bytes[r.type] += r.bytes}
|
||||
const fcp = nav.fcp ?? 0
|
||||
const tbt = vitals.longTasks.filter(([start]) => start >= fcp).reduce((sum, [, d]) => sum + Math.max(0, d - 50), 0)
|
||||
const round = (n) => (n == null ? null : Math.round(n))
|
||||
return {
|
||||
bytes: Object.fromEntries(Object.entries(bytes).map(([k, b]) => [k, Math.round(b)])),
|
||||
cls: Math.round(vitals.cls * 1000) / 1000,
|
||||
fcp: round(nav.fcp),
|
||||
inp: vitals.events.length ? round(Math.max(...vitals.events.map((e) => e.d))) : interaction ? 0 : null,
|
||||
interaction,
|
||||
lcp: round(vitals.lcp?.at),
|
||||
lcpElement: vitals.lcp ? { fetchpriority: vitals.lcp.fetchpriority, loading: vitals.lcp.loading, src: vitals.lcp.src ? vitals.lcp.src.replace(origin, '') : null, tag: vitals.lcp.tag } : null,
|
||||
load: round(nav.load),
|
||||
prefetches,
|
||||
profile: profileName,
|
||||
renderBlocking: nav.blocking.map((u) => u.replace(origin, '')),
|
||||
requests: list.length,
|
||||
scriptMs: round(metric('ScriptDuration') * 1000),
|
||||
status: response?.status() ?? null,
|
||||
tbt: round(tbt),
|
||||
thirdParty: [...new Set(list.filter((r) => !r.url.startsWith(origin)).map((r) => new URL(r.url).origin))],
|
||||
ttfb: round(nav.ttfb),
|
||||
url: url.replace(origin, ''),
|
||||
}
|
||||
}
|
||||
|
||||
export const median = (values) => {
|
||||
const sorted = values.filter((v) => typeof v === 'number').sort((a, b) => a - b)
|
||||
if (!sorted.length) {return null}
|
||||
const mid = Math.floor(sorted.length / 2)
|
||||
return sorted.length % 2 ? sorted[mid] : Math.round(((sorted[mid - 1] + sorted[mid]) / 2) * 1000) / 1000
|
||||
}
|
||||
|
||||
/**
|
||||
* The median of `runs` measurements for every number; the rest from the last run.
|
||||
* @param {import('@playwright/test').Browser} browser
|
||||
* @param {string} url
|
||||
* @param {'mobile'|'desktop'} profileName
|
||||
* @param {number} [runs]
|
||||
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
|
||||
* @returns {Promise<PageMeasurement>}
|
||||
*/
|
||||
export async function measureMedian(browser, url, profileName, runs = 3, options = {}) {
|
||||
const all = []
|
||||
for (let i = 0; i < runs; i++) {all.push(await measurePage(browser, url, profileName, options))}
|
||||
const last = all.at(-1)
|
||||
const out = { ...last, runs }
|
||||
for (const key of ['cls', 'fcp', 'inp', 'lcp', 'load', 'requests', 'scriptMs', 'tbt', 'ttfb']) {out[key] = median(all.map((r) => r[key]))}
|
||||
out.bytes = Object.fromEntries(Object.keys(last.bytes).map((k) => [k, median(all.map((r) => r.bytes[k]))]))
|
||||
return out
|
||||
}
|
||||
|
||||
export const launch = () => chromium.launch()
|
||||
@@ -0,0 +1,48 @@
|
||||
// e2e/performance.spec.ts — the project's performance budget gate (iapl-performance skill, docs/performance.md).
|
||||
// Copy this file and perf-lab.mjs (same folder) to e2e/. Runs against the BUILT site: pnpm build && pnpm test:e2e.
|
||||
// It fails when a page breaks a budget: the plugin's defaults (Core Web Vitals "good", bytes, requests), tightened
|
||||
// below to what this site measured, so a change that makes it slower fails. Loosen a number only with a reason.
|
||||
import type { Browser } from '@playwright/test'
|
||||
|
||||
import { overBudget, perfBudgets } from '@intecion/ipal-kit/doctor'
|
||||
import { chromium, expect, test } from '@playwright/test'
|
||||
|
||||
// a plain ES module (JSDoc types) — perf-lab.mjs from the skill's resources
|
||||
import { measureMedian } from './perf-lab.mjs'
|
||||
|
||||
const runs = Number(process.env.PERF_RUNS ?? 1)
|
||||
|
||||
// Start from the defaults; after the first run, set each number to what you measured plus ~20 % (the lab is noisy).
|
||||
const budgets = perfBudgets({
|
||||
desktop: {},
|
||||
mobile: {},
|
||||
})
|
||||
|
||||
// One page of each template the site has (AGENTS.md → Site map). `budget` changes a number for one page, with a reason.
|
||||
const PAGES: Array<{ budget?: Partial<typeof budgets.mobile>; name: string; path: string }> = [
|
||||
{ name: 'home', path: '/pl' },
|
||||
// { name: 'page', path: '/pl/o-nas' },
|
||||
// { name: 'post', path: '/pl/blog/<a-post>' },
|
||||
// { name: 'form', path: '/pl/kontakt', budget: { thirdParty: ['https://challenges.cloudflare.com'] } }, // Turnstile
|
||||
]
|
||||
|
||||
let browser: Browser
|
||||
test.beforeAll(async () => {
|
||||
browser = await chromium.launch()
|
||||
})
|
||||
test.afterAll(async () => {
|
||||
await browser?.close()
|
||||
})
|
||||
|
||||
for (const page of PAGES) {
|
||||
for (const profile of ['mobile', 'desktop'] as const) {
|
||||
test(`${page.name} (${profile}) stays within its performance budget`, async ({ baseURL }) => {
|
||||
test.setTimeout(120_000)
|
||||
// third-party requests are recorded, then aborted: an external host cannot fail or hang the test
|
||||
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 }), type: 'measured' })
|
||||
expect(overBudget(measured, { ...budgets[profile], ...page.budget }), `${page.path} ${profile}`).toEqual([])
|
||||
if (measured.lcpElement?.tag === 'img') {expect(measured.lcpElement.loading, 'the LCP image is lazy').not.toBe('lazy')}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -218,6 +218,7 @@ Mandatory set: AGENT.md §0b, skill **iapl-setup**; checks: **iapl-audit**, **ia
|
||||
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
|
||||
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site integrations → E-mail sending → **Send test** | email.md |
|
||||
| forms — action | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | submit → document in Form Submissions + e-mails | forms.md, skill **iapl-form** |
|
||||
| forms — retention | config (client decision) | `forms: { submissionRetentionDays: 365 }` (1.18.0; default: kept) | `iapl-doctor --deep --only growth-submissions` quiet; old submissions gone a day after the next submission | performance.md §6, forms.md |
|
||||
| forms — files | config + panel | `forms: { attachments: true }`; a **File** field on the form; an e-mail with fixed recipients in Forms → E-mails; `mailAdapter({ graph: { largeAttachments } })` when Graph must stay under 3 MB; Azure: `Mail.ReadWrite` limited to the forms mailbox for files of 3 MB and more over Graph | Test e-mail with "Attach a 10 MB test file" arrives; a submission with a PDF arrives with the attachment; nothing in Media | forms.md "Files", email.md "Attachments" |
|
||||
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
|
||||
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site integrations → Spam protection or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
|
||||
|
||||
@@ -338,7 +338,7 @@ Opt-in with `iapl({ cookieScanner: true })`; the plugin wires the collection, en
|
||||
|---|---|---|
|
||||
| `createContentHelpers({ config, content?, i18n?, baseUrl?, … })` | `@intecion/ipal-kit` | factory for `src/lib/content.ts`: cached `getCachedPayload`, `getSettings`, `resolveRoute`, `getEntries`, `generatePageMetadata`, `getSiteShell`, `sitemap`, `robots`, `getRobots`, `isPathVisible`, `markdownRoute`, `healthRoute`, `mcpGET`/`mcpPOST`… — do not write these wrappers yourself |
|
||||
| `createPageRoute(content, { blocks, notFound, permanentRedirect, redirect?, … })` | `@intecion/ipal-kit/rsc` | ready `[[...slug]]` catch-all page → `{ Page, generateMetadata, generateStaticParams }` (blocks, slug history redirects, JSON-LD, under-construction mode); does not paginate `?page=` |
|
||||
| `createNotFoundPage(content, { load } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended) |
|
||||
| `createNotFoundPage(content, { load, placeholder? } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended; `placeholder` (1.18.0) reserves the 404 content's height until it arrives — no layout shift, performance.md) |
|
||||
| `renderNotFoundView(content, { blocks, fallback?, blockProps?, layoutField? }, locale)` | `@intecion/ipal-kit/rsc` | 404 content in one language — called from a server action for the lazy `createNotFoundPage({ load })` (pages.md) |
|
||||
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script (and `lightbox` → `LightboxProvider`); `nonce` (from `x-nonce`) goes on the theme script and the GA4/GTM tag; does not mount `AlternateLinksProvider` |
|
||||
|
||||
@@ -454,7 +454,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Creates the server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → text from Notifications; returns `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` in `actions.ts` |
|
||||
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `iapl({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
|
||||
| `submitForm({ payload, formId, data, files?, attemptKey?, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName?, turnstileHostnames? })` | `@intecion/ipal-kit/server` | Server core (`consentFieldName`: argument → `iapl({ forms: { consentFieldName } })` → `'consent'`; `turnstileHostnames` rejects a token solved on another domain): rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission (and, with `forms.submissionRetentionDays`, deletes older ones at most once a day); returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
|
||||
|
||||
### Honeypot
|
||||
|
||||
@@ -532,7 +532,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `mediaImageProps(resource, { sizes?, priority?, alt?, placeholderColor? })` | `@intecion/ipal-kit` | `next/image` props for an image upload (dimensions, focal point → `objectPosition`, blur placeholder, `preload` for LCP) or `null` (video/PDF/ID) — for your own `<Media>` |
|
||||
| `mediaImageProps(resource, { sizes?, priority?, eager?, alt?, placeholderColor? })` | `@intecion/ipal-kit` | `next/image` props for an image upload (dimensions, focal point → `objectPosition`, blur placeholder, `preload` for LCP) or `null` (video/PDF/ID) — for your own `<Media>`. `eager` (1.18.0): above the fold but not the LCP image (a logo) — eager without high priority or a preload |
|
||||
| `videoProps(resource, { mode?, poster?, reducedMotion? })` | `@intecion/ipal-kit` | `<video>` attributes for a video upload (`'background'`: autoplay/muted/loop; `'player'`: controls, `preload="none"`) or `null` |
|
||||
| `MEDIA_SIZES` | `@intecion/ipal-kit` | Ready constant `sizes` values: `full`, `half`, `third`, `quarter`, `thumb` |
|
||||
| `normalizeFilename(filename)` | `@intecion/ipal-kit` | Slugifies a file name, keeping the extension (`"Zdjęcie 1.JPG"` → `"zdjecie-1.jpg"`) |
|
||||
@@ -881,7 +881,10 @@ Bin: `iapl-doctor` (`pnpm exec iapl-doctor [dir] [--json] [--md] [--strict] [--f
|
||||
| `findFrontend(ctx)` | `@intecion/ipal-kit/doctor` | The folder of the site's pages (`FrontendLayout`: `dir`, `multi`, `ambiguous`, `missingOverride`) — found by structure (any route group with the catch-all page, a localized one first); `layout.frontend` in `iapl-doctor.json` wins. |
|
||||
| `createLiveFetcher(url, { adminRoute, staging })` | `@intecion/ipal-kit/doctor` | Cached GET-only fetcher for the live rules. |
|
||||
| `runDeepProbe(ctx)` | `@intecion/ipal-kit/doctor` | `pnpm exec payload run …/dist/modules/doctor/probe.js` in the project → `DoctorStatus`. |
|
||||
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `plugin`, `node`. |
|
||||
| `collectDoctorStatus(payload)` | `@intecion/ipal-kit/doctor` | Read-only counts: `usersWithout2fa`, `pendingCookies`, `media` (images over `IMAGE_RULES`, 1.18.0), `plugin`, `node`. |
|
||||
| `PERF_BUDGETS`, `SERVER_BUDGET`, `perfBudgets(overrides)`, `overBudget(measured, budget)`, `IMAGE_RULES` | `@intecion/ipal-kit/doctor` | Performance budgets (1.18.0, performance.md): the defaults per profile (`mobile`, `desktop`: `lcp`, `cls`, `inp`, `tbt`, `jsBytes`, `cssBytes`, `fontBytes`, `requests`, `renderBlocking`, `thirdParty`) and per render (`queriesPerRender`); a project's own on top; the broken budgets of one measurement as lines (empty = within budget); the image limits (1.5 MB, 2560 px, AVIF/WebP). Types `PerfBudget`, `PerfMeasurement`, `PerfProfile`, `ServerBudget`. The gate: `iapl-performance/resources/performance.spec.template.ts` + `perf-lab.mjs`. |
|
||||
| `collectGrowth(payload)` → `GrowthStatus`, `growthRules`, `GROWTH_DEFAULTS`, `folderBytes(dir)` | `@intecion/ipal-kit/doctor` | What grows (1.18.0, performance.md §6): per collection documents, bytes (MongoDB) and the oldest record; versions per collection and global with their limit; `payload-kv` entries and expired ones; media no document points at (first 5000 documents) — counts only. The `growth` rules (`growth-size`, `-versions`, `-retention`, `-submissions`, `-kv`, `-media`, `-disk`) and their default thresholds (`iapl-doctor.json` → `growth`, type `GrowthThresholds`). |
|
||||
| `performanceRules` | `@intecion/ipal-kit/doctor` | The doctor's `performance` group (`perf-images-config`, `perf-fonts`, `perf-render-blocking`, `perf-embeds`, `perf-animations`, `perf-budgets`, `perf-live`, `perf-images`) — part of `doctorRules`. |
|
||||
| `buildDoctorEndpoint({ tokenVar, access })` | `@intecion/ipal-kit/doctor` | `GET /ipal/doctor` (`/api/ipal/doctor`): 404 until the token variable (default `IAPL_DOCTOR_TOKEN`, ≥ 32 chars) is set, Bearer token or `access`, rate-limited. Added by `iapl` unless `doctor: false`. |
|
||||
| `jobsRunAccess({ secretVar? })` | `@intecion/ipal-kit` | The rule iapl puts on `jobs.access.run` when the project writes none: `cronSecretMatches(req, process.env[secretVar])` or an admin with the second factor. Reuse it in your own rule: `run: (a) => jobsRunAccess()(a) \|\| myCheck(a)`. Type `JobsRunAccessOptions`. |
|
||||
| `withJobsRunAccess(config, options \| false)` / `jobsRunNotice(config)` | `@intecion/ipal-kit` | The config with that rule (only when `jobs.access.run` is missing; marks `custom.iapl.jobsRunDefault`); the start-up line when the queue is on and the secret is missing (null otherwise). |
|
||||
|
||||
Reference in New Issue
Block a user