From d6288392350fbd2551b51cba234b8a055d73a04d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 1 Dec 2026 15:38:38 +0100 Subject: [PATCH 1/3] 1.18.0 performance items: reference 404 placeholder and heading font without preload, lazy form and Turnstile code (eager entry /client/eager), Turnstile space kept, background video paused for reduced motion, card hover on opacity, metadata stripped on upload, MongoDB TTL indexes for the consent log and statistics, unused-media notice, version limit for the plugin's entities Co-Authored-By: Claude Opus 5.5 --- docs/agent/reference-site/INDEX.md | 8 +- docs/dev/perf/webpack-1180-after.json | 768 ++++++++++++++++++ docs/dev/perf/webpack-1180-before.json | 768 ++++++++++++++++++ package.json | 5 + reference/e2e/performance.spec.ts | 37 +- reference/e2e/unused-media.spec.ts | 46 ++ .../src/app/(frontend)/[locale]/layout.tsx | 4 +- .../src/app/(frontend)/[locale]/not-found.tsx | 7 +- .../src/app/(payload)/admin/importMap.js | 2 + reference/src/payload-types.ts | 2 + reference/src/payload.config.ts | 2 + scripts/e2e-built.mjs | 2 +- scripts/reference-index.mjs | 1 + src/exports/admin.ts | 1 + src/exports/blocks-rsc.ts | 2 +- src/exports/client-eager.ts | 11 + src/exports/client.ts | 4 +- src/index.ts | 3 +- .../block-library/ui/BackgroundVideo.tsx | 34 + src/modules/block-library/ui/Card.tsx | 10 +- src/modules/block-library/ui/Media.tsx | 6 +- src/modules/consent/consentLog.ts | 8 + src/modules/doctor/growth.ts | 122 ++- src/modules/doctor/rules/growth.ts | 34 + src/modules/forms/BuilderForm.tsx | 5 +- src/modules/forms/LazyBuilderForm.tsx | 22 + src/modules/forms/RenderForm.tsx | 19 +- src/modules/forms/useBuilderForm.ts | 4 +- src/modules/forms/useContactForm.ts | 4 +- src/modules/forms/useForm.ts | 4 +- src/modules/media/UnusedMediaNotice.tsx | 66 ++ src/modules/media/index.ts | 2 + src/modules/media/optimizeUpload.ts | 34 +- src/modules/media/stripMetadata.ts | 94 +++ src/modules/shared/ttl.ts | 63 ++ src/modules/shared/versionLimit.ts | 19 + src/modules/stats/collection.ts | 5 + src/modules/stats/endpoint.ts | 3 + src/modules/turnstile/LazyTurnstile.tsx | 23 + src/modules/turnstile/Turnstile.tsx | 10 +- src/modules/turnstile/TurnstileProvider.tsx | 22 +- src/modules/turnstile/client.ts | 3 +- src/modules/turnstile/turnstileHeight.ts | 5 + src/plugin.ts | 54 +- src/types.ts | 7 + test/performance1180.test.ts | 180 ++++ test/stripMetadata.test.ts | 89 ++ 47 files changed, 2546 insertions(+), 78 deletions(-) create mode 100644 docs/dev/perf/webpack-1180-after.json create mode 100644 docs/dev/perf/webpack-1180-before.json create mode 100644 reference/e2e/unused-media.spec.ts create mode 100644 src/exports/client-eager.ts create mode 100644 src/modules/block-library/ui/BackgroundVideo.tsx create mode 100644 src/modules/forms/LazyBuilderForm.tsx create mode 100644 src/modules/media/UnusedMediaNotice.tsx create mode 100644 src/modules/media/stripMetadata.ts create mode 100644 src/modules/shared/ttl.ts create mode 100644 src/modules/shared/versionLimit.ts create mode 100644 src/modules/turnstile/LazyTurnstile.tsx create mode 100644 src/modules/turnstile/turnstileHeight.ts create mode 100644 test/performance1180.test.ts create mode 100644 test/stripMetadata.test.ts diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md index 9c134fb..1766d0a 100644 --- a/docs/agent/reference-site/INDEX.md +++ b/docs/agent/reference-site/INDEX.md @@ -829,7 +829,12 @@ import * as content from '@/lib/content' import { loadNotFoundView } from './notFoundView' -export default createNotFoundPage(content, { load: loadNotFoundView }) +// The lazy 404 content arrives after hydration: a block as tall as it keeps the footer still (no layout shift). +// Measured for this site's 404 content: 282 px at 360 px wide to 432 px at 1920 — change it with that content. +export default createNotFoundPage(content, { + load: loadNotFoundView, + placeholder:
, +}) ``` ### `src/app/(frontend)/[locale]/notFoundView.ts` @@ -1150,6 +1155,7 @@ Rules: AGENT.md §8a. | `e2e/two-factor-back.spec.ts` | browser test of the 2FA screens' `back` link (twoFactor.safeBack): a prepared link — script or another host — ends on the admin root, an ordinary one is followed | | `e2e/two-factor-enrolment.spec.ts` | the first 2FA set-up confirmed by e-mail on the built site (run by `pnpm e2e:built` in both bundlers): the password alone no longer enrols an attacker's factor (the link goes to the owner and is refused in another browser), and the panel flow — code, notice, link from the mail sink, sign in again | | `e2e/two-factor-setup.spec.ts` | browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator's reset on the account page | +| `e2e/unused-media.spec.ts` | the unused-files notice above the Media list (`unusedMedia: true`): an image nothing uses is listed and the link opens Payload's list filtered to it; the test deletes its own upload, the panel never deletes | ### `e2e/enrolment.ts` diff --git a/docs/dev/perf/webpack-1180-after.json b/docs/dev/perf/webpack-1180-after.json new file mode 100644 index 0000000..3a2e914 --- /dev/null +++ b/docs/dev/perf/webpack-1180-after.json @@ -0,0 +1,768 @@ +{ + "client": { + "mobile": { + "home": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 19948, + "image": 9544, + "js": 188341, + "other": 0 + }, + "cls": 0.036, + "fcp": 768, + "inp": 32, + "interaction": "PL", + "lcp": 768, + "lcpElement": { + "fetchpriority": "high", + "loading": "eager", + "src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3", + "tag": "img" + }, + "load": 2432, + "prefetches": 4, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 22, + "scriptMs": 126, + "status": 200, + "tbt": 14, + "thirdParty": [], + "ttfb": 151, + "url": "/pl", + "runs": 3 + }, + "page": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 17081, + "image": 8457, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 756, + "inp": 32, + "interaction": "PL", + "lcp": 756, + "lcpElement": { + "fetchpriority": "high", + "loading": "eager", + "src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3", + "tag": "img" + }, + "load": 2435, + "prefetches": 2, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 19, + "scriptMs": 126, + "status": 200, + "tbt": 12, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/o-nas", + "runs": 3 + }, + "archive": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 16640, + "image": 5322, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 740, + "inp": 40, + "interaction": "PL", + "lcp": 740, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2437, + "prefetches": 3, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 19, + "scriptMs": 130, + "status": 200, + "tbt": 14, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/blog", + "runs": 3 + }, + "post": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 17135, + "image": 5322, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 752, + "inp": 40, + "interaction": "PL", + "lcp": 752, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2435, + "prefetches": 2, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 19, + "scriptMs": 137, + "status": 200, + "tbt": 15, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/blog/zanim-kupisz-dzialke", + "runs": 3 + }, + "caseStudy": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 16540, + "image": 4376, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 772, + "inp": 40, + "interaction": "PL", + "lcp": 772, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2442, + "prefetches": 2, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 18, + "scriptMs": 129, + "status": 200, + "tbt": 15, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/realizacje/dom-pod-lasem", + "runs": 3 + }, + "form": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 16793, + "image": 0, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 776, + "inp": 40, + "interaction": "PL", + "lcp": 776, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2380, + "prefetches": 2, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 16, + "scriptMs": 215, + "status": 200, + "tbt": 13, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/wycena", + "runs": 3 + }, + "showcase": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 37303, + "image": 2018, + "js": 216609, + "other": 0 + }, + "cls": 0, + "fcp": 768, + "inp": 40, + "interaction": "PL", + "lcp": 768, + "lcpElement": { + "fetchpriority": "high", + "loading": "eager", + "src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3", + "tag": "img" + }, + "load": 2459, + "prefetches": 4, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 21, + "scriptMs": 205, + "status": 200, + "tbt": 21, + "thirdParty": [ + "https://challenges.cloudflare.com" + ], + "ttfb": 151, + "url": "/pl/bloki", + "runs": 3 + }, + "notFound": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 7711, + "image": 0, + "js": 188341, + "other": 2472 + }, + "cls": 0, + "fcp": 1900, + "inp": 40, + "interaction": "PL", + "lcp": 1900, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2845, + "prefetches": 10, + "profile": "mobile", + "renderBlocking": [], + "requests": 17, + "scriptMs": 172, + "status": 404, + "tbt": 0, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/nie-ma-takiej-strony", + "runs": 3 + } + }, + "desktop": { + "home": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 19948, + "image": 9286, + "js": 188341, + "other": 0 + }, + "cls": 0.001, + "fcp": 284, + "inp": 40, + "interaction": "PL", + "lcp": 284, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "h1" + }, + "load": 477, + "prefetches": 11, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 22, + "scriptMs": 51, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl", + "runs": 3 + }, + "page": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 17081, + "image": 10684, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 284, + "inp": 40, + "interaction": "PL", + "lcp": 284, + "lcpElement": { + "fetchpriority": "high", + "loading": "eager", + "src": "/_next/image?url=http%3A%2F%2Flocalhost%3A3370%2Fapi%2Fmedia%2Ffile%2Flibrary-2.webp&w=750&q=75", + "tag": "img" + }, + "load": 476, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 20, + "scriptMs": 47, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/o-nas", + "runs": 3 + }, + "archive": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 16640, + "image": 4815, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 284, + "inp": 40, + "interaction": "PL", + "lcp": 284, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 469, + "prefetches": 11, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 19, + "scriptMs": 51, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/blog", + "runs": 3 + }, + "post": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 17135, + "image": 4815, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 276, + "inp": 40, + "interaction": "PL", + "lcp": 276, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 472, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 19, + "scriptMs": 46, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/blog/zanim-kupisz-dzialke", + "runs": 3 + }, + "caseStudy": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 16540, + "image": 9286, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 292, + "inp": 40, + "interaction": "PL", + "lcp": 292, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "h1" + }, + "load": 471, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 20, + "scriptMs": 40, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/realizacje/dom-pod-lasem", + "runs": 3 + }, + "form": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 16793, + "image": 0, + "js": 188341, + "other": 0 + }, + "cls": 0, + "fcp": 280, + "inp": 40, + "interaction": "PL", + "lcp": 280, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 439, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 16, + "scriptMs": 51, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/wycena", + "runs": 3 + }, + "showcase": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 37303, + "image": 5267, + "js": 216587, + "other": 0 + }, + "cls": 0, + "fcp": 304, + "inp": 40, + "interaction": "PL", + "lcp": 304, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 493, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/b2d8ea1877879cf5.css" + ], + "requests": 22, + "scriptMs": 60, + "status": 200, + "tbt": 0, + "thirdParty": [ + "https://challenges.cloudflare.com" + ], + "ttfb": 41, + "url": "/pl/bloki", + "runs": 3 + }, + "notFound": { + "bytes": { + "css": 11177, + "font": 209501, + "html": 7711, + "image": 0, + "js": 188341, + "other": 2472 + }, + "cls": 0, + "fcp": 428, + "inp": 40, + "interaction": "PL", + "lcp": 480, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "h1" + }, + "load": 412, + "prefetches": 14, + "profile": "desktop", + "renderBlocking": [], + "requests": 17, + "scriptMs": 44, + "status": 404, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/nie-ma-takiej-strony", + "runs": 3 + } + }, + "admin": { + "bytes": { + "css": 98168, + "font": 0, + "html": 24047, + "image": 0, + "js": 843378, + "other": 1690 + }, + "cls": 0, + "fcp": 1040, + "inp": null, + "interaction": null, + "lcp": 1040, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "a" + }, + "load": 962, + "prefetches": 0, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/de3d54fcc6ee5dc6.css", + "/_next/static/css/c1e0b959dd828ab8.css", + "/_next/static/css/e5d1b6185968e333.css", + "/_next/static/css/4858144d3215dfc6.css", + "/_next/static/css/dc48c3ee3f159f65.css" + ], + "requests": 20, + "scriptMs": 351, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 89, + "url": "/admin/login", + "runs": 3 + } + }, + "date": "2026-12-01T14:09:30.949Z", + "label": "webpack-1180-after", + "method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs", + "runs": 3, + "server": { + "coldStartHealthMs": 1197, + "coldStartFirstPageMs": 1221, + "firstPageMs": 22, + "ttfb_home": { + "median": 3.5, + "p95": 6.8 + }, + "ttfb_md": { + "median": 30.7, + "p95": 37.1 + }, + "ttfb_sitemap": { + "median": 1.8, + "p95": 2.4 + }, + "ttfb_llms": { + "median": 44.6, + "p95": 56.7 + }, + "render": { + "home": { + "medianMs": 68.1, + "queries": 24, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 33, + "media": 9, + "forms": 3 + } + }, + "page": { + "medianMs": 53.1, + "queries": 21, + "queryMs": 1, + "byCollection": { + "globals": 27, + "media": 6, + "pages": 27, + "forms": 3 + } + }, + "archive": { + "medianMs": 62, + "queries": 23, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 27, + "media": 6, + "forms": 3, + "posts": 6 + } + }, + "post": { + "medianMs": 65.3, + "queries": 26, + "queryMs": 0, + "byCollection": { + "globals": 27, + "media": 9, + "pages": 24, + "posts": 15, + "forms": 3 + } + }, + "caseStudy": { + "medianMs": 50.2, + "queries": 22, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 21, + "media": 6, + "casestudies": 9, + "forms": 3 + } + }, + "form": { + "medianMs": 31.4, + "queries": 19, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 24, + "media": 3, + "forms": 3 + } + }, + "showcase": { + "medianMs": 48.8, + "queries": 27, + "queryMs": 0, + "byCollection": { + "globals": 24, + "pages": 33, + "media": 12, + "forms": 6, + "posts": 6 + } + }, + "notFound": { + "medianMs": 21.3, + "queries": 20, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 27, + "media": 6 + } + }, + "md": { + "medianMs": 29, + "queries": 16, + "queryMs": 0, + "byCollection": { + "globals": 4, + "media": 5, + "pages": 6, + "forms": 1 + } + }, + "sitemap": { + "medianMs": 3, + "queries": 0, + "queryMs": 0, + "byCollection": {} + }, + "llms": { + "medianMs": 42, + "queries": 22, + "queryMs": 0, + "byCollection": { + "globals": 4, + "media": 3, + "pages": 7, + "posts": 4, + "casestudies": 4 + } + }, + "llmsFull": { + "medianMs": 55, + "queries": 38, + "queryMs": 0, + "byCollection": { + "globals": 6, + "media": 9, + "pages": 13, + "forms": 2, + "posts": 4, + "casestudies": 4 + } + } + }, + "rssMiB": 305 + } +} diff --git a/docs/dev/perf/webpack-1180-before.json b/docs/dev/perf/webpack-1180-before.json new file mode 100644 index 0000000..e0f8333 --- /dev/null +++ b/docs/dev/perf/webpack-1180-before.json @@ -0,0 +1,768 @@ +{ + "client": { + "mobile": { + "home": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 19869, + "image": 9544, + "js": 188112, + "other": 0 + }, + "cls": 0.036, + "fcp": 812, + "inp": 40, + "interaction": "PL", + "lcp": 812, + "lcpElement": { + "fetchpriority": "high", + "loading": "eager", + "src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3", + "tag": "img" + }, + "load": 2543, + "prefetches": 4, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 22, + "scriptMs": 174, + "status": 200, + "tbt": 46, + "thirdParty": [], + "ttfb": 151, + "url": "/pl", + "runs": 3 + }, + "page": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 17109, + "image": 8457, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 812, + "inp": 48, + "interaction": "PL", + "lcp": 812, + "lcpElement": { + "fetchpriority": "high", + "loading": "eager", + "src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3", + "tag": "img" + }, + "load": 2571, + "prefetches": 2, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 19, + "scriptMs": 197, + "status": 200, + "tbt": 73, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/o-nas", + "runs": 3 + }, + "archive": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 16552, + "image": 5322, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 836, + "inp": 48, + "interaction": "PL", + "lcp": 836, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2548, + "prefetches": 3, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 19, + "scriptMs": 179, + "status": 200, + "tbt": 59, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/blog", + "runs": 3 + }, + "post": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 17079, + "image": 5322, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 796, + "inp": 40, + "interaction": "PL", + "lcp": 796, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2511, + "prefetches": 2, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 19, + "scriptMs": 128, + "status": 200, + "tbt": 27, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/blog/zanim-kupisz-dzialke", + "runs": 3 + }, + "caseStudy": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 16570, + "image": 4376, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 816, + "inp": 40, + "interaction": "PL", + "lcp": 816, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2502, + "prefetches": 2, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 18, + "scriptMs": 132, + "status": 200, + "tbt": 35, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/realizacje/dom-pod-lasem", + "runs": 3 + }, + "form": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 16294, + "image": 0, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 816, + "inp": 40, + "interaction": "PL", + "lcp": 816, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2466, + "prefetches": 2, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 16, + "scriptMs": 126, + "status": 200, + "tbt": 23, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/wycena", + "runs": 3 + }, + "showcase": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 36926, + "image": 2018, + "js": 216415, + "other": 0 + }, + "cls": 0, + "fcp": 848, + "inp": 40, + "interaction": "PL", + "lcp": 848, + "lcpElement": { + "fetchpriority": "high", + "loading": "eager", + "src": "data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1000'%3", + "tag": "img" + }, + "load": 2485, + "prefetches": 4, + "profile": "mobile", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 21, + "scriptMs": 207, + "status": 200, + "tbt": 31, + "thirdParty": [ + "https://challenges.cloudflare.com" + ], + "ttfb": 151, + "url": "/pl/bloki", + "runs": 3 + }, + "notFound": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 7700, + "image": 0, + "js": 188112, + "other": 2470 + }, + "cls": 0.319, + "fcp": 2524, + "inp": 40, + "interaction": "PL", + "lcp": 2524, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 2594, + "prefetches": 10, + "profile": "mobile", + "renderBlocking": [], + "requests": 17, + "scriptMs": 232, + "status": 404, + "tbt": 0, + "thirdParty": [], + "ttfb": 151, + "url": "/pl/nie-ma-takiej-strony", + "runs": 3 + } + }, + "desktop": { + "home": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 19869, + "image": 9286, + "js": 188112, + "other": 0 + }, + "cls": 0.001, + "fcp": 292, + "inp": 40, + "interaction": "PL", + "lcp": 292, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "h1" + }, + "load": 479, + "prefetches": 11, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 22, + "scriptMs": 43, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl", + "runs": 3 + }, + "page": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 17109, + "image": 10684, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 284, + "inp": 40, + "interaction": "PL", + "lcp": 284, + "lcpElement": { + "fetchpriority": "high", + "loading": "eager", + "src": "/_next/image?url=http%3A%2F%2Flocalhost%3A3370%2Fapi%2Fmedia%2Ffile%2Flibrary-2.webp&w=750&q=75", + "tag": "img" + }, + "load": 460, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 20, + "scriptMs": 29, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/o-nas", + "runs": 3 + }, + "archive": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 16552, + "image": 4815, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 288, + "inp": 40, + "interaction": "PL", + "lcp": 288, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 473, + "prefetches": 11, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 19, + "scriptMs": 31, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/blog", + "runs": 3 + }, + "post": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 17079, + "image": 4815, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 280, + "inp": 40, + "interaction": "PL", + "lcp": 280, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 461, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 19, + "scriptMs": 29, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/blog/zanim-kupisz-dzialke", + "runs": 3 + }, + "caseStudy": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 16570, + "image": 9286, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 304, + "inp": 40, + "interaction": "PL", + "lcp": 304, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "h1" + }, + "load": 465, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 20, + "scriptMs": 31, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/realizacje/dom-pod-lasem", + "runs": 3 + }, + "form": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 16294, + "image": 0, + "js": 188112, + "other": 0 + }, + "cls": 0, + "fcp": 280, + "inp": 40, + "interaction": "PL", + "lcp": 280, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 457, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 16, + "scriptMs": 29, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/wycena", + "runs": 3 + }, + "showcase": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 36926, + "image": 5267, + "js": 216415, + "other": 0 + }, + "cls": 0, + "fcp": 304, + "inp": 40, + "interaction": "PL", + "lcp": 304, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "p" + }, + "load": 470, + "prefetches": 8, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/2419e69855bb1a63.css" + ], + "requests": 22, + "scriptMs": 47, + "status": 200, + "tbt": 0, + "thirdParty": [ + "https://challenges.cloudflare.com" + ], + "ttfb": 41, + "url": "/pl/bloki", + "runs": 3 + }, + "notFound": { + "bytes": { + "css": 11070, + "font": 209501, + "html": 7700, + "image": 0, + "js": 188112, + "other": 2470 + }, + "cls": 0, + "fcp": 508, + "inp": 40, + "interaction": "PL", + "lcp": 564, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "h1" + }, + "load": 500, + "prefetches": 14, + "profile": "desktop", + "renderBlocking": [], + "requests": 17, + "scriptMs": 43, + "status": 404, + "tbt": 0, + "thirdParty": [], + "ttfb": 41, + "url": "/pl/nie-ma-takiej-strony", + "runs": 3 + } + }, + "admin": { + "bytes": { + "css": 98168, + "font": 0, + "html": 24044, + "image": 0, + "js": 843325, + "other": 1690 + }, + "cls": 0, + "fcp": 1012, + "inp": null, + "interaction": null, + "lcp": 1012, + "lcpElement": { + "fetchpriority": null, + "loading": null, + "src": null, + "tag": "a" + }, + "load": 942, + "prefetches": 0, + "profile": "desktop", + "renderBlocking": [ + "/_next/static/css/de3d54fcc6ee5dc6.css", + "/_next/static/css/c1e0b959dd828ab8.css", + "/_next/static/css/e5d1b6185968e333.css", + "/_next/static/css/4858144d3215dfc6.css", + "/_next/static/css/dc48c3ee3f159f65.css" + ], + "requests": 20, + "scriptMs": 348, + "status": 200, + "tbt": 0, + "thirdParty": [], + "ttfb": 86, + "url": "/admin/login", + "runs": 3 + } + }, + "date": "2026-12-01T14:02:14.941Z", + "label": "webpack-1180-before", + "method": "scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs", + "runs": 3, + "server": { + "coldStartHealthMs": 1460, + "coldStartFirstPageMs": 1487, + "firstPageMs": 26, + "ttfb_home": { + "median": 3.5, + "p95": 6 + }, + "ttfb_md": { + "median": 38.1, + "p95": 54.6 + }, + "ttfb_sitemap": { + "median": 2, + "p95": 3.2 + }, + "ttfb_llms": { + "median": 53.1, + "p95": 83.3 + }, + "render": { + "home": { + "medianMs": 63.8, + "queries": 24, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 33, + "media": 9, + "forms": 3 + } + }, + "page": { + "medianMs": 38.7, + "queries": 21, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 27, + "media": 6, + "forms": 3 + } + }, + "archive": { + "medianMs": 40.8, + "queries": 23, + "queryMs": 0, + "byCollection": { + "globals": 27, + "media": 6, + "pages": 27, + "forms": 3, + "posts": 6 + } + }, + "post": { + "medianMs": 42.1, + "queries": 26, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 24, + "media": 9, + "posts": 15, + "forms": 3 + } + }, + "caseStudy": { + "medianMs": 45.1, + "queries": 22, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 21, + "media": 6, + "casestudies": 9, + "forms": 3 + } + }, + "form": { + "medianMs": 30.6, + "queries": 19, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 24, + "media": 3, + "forms": 3 + } + }, + "showcase": { + "medianMs": 75.5, + "queries": 27, + "queryMs": 0, + "byCollection": { + "globals": 24, + "pages": 33, + "media": 12, + "forms": 6, + "posts": 6 + } + }, + "notFound": { + "medianMs": 45.8, + "queries": 20, + "queryMs": 0, + "byCollection": { + "globals": 27, + "pages": 27, + "media": 6 + } + }, + "md": { + "medianMs": 38, + "queries": 16, + "queryMs": 0, + "byCollection": { + "globals": 4, + "media": 5, + "pages": 6, + "forms": 1 + } + }, + "sitemap": { + "medianMs": 2, + "queries": 0, + "queryMs": 0, + "byCollection": {} + }, + "llms": { + "medianMs": 59, + "queries": 22, + "queryMs": 0, + "byCollection": { + "globals": 4, + "media": 3, + "pages": 7, + "posts": 4, + "casestudies": 4 + } + }, + "llmsFull": { + "medianMs": 71, + "queries": 38, + "queryMs": 0, + "byCollection": { + "globals": 6, + "media": 9, + "pages": 13, + "forms": 2, + "posts": 4, + "casestudies": 4 + } + } + }, + "rssMiB": 378 + } +} diff --git a/package.json b/package.json index e930712..60ae788 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,11 @@ "types": "./dist/exports/client.d.ts", "default": "./dist/exports/client.js" }, + "./client/eager": { + "import": "./dist/exports/client-eager.js", + "types": "./dist/exports/client-eager.d.ts", + "default": "./dist/exports/client-eager.js" + }, "./rsc": { "import": "./dist/exports/rsc.js", "types": "./dist/exports/rsc.d.ts", diff --git a/reference/e2e/performance.spec.ts b/reference/e2e/performance.spec.ts index 1c82dcd..d7c2387 100644 --- a/reference/e2e/performance.spec.ts +++ b/reference/e2e/performance.spec.ts @@ -37,10 +37,8 @@ const PAGES: Array<{ budget?: { desktop?: Budget; mobile?: Budget }; name: strin { name: 'form', path: '/pl/wycena' }, // every block × variant on one page, the contact form's Turnstile included (a necessary service, before consent) { budget: { desktop: { jsBytes: 230_000, thirdParty: ['https://challenges.cloudflare.com'] }, mobile: { jsBytes: 230_000, thirdParty: ['https://challenges.cloudflare.com'] } }, name: 'showcase', path: '/pl/bloki' }, - // The 404 content loads after hydration (createNotFoundPage `load`, so it is not in every page's payload): it - // arrives late and moves the footer — measured CLS 0.32 and LCP 2.5 s on the phone. An owner decision in - // docs/performance.md; until then the gate holds it where it is (no worse). - { budget: { mobile: { cls: 0.35, lcp: 3000 } }, name: '404', path: '/pl/nie-ma-takiej-strony', why: 'lazy 404 (owner decision pending)' }, + // the lazy 404: its content arrives after hydration; the placeholder in not-found.tsx keeps its height (CLS 0) + { budget: { mobile: { lcp: 2200 } }, name: '404', path: '/pl/nie-ma-takiej-strony', why: 'the 404 content comes from a server action after hydration' }, ] let browser: Browser @@ -110,3 +108,34 @@ test.describe('queries per render', () => { } }) }) + +/** + * MongoDB TTL index of the consent log (1.18.0, shared/ttl.ts): the database deletes records older than the retention + * itself, also on a quiet site. The index exists with the retention's lifetime, and a new record carries the date it + * counts from. Skipped when not MongoDB. + */ +test('consent log: the TTL index is there and a new record carries its date', async ({ baseURL }) => { + const uri = process.env.DATABASE_URI + test.skip(!uri?.startsWith('mongodb'), 'not MongoDB') + const site = process.cwd() + const requireFromAdapter = createRequire(createRequire(path.join(site, 'package.json')).resolve('@payloadcms/db-mongodb')) + const mongoose = requireFromAdapter('mongoose') as typeof import('mongoose') + const conn = await mongoose.createConnection(uri!).asPromise() + try { + const records = conn.db!.collection('consent-records') + const ttl = (await records.indexes()).find((i) => i.name === 'iapl_ttl') + expect(ttl, 'the TTL index').toMatchObject({ expireAfterSeconds: 1095 * 86_400, key: { iaplTtlFrom: 1 } }) + const id = [...crypto.getRandomValues(new Uint8Array(12))].map((b) => b.toString(16).padStart(2, '0')).join('') + const res = await fetch(`${baseURL}/api/ipal/consent`, { + body: JSON.stringify({ id, state: { analytics: false, functional: false, marketing: false, necessary: true }, version: 1 }), + headers: { 'content-type': 'application/json', origin: baseURL! }, + method: 'POST', + }) + expect(res.status).toBe(201) + const record = await records.findOne({ consentId: id }) + expect(record?.iaplTtlFrom, 'the date the TTL counts from').toBeInstanceOf(Date) + await records.deleteOne({ consentId: id }) + } finally { + await conn.close() + } +}) diff --git a/reference/e2e/unused-media.spec.ts b/reference/e2e/unused-media.spec.ts new file mode 100644 index 0000000..cbf2f8b --- /dev/null +++ b/reference/e2e/unused-media.spec.ts @@ -0,0 +1,46 @@ +import { expect, test } from '@playwright/test' + +import { editorTestAccount, totp } from './totp' + +/** + * `iapl({ unusedMedia: true })` (1.18.0; docs/media.md): above the Media list, how many files nothing uses, with a + * link to Payload's own list filtered to them. An image uploaded here and used nowhere must be listed; it is deleted + * by this test afterwards, never by the panel. Signs in as the test editor (the admins' 2FA attempts stay for the + * other specs). + */ +test('Media: the unused-files notice lists a file nothing uses and links to the filtered list', async ({ baseURL, page }) => { + const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: secret } = process.env + test.skip(!email || !password || !secret, 'E2E_* test admin not configured') + await page.goto('/admin/login') + await page.fill('#field-email', editorTestAccount(email!)) + await page.fill('#field-password', password!) + await page.click('.form-submit button') + await page.waitForURL(/verify-totp|\/admin(\?|$)/, { waitUntil: 'commit' }) + if (page.url().includes('verify-totp')) { + await page.getByRole('textbox').first().click() + await page.keyboard.type(totp(secret!)) + } + await expect(page).toHaveTitle(/Dashboard|Pulpit/, { timeout: 20_000 }) + + // a 1×1 PNG nobody points at + const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64') + // the session cookie counts only with the site's own Origin (Payload's CSRF rule) + const origin = { origin: new URL(baseURL!).origin } + const created = await page.request.post('/api/media', { + headers: origin, + multipart: { _payload: JSON.stringify({ alt: 'unused-media e2e' }), file: { buffer: png, mimeType: 'image/png', name: 'unused-media-e2e.png' } }, + }) + expect(created.status(), await created.text()).toBe(201) + const id = ((await created.json()) as { doc: { id: string } }).doc.id + try { + await page.goto('/admin/collections/media') + const notice = page.locator('[data-iapl="unused-media"]') + await expect(notice).toBeVisible() + const href = await notice.locator('a').getAttribute('href') + expect(href).toContain(`=${id}`) + await notice.locator('a').click() + await expect(page.getByText('unused-media-e2e', { exact: false }).first()).toBeVisible() + } finally { + await page.request.delete(`/api/media/${id}`, { headers: origin }) + } +}) diff --git a/reference/src/app/(frontend)/[locale]/layout.tsx b/reference/src/app/(frontend)/[locale]/layout.tsx index 6ebf29d..e59557d 100644 --- a/reference/src/app/(frontend)/[locale]/layout.tsx +++ b/reference/src/app/(frontend)/[locale]/layout.tsx @@ -15,7 +15,9 @@ import '../styles.css' // Fixed slot names from the token standard: --font-family-body / --font-family-heading (design-tokens.md) const body = Inter({ display: 'swap', subsets: ['latin', 'latin-ext'], variable: '--font-family-body' }) -const heading = Fraunces({ display: 'swap', subsets: ['latin', 'latin-ext'], variable: '--font-family-heading' }) +// The heading font is not preloaded: the stylesheet and the hero image get the first round trips (measured on a +// phone: first paint and LCP 36–52 ms sooner; headings swap in with fallback metrics, CLS stays < 0.1 — docs/performance.md) +const heading = Fraunces({ display: 'swap', preload: false, subsets: ['latin', 'latin-ext'], variable: '--font-family-heading' }) type Props = { children: React.ReactNode; params: Promise<{ locale: string }> } diff --git a/reference/src/app/(frontend)/[locale]/not-found.tsx b/reference/src/app/(frontend)/[locale]/not-found.tsx index 618dfab..800c1de 100644 --- a/reference/src/app/(frontend)/[locale]/not-found.tsx +++ b/reference/src/app/(frontend)/[locale]/not-found.tsx @@ -4,4 +4,9 @@ import * as content from '@/lib/content' import { loadNotFoundView } from './notFoundView' -export default createNotFoundPage(content, { load: loadNotFoundView }) +// The lazy 404 content arrives after hydration: a block as tall as it keeps the footer still (no layout shift). +// Measured for this site's 404 content: 282 px at 360 px wide to 432 px at 1920 — change it with that content. +export default createNotFoundPage(content, { + load: loadNotFoundView, + placeholder:
, +}) diff --git a/reference/src/app/(payload)/admin/importMap.js b/reference/src/app/(payload)/admin/importMap.js index 2cf1481..205d4bf 100644 --- a/reference/src/app/(payload)/admin/importMap.js +++ b/reference/src/app/(payload)/admin/importMap.js @@ -28,6 +28,7 @@ import { MetaDescriptionComponent as MetaDescriptionComponent_a8a977ebc872c5d5ea import { MetaDescriptionCheck as MetaDescriptionCheck_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { MetaImageComponent as MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client' import { PreviewComponent as PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client' +import { UnusedMediaNotice as UnusedMediaNotice_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc' import { TwoFactorStatusField as TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin' @@ -84,6 +85,7 @@ export const importMap = { "@intecion/ipal-kit/admin#MetaDescriptionCheck": MetaDescriptionCheck_7568fe47d582ff15ce85d2e1873c2c23, "@payloadcms/plugin-seo/client#MetaImageComponent": MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860, "@payloadcms/plugin-seo/client#PreviewComponent": PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860, + "@intecion/ipal-kit/admin#UnusedMediaNotice": UnusedMediaNotice_7568fe47d582ff15ce85d2e1873c2c23, "@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23, "@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128, "@intecion/ipal-kit/admin#TwoFactorStatusField": TwoFactorStatusField_7568fe47d582ff15ce85d2e1873c2c23, diff --git a/reference/src/payload-types.ts b/reference/src/payload-types.ts index d9f5e6c..bf02d4a 100644 --- a/reference/src/payload-types.ts +++ b/reference/src/payload-types.ts @@ -1372,6 +1372,7 @@ export interface ConsentRecord { analytics?: boolean | null; marketing?: boolean | null; }; + iaplTtlFrom?: string | null; updatedAt: string; createdAt: string; } @@ -2442,6 +2443,7 @@ export interface ConsentRecordsSelect { analytics?: T; marketing?: T; }; + iaplTtlFrom?: T; updatedAt?: T; createdAt?: T; } diff --git a/reference/src/payload.config.ts b/reference/src/payload.config.ts index 0a84270..d0e19f0 100644 --- a/reference/src/payload.config.ts +++ b/reference/src/payload.config.ts @@ -94,6 +94,8 @@ export default buildConfig({ // @starter:else //: forms: { redirectRelationships: ['pages'], emailLayout: true }, // files on forms: add `attachments: true` (forms.md "Files") // @starter:endif + // Media → above the list: files no page, entry or setting uses, with a link to review and delete them by hand + unusedMedia: true, // @starter:if twoFactor twoFactor: { issuer: 'Example Studio', plugin: payloadTotp }, // @starter:else diff --git a/scripts/e2e-built.mjs b/scripts/e2e-built.mjs index 7da8cba..e4763b1 100644 --- a/scripts/e2e-built.mjs +++ b/scripts/e2e-built.mjs @@ -100,7 +100,7 @@ for (const bundler of bundlers) { process.exit(1) } console.log(`[e2e:built] ✓ ${bundler}: no package manifest among ${files.length} public files`) - run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look, the sign-in answers and the own account`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', 'two-factor-enrolment', '--grep', '2FA enrolment|late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' }) + run(`${bundler}: the built site — late-staff spec, the mail service, closed doors, the published-files check, the client hints, consent, the sign-in look, the sign-in answers, the own account and the unused-files notice`, 'pnpm', ['exec', 'playwright', 'test', 'late-staff', 'mail-relay', 'closed-doors', 'smoke', 'sign-in-look', 'sign-in-answers', 'own-account', 'two-factor-enrolment', 'unused-media', '--grep', 'unused-files notice|2FA enrolment|late staff collection|the mail service|closed doors|no package.json is published|client hints|consent|sign-in look|locked staff account|panel actions|own account|staff sign-in'], site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', CRON_SECRET: cronSecret, E2E_LATE_STAFF: '1' }) // the budgets are the built site's own numbers: they hold for each bundler (docs/performance.md, docs/dev/perf/) run(`${bundler}: performance budgets — every page type on a phone and a desktop, queries per render`, 'pnpm', ['exec', 'playwright', 'test', 'e2e/performance.spec'] /* a regex on the file path: a checkout path may hold "performance" */, site, { ALLOW_LOCAL_MEDIA: process.env.ALLOW_LOCAL_MEDIA ?? '1', E2E_LATE_STAFF: '1' }) passed.push(bundler) diff --git a/scripts/reference-index.mjs b/scripts/reference-index.mjs index 47605fa..7222078 100644 --- a/scripts/reference-index.mjs +++ b/scripts/reference-index.mjs @@ -70,6 +70,7 @@ export const DESCRIPTIONS = { 'e2e/two-factor-setup.spec.ts': 'browser check of "2FA setup required": the first admin of a fresh site, a new editor, the administrator\'s reset on the account page', '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/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/unused-media.spec.ts': 'the unused-files notice above the Media list (`unusedMedia: true`): an image nothing uses is listed and the link opens Payload\'s list filtered to it; the test deletes its own upload, the panel never deletes', 'e2e/smoke.spec.ts': 'the smoke tests every release must pass: pages, showcase, forms (also a file sent by e-mail), sitemap, SEO/GEO, headers, consent, 2FA', 'e2e/mail-relay-fixture.ts': 'test fixture, on only with E2E_MAIL_RELAY_URL: points the mail service\'s client at the stand-in the spec starts; never in a real site (a real site names no address)', '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)', diff --git a/src/exports/admin.ts b/src/exports/admin.ts index 010b6d0..5d3b61a 100644 --- a/src/exports/admin.ts +++ b/src/exports/admin.ts @@ -22,6 +22,7 @@ export { CookieScanButton } from '../modules/consent/scanner/CookieScanButton.js export { CookieSiteCheckTab } from '../modules/consent/scanner/CookieSiteCheckTab.js' export { CookieCrawlAlert } from '../modules/consent/scanner/crawl/CookieCrawlAlert.js' export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js' +export { UNUSED_MEDIA_LINK_LIMIT, UnusedMediaNotice } from '../modules/media/UnusedMediaNotice.js' export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js' export { SafeTotpView } from '../modules/security/totp/SafeTotpView.js' export type { SafeTotpViewProps } from '../modules/security/totp/SafeTotpView.js' diff --git a/src/exports/blocks-rsc.ts b/src/exports/blocks-rsc.ts index 47f25a2..36114fb 100644 --- a/src/exports/blocks-rsc.ts +++ b/src/exports/blocks-rsc.ts @@ -46,7 +46,7 @@ export { Anchor } from '../modules/block-library/ui/Anchor.js' export type { LinkComponent } from '../modules/block-library/ui/Anchor.js' export { BUTTON_CLASSES, buttonClass } from '../modules/block-library/ui/Button.js' export { Buttons, GRID_COLUMNS, headingId } from '../modules/block-library/ui/Buttons.js' -export { Card, CARD_CLASS, CARD_INTERACTIVE_CLASS } from '../modules/block-library/ui/Card.js' +export { Card, CARD_CLASS, CARD_INTERACTIVE_CLASS, CARD_INTERACTIVE_SHADOW_CLASS } from '../modules/block-library/ui/Card.js' export type { CardProps } from '../modules/block-library/ui/Card.js' export { CMSLink } from '../modules/block-library/ui/CMSLink.js' export type { CMSLinkProps, ResolveLink } from '../modules/block-library/ui/CMSLink.js' diff --git a/src/exports/client-eager.ts b/src/exports/client-eager.ts new file mode 100644 index 0000000..4304ba0 --- /dev/null +++ b/src/exports/client-eager.ts @@ -0,0 +1,11 @@ +/** + * Entry point: @intecion/ipal-kit/client/eager + * + * The form and the Turnstile widget WITHOUT lazy loading (1.18.0). `@intecion/ipal-kit/client` exports lazy wrappers + * with the same props, so a page without a form carries none of this code. Import from here only when a project + * wants the code in every page's bundle (e.g. a form that must work before hydration finishes): + * import { BuilderForm } from '@intecion/ipal-kit/client/eager' + * + */ +export { BuilderForm } from '../modules/forms/BuilderForm.js' +export { Turnstile } from '../modules/turnstile/Turnstile.js' diff --git a/src/exports/client.ts b/src/exports/client.ts index d3ccb4b..f7e675a 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -41,7 +41,9 @@ export type { ConstructionNoticeClassNames } from '../modules/construction/Const export { CONSTRUCTION_CLOSE_LABEL, CONSTRUCTION_CLOSE_LABEL_PL, constructionCloseLabel } from '../modules/construction/texts.js' export type { ConstructionMode } from '../modules/construction/types.js' export { formatFileSize } from '../modules/forms/attachments/fileTypes.js' -export { BuilderForm } from '../modules/forms/BuilderForm.js' +// `BuilderForm` is the lazy wrapper since 1.18.0 (same props, the server renders the whole form): the form's code +// loads only on a page that shows one. The eager component: `@intecion/ipal-kit/client/eager`. +export { LazyBuilderForm as BuilderForm } from '../modules/forms/LazyBuilderForm.js' export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js' export { autoCompleteFor, fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from '../modules/forms/builderLogic.js' export type { BuilderFile } from '../modules/forms/builderLogic.js' diff --git a/src/index.ts b/src/index.ts index 2d34799..b0ed43b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -435,7 +435,8 @@ export type { } from './modules/links/index.js' // Read-only MCP server (Claude/agents connect to the site and query it). export { createMcpRoute } from './modules/mcp/index.js' -export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js' +export { buildOptimizeUploadField, buildOptimizeUploadHook, exifOrientation, normalizeFilename, normalizeFilenameHook, stripImageMetadata } from './modules/media/index.js' +export type { StripResult } from './modules/media/index.js' export type { OptimizeUploadOptions } from './modules/media/index.js' export { buildMediaPlaceholderField, diff --git a/src/modules/block-library/ui/BackgroundVideo.tsx b/src/modules/block-library/ui/BackgroundVideo.tsx new file mode 100644 index 0000000..2c7ca82 --- /dev/null +++ b/src/modules/block-library/ui/BackgroundVideo.tsx @@ -0,0 +1,34 @@ +'use client' +import type { VideoHTMLAttributes } from 'react' + +import { useEffect, useRef } from 'react' + +const QUERY = '(prefers-reduced-motion: reduce)' + +/** + * A background video that stops for visitors who asked for less motion (WCAG 2.2.2, 2.3.3; + * web.dev/articles/prefers-reduced-motion). The server renders the same
- {f.isLast ?
: null} + {f.isLast ?
: null} {f.errorMessage ?

{f.errorMessage}

: null}
{!f.isFirst ? : null} diff --git a/src/modules/forms/LazyBuilderForm.tsx b/src/modules/forms/LazyBuilderForm.tsx new file mode 100644 index 0000000..81431e7 --- /dev/null +++ b/src/modules/forms/LazyBuilderForm.tsx @@ -0,0 +1,22 @@ +'use client' +import { lazy, Suspense } from 'react' + +import type { BuilderFormProps } from './BuilderForm.js' + +/** + * loaded only on a page that renders a form (1.18.0). RenderForm uses this: the catch-all route can + * render any block, so a static import put the form engine (fields, steps, validation, the Turnstile widget) into + * the JavaScript of every page. The server still renders the whole form (the HTML is complete without JavaScript, + * search engines and the first paint see it); the browser fetches the code while it hydrates the rest of the page. + * It is `BuilderForm` in `@intecion/ipal-kit/client` (same props). The eager component, in every page's bundle: + * `@intecion/ipal-kit/client/eager` → `` (docs/forms.md). + */ +const Impl = lazy(() => import('./BuilderForm.js').then((m) => ({ default: m.BuilderForm }))) + +export function LazyBuilderForm(props: BuilderFormProps) { + return ( + + + + ) +} diff --git a/src/modules/forms/RenderForm.tsx b/src/modules/forms/RenderForm.tsx index 5f0810b..780e0d7 100644 --- a/src/modules/forms/RenderForm.tsx +++ b/src/modules/forms/RenderForm.tsx @@ -1,16 +1,16 @@ import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical' import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react' -import type { ReactNode } from 'react' +import type { ComponentType, ReactNode } from 'react' import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js' import type { TurnstileTheme } from '../turnstile/Turnstile.js' -import type { BuilderFormClassNames } from './BuilderForm.js' +import type { BuilderFormClassNames, BuilderFormProps } from './BuilderForm.js' import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js' import type { SubmitActionResult } from './createSubmitAction.js' import { resolveLinkHref, safeHref } from '../links/resolveLinkHref.js' import { RenderRichText } from '../richtext/RenderRichText.js' -import { BuilderForm } from './BuilderForm.js' +import { LazyBuilderForm } from './LazyBuilderForm.js' /** The action from createSubmitAction — `sendForm(formId, locale, values, token?)`. */ export type SendFormAction = ( @@ -24,6 +24,11 @@ export type RenderFormProps = { /** The project's `sendForm` server action (createSubmitAction). */ action: SendFormAction classNames?: BuilderFormClassNames + /** + * The client form component. Default: the lazy one (1.18.0) — its code loads only on pages with a form, the HTML + * is complete either way. `Form={BuilderForm}` from `@intecion/ipal-kit/client/eager` = in every page's bundle. + */ + Form?: ComponentType /** Rich text styling for message blocks and the confirmation (same as RenderRichText). */ converters?: JSXConvertersFunction /** The `form` relationship of the block, populated (page query depth ≥ 1). An id or null renders nothing. */ @@ -39,6 +44,8 @@ export type RenderFormProps = { /** Notifications → form texts in this locale (getNotificationTexts(...).form). */ texts: BuilderFormTexts /** Widget theme. Default 'page' — follows the site's light/dark theme. */ + /** Space kept for the Turnstile widget before it is drawn (default 73 px; 0 for an invisible widget). */ + turnstileReserveHeight?: number turnstileTheme?: TurnstileTheme /** Values of fields the page already knows, by field name — read-only for the visitor, sent with the form. */ values?: Record @@ -143,22 +150,26 @@ export function RenderForm({ classNames, converters, form, + Form = LazyBuilderForm, linkOptions, locale, requiredMark, richTextClassName, texts, + turnstileReserveHeight, turnstileTheme, values, }: RenderFormProps) { const prepared = prepareBuilderForm({ action, converters, form, linkOptions, locale, richTextClassName }) if (!prepared) {return null} + // the form's code is fetched only on pages that have a form (the HTML stays complete): LazyBuilderForm.tsx return ( - diff --git a/src/modules/forms/useBuilderForm.ts b/src/modules/forms/useBuilderForm.ts index 0aca667..19f5215 100644 --- a/src/modules/forms/useBuilderForm.ts +++ b/src/modules/forms/useBuilderForm.ts @@ -1,5 +1,5 @@ -'use client' - +// No 'use client' (1.18.0): a hook runs inside a client component (the form); as its own client boundary the +// /client entry shipped it with every page (docs/performance.md). import type { ChangeEvent } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' diff --git a/src/modules/forms/useContactForm.ts b/src/modules/forms/useContactForm.ts index c85755c..774cee4 100644 --- a/src/modules/forms/useContactForm.ts +++ b/src/modules/forms/useContactForm.ts @@ -1,5 +1,5 @@ -'use client' - +// No 'use client' (1.18.0): a hook runs inside a client component (the form); as its own client boundary the +// /client entry shipped it with every page (docs/performance.md). import { useMemo } from 'react' import { type FormSubmitAction, useForm } from './useForm.js' diff --git a/src/modules/forms/useForm.ts b/src/modules/forms/useForm.ts index 9cb3d7b..0a1e8d4 100644 --- a/src/modules/forms/useForm.ts +++ b/src/modules/forms/useForm.ts @@ -1,5 +1,5 @@ -'use client' - +// No 'use client' (1.18.0): a hook runs inside a client component (the form); as its own client boundary the +// /client entry shipped it with every page (docs/performance.md). import { useCallback, useMemo, useRef, useState } from 'react' /** diff --git a/src/modules/media/UnusedMediaNotice.tsx b/src/modules/media/UnusedMediaNotice.tsx new file mode 100644 index 0000000..d6538fe --- /dev/null +++ b/src/modules/media/UnusedMediaNotice.tsx @@ -0,0 +1,66 @@ +import type { Payload } from 'payload' + +import { userMeetsRole } from '../access/predicates.js' +import { findUnusedMedia } from '../doctor/growth.js' + +type Props = { + adminRoute?: string + /** The upload collection this list shows (set by iapl). */ + collection?: string + /** Injected by Payload into admin server components. */ + i18n?: { language?: string } + /** Injected by Payload into admin server components. */ + payload?: Payload + /** Injected by Payload into admin server components. */ + user?: null | Record +} + +/** Files listed in one link: a longer address may be cut by a proxy. */ +export const UNUSED_MEDIA_LINK_LIMIT = 100 + +const TEXT = { + en: { + incomplete: 'Unused files: the site has too many documents to check them all here — run iapl-doctor --deep (growth-media).', + none: '', + show: (n: number) => (n > UNUSED_MEDIA_LINK_LIMIT ? `Show the first ${UNUSED_MEDIA_LINK_LIMIT}` : 'Show them'), + title: (n: number) => `${n} file${n === 1 ? ' is' : 's are'} not used on any page, entry or setting.`, + why: 'Check each one before you delete it (select them in the list → Delete). Nothing is deleted by itself.', + }, + pl: { + incomplete: 'Nieużywane pliki: strona ma zbyt wiele dokumentów, by sprawdzić je tutaj — uruchom iapl-doctor --deep (growth-media).', + none: '', + show: (n: number) => (n > UNUSED_MEDIA_LINK_LIMIT ? `Pokaż pierwsze ${UNUSED_MEDIA_LINK_LIMIT}` : 'Pokaż je'), + title: (n: number) => `Plików nieużywanych na żadnej stronie, we wpisie ani w ustawieniach: ${n}.`, + why: 'Sprawdź każdy przed usunięciem (zaznacz je na liście → Usuń). Nic nie jest usuwane samo.', + }, +} + +/** + * `iapl({ unusedMedia: true })` (1.18.0; docs/media.md): above the list of an upload collection, how many files no + * document or global uses, and a link that opens Payload's own list filtered to them — deleting stays the panel's + * manual bulk delete, with its confirmation and access rules. For editors and admins; renders nothing when every + * file is used, and only a hint when the site is too big to check every document here. Never throws. + */ +export async function UnusedMediaNotice({ adminRoute = '/admin', collection, i18n, payload, user }: Props) { + if (!payload || !collection || !user || !userMeetsRole({ payload, user }, 'editor')) {return null} + const t = i18n?.language === 'pl' ? TEXT.pl : TEXT.en + let ids: Array + try { + const unused = await findUnusedMedia(payload, { only: [collection] }) + if (!unused) {return null} + if (!unused.complete) {return

{t.incomplete}

} + ids = (unused.byCollection[collection] ?? []).map((f) => f.id) + } catch { + return null + } + if (!ids.length) {return null} + const query = ids.slice(0, UNUSED_MEDIA_LINK_LIMIT).map((id, i) => `where[id][in][${i}]=${encodeURIComponent(String(id))}`).join('&') + return ( +
+ {t.title(ids.length)} {t.why}{' '} + {t.show(ids.length)} +
+ ) +} + +const BOX = { border: '1px solid var(--theme-elevation-150)', borderRadius: 4, margin: '0 0 1rem', padding: '0.75rem 1rem' } as const diff --git a/src/modules/media/index.ts b/src/modules/media/index.ts index 2d075aa..bd72a9f 100644 --- a/src/modules/media/index.ts +++ b/src/modules/media/index.ts @@ -4,3 +4,5 @@ export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js' export type { OptimizeUploadOptions } from './optimizeUpload.js' export { buildMediaPlaceholderField, buildMediaPlaceholderHook } from './placeholder.js' +export { exifOrientation, stripImageMetadata } from './stripMetadata.js' +export type { StripResult } from './stripMetadata.js' diff --git a/src/modules/media/optimizeUpload.ts b/src/modules/media/optimizeUpload.ts index eb9ac66..7e67abe 100644 --- a/src/modules/media/optimizeUpload.ts +++ b/src/modules/media/optimizeUpload.ts @@ -1,8 +1,10 @@ -import type { CheckboxField, CollectionBeforeOperationHook } from 'payload' +import type { CheckboxField, CollectionBeforeOperationHook, PayloadRequest } from 'payload' import { readFile } from 'node:fs/promises' import { APIError } from 'payload' +import { stripImageMetadata } from './stripMetadata.js' + /** * Safety net for oversized uploads — NOT an image pipeline. The developer and * editor are expected to upload prepared files; this only catches the 8 MB @@ -35,9 +37,33 @@ export type OptimizeUploadOptions = { png?: 'lossless' | 'lossy' /** WebP quality for lossy output (JPG, and PNG when png: 'lossy'). Default 82. */ quality?: number + /** + * Remove the metadata (camera, date, GPS position, comments) of every JPEG and PNG upload that passes the limits, + * without re-encoding it (stripImageMetadata; 1.18.0). A photo whose EXIF says "rotate" is turned once (sharp, + * JPEG quality 92) so it does not show sideways. Default true; `false` keeps uploads byte for byte as before. + * Images over the limits lose their metadata anyway when the editor lets the plugin optimise them. + */ + stripMetadata?: boolean } const OPTIMIZABLE = new Set(['image/jpeg', 'image/png']) + +type Sharp = NonNullable + +/** The upload without its metadata (stripImageMetadata); a "rotate" in the EXIF is applied to the pixels first. */ +async function stripUploadMetadata(file: UploadFile, buffer: Buffer, sharp: Sharp | undefined): Promise { + const result = stripImageMetadata(buffer, file.mimetype) + if (!result.changed) {return} + let output = result.buffer + if (result.orientation !== 1) { + // without sharp the file stays as it was: an upright picture matters more than its metadata + if (!sharp) {return} + output = await sharp(buffer).rotate().jpeg({ quality: 92 }).toBuffer() + } + file.data = output + file.size = output.length + delete file.tempFilePath // Payload must read the new buffer, not the temp file +} const MB = 1024 * 1024 /** Size in MB with one decimal, in the admin language's number format. */ const fmt = (bytes: number, language: string) => @@ -90,6 +116,7 @@ export function buildOptimizeUploadHook( maxVideoBytes = 20 * MB, png = 'lossless', quality = 82, + stripMetadata = true, } = options return async ({ args, operation, req }) => { @@ -142,7 +169,10 @@ export function buildOptimizeUploadHook( const tooHeavy = size > maxImageBytes const tooWide = width !== undefined && width > maxImageWidth - if (!tooHeavy && !tooWide) {return} + if (!tooHeavy && !tooWide) { + if (stripMetadata) {await stripUploadMetadata(file, buffer, sharp)} + return + } const problem = [ tooHeavy ? `${fmt(size, lang)} (limit ${fmt(maxImageBytes, lang)})` : null, diff --git a/src/modules/media/stripMetadata.ts b/src/modules/media/stripMetadata.ts new file mode 100644 index 0000000..aef7a0b --- /dev/null +++ b/src/modules/media/stripMetadata.ts @@ -0,0 +1,94 @@ +/** + * Removes the metadata a photo carries (camera, date, GPS position, editing software, comments) from a JPEG or a PNG + * WITHOUT re-encoding it: the pixels and the file's quality stay byte for byte, only the metadata blocks go + * (1.18.0; docs/media.md). Kept: what changes how the image looks — the JFIF header and Adobe marker, the colour + * profile (ICC), PNG gamma, chromaticity, sRGB and pixel density. + * + * JPEG: the APP1 (EXIF, XMP), APP13 (IPTC / Photoshop) and COM segments before the image data are dropped. EXIF also + * holds the orientation: `orientation` reports it (1 = upright), so a caller can rotate the pixels first — otherwise a + * phone photo taken sideways would show sideways. + * PNG: tEXt, zTXt, iTXt, eXIf and tIME chunks are dropped. + * Anything it cannot read is returned unchanged (`changed: false`). + */ +export type StripResult = { buffer: Buffer; changed: boolean; orientation: number } + +const JPEG_DROP = new Set([0xe1, 0xed, 0xfe]) // APP1 (EXIF/XMP), APP13 (IPTC), COM +const PNG_DROP = new Set(['eXIf', 'iTXt', 'tEXt', 'tIME', 'zTXt']) +const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) + +/** EXIF orientation (tag 0x0112 of IFD0) in an APP1 payload, or 1. */ +export function exifOrientation(app1: Buffer): number { + if (app1.length < 14 || app1.toString('latin1', 0, 6) !== 'Exif\0\0') {return 1} + const tiff = app1.subarray(6) + const little = tiff.toString('latin1', 0, 2) === 'II' + if (!little && tiff.toString('latin1', 0, 2) !== 'MM') {return 1} + const u16 = (at: number) => (little ? tiff.readUInt16LE(at) : tiff.readUInt16BE(at)) + const u32 = (at: number) => (little ? tiff.readUInt32LE(at) : tiff.readUInt32BE(at)) + try { + const ifd = u32(4) + const entries = u16(ifd) + for (let i = 0; i < entries; i++) { + const at = ifd + 2 + i * 12 + if (u16(at) === 0x0112) { + const value = u16(at + 8) + return value >= 1 && value <= 8 ? value : 1 + } + } + } catch { + // truncated EXIF: no orientation + } + return 1 +} + +function stripJpeg(input: Buffer): StripResult { + const same = { buffer: input, changed: false, orientation: 1 } + if (input.length < 4 || input[0] !== 0xff || input[1] !== 0xd8) {return same} + const parts: Buffer[] = [input.subarray(0, 2)] + let orientation = 1 + let changed = false + let at = 2 + while (at + 4 <= input.length) { + if (input[at] !== 0xff) {return same} // not a marker where one must be: leave the file alone + const marker = input[at + 1] + if (marker === 0xff) {at++; continue} // fill byte + if (marker === 0xda || marker === 0xd9) { // start of scan / end: the rest is image data + parts.push(input.subarray(at)) + break + } + const length = input.readUInt16BE(at + 2) + if (length < 2 || at + 2 + length > input.length) {return same} + const segment = input.subarray(at, at + 2 + length) + if (JPEG_DROP.has(marker)) { + if (marker === 0xe1 && orientation === 1) {orientation = exifOrientation(segment.subarray(4))} + changed = true + } else { + parts.push(segment) + } + at += 2 + length + } + return changed ? { buffer: Buffer.concat(parts), changed, orientation } : same +} + +function stripPng(input: Buffer): StripResult { + const same = { buffer: input, changed: false, orientation: 1 } + if (input.length < 8 || !input.subarray(0, 8).equals(PNG_SIGNATURE)) {return same} + const parts: Buffer[] = [PNG_SIGNATURE] + let changed = false + let at = 8 + while (at + 12 <= input.length) { + const length = input.readUInt32BE(at) + const type = input.toString('latin1', at + 4, at + 8) + const end = at + 12 + length + if (end > input.length) {return same} + if (PNG_DROP.has(type)) {changed = true} else {parts.push(input.subarray(at, end))} + at = end + if (type === 'IEND') {break} + } + return changed ? { buffer: Buffer.concat(parts), changed, orientation: 1 } : same +} + +export function stripImageMetadata(input: Buffer, mimeType: string): StripResult { + if (mimeType === 'image/jpeg' || mimeType === 'image/jpg' || mimeType === 'image/pjpeg') {return stripJpeg(input)} + if (mimeType === 'image/png') {return stripPng(input)} + return { buffer: input, changed: false, orientation: 1 } +} diff --git a/src/modules/shared/ttl.ts b/src/modules/shared/ttl.ts new file mode 100644 index 0000000..344b228 --- /dev/null +++ b/src/modules/shared/ttl.ts @@ -0,0 +1,63 @@ +import type { BasePayload, Config, DateField } from 'payload' + +/** + * MongoDB TTL index for a plugin log (1.18.0; docs/performance.md §6): the database itself deletes records once + * they are older than the retention — also on a quiet site, where the purge after a new record never runs. + * + * Why a field of its own: Payload already keeps a plain index on `createdAt` (and the statistics on `lastAt`), and + * Mongoose recreates its indexes at every start — turning that index into a TTL one makes the start fail with + * IndexOptionsConflict. So the TTL counts from `iaplTtlFrom` (hidden; the record's `createdAt`, the visit's `lastAt`), + * with an index named `iapl_ttl` that only the plugin manages. At every start its time is set to the current + * `retentionDays` (collMod), so a changed retention applies at once; records written before 1.18.0 get the field + * from their own date once (a single updateMany). Postgres and SQLite: no field, no index — the purge does it. + * Opt-out: `ttlIndex: false` on the option; the index is then dropped at the next start (nothing more is deleted + * by it), the purge stays. + */ +export const TTL_FIELD = 'iaplTtlFrom' +export const TTL_INDEX = 'iapl_ttl' + +export const isMongo = (config: Pick) => (config.db as { name?: string } | undefined)?.name === 'mongoose' + +/** The hidden date the TTL counts from. Not indexed by Payload (the plugin's own index is the TTL one). */ +export const ttlField = (): DateField => ({ + name: TTL_FIELD, + type: 'date', + admin: { disableBulkEdit: true, hidden: true }, +}) + +type NativeCollection = { + collectionName: string + createIndex: (key: object, options: object) => Promise + dropIndex: (name: string) => Promise + indexes: () => Promise> + updateMany: (filter: object, update: object[]) => Promise<{ modifiedCount?: number }> +} + +export type TtlSyncResult = 'created' | 'dropped' | 'none' | 'updated' + +/** Creates, updates or drops the TTL index of one collection (MongoDB only; anything else does nothing). */ +export async function syncTtlIndex( + payload: BasePayload, + slug: string, + { days, enabled, from }: { days: number; enabled: boolean; from: string }, +): Promise { + const db = payload.db as unknown as { collections?: Record; connection?: { db?: { command: (c: object) => Promise } }; name?: string } + const coll = db.collections?.[slug]?.collection + if (db.name !== 'mongoose' || !coll) {return 'none'} + const existing = (await coll.indexes()).find((i) => i.name === TTL_INDEX) + if (!enabled) { + if (!existing) {return 'none'} + await coll.dropIndex(TTL_INDEX) + return 'dropped' + } + // records from before 1.18.0 (or written by another path): the TTL counts from their own date + await coll.updateMany({ [TTL_FIELD]: { $exists: false }, [from]: { $type: 'date' } }, [{ $set: { [TTL_FIELD]: `$${from}` } }]) + const seconds = Math.round(days * 86_400) + if (!existing) { + await coll.createIndex({ [TTL_FIELD]: 1 }, { expireAfterSeconds: seconds, name: TTL_INDEX }) + return 'created' + } + if (existing.expireAfterSeconds === seconds) {return 'none'} + await db.connection!.db!.command({ collMod: coll.collectionName, index: { expireAfterSeconds: seconds, name: TTL_INDEX } }) + return 'updated' +} diff --git a/src/modules/shared/versionLimit.ts b/src/modules/shared/versionLimit.ts new file mode 100644 index 0000000..9f07ba6 --- /dev/null +++ b/src/modules/shared/versionLimit.ts @@ -0,0 +1,19 @@ +/** + * The plugin's own collections and globals turn versions on nowhere. When a project turns them on (globalOverrides, + * collectionOverrides, formOverrides…) without a limit, each keeps at most 20 versions per document (1.18.0; + * docs/performance.md §6) instead of Payload's 100 — a global like Site integrations is saved by the site itself on + * every status change. A limit the project writes wins (`max` for globals, `maxPerDoc` for collections, 0 = + * unlimited). Payload trims the oldest versions of a document on its next save. + */ +export const PLUGIN_VERSION_LIMIT = 20 + +type Versioned = { slug: string; versions?: unknown } + +export function withVersionLimit(entity: T, kind: 'collection' | 'global', limit = PLUGIN_VERSION_LIMIT): T { + const v = entity.versions + if (!v) {return entity} + const key = kind === 'global' ? 'max' : 'maxPerDoc' + if (v === true) {return { ...entity, versions: { [key]: limit } }} + if (typeof v === 'object' && typeof (v as Record)[key] !== 'number') {return { ...entity, versions: { ...(v as object), [key]: limit } }} + return entity +} diff --git a/src/modules/stats/collection.ts b/src/modules/stats/collection.ts index 1073e40..2c78c78 100644 --- a/src/modules/stats/collection.ts +++ b/src/modules/stats/collection.ts @@ -30,6 +30,11 @@ export type StatsOptions = { retentionDays?: number /** Time zone that decides where a day starts. Default 'Europe/Warsaw'. */ timeZone?: string + /** + * MongoDB: a TTL index deletes visits whose last page view is older than `retentionDays`, also on a quiet site + * (1.18.0). Default true; `false` drops the index at the next start, the purge stays. Postgres / SQLite: not used. + */ + ttlIndex?: boolean } export type StatsPage = { p: string; t: string } diff --git a/src/modules/stats/endpoint.ts b/src/modules/stats/endpoint.ts index 3b8cf21..9adc5df 100644 --- a/src/modules/stats/endpoint.ts +++ b/src/modules/stats/endpoint.ts @@ -1,5 +1,6 @@ import type { Endpoint, PayloadRequest } from 'payload' +import { TTL_FIELD } from '../shared/ttl.js' import type { StatsOptions, StatsPage, StatsVisit } from './collection.js' import { gpcFromHeaders, resolveConsent } from '../consent/gpc.js' @@ -119,6 +120,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars data: { exit: path, lastAt: now.toISOString(), + [TTL_FIELD]: now.toISOString(), // MongoDB TTL (shared/ttl.ts) pageCount: pages.length, pages, ...(visitorId && !visit.visitorId ? { visitorId } : {}), @@ -136,6 +138,7 @@ export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Wars entry: path, exit: path, lastAt: now.toISOString(), + [TTL_FIELD]: now.toISOString(), // MongoDB TTL (shared/ttl.ts) pageCount: 1, pages: [{ p: path, t: now.toISOString() }], referrer: referrerHost(body.r, host), diff --git a/src/modules/turnstile/LazyTurnstile.tsx b/src/modules/turnstile/LazyTurnstile.tsx new file mode 100644 index 0000000..0dabc06 --- /dev/null +++ b/src/modules/turnstile/LazyTurnstile.tsx @@ -0,0 +1,23 @@ +'use client' +import type { ComponentProps } from 'react' + +import { lazy, Suspense } from 'react' + +import type { Turnstile as TurnstileType } from './Turnstile.js' + +import { TURNSTILE_HEIGHT } from './turnstileHeight.js' + +const Impl = lazy(() => import('./Turnstile.js').then((m) => ({ default: m.Turnstile }))) + +/** + * The Turnstile widget, loaded where it is shown (1.18.0): `` from `@intecion/ipal-kit/client` is this + * wrapper, so a page without a form carries none of its code. Same props; the eager one: + * `@intecion/ipal-kit/client/eager`. + */ +export function LazyTurnstile(props: ComponentProps) { + return ( + : null}> + + + ) +} diff --git a/src/modules/turnstile/Turnstile.tsx b/src/modules/turnstile/Turnstile.tsx index 57bec17..fc41389 100644 --- a/src/modules/turnstile/Turnstile.tsx +++ b/src/modules/turnstile/Turnstile.tsx @@ -1,4 +1,5 @@ 'use client' +import { TURNSTILE_HEIGHT } from './turnstileHeight.js' import { useEffect, useRef } from 'react' import { useTheme } from '../theme/useTheme.js' @@ -29,6 +30,11 @@ function ensureScript(): void { export type TurnstileProps = { /** Called with the token once solved, or null on expiry/error. */ onToken: (token: null | string) => void + /** + * Height kept free for the widget before Cloudflare draws it (1.18.0): the form below does not jump when it + * appears (layout shift). Default 73 (the standard widget as drawn); 0 for an invisible widget. + */ + reserveHeight?: number /** * Change this value to make the widget issue a NEW token (a token is * single-use: after a submission the server refused, the next one needs a @@ -60,7 +66,7 @@ export type TurnstileTheme = 'auto' | 'dark' | 'light' | 'page' * The script is injected directly (no next/script dependency) so the widget * stays framework-agnostic. */ -export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }: TurnstileProps) { +export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page', reserveHeight = TURNSTILE_HEIGHT }: TurnstileProps) { const ref = useRef(null) const widgetId = useRef(null) const pageTheme = useTheme().theme @@ -115,5 +121,5 @@ export function Turnstile({ onToken, resetSignal = 0, siteKey, theme = 'page' }: if (!siteKey) {return null} - return
+ return
} diff --git a/src/modules/turnstile/TurnstileProvider.tsx b/src/modules/turnstile/TurnstileProvider.tsx index d5fe35a..5afc7ea 100644 --- a/src/modules/turnstile/TurnstileProvider.tsx +++ b/src/modules/turnstile/TurnstileProvider.tsx @@ -1,10 +1,13 @@ 'use client' -import { createContext, use, useCallback, useState } from 'react' +import { createContext, lazy, Suspense, use, useCallback, useState } from 'react' import type { TurnstileTheme } from './Turnstile.js' -import { Turnstile } from './Turnstile.js' +import { TURNSTILE_HEIGHT } from './turnstileHeight.js' + +// The widget is loaded where a form shows it (1.18.0): the provider sits in the layout of every page. +const Turnstile = lazy(() => import('./Turnstile.js').then((m) => ({ default: m.Turnstile }))) type TurnstileContextValue = { /** Clears the token and makes the widget issue a new one. */ @@ -69,7 +72,7 @@ export function useTurnstile(): { enabled: boolean reset: () => void token: null | string - TurnstileWidget: (props?: { theme?: TurnstileTheme }) => React.ReactNode + TurnstileWidget: (props?: { reserveHeight?: number; theme?: TurnstileTheme }) => React.ReactNode } { const ctx = use(TurnstileContext) if (!ctx) { @@ -93,9 +96,9 @@ function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType { + (props?: { reserveHeight?: number; theme?: TurnstileTheme }) => { if (!siteKey) {return null} - return + return }, [siteKey], ) @@ -104,8 +107,13 @@ function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType + // the same reserved height while the widget's code loads: nothing below moves when it arrives + return ( + : null}> + + + ) } diff --git a/src/modules/turnstile/client.ts b/src/modules/turnstile/client.ts index 403b8eb..9523622 100644 --- a/src/modules/turnstile/client.ts +++ b/src/modules/turnstile/client.ts @@ -2,6 +2,7 @@ // 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' +// `Turnstile` is the lazy wrapper since 1.18.0 (same props): the widget's code loads where a form shows it +export { LazyTurnstile as Turnstile } from './LazyTurnstile.js' export type { TurnstileProps, TurnstileTheme } from './Turnstile.js' export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from './TurnstileProvider.js' diff --git a/src/modules/turnstile/turnstileHeight.ts b/src/modules/turnstile/turnstileHeight.ts new file mode 100644 index 0000000..04d3ecc --- /dev/null +++ b/src/modules/turnstile/turnstileHeight.ts @@ -0,0 +1,5 @@ +/** + * Height kept free for the Turnstile widget before Cloudflare draws it: the widget measures 72.6 px in the browser + * (Cloudflare documents 300×65 for the frame; the container adds the rest). Measured 2026-12 on the reference site. + */ +export const TURNSTILE_HEIGHT = 73 diff --git a/src/plugin.ts b/src/plugin.ts index 7a37a92..fab139c 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -26,7 +26,7 @@ import { SIGN_IN_LOOK } from './modules/branding/signIn/brand.js' import { lockBrandFields } from './modules/branding/signIn/brandAccess.js' import { buildAdminLanguageEndpoint } from './modules/branding/signIn/languageEndpoint.js' import { resolveSignInLook } from './modules/branding/signIn/options.js' -import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js' +import { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_SLUG } from './modules/consent/consentLog.js' import { addCookieScannerTabs } from './modules/consent/scanner/adminTabs.js' import { buildCookieApprovalEndpoints, COOKIE_APPROVAL_VIEW_PATH } from './modules/consent/scanner/approval.js' import { buildCookieReviewCollection } from './modules/consent/scanner/collection.js' @@ -77,6 +77,8 @@ import { migrateTitleSeparator } from './modules/seo/titleSeparator.js' import { applyCollectionOverride } from './modules/shared/collectionOverride.js' import { assertDevelopmentHosts } from './modules/shared/developmentHosts.js' import { withRetention } from './modules/shared/retention.js' +import { isMongo, syncTtlIndex, ttlField } from './modules/shared/ttl.js' +import { withVersionLimit } from './modules/shared/versionLimit.js' import { assertPluginSwitches } from './modules/shared/switches.js' import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js' import { visitorCookieFor } from './modules/stats/visitorCookie.js' @@ -133,6 +135,10 @@ export const iapl = (options: IaplOptions): Plugin => { } async function transform(incomingConfig: Config): Promise { + /** MongoDB TTL indexes to set at start (consent log, statistics): shared/ttl.ts. */ + const ttlSyncs: Array<{ days: number; enabled: boolean; from: string; slug: string }> = [] + /** Slugs of the plugin's own collections and globals (their versions get a limit: shared/versionLimit.ts). */ + const pluginEntities = new Set() let config = { ...incomingConfig } /** The project's own endpoints: the panel-action origin rule (adminSameOrigin) is for the plugin's only. */ @@ -811,6 +817,7 @@ export const iapl = (options: IaplOptions): Plugin => { : pluginGlobals // The project's globalOverrides win (access, admin, hooks merged; a function = full control). config.globals = [...(config.globals ?? []), ...applyGlobalOverrides(withRevalidate, options.globalOverrides)] + for (const g of pluginGlobals) {pluginEntities.add(g.slug)} // The brand the sign-in screens show (name, logo, icon) is changed by admins only — with the sign-in look, // unless the project says `brandAccess: 'editor'`; without the look only when it says `'admin'`. const brandWl = options.whiteLabel === true ? {} : options.whiteLabel @@ -873,7 +880,11 @@ export const iapl = (options: IaplOptions): Plugin => { // --- consent log: proof of consent (on by default since 1.17.0; `consentLog: false` turns it off) --- if (options.consentLog !== false) { const logOptions = options.consentLog === true || options.consentLog === undefined ? {} : options.consentLog - config.collections = [...(config.collections ?? []), applyCollectionOverride(buildConsentLogCollection(), logOptions.collectionOverrides)] + const consentCollection = buildConsentLogCollection() + // MongoDB: the hidden date the TTL index counts from (shared/ttl.ts); SQL keeps its schema as it was + if (isMongo(config)) {consentCollection.fields = [...consentCollection.fields, ttlField()]} + config.collections = [...(config.collections ?? []), applyCollectionOverride(consentCollection, logOptions.collectionOverrides)] + ttlSyncs.push({ days: logOptions.retentionDays ?? 1095, enabled: logOptions.ttlIndex !== false, from: 'createdAt', slug: CONSENT_LOG_SLUG }) config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)] config = withRetention(config, 'consent-records', logOptions.retentionDays ?? 1095) } @@ -955,7 +966,10 @@ export const iapl = (options: IaplOptions): Plugin => { const statsOptions = options.stats === true ? {} : options.stats const adminRoute = options.adminRoute ?? '/admin' const viewProps = { adminRoute, ...(statsOptions.timeZone ? { timeZone: statsOptions.timeZone } : {}) } - config.collections = [...(config.collections ?? []), applyCollectionOverride(buildStatsCollection(), statsOptions.collectionOverrides)] + const statsCollection = buildStatsCollection() + if (isMongo(config)) {statsCollection.fields = [...statsCollection.fields, ttlField()]} + config.collections = [...(config.collections ?? []), applyCollectionOverride(statsCollection, statsOptions.collectionOverrides)] + ttlSyncs.push({ days: statsOptions.retentionDays ?? 90, enabled: statsOptions.ttlIndex !== false, from: 'lastAt', slug: 'stats-visits' }) config.endpoints = [...(config.endpoints ?? []), buildStatsEndpoint(statsOptions)] config = withRetention(config, 'stats-visits', statsOptions.retentionDays ?? 90) config.admin = { @@ -1018,6 +1032,26 @@ export const iapl = (options: IaplOptions): Plugin => { }, } + // --- unused media above the upload lists (opt-in; the notice only links, deleting stays manual) --- + if (options.unusedMedia && options.enabled !== false) { + const only = options.unusedMedia === true ? null : options.unusedMedia.collections + const adminRoute = options.adminRoute ?? '/admin' + config.collections = (config.collections ?? []).map((c) => + c.upload && (!only || only.includes(c.slug)) + ? { + ...c, + admin: { + ...c.admin, + components: { + ...c.admin?.components, + beforeListTable: [...(c.admin?.components?.beforeListTable ?? []), { path: '@intecion/ipal-kit/admin#UnusedMediaNotice', serverProps: { adminRoute, collection: c.slug } }], + }, + }, + } + : c, + ) + } + // --- Payload's job queue over HTTP: an admin or the cron secret, unless the project wrote its own rule config = withJobsRunAccess(config, options.jobsRunAccess ?? {}) @@ -1132,10 +1166,24 @@ export const iapl = (options: IaplOptions): Plugin => { } await migrateCookieSettingsSaveButton(payload) await migrateTitleSeparator(payload, settingsSlug) + // MongoDB TTL indexes of the plugin's logs: created, kept at the current retention, or dropped when turned off + for (const { slug, ...ttl } of ttlSyncs) { + try { + const done = await syncTtlIndex(payload, slug, ttl) + if (done !== 'none') {payload.logger.info(`[iapl] ${slug}: TTL index ${done} (${ttl.enabled ? `${ttl.days} days` : 'off'})`)} + } catch (err) { + payload.logger.error(`[iapl] ${slug}: the TTL index could not be set (${err instanceof Error ? err.message : String(err)}); the purge after a new record still runs`) + } + } if (adminMeta) {await syncAdminMeta(payload, adminMeta, { nameField: brandFields.nameField, settingsSlug })} payload.logger.info('[iapl] Plugin initialized.') } + // The plugin's own entities whose versions a project turned on: at most 20 per document unless it set a limit + for (const slug of ['consent-records', 'cookie-review', 'cookie-crawl', 'stats-visits', 'forms', 'form-submissions']) {pluginEntities.add(slug)} + config.collections = (config.collections ?? []).map((c) => (pluginEntities.has(c.slug) ? withVersionLimit(c, 'collection') : c)) + config.globals = (config.globals ?? []).map((g) => (pluginEntities.has(g.slug) ? withVersionLimit(g, 'global') : g)) + // readVersions: readPublished() asks for `version._status` on version history (readPublishedVersions). config.collections = withVersionReadRules(config.collections) config.globals = withVersionReadRules(config.globals) diff --git a/src/types.ts b/src/types.ts index 9e0c780..e1c6036 100644 --- a/src/types.ts +++ b/src/types.ts @@ -154,6 +154,13 @@ export type IaplOptions = { * factor: whoever the dashboard is drawn for sees the full text. */ dashboardAlerts?: { cookies?: 'all' | 'editor'; integrations?: 'admin' | 'all' | 'editor' } + /** + * Unused media in the panel (1.18.0; docs/media.md): above the list of every upload collection (or the ones + * named), how many files no page, entry or setting uses, with a link to Payload's list filtered to them — the + * editor checks and deletes them by hand (nothing is deleted by itself). Off by default: it adds an entry to the + * admin import map (`pnpm generate:importmap`). `true` or `{ collections: ['media'] }`. + */ + unusedMedia?: boolean | { collections?: string[] } /** * Host patterns of the project's development, preview and staging addresses (`*` = any characters). diff --git a/test/performance1180.test.ts b/test/performance1180.test.ts new file mode 100644 index 0000000..e56d2b6 --- /dev/null +++ b/test/performance1180.test.ts @@ -0,0 +1,180 @@ +// @vitest-environment happy-dom +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { act, createElement } from 'react' +import { createRoot } from 'react-dom/client' +import { renderToStaticMarkup } from 'react-dom/server' +import { afterEach, describe, expect, test, vi } from 'vitest' + +import { BackgroundVideo } from '../src/modules/block-library/ui/BackgroundVideo.js' +import { CARD_INTERACTIVE_CLASS, CARD_INTERACTIVE_SHADOW_CLASS } from '../src/modules/block-library/ui/Card.js' +import { Media } from '../src/modules/block-library/ui/Media.js' +import { runDoctor } from '../src/modules/doctor/run.js' +import { UnusedMediaNotice } from '../src/modules/media/UnusedMediaNotice.js' +import { syncTtlIndex, TTL_FIELD, TTL_INDEX } from '../src/modules/shared/ttl.js' +import { PLUGIN_VERSION_LIMIT, withVersionLimit } from '../src/modules/shared/versionLimit.js' +import { Turnstile } from '../src/modules/turnstile/Turnstile.js' +import { TURNSTILE_HEIGHT } from '../src/modules/turnstile/turnstileHeight.js' + +const root = path.resolve(import.meta.dirname, '..') +const read = (rel: string) => readFileSync(path.join(root, rel), 'utf8') + +describe('lazy form code (item 3)', () => { + test('the /client entry exports the lazy form and widget; /client/eager the eager ones; hooks are no client boundary', () => { + expect(read('src/exports/client.ts')).toMatch(/export \{ LazyBuilderForm as BuilderForm \} from '\.\.\/modules\/forms\/LazyBuilderForm\.js'/) + expect(read('src/modules/turnstile/client.ts')).toMatch(/export \{ LazyTurnstile as Turnstile \}/) + expect(read('src/exports/client-eager.ts')).toMatch(/export \{ BuilderForm \} from '\.\.\/modules\/forms\/BuilderForm\.js'/) + expect(JSON.parse(read('package.json')).exports['./client/eager']).toMatchObject({ import: './dist/exports/client-eager.js' }) + for (const hook of ['useBuilderForm', 'useForm', 'useContactForm']) {expect(read(`src/modules/forms/${hook}.ts`)).not.toMatch(/^'use client'/m)} + // nothing imports the eager modules statically but the eager entry and the lazy wrappers' import() + expect(read('src/modules/forms/RenderForm.tsx')).not.toMatch(/^import \{ BuilderForm \}/m) + expect(read('src/modules/turnstile/TurnstileProvider.tsx')).toMatch(/lazy\(\(\) => import\('\.\/Turnstile\.js'\)/) + }) + + test('the Turnstile widget keeps its height free before Cloudflare draws it; 0 turns it off', () => { + expect(renderToStaticMarkup(createElement(Turnstile, { onToken: () => {}, siteKey: 'k' }))).toBe(`
`) + expect(renderToStaticMarkup(createElement(Turnstile, { onToken: () => {}, reserveHeight: 0, siteKey: 'k' }))).toBe('
') + }) +}) + +describe('background video and reduced motion (item 4)', () => { + const video = { filename: 'loop.mp4', mimeType: 'video/mp4', url: '/api/media/file/loop.mp4' } + test('Media renders the background video through BackgroundVideo, same markup; opt-out keeps a plain