Compare commits

...
278 Commits
Author SHA1 Message Date
Radosław SmolińskiandClaude Opus 5.5 45d52c4690 1.16.5 upgrade notes
CI / check (push) Failing after 5m27s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:50:25 +01:00
Radosław SmolińskiandClaude Opus 5.5 bef3a682b8 1.16.5
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:50:25 +01:00
Radosław SmolińskiandClaude Opus 5.5 f96b5c15d0 Merge claude/2fa-safe-back: the back link of the 2FA screens is checked on the server (twoFactor.safeBack)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 17:49:47 +01:00
Radosław SmolińskiandClaude Fable 5.2 3eee841dd0 ipal-doctor: the raw 2FA view warning only for a view component
R3-1: the warning fired on any mention of the 2FA package's setup / verify view
in the config, so it stayed after the fix its own text suggests (SafeTotpView
with the path as ipalTotpView, plus the path in admin.dependencies). It now
warns only when the path is a view's Component.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 17:49:06 +01:00
Radosław SmolińskiandClaude Fable 5.2 b2c1dca5da 2FA back link: the stale import-map notice never replaces the screen
R2-1: the notice was rendered instead of the 2FA screen, and its flag is a text
search of the importMap.js on disk — not the map in the build. A false alarm
(map generated in the build with the repository's file in the running image, a
re-exporting map) hid a working code form and locked everyone out. The notice
is now rendered above the screen, the log line says "may be", and the flag goes
to ipal-kit's own provider only.

R2-2: views are compared against copies, so a factory that reuses its view
objects is guarded too; copyViews, changedViewKeys, SAFE_TOTP_VIEW,
totpViewImportKey, findImportMapFile and missingImportMapEntries are exported;
ipal-doctor warns when the config registers the 2FA package's own view; docs
wording and a misplaced comment fixed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 16:35:16 +01:00
Radosław SmolińskiandClaude Fable 5.2 ad51456eaa 2FA back link: review fixes — views guarded by object, client views, a loud stale import map
SB-1: the 2FA package replaces a view that already stands under its keys, so a
key that existed before the factory ran was wrongly treated as the project's own
and left unguarded (also with a double registration, or ipalKit over its own
output). Views are now compared by object, right after the factory.

SB-2: SafeTotpView renders through Payload's RenderServerComponent: a client
component set as a 2FA view gets only client props plus the checked back.

SB-3: a production build with the previous import map shows an empty 2FA screen.
twoFactor.importMapCheck (on, production only) reads the committed map at start:
an error in the log and a message on the 2FA screens. Docs name the real symptom.

SB-4: enabled: false restores admin.dependencies; wrapTotpViews keeps exportName.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 16:16:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 93e75426ab 2FA screens: the back link is checked on the server (twoFactor.safeBack)
@clocklimited/payload-2fa sends the browser to the `back` query value after a
valid code without checking it (GHSA-rffw-fq79-g3ch upstream, not fixed in the
fork): a prepared link ran script in the panel or left the site.

SafeTotpView now stands in front of the package's setup and verify views and
passes on a checked value: a path on the site's origin inside the admin route,
else the admin root. The package's views stay in the import map through
admin.dependencies, so ipal-kit still never imports the package.

twoFactor.safeBack: false turns it off, a function replaces the rule;
safeAdminBack, wrapTotpViews and SafeTotpView are exported. Projects with 2FA
must regenerate the admin import map.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 15:29:06 +01:00
Radosław SmolińskiandClaude Opus 5.5 39309c5c1c CHANGELOG 1.16.4: the verify limit counts every try; lockout from a sibling subdomain
CI / check (push) Failing after 5m29s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:36:54 +01:00
Radosław SmolińskiandClaude Opus 5.5 d722157e20 1.16.4 upgrade notes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:35:08 +01:00
Radosław SmolińskiandClaude Opus 5.5 03443fd7ee 1.16.4
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 09:35:08 +01:00
Radosław SmolińskiandClaude Opus 5.5 f0f26393a3 Merge claude/security-fix-staff-check-2fa: staff checks only for staff collections; 2FA covers everything
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 02:26:56 +01:00
Radosław SmolińskiandClaude Fable 5.2 dc5326ea1c Review round 3: job-queue rules keep Payload's own defaults; a failed 2FA lookup fails closed
Job queue (R3-1): only a rule that exists is wrapped. At config time that
is what the project wrote; Payload fills in the rest when it builds the
config (3.94.1: run, queue and cancel are all defaultAccess, a logged-in
user) and the sweep of the running config wraps those. No default is
invented, so a request without a user gets what Payload itself answers.

hasTotp false while the account's record carries a TOTP secret (the 2FA
package's own lookup failed, R3-4): the account owes its code, not
'not set up yet'.

Docs: the two-configs-in-one-process case for calls without a source, and
that a half-logged-in editor's browser is refused media files.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 02:22:04 +01:00
Radosław SmolińskiandClaude Fable 5.2 c56f0d41b8 Security review round 2: no exception by name, staff list fails closed, verify limit
R2-1: the sweep skipped every collection whose slug starts with payload-,
so a plugin's payload-... collection added after ipalKit was never guarded.
There is no exception by name or prefix now: every collection and global
is guarded, Payload's own included, and the job queue's run / queue /
cancel rules too.

R2-2: role predicates called without a source fail closed where the staff
collections are not known (browser bundle, middleware, edge): nobody is
staff. They accept req.payload, a config (also the client config) or
{ staffCollections } as the source.

R2-3: the staff list is filed per config / Payload instance; a call without
a source gets only what every config in the process calls staff.

R2-4: payload.config is watched on the instance, so a config swapped in by
a dev reload is guarded before any request or Local API call.

R2-5: verify attempts are limited per account (default 5 in 10 minutes,
twoFactor.verifyLimit), counted in memory, never skipped.

R2-6: a user object without collection owes the second factor; endpoints
the 2FA package may add on collections or globals are guarded too; a
warning names staff collections that 2FA does not cover; docs state what
is not covered, fix the one-argument examples and the doctor example.

HTTP tests for each on payload-2fa beta.7, run on SQLite, Postgres and
MongoDB (test adapter added).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 01:46:25 +01:00
Radosław SmolińskiandClaude Fable 5.2 32faaa5e30 Security review fixes: staff collection first everywhere, 2FA package endpoints guarded, per-entity opt-out, hot reload
F1: roles count only for accounts of a staff collection, in every exported
predicate and access builder (isAdmin, isEditor, hasMinimumRole, adminOnly,
adminOrEditor, requireRole, adminOrSelf, adminOrSelfIn, the Field variants,
the roles field) and first in userMeetsRole. An account of another auth
collection with its own roles: ['admin'] gets nothing. Staff collections:
admin.user, access.authCollection, access.staffCollections. Predicates take
req.payload as an optional last argument and otherwise use the staff
collections of the config ipalKit built in this process.

F2: every endpoint @clocklimited/payload-2fa registers answers accounts of
the 2FA collection only (setup-totp wrote the secret into the 2FA collection
under the caller's id, whatever collection the caller came from); remove and
the admin reset/remove endpoints also need the second factor.

F3: per-entity opt-out honoured, operation by operation: the package's
custom.totp.disableAccessWrapper and ipal-kit's custom.ipal.secondFactor
(passed on to the package); the package's global disableAccessWrapper too.

F4: a no-user auth strategy on the 2FA collection guards the live config at
the start of each request, so entities from plugins listed after ipalKit
stay guarded after a dev hot reload and with disableOnInit.

Tests through HTTP for all four; the 2FA tests now run on payload-2fa
3.0.0-beta.7 (what client sites use), a second file on beta.1 (alias), and
the HTTP files can run against Postgres (IPAL_TEST_POSTGRES_URI). Docs,
agent guide, skills and changelog updated; the not-yet-enrolled limitation
is stated plainly.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 01:02:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 97ee1289aa Reference smoke test: send the site origin so the login cookie counts; test typing
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 00:38:01 +01:00
Radosław SmolińskiandClaude Fable 5.2 0c61ac231b Security: staff checks only for staff collections; 2FA covers what the plugin adds
Staff check (userMeetsRole): the 'no roles field = every account passes'
rule applied to the account's own collection, so an account of a second
auth collection (customers) passed every staff check. It now applies only
to staff collections: the panel's login collection plus the new
access.staffCollections. The injected auth collection uses the new
adminOrSelfIn(slug), so an account of another collection with the same
numeric id is not 'self'.

2FA: @clocklimited/payload-2fa wraps the collections and globals present
when it runs; ipalKit's own globals and collections were added later and
stayed unwrapped, so a password without the TOTP code opened them over
REST and GraphQL. ipal-kit now has its own second-factor check
(secondFactorPassed / requireSecondFactor): applied to every collection
and global at the end of ipalKit, again in onInit for entities added by
plugins listed after it, and inside userMeetsRole and the endpoints that
take a project access function. It fails closed: an unrecognised user
shape is refused, and startup stops when the injected 2FA plugin lacks
the parts the check reads (twoFactor.guard: false opts out).

Tests through real HTTP requests (REST and GraphQL) against Payload's
route handlers, plus the reference smoke test. Docs, agent guide, skills
and the reference skills copy updated; changelog entry without a version.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-24 00:31:55 +01:00
Radosław SmolińskiandClaude Opus 5.5 bc1045a5b7 Merge claude/drift-decisions-1163: PAYLOAD_SECRET minimum in production, doctor seen in CI, create --external
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:09:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 71fea221f1 Merge claude/docs-drift-1163: docs brought in line with the 1.16.3 code
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:09:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 0d8d906653 Comments: tab name Search engines, credit text, generateStaticParams scope
Comments and the ipal-kit usage line only (adds ipal-doctor); no behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 b5df59691c ipal-kit create: a bare --external installs every external skill
Matches the help text and docs/project-starter.md; a list stays as given,
no flag leaves it to the answers. resolveExternal() + test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 5cd0224ebd ipal-doctor: never write first-seen dates when CI is set
The CLI ignored CI (writeSeen was only !sites && !json); docs and comments
already said "not in CI". shouldWriteSeen() + test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 36f8f69f82 ipalEnvRules: PAYLOAD_SECRET at least 32 characters in production
New option secretMinLength (default 32, 0 turns it off); checked only with
NODE_ENV=production. Docs: env table, deployment (what changing the secret
does, checked in Payload 3.94.1 and payload-2fa), AGENT.md, ipal-reference,
ipal-setup. Tests: short secret fails in production, passes in dev, 0 and a
custom minimum.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 40fed78da2 Docs: forms reject text over 5000 characters; Site settings update is editor+
(a) The code rejects an over-long value (kind 'too_long', validation text at
the field, answers kept); the limit is fixed. (c) Site settings update needs
the editor role; overridable with globalOverrides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 37592764b5 Docs: fix doc/code drift found against 1.16.3 (docs only)
Verified the IAWL summary's "Doc/code" notes against the code and swept
CLI flags, option names/defaults and env vars. Fixed in the docs:
admin groups (consent-records, cookie-review → Privacy; Form messages
global → Forms), tab labels (More, Spam protection, E-mail sending,
Search engines; Sending method), construction field labels, {field} =
label, globalOverrides instead of "a plugin after ipalKit", enabled:false
keeps globals, pages role labels en+pl, switchLocalePath prefix,
accessibility cookie (necessary), seeding summary() shape, prepublishOnly
chain, doctor --strict --offline in the starter, package files list,
ipal-skills --external in PROGRAMISTA, DATABASE_URI (not _URL),
uploadsCollection exists, SiteProviders nonce, buildLinksField labels,
MCP list_pages limit wording, IPAL_DOCTOR_TOKEN in the env table; shipped
seo-check message "Search engines". Reference skills copy refreshed.

Open questions (not changed): forms over-long text, PAYLOAD_SECRET
length, Site settings update access, doctor seen in CI, bare
`ipal-kit create --external`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 23:47:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 e603561de4 1.16.3: renumber the prepared release (was 1.17.0)
CI / check (push) Failing after 6m22s
CI / reference (push) Skipped
CI / reference-full (push) Skipped
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:53:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 e29f882aa6 1.17.0 upgrade notes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:46:47 +01:00
Radosław SmolińskiandClaude Opus 5.5 195ca3ab11 1.17.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:46:40 +01:00
Radosław SmolińskiandClaude Opus 5.5 b9df570e84 Merge claude/deps-payload-3-94: Payload 3.94.1, dependency updates, overrides re-checked
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:43:23 +01:00
Radosław SmolińskiandClaude Opus 5.5 a0c576e54c Dev audit: @swc/cli 0.8.2, vite 7.3.8; Node 22.23.5 check in Coolify
@swc/cli 0.8.0 still resolved piscina 4.9.3 and @xhmikosr/decompress 10.2.1
(the two criticals). 0.8.2 with refreshed transitive deps and vite 7.3.8 as a
direct dev dependency take the dev-tree audit from 31 to 4 (0 high, 0 critical).
Docs: Payload 3.94 needs Node 22.23.5+ also in Coolify; how to check it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 17:43:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 ab51027617 Payload 3.94.1, dependency updates, overrides re-checked
- payload and every @payloadcms/* 3.94.1 in the plugin's dev dependencies, the
  reference site and the starter (peer range unchanged: ^3.90.2); react/react-dom
  19.3.1; reference engines node >=22.23.5 <23 (Payload 3.94's minimum).
- Overrides re-checked: dompurify and happy-dom still needed; mongoose (3.90–3.93)
  and undici (3.90–3.91) only on an older Payload; graphql-scalars no longer needed
  (GHSA-x8rm-f576-gq67 covers 1.24.1–2.0.0; Payload pins 1.22.2). Reference keeps
  dompurify + happy-dom; plugin root drops graphql-scalars.
- ipal-doctor transitive-min: the mongoose fix names the Payload upgrade first.
- nodemailer 10.6.1; dev: playwright 1.65.1, vitest 5.1.1, prettier 3.10.1,
  @swc/cli 0.8, rimraf 6 (clean uses --glob), cross-env 10, open 11,
  sort-package-json 4, @swc-node/register 1.12.1, vite-tsconfig-paths 6.1.1;
  reference tailwind 4.3.5, postcss 8.5.33.
- Kept back: typescript 7, eslint 10, graphql 17, @types/node 26, lucide-react 1.x.
- AGENT.md §4 item 12, ipal-setup, ipal-upgrade, README, PROGRAMISTA §1, forms.md,
  doctor.md; reference skills copy; CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 15:18:58 +01:00
Radosław SmolińskiandClaude Opus 5.5 13b66413f8 1.16.2 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.2" section. PROGRAMISTA §6: item 63. Reference site: skills
and the AGENTS.md pointer on 1.16.2; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:19:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 5d9bc10cfd 1.16.2
Version bump; the Unreleased section becomes 1.16.2: pnpm.overrides for Payload's
mongoose (8.24.1 → ~8.24.10; GHSA-pcrw-h46h-c93h critical and four more) and
happy-dom (20.x → ^21.0.4; two highs) in the reference site and the starter; new
ipal-doctor rule transitive-min and DoctorContext.installedAll(name). What projects
must update: every MongoDB site adds the two override lines (Postgres/SQLite: the
happy-dom one), reinstalls, rebuilds and redeploys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:19:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 1917686b52 Merge claude/inspiring-goldstine-66f9c2: mongoose and happy-dom overrides, doctor rule transitive-min
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-17 00:18:49 +01:00
Radosław SmolińskiandClaude Fable 5.2 de8362820f Overrides for Payload's mongoose and happy-dom advisories; doctor rule transitive-min
@payloadcms/db-mongodb pins mongoose 8.24.1 (one critical, two high, two moderate
advisories, fixed by 8.24.7) and @lexical/headless 0.50 brings happy-dom 20.x (two
high, fixed by 21.0.4). Payload 3.93.0 fixes neither.

- reference/package.json (and so the starter): pnpm.overrides for mongoose
  (~8.24.10) and happy-dom (^21.0.4); pnpm audit --prod on the reference is clean
- root package.json: the happy-dom override for the plugin's own dev tree
- ipal-doctor: transitive-min reports mongoose 8.x < 8.24.7 (error) and
  happy-dom < 21.0.4 (warning) from the lockfile and prints the override line;
  DoctorContext.installedAll(name)
- AGENT.md §4 item 12, ipal-setup, ipal-upgrade, doctor.md, README, CHANGELOG

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-17 00:01:58 +01:00
Radosław SmolińskiandClaude Opus 5.5 7c034a07ef 1.16.1 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.1" section. PROGRAMISTA §6: item 62. Reference site: skills
and the AGENTS.md pointer on 1.16.1; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:14 +01:00
Radosław SmolińskiandClaude Opus 5.5 5c9eeaf330 1.16.1
Version bump; the Unreleased section becomes 1.16.1: Next.js 16.4.6 in the plugin,
the reference site and the starter; minimum safe version 16.4.5 because of
GHSA-mfr8-8qww-v76h (16.3.0–16.4.4); ipal-doctor next-min raised. What projects
must update: every site below 16.4.5 runs
`pnpm add [email protected] [email protected]` and redeploys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:10 +01:00
Radosław SmolińskiandClaude Opus 5.5 ad6011b66a Merge claude/next-16-4-6: Next.js 16.4.6, minimum safe 16.4.5 (GHSA-mfr8-8qww-v76h)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:49:02 +01:00
Radosław SmolińskiandClaude Opus 5.5 9b03c94979 Next.js 16.4.6; minimum safe version 16.4.5 (GHSA-mfr8-8qww-v76h)
Next.js 16.3.0–16.4.4 is affected by GHSA-mfr8-8qww-v76h (CVE-2026-119790, moderate:
information disclosure across root params when a 'use cache' function is called
through unstable_cache()), first patched in 16.4.5.

- next and eslint-config-next 16.4.6 in the plugin's dev dependencies and the
  reference site (the starter is generated from it); lockfiles refreshed.
- ipal-doctor next-min: error below 16.4.5, naming the advisory; fix
  `pnpm add [email protected] [email protected]`; still silenceable. Tests.
- AGENT.md §4 item 11, ipal-setup, ipal-upgrade, doctor.md: minimum 16.4.5;
  reference skills copy refreshed. CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 23:45:17 +01:00
Radosław SmolińskiandClaude Opus 5.5 ba3d57a77a 1.16.0 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.16.0" section. PROGRAMISTA §6: item 61. Reference site: skills
and the AGENTS.md pointer on 1.16.0; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:19:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 7f0c2f9d72 1.16.0
Version bump; the Unreleased section becomes 1.16.0: files on panel forms, checked,
e-mailed to the company and never stored (forms.attachments, File field, streamed
endpoint with the security wall and abort/timeout handling); attachments over SMTP
and Microsoft Graph (upload session, mailbox copy deleted); test e-mail with a
10 MB file; Turnstile reset and BuilderForm honeypot fixes; Graph token cache.
What projects must update: nothing required; to use files — option, File field,
migration on Postgres/SQLite, formClasses keys, proxy body limit, Graph
Mail.ReadWrite or SMTP. Verify on real systems: Graph 10 MB send and cleanup,
Traefik timeout on a slow upload, SMTP size limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:18:50 +01:00
Radosław SmolińskiandClaude Opus 5.5 3cde9974d0 Merge claude/form-attachments-9694cb: files on forms, e-mailed and never stored
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 17:13:55 +01:00
Radosław SmolińskiandClaude Fable 5.2 6f006825a4 Form files: an upload aborted while the gates are pending no longer leaves its attempt key registered
Re-review of 1.16.0: beforeFiles could resume after the request was answered and
register the attempt key with nobody left to release it. It now stops after every
await once the request is over; the registration has no await before it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:09:14 +01:00
Radosław SmolińskiandClaude Fable 5.2 7ecfb26eb1 Reference: refreshed skills copy (upload timeouts)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:04:03 +01:00
Radosław SmolińskiandClaude Fable 5.2 e24c918d4b Form files: a dropped, stalled or endless upload is aborted and frees its slot, attempt key and buffers
Security review of 1.16.0 (blocking): a request body that errored mid-file never
resolved, leaking the concurrency slot and the attempt key. Also: idle and request
timeouts (submit.idleTimeoutMs / timeoutMs), ImmutableId preference on every Graph
draft call, the remaining total in the too-large message, files sent to a form
without a File field are refused and logged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 17:02:10 +01:00
Radosław SmolińskiandClaude Fable 5.2 cd74d7decb Reference: refreshed skills copy and generated types for the file messages
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:52:18 +01:00
Radosław SmolińskiandClaude Fable 5.2 97202ee03e Form files: the visitor is told when the problem is the file — why and what to do; UTF-8 file names
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:51:05 +01:00
Radosław SmolińskiandClaude Fable 5.2 b6f9f34705 Form attachments: tests for project options and the concurrency guard
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:44:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 ea43d94dd2 Reference index: describe the mail sink
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:43:41 +01:00
Radosław SmolińskiandClaude Fable 5.2 fdb6140c09 Form attachments: reference smoke test with a mail sink, Turnstile reset fix, docs
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:42:39 +01:00
Radosław SmolińskiandClaude Fable 5.2 387debc88c WIP: reference site — File field on the quote form, mail sink smoke test
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:34:34 +01:00
Radosław SmolińskiandClaude Fable 5.2 b7fb1b0e31 WIP: form attachments — agent guide, skills, seed template, changelog
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:32:45 +01:00
Radosław SmolińskiandClaude Fable 5.2 344574d6bd WIP: form attachments docs (forms, email, security, storage, deployment, notifications), honeypot value sent
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:30:44 +01:00
Radosław SmolińskiandClaude Fable 5.2 701bb420c1 WIP: form attachments — unit tests, test e-mail with attachment, lint
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:28:22 +01:00
Radosław SmolińskiandClaude Fable 5.2 02b1e96d3d WIP: form attachments tests
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:24:27 +01:00
Radosław SmolińskiandClaude Fable 5.2 6003b3d7d7 WIP: form attachments (e-mail only) — core, endpoint, Graph large upload
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:20:02 +01:00
Radosław SmolińskiandClaude Fable 5.2 0ba0014ed5 Form attachments proposal: Graph upload session recommended (Mail.ReadWrite already granted)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:04:07 +01:00
Radosław SmolińskiandClaude Fable 5.2 62bed415ed Form attachments proposal: e-mail only, no storage (revision 2)
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 16:01:18 +01:00
Radosław SmolińskiandClaude Fable 5.2 d2caf8c2ae Form attachments: design proposal
Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-13 15:55:45 +01:00
Radosław SmolińskiandClaude Opus 5.5 755f510c9f 1.15.5 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.5" section. PROGRAMISTA §6: item 60. Reference site: skills
and the AGENTS.md pointer on 1.15.5; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 970307f3ab 1.15.5
Version bump; the Unreleased section becomes 1.15.5: required fields with
references are seeded complete; a stricter dry run (missing $form / $page is an
error there too). What projects must update: nothing required; a required reference
cycle now fails clearly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:35:22 +01:00
Radosław Smoliński c7e198fd92 Merge claude/seeder-required-refs: required fields with references are created complete
createSeeder's first pass resolves { $page } / { $form } references to existing
records, so a required layout is created complete; a forward $page is filled in
pass 2 and a record whose required field needs it waits for that page. Required
cycles and never-appearing targets are an error with nothing written; the dry run
reports the same, including a missing $form. Guards, create-only, the edit check
and SEED_ONLY are unchanged. Reported from vanstevpl-web.
2026-11-13 14:31:52 +01:00
Radosław SmolińskiandClaude Opus 5.5 748ef9286f Seeder: required fields with references are created complete (1.15.5)
A page whose required layout holds a { $page } / { $form } reference could not be
created: pass 1 left the whole field out, validation rejected the record, and the
dry run reported a create (vanstevpl-web, 1.15.4).

- pass 1 resolves references to records that exist (or were created earlier in
  the run), so the field is written complete
- a { $page } to a page later in the same call is null in pass 1 and filled in
  pass 2; a record whose required field needs it is retried once that page exists
- required links in a cycle and references to pages or forms that never appear
  are an error with nothing written; unknown page targets are found while
  planning, so the dry run reports them too
- dry run: a missing form is an error (was a placeholder); a form planned earlier
  in the same dry run counts as existing
- real-Payload tests (pl, en, de): the report's careers page, an existing form
  target, optional and required forward links, a cycle, missing page and form,
  create-only second runs, dry-run parity
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:29:41 +01:00
Radosław SmolińskiandClaude Opus 5.5 179d5b0d79 1.15.4 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.4" section (repair with SEED_UPDATE, live site with SEED_ONLY,
edited records and global arrays by hand). PROGRAMISTA §6: item 59. Reference site:
skills and the AGENTS.md pointer on 1.15.4; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:27 +01:00
Radosław SmolińskiandClaude Opus 5.5 2f00fe3ad6 1.15.4
Version bump; the Unreleased section becomes 1.15.4: seeding whole localized arrays
keeps every language. What projects must update: nothing required; repairing records
an earlier seed wrote needs SEED_UPDATE=1 (locally first; on production with SEED_ONLY
and IPAL_SEED_ALLOW_PROD_UPDATE=1 after a backup), edited records and global arrays
by hand.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:39:26 +01:00
Radosław Smoliński a79740cd44 Merge claude/seeder-localized-arrays: whole localized arrays keep every language
createSeeder / writeLocales: a value seeded per language as a whole (form fields,
nested select options, page layouts, global arrays) keeps the stored row ids in
every locale instead of only the last language surviving; localized: true fields
keep rows per locale. Seed guards, the edit check and SEED_ONLY are unchanged.
Reported from vanstevpl-web.
2026-11-12 15:35:38 +01:00
Radosław SmolińskiandClaude Opus 5.5 00e814e3ca Seeder: whole localized arrays keep every language (1.15.4)
createSeeder / writeLocales: a value written per locale as a whole —
fields: { pl: [...], en: [...], de: [...] }, a page layout, a global array —
returned the picked locale without walking into it, so each locale write made new
shared rows and only the last language survived (vanstevpl-web, 1.15.3).

- localize() localizes the picked value again with the stored rows, so row ids
  are shared across locales (arrays, blocks, nested arrays in blocks, groups)
- writeLocales passes the target's fields: a field that is itself localized
  (localized: true layout) never reuses another locale's row ids
- real-Payload regression test (pl, en, de): form with blocks and nested select
  options, shared and localized page layouts, global array via fillGlobal; a later
  PL save validates
- CHANGELOG Unreleased, seeding.md, api.md; reference skills refreshed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 15:33:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 4d1de4c66a 1.15.3 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.3" section. PROGRAMISTA §6: item 58. Reference site: skills
and the AGENTS.md pointer on 1.15.3; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 13:03:14 +01:00
Radosław SmolińskiandClaude Opus 5.5 3edf8865ed 1.15.3
Version bump; the Unreleased section becomes 1.15.3: ipal-audit and ipal-doctor no
longer report the panel's bilingual labels (adminText(), { en, pl }) as hardcoded
text; public text is still reported. What projects must update: nothing required;
pnpm ipal:skills for the updated audit scripts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 13:03:14 +01:00
Radosław Smoliński 594b958bb2 Merge claude/audit-admin-labels: the panel's bilingual labels are not hardcoded text
ipal-audit and the doctor's i18n-literals read the syntax tree (polish-literals.mjs,
a plain grep without TypeScript): adminText(), { en, pl } as label, singular, plural,
description, placeholder or group, a rowLabel() fallback and const x: AdminText in a
schema file are accepted. Still reported: every .tsx file, Polish-only labels, other
keys, anything under defaultValue. Reported from the Niezly Dandys project.
2026-11-05 12:59:28 +01:00
Radosław SmolińskiandClaude Opus 5.5 f73465c3bb ipal-audit, ipal-doctor: the panel's bilingual labels are not hardcoded text
"Hardcoded Polish text in code" (i18n-literals) grepped every string, so adminText() and { en, pl }
labels in schema files were reported, though AGENT.md 6.5a asks for them. polish-literals.mjs reads
the syntax tree with the project's TypeScript (a plain grep without it) and spares those forms in
schema files only; every .tsx file, Polish-only labels, other keys and defaultValue still fail.
Reported by Niezly Dandys (1.15.2).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 12:55:44 +01:00
Radosław SmolińskiandClaude Opus 5.5 36b27ed323 1.15.2 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.2" section. PROGRAMISTA §6: item 57. Reference site: skills
and the AGENTS.md pointer on 1.15.2; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:08:08 +01:00
Radosław SmolińskiandClaude Opus 5.5 627cad792a 1.15.2
Version bump; the Unreleased section becomes 1.15.2: ipal-doctor finds the frontend
route group by structure (any app/(<group>) with the catch-all page, layout.frontend
override, findFrontend), accepts notFoundView.ts/.tsx. What projects must update:
nothing required; remove a temporary layout-required silence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:08:08 +01:00
Radosław Smoliński c33b264306 Merge claude/doctor-route-groups: ipal-doctor finds the frontend by structure
layout-required takes any app/(<group>) (or app) that holds the catch-all page, a
localized one first, instead of the literal (frontend); two candidates warn.
notFoundView may be .ts or .tsx; required files accept their usual extensions.
ipal-doctor.json layout.frontend wins; new export findFrontend. Reported from the
Say Diamonds project.
2026-11-03 15:04:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 b80770bc2e ipal-doctor: find the frontend route group by structure, accept notFoundView.tsx
layout-required no longer assumes src/app/(frontend): any app/(<group>) (or app itself) holding the
catch-all page is the frontend, a localized one first; two candidates give a warning naming both.
notFoundView.ts or .tsx, and the usual extensions for the other required files. New
ipal-doctor.json layout.frontend override and export findFrontend. Reported by Say Diamonds
(1.15.1, route group (site)).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 15:00:05 +01:00
Radosław SmolińskiandClaude Opus 5.5 a515bd6851 1.15.1 upgrade notes
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
ipal-upgrade: "→ 1.15.1" section. PROGRAMISTA §6: item 56. Reference site: skills
and the AGENTS.md pointer on 1.15.1; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:27:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 09bff6a683 1.15.1
Version bump; the Unreleased section becomes 1.15.1: guardSeedExit() (a seed that
ends early exits 1 with the reason), wired into the seed templates and the
reference site; reference smoke tests start their own server. What projects must
update: nothing required; add guardSeedExit(), check echo $? after a seed in Coolify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:27:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 e715b5720d Reference smoke tests never test another project's server; skills refreshed
- reference/playwright.config.ts: reuseExistingServer only with E2E_REUSE_SERVER=1.
  Playwright starts the built site itself on E2E_BASE_URL's port (default 3100) and
  fails when the port is taken — before, a dev server of another project on 3100
  (intecion.com's) was tested instead. CI is unchanged: it starts nothing before
  test:e2e. README's production check follows.
- reference/.agents/skills refreshed after the seed-exit-guard merge (ipal-form and
  ipal-site seed templates, ipal-reference); INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:24:05 +01:00
Radosław Smoliński 03515c66c4 Merge claude/seed-exit-guard: guardSeedExit() — a seed that ends early exits 1, never a silent 0
guardSeedExit() (@intecion/ipal-kit/seed, opt-in): a beforeExit guard exits 1 with
the reason when a seed run ends before Payload initializes or before summary();
createSeeder and summary() mark the stages. Wired into the reference seed and the
ipal-site / ipal-form seed templates. Normal exit codes are unchanged.
2026-10-29 19:23:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 f789e36636 Seeds: guardSeedExit() — a run that ends early exits 1 with the reason, never a silent 0
payload run starts the CLI with `void start()` and imports the script; when the script's top-level await
is left without live handles, Node exits with code 0 and no output — a success in Coolify's Terminal.
guardSeedExit() (@intecion/ipal-kit/seed, dependency-free) listens for beforeExit: until summary() runs it
prints "[seed] ended before Payload initialized" / "… before the seed finished" and exits 1. createSeeder
marks the run initialized, summary() finished; process.exit paths (normal, errors, the production
refusals) are untouched. Wired into the ipal-site and ipal-form seed templates and the reference seed, so
ipal-kit create sites get it. Tests include a real child process started like payload run.
Docs: seeding.md, deployment.md §4.7, AGENT.md, ipal-reference (+ api.md), CHANGELOG Unreleased.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 19:19:14 +01:00
Radosław Smoliński 55dc69b69f Merge claude/starter-gate-refusal: the production full-seed check needs the guard's message
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
starter:gate passes the production full-seed check only when the output says
"full seed refused" and the exit is non-zero; a payload run that ends before
Payload initializes (exit 0, no output) is inconclusive and retried, up to 3 times.
Fixes the flaky check found in the 1.15.0 gate.
2026-10-29 17:03:28 +01:00
Radosław SmolińskiandClaude Opus 5.5 7e1f09c95a starter:gate: the production full-seed check needs the guard's message; an early exit is retried
payload run can end with exit 0 and no output before Payload initializes (its bin does `void start()`;
when the script's top-level await is left without live handles, Node exits). Such a run proved nothing
but passed or failed the `refused !== 0` check at random. Now only "full seed refused" with a non-zero
exit counts; a run without "[ipal] Plugin initialized" is inconclusive and retried up to 3 times; all
three inconclusive fails the gate with that reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 17:01:43 +01:00
Radosław Smoliński 27a6e78ea3 Merge claude/reference-e2e-entrylist: blog-archive smoke test expects h2 or h3 card titles
After the entry-list heading fix (37131e9/6f56ef4) card titles are h2 when the list
has no section heading; the reference smoke test selector is now :is(h2, h3) a.
Without it CI's reference-full job fails. One file: reference/e2e/smoke.spec.ts.
2026-10-29 17:01:40 +01:00
Radosław SmolińskiandClaude Opus 5.5 ec649acb36 Reference smoke test: entry card titles are h2 or h3
The entry-list SEO fix (37131e9) renders card titles as h2 when the list has no
section heading; the blog-archive test looked for h3 only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 17:00:34 +01:00
Radosław SmolińskiandClaude Opus 5.5 d944217e3a 1.15.0 upgrade notes
ipal-upgrade: "→ 1.15.0" section with the 10 steps and a check. PROGRAMISTA §6:
item 55. Reference site: skills refreshed (ipal-upgrade) and the AGENTS.md pointer
on 1.15.0; INDEX.md regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:56:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 a5802f591f 1.15.0
Version bump; the Unreleased section becomes 1.15.0: ipal-kit create (starter),
ipal-doctor, design tokens, block library and page templates, reference site
(INDEX.md shipped), database names and seeding after launch, reference-site plugin
fixes, 2FA texts, CookieButton, SEO fixes, exact dependency pins; What projects must
update (10 steps).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:56:18 +01:00
Radosław SmolińskiandClaude Opus 5.5 40925f9331 Reference index regenerated after the merges
The merge-time regeneration ran while reference/ipal-doctor.json was still
unmerged, and git ls-files lists an unmerged path once per stage, so its section
was written three times. Regenerated with the merges complete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:48:42 +01:00
Radosław Smoliński 6ffcfaf461 Merge claude/starter-gate-fresh: starter:gate packs a fresh tarball every run
starter:gate gives every run a fresh tarball (no stale pnpm dlx cache) and proves
which plugin code generated the site (bundle/cli stamp). No conflicts; the
until-silence filter in generate.ts (aa88e4e) is kept.
2026-10-29 16:47:00 +01:00
Radosław Smoliński ba73e82e6f Merge claude/reference-seo-content: own meta descriptions, fuller demo content
Reference site: every page has its own meta description, demo archive and service
pages have real-length content; blocksToMarkdown reads section headers.

Conflicts resolved: reference/ipal-doctor.json — both branches removed their own
two live-seo silences, so the merged file keeps only the two permanent rules
(audit:collections-present, i18n-literals); docs/agent/reference-site/INDEX.md
regenerated with pnpm reference:index.
2026-10-29 16:46:53 +01:00
Radosław Smoliński 7432ee751f Merge claude/entrylist-seo: item headings follow the section, LCP image, fillGlobal skip
Block library: item headings sit one level below their section (itemHeadingLevel),
the leading block's first image is the LCP image (blockPosition, leadsWithImage,
blockHasImage); fillGlobal skips a field that already holds the seeded value.
Removes the two block-library live-seo silences from reference/ipal-doctor.json.
2026-10-29 16:46:31 +01:00
Radosław SmolińskiandClaude Opus 5.5 37131e9930 fillGlobal: a field already holding the seeded value is skipped, not rewritten
Seeding exactly the default (allowThemeToggle: true) used to count as unset,
rewrite it and report create on every run. Now: skip (exists), no write. A choice
at its default is still replaced by a different seeded value; editor changes stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:39:55 +01:00
Radosław SmolińskiandClaude Opus 5.5 64ee581098 Reference site SEO: own meta descriptions, fuller demo content; blocksToMarkdown reads section headers
- blocksToMarkdown: the library's section header (heading → ##, then intro; eyebrow
  skipped), intro, quote and bio are content. Pages whose text sat only in a hero
  (archive pages, quote, 404) auto-filled no meta description and fell back to the
  site description; /md and llms-full.txt also missed every section heading.
- legal() template: the placeholder names its page, so unfilled privacy/terms pages
  don't share a description.
- reference: every demo page has its own meta description (pl/en), posts and case
  studies use their excerpt; fuller made-up text on services, contact, quote and
  the archives (all pages >= 150 words); no seeding of allowThemeToggle (its default,
  fillGlobal rewrote it on every run). The two content silences are gone.

ipal-doctor --strict --offline --deep --url: 0/0/0 (4 silenced: 2 permanent,
2 entryList follow-ups of the block-library track). Smoke tests 15/15.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:38:09 +01:00
Radosław SmolińskiandClaude Opus 5.5 6f56ef4205 Block library: item headings follow the section; the leading block's first image is the LCP image
Found by ipal-doctor live-seo on the reference archive pages (entry list under a
page header without a picture): cards jumped h1 → h3, and the first card image
was lazy.

- itemHeadingLevel: items one below the section heading (h3 under h2, h2 under the
  page h1, h2 when the block shows no heading); createBlockRegistry({ itemHeadings })
  fixes a level per block. featureGrid, entryList, pricing, steps, team.
- blockPosition / blockHasImage (root): createPageRoute and the 404 view pass
  firstImage next to isFirst; leadsWithImage marks the first image of the leading
  block eager + fetchPriority high (hero, textMedia, featureGrid, gallery, team,
  entryList); priorityImage: false turns it off.
- reference/ipal-doctor.json: the two live-seo silences removed; reference skills
  and docs/agent/reference-site/INDEX.md refreshed.
- bin/ipal-blocks.mjs executable like the other bins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:38:04 +01:00
Radosław SmolińskiandClaude Opus 5.5 e7e756a0d7 starter:gate: a fresh tarball every run and proof of which code made the site
pnpm's dlx cache is keyed by the spec, so the gate reused the previous run's plugin when the
tarball path stayed the same. Each run now packs to a new file name and calls dlx with
--config.dlx-cache-max-age=0. build:starter records the plugin commit in the bundle; ipal-kit
create records the bundle's sha256 and that commit in .ipal/starter.json; the gate checks both,
and the installed plugin, against the packed tarball.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:30:24 +01:00
Radosław SmolińskiandClaude Opus 5.5 dd11bc8146 ipal-audit: skip the starter's //: alternative lines; reference skills refreshed
CI / check (push) Canceled after 0s
CI / reference (push) Canceled after 0s
CI / reference-full (push) Canceled after 0s
- audit.sh g(): matches on a starter alternative line (`//: …` after file:line:,
  the commented-out variants inside @starter:if markers) are dropped. The reference
  site's `//: robots: { aiBots: 'block-training' }` / 'disallow' alternatives made
  `audit:robots-blocks-ai-bots` fire although the site blocks no AI bots. The doctor
  runs audit.sh, so it follows. Tests: a //: line is not a finding, a real
  robots: { aiBots: 'block-training' } line still is.
- reference/.agents/skills refreshed with ipal-skills (ipal-reference, ipal-setup,
  ipal-site and ipal-audit were behind the plugin's after the doctor/starter merges).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:27:49 +01:00
Radosław SmolińskiandClaude Opus 5.5 aa88e4ea39 Starter: new sites don't inherit the reference site's temporary silences
Merge follow-up for doctor + starter (both fine alone; three tests failed
together):
- generate.ts: an inherited ipal-doctor.json rule with `until` is a temporary
  follow-up of the reference site itself (the four live-seo silences until
  2026-11-30); a new site starts with those checks on. Permanent, reasoned
  exceptions (i18n-literals, audit:collections-present) are still inherited.
- reference/src/instrumentation.ts: the doctor's cookieCrawl header comment is
  wrapped in @starter:if crawl, so a site without crawl doesn't mention it.
- docs/agent/reference-site/INDEX.md regenerated (the merge-time copy repeated
  the ipal-doctor.json section).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:20:36 +01:00
Radosław Smoliński 6d7d39bc95 Merge claude/project-starter-build: ipal-kit create (project starter)
ipal-kit create <domain> generates a new site from the reference site (bin
ipal-kit, /starter entry, gzipped template bundle built at prepublishOnly,
starter:gate); exact pins of the plugin's own four dependencies (D15, nodemailer
10.3.1); the single-language / non-pl-default refusal; reference/ @starter:if
markers, packageManager, cookieCrawl.

Conflicts resolved:
- reference/src/instrumentation.ts: the starter's multi-line ipalEnvRules with
  the @starter:if markers (the doctor's cookieCrawl comment line merged above
  assertEnv already).
- reference/ipal-doctor.json: the doctor's version, keeping the four live-seo
  silences (until 2026-11-30) — the starter's side was the pre-silence copy.
- docs/agent/skills/ipal-reference/resources/api.md: both /starter and /doctor.
- docs/CHANGELOG.md: both sides in both hunks; one Unreleased section.
- docs/agent/reference-site/INDEX.md: regenerated with pnpm reference:index.
2026-10-29 16:16:49 +01:00
Radosław Smoliński 704f3104df Merge claude/ipal-doctor-build: ipal-doctor (one command that checks a site against the team rules)
The ipal-doctor bin and /doctor entry: static and deep checks (blockLibraryManifest,
old-style block maps, 2FA behind a switch, folder name as database base), per-site
ipal-doctor.json with per-rule off/files/reason/until, and the reference CI doctor
steps turned on. The reference site runs at zero findings with four live-seo
follow-ups silenced with reasons until 2026-11-30.
2026-10-29 16:15:52 +01:00
Radosław SmolińskiandClaude Opus 5.5 4c97bc1a81 Reference site: deep + live ipal-doctor run at zero; four seo-check follow-ups silenced with reasons until 2026-11-30
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:11:58 +01:00
Radosław SmolińskiandClaude Opus 5.5 01afa6fab8 Starter: inherit the reference doctor silences and packageManager; cookieCrawl active in the reference
Same reference/package.json, reference/ipal-doctor.json and ci.yml env lines as claude/ipal-doctor-build,
so the two branches merge cleanly there. ipal-doctor.json of a new site keeps i18n-literals (the /design
styleguide) and audit:collections-present only while posts/caseStudies are in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:11:33 +01:00
Radosław Smoliński 04ae19e489 Merge commit '977872b' into claude/ipal-doctor-build
# Conflicts:
#	src/modules/seo/buildSitemapEntries.ts
2026-10-29 16:08:40 +01:00
Radosław SmolińskiandClaude Opus 5.5 e97cf6d7d9 ipal-doctor: old-style block maps, 2FA behind a switch, folder name as database base; first sweep table
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:06:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 a4e8cfeae8 ipal-doctor: one command that checks a site against the team rules
bin ipal-doctor + @intecion/ipal-kit/doctor: static rules (versions, Node 22, AGENT.md §3
layout and naming, database names, env rules, headers, X-Powered-By, CSP, 2FA, cookie
scanner, adminMeta, AGENTS.md, skills, seeds, block library via blockLibraryManifest,
ipal-audit --quick), registry rules (latest plugin, pnpm audit --prod), live rules (--url,
ipal-seo-check), deep rules (--deep via payload run; GET /api/ipal/doctor, off until
IPAL_DOCTOR_TOKEN). Human / JSON output, --strict, exit codes 0/1/2/3, --sites drift table,
ipal-doctor.json with reasons, until, files, seen.

Fixes found on the way: sitemap leaves out the System pages 404 page; ipal-audit finds
array labels after fields, any form seed, runs grep in UTF-8; ipal-seo-check counts
duplicate titles per language. Reference site at zero findings (static), CI steps on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 16:03:00 +01:00
Radosław SmolińskiandClaude Opus 5.5 0dffb85ec1 Starter: refuse single-language and non-pl-default sites explicitly (later); docs and tests
ipal-kit create stops before writing anything and points to the manual ipal-setup path;
project-starter.md, AGENT.md, ipal-setup, ipal-site and the CHANGELOG say the same.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:56:19 +01:00
Radosław Smoliński 0170419473 Merge commit '977872b' into claude/project-starter-build 2026-10-29 15:51:32 +01:00
Radosław SmolińskiandClaude Opus 5.5 804a09efed Project starter: ipal-kit create <domain> generates a new site from the reference site
- bin `ipal-kit` (subcommand `create`): the architecture questions (or --answers JSON),
  rendering from reference/ through starter.manifest.json (placeholders, @starter:if variants,
  //: alternatives, demo dropped), answers into AGENTS.md "Project decisions" and ipal-doctor.json,
  local .env with a fresh PAYLOAD_SECRET, install from the shipped lockfile, ipal-skills,
  ipal-tokens, generate:types/importmap, typecheck, ipal-doctor when shipped, secret check,
  first commit
- @intecion/ipal-kit/starter: the building blocks (renderSite, validateAnswers, applyVariants,
  collectBundle, lockfileWithoutPlugin, secretFindings …)
- build:starter packs reference/ into dist/starter/template.json.gz (90 KB);
  starter:gate in prepublishOnly: site from the packed tarball, frozen install, seed, build,
  targeted SEED_ONLY seed in production mode, full seed refused, pnpm start checks
- D15: plugin dependencies pinned exactly (nodemailer 10.3.1)
- reference/: @starter:if markers (runs as before), manifest generate/variants/rewrite
- docs: project-starter.md, AGENT.md, ipal-setup, ipal-site, ipal-reference (+ api.md),
  README, PROGRAMISTA §2, CHANGELOG, docs/README, reference index

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:50:44 +01:00
Radosław SmolińskiandClaude Opus 5.5 977872b0ad Reference smoke test: drop the KNOWN 404 sitemap filter
ipal-kit now leaves the page assigned as 404 out of the sitemap (unlistedPageIds,
merged in 30c1015), so the smoke test checks every sitemap URL again. Verified:
seed, build and 15/15 Playwright smoke tests on a throwaway MongoDB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:48:52 +01:00
Radosław Smoliński fd6eb293cb Merge claude/totp-pl-cookie-button: plain en/pl 2FA texts, CookieButton above the footer
TOTP_TEXTS (en, pl) merged over payload-2fa's, project translations still win,
twoFactor.texts: false keeps the package's; tab titles on the 2FA views
(TOTP_VIEW_TITLE). CookieButton lifts above the footer (avoid, default
COOKIE_BUTTON_AVOID; side; bottomOverlap; --ipal-cookie-button-inset). Admin
language keeps following the browser (no fallbackLanguage change).

Merge addition: the branch had no CHANGELOG entry — both items added under New
in the one Unreleased section, plus Requires project changes item 6 (CookieButton).
2026-10-29 15:46:09 +01:00
Radosław Smoliński 30c1015daa Merge claude/reference-site-plugin-fixes: 404 page unlisted, own-origin media, fillGlobal defaults
The page assigned as the 404 page is left out of the sitemap, llms.txt, the site
index, search, the search route and MCP search_content (unlistedPageIds;
createSearchRoute settingsSlug). buildImagesConfig allows the site's own
/api/media/file/** when R2_PUBLIC_URL is empty. fillGlobal treats a choice field
still at its default as empty. i18n.md: renderLabel client wrapper. No conflicts;
one Unreleased CHANGELOG section.
2026-10-29 15:45:49 +01:00
Radosław SmolińskiandClaude Opus 5.5 2886c89d8a 2FA screens: plain en/pl texts and tab title; CookieButton moves up above the footer
- TOTP_TEXTS (admin-ux.md wording) merged over @clocklimited/payload-2fa's
  long, informal texts; the project's i18n.translations still win;
  twoFactor.texts: false keeps the package's. Setup/verify screens titled
  "Two-step verification" / "Weryfikacja dwuetapowa" instead of "Payload".
- CookieButton: position via --ipal-cookie-button-offset / -inset and
  --ipal-z-header; lifts above the footer (avoid, default COOKIE_BUTTON_AVOID)
  while it is on screen; side prop; className still replaces the look.
- dev: a footer in the frontend layout to check the button against.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:34:01 +01:00
Radosław SmolińskiandClaude Opus 5.5 0ab133fbd7 ipal-doctor proposal: build order
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:33:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 6493b58ccd ipal-doctor proposal: owner's decisions D1-D9 (D5 = createSeeder only/SEED_ONLY, D7 = new sites only, no Dockerfile rules)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:33:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 9e583a92c9 ipal-doctor proposal: blockLibraryManifest, slug-based duplicate match
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:33:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 8cd9830a22 ipal-doctor proposal: block library rules
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:33:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 1a3a52a1be ipal-doctor proposal: starter clashes (src allow list, ui/ with createBlockRegistry, per-rule reasons, plugin-latest warning)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:33:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 a1f810e9de ipal-doctor proposal: [dir], --strict, localhost HSTS exemption
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:33:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 a65e109894 ipal-doctor proposal with dry-run table
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:33:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 6b2c9b3cc6 Search leaves out the 404 page: searchContent, the search route, MCP search_content
searchContent / listContent read Site settings once (depth 0, homepage + notFound)
and skip unlistedPageIds; createSearchRoute and the MCP route pass settingsSlug.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:31:43 +01:00
Radosław Smoliński 154049662e Merge claude/reference-site-build: reference site (Example Studio) on ipal-kit
reference/ (not shipped, own lockfile, plugin as file:..) builds a complete site
on the plugin; docs/agent/reference-site/INDEX.md (shipped) maps features to its
files, with a test; AGENT.md and skill pointers, PROGRAMISTA §8.1b, a Gitea CI job
that builds, seeds and smoke-tests it. Checked here: plugin gate green; reference
seed, next build (SSG) and 15/15 Playwright smoke tests on a throwaway MongoDB.

Merge addition: CHANGELOG Unreleased line for the reference site index.
2026-10-29 15:31:20 +01:00
Radosław SmolińskiandClaude Opus 5.5 3645e61f7d Fixes from the reference site: 404 page unlisted, own-origin media, fillGlobal defaults, switcher docs
- sitemap, llms.txt and the site index leave out the page assigned as the 404
  page (unlistedPageIds, exported); it stays when it is also the homepage
- buildImagesConfig: in production with R2_PUBLIC_URL empty, allow the site's
  own /api/media/file/** so next/image no longer answers 400
- fillGlobal: a choice field (select, radio, checkbox, number, date) still at its
  defaultValue counts as empty; text is never overwritten
- docs: LanguageSwitcher renderLabel needs a 'use client' wrapper (i18n.md,
  ipal-site, ipal-setup, api.md)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:29:07 +01:00
Radosław SmolińskiandClaude Opus 5.5 e43198b2fe Reference site: follow main's block and token fixes
- entryList entryCollection, post template hero with the title, legal templates noindex
  (drop the reference's own workarounds)
- brand primary-inverse roles: 74/74 contrast pairs
- /design shows Light and Dark panels (tokens switch on any element)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:21:55 +01:00
Radosław Smoliński 353e65e7bd Merge branch 'main' into claude/reference-site-build 2026-10-29 15:17:24 +01:00
Radosław SmolińskiandClaude Opus 5.5 8adac41f92 Reference site: Example Studio on ipal-kit (reference/), index for agents, CI job
reference/ is one complete client site on the plugin (made-up company, pl/en,
MongoDB, every library block and template, token standard light/dark, forms,
consent, SEO/GEO, enforced CSP, 2FA, base + demo seeds, Coolify runbook,
smoke tests). It uses the plugin as file:.. (injected) and is not shipped.

- docs/agent/reference-site/INDEX.md (generated by scripts/reference-index.mjs,
  kept current by test/referenceIndex.test.ts)
- AGENT.md section and pointers in ipal-site, ipal-setup, ipal-reference,
  ipal-upgrade, ipal-block; release steps in PROGRAMISTA §8.1b
- CI: reference (fast) on every push, reference-full on main; doctor steps
  wired, commented until ipal-doctor ships

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:17:11 +01:00
Radosław Smoliński d992d131a2 Merge claude/block-library-fixes: block fixes from the visual test, tokens on any element
The seven block fixes from the reference site's first visual test (entryList field
entryCollection: Mongoose reserves 'collection'; contact, hero, CMSLink, templates),
plus claude/design-tokens-build d6675d2: data-theme switches tokens on any element
(LIGHT_SELECTOR / DARK_SELECTOR), primary-inverse / primary-inverse-text roles in
the contrast report, theme.md one-icon note, ipal-form formClasses.ts on token
utilities. No conflicts; one Unreleased CHANGELOG section.

Merge addition: AGENT.md names primary-inverse-text next to primary-inverse.
2026-10-29 15:10:34 +01:00
Radosław SmolińskiandClaude Opus 5.5 570a90761b Merge claude/design-tokens-build (d6675d2): theme on any element, primary-inverse roles
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:05:14 +01:00
Radosław SmolińskiandClaude Opus 5.5 d6675d2979 Design tokens: themes on any element, primary-inverse, form template
Follow-ups from the reference site's first visual test:
- data-theme="dark"/"light" switches the tokens on any element (LIGHT_SELECTOR,
  DARK_SELECTOR as selector lists); the base layer colours a themed panel's text
- inverted sections re-map primary / primary-hover / primary-text to the new
  primary-inverse / primary-inverse-text roles; the contrast report checks them
  (inherited roles resolved on the ancestor, as the cascade does)
- ipal-form formClasses.ts on token utilities + buttonClass(); theme.md: one-icon
  ThemeSwitcher pattern (the default two-option toggle stays)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:04:54 +01:00
Radosław SmolińskiandClaude Opus 5.5 29ede3ad4b Block library: fixes from the first visual test on the reference site
- CMSLink: a link that wraps content (a logo, a card) and leads nowhere keeps the
  content — an empty link group ({ type: 'internal' }) no longer hides logos
- entryList: field `collection` → `entryCollection` (Mongoose reserves
  `collection`; unreleased, snapshot updated) + a test against reserved names
- post template starts with a page hero holding the title (the page's h1)
- legal and cookie policy templates set noindex: true (AGENT.md §0c)
- hero background: a full bg-overlay scrim under the text
- MediaValue accepts any object (generated Media types fit without a cast)
- contact: Turnstile renders dark in an inverted section

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 15:03:39 +01:00
Radosław SmolińskiandClaude Opus 5.5 8bb5ebd394 Reference site proposal (approved design, D1-D10)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:32:19 +01:00
Radosław Smoliński 51f80cea13 Merge claude/block-library-build: block library (15 blocks, /blocks, /blocks/rsc, /templates, ipal-blocks)
Fifteen opt-in library blocks (libraryBlocks({ ... }) from /blocks, rendered with
createBlockRegistry from /blocks/rsc), templates (/templates), the ipal-blocks
eject CLI and blockLibraryManifest; block sources ship in src/modules/block-library
for eject. Nothing is on by default; fields, variants, slugs, labels, part
classes, primitives and components are overridable. Seeder { $form } fix. Label
changes "New tab" / "Show contents" (no data change). Contains the design-tokens
branch (already merged). No conflicts; one Unreleased CHANGELOG section.
2026-10-29 14:30:42 +01:00
Radosław Smoliński f5dba85155 Merge claude/design-tokens-build: design tokens (tokens.css, tailwind.css, a11y.css, ipal-tokens)
One design-token standard: tokens.css (neutral defaults, light/dark on
data-theme), tailwind.css preset, a11y.css, fluid variables, the /tokens entry and
the ipal-tokens CLI. CookieBanner and CookieButton read the single token names;
the legacy -dark variables stay as the dark fallback, which now follows the
page's color-scheme (a site without a dark theme no longer gets a dark banner on
a dark-mode device). Font slots --font-family-body / --font-family-heading.
2026-10-29 14:30:26 +01:00
Radosław SmolińskiandClaude Opus 5.5 f338324762 Block library: styles step uses the token styles.css; test that every token utility exists in the preset
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:17:00 +01:00
Radosław SmolińskiandClaude Opus 5.5 e686fb2af5 Merge claude/design-tokens-build: design tokens (tokens.css, tailwind.css, ipal-tokens)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:14:17 +01:00
Radosław SmolińskiandClaude Opus 5.5 6e6de5d0cc Block library: noSnippet option for sections repeated on every page
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:13:37 +01:00
Radosław SmolińskiandClaude Opus 5.5 2a07fb8844 Block library: docs, agent guide, skills; picker order as an explicit list
- docs/block-library.md: setup, every block (fields, variants, accessibility),
  options, registry, primitives, eject, page templates, seeding after launch,
  versioning, manifest, turn off / override / extend
- AGENT.md (compass, how to add, §6, §6.3, module map), ipal-block (library
  block first), ipal-site (phases 2, 4, 6, 8), ipal-reference (wiring rows,
  export index), seed-content template from pageTemplates, seeding.md ($form)
- CHANGELOG Unreleased; proposal marked built with an as-built section

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:12:50 +01:00
Radosław SmolińskiandClaude Opus 5.5 2d1cc0e77d Block library: 15 blocks, registry, primitives, templates, manifest, eject
- @intecion/ipal-kit/blocks: libraryBlocks() opt-in, one builder per block, field
  builders, option merging, blockLibraryManifest, faqItemsFromLayout
- @intecion/ipal-kit/blocks/rsc: createBlockRegistry, the block components and UI
  primitives (token utilities only; next/image and next/link passed in)
- @intecion/ipal-kit/templates: 10 page templates as createSeeder data
- createSeeder: { $form: title } references
- ipal-blocks eject <block>
- tests: options, rendering and a11y per block, Payload + seeding, GraphQL, admin
  wording, schema snapshot (versioning), eject imports
- shorter admin labels: link "New tab", table of contents "Show contents"

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:05:47 +01:00
Radosław SmolińskiandClaude Opus 5.5 07d54da893 Design tokens: lint fixes (sorted catalogue, linear regexes), tokens.css regenerated
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:02:49 +01:00
Radosław SmolińskiandClaude Opus 5.5 cf205c59ef Design tokens: docs, agent guide, skills, audit checks
- docs/design-tokens.md (new module page), README index, CHANGELOG
- AGENT.md §0b row 19, §6.11 rewritten for the standard, §6.11a, §7, §10, §12, §14
- ipal-setup stage 5, ipal-block section-code (Section with data-surface, Button,
  card on token utilities), ipal-site phase 8, ipal-reference (+ api.md /tokens
  section), ipal-upgrade 1.15.0 note, ipal-audit SKILL + audit.sh token checks
- theme.md, consent.md, accessibility.md (a11y.css), lightbox.md, PROGRAMISTA §2.5
- /tokens entry lists its exports explicitly; docs coverage test includes it

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 14:00:31 +01:00
Radosław SmolińskiandClaude Opus 5.5 ca8e93eaf4 Design tokens: ipal-tokens CLI, components on single names, templates, tests
- bin ipal-tokens: src/design/tokens.ts → src/design/tokens.css, --check, WCAG
  contrast report (fails on AA errors; --report, --warn-only)
- CookieBanner / CookieButton read the single --ipal-* roles; the fallback follows
  color-scheme via light-dark() and still honours the legacy -dark variables
- lightbox fade reads --ipal-duration / --ipal-ease-out
- DESIGN.md and tokens.ts templates in ipal-setup/resources

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:55:59 +01:00
Radosław SmolińskiandClaude Opus 5.5 9511b12d19 Design tokens: tokens.css, tailwind.css, a11y.css and the TS token module
tokens.css (neutral --ipal-* defaults, light/dark, inverse scope, reduced motion) is
generated from src/modules/tokens/catalog.ts. tailwind.css maps the utilities.
New @intecion/ipal-kit/tokens entry: IPAL_TOKENS, ipalVar, IPAL_BREAKPOINTS,
defineTokens, tokensToCss, contrastReport, fluidClamp. fluid.css / fluid-wide.css
gain fs-xs, fs-h4, space-stack, space-section-sm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:52:37 +01:00
Radosław SmolińskiandClaude Opus 5.5 7918eaf6d4 Block library proposal: blockLibraryManifest export for ipal-doctor
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:44:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 48c2a3a5a8 Block library proposal: record the owner's decisions D1–D10
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:44:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 0eeb7cd280 Block library proposal: inverse section scope agreed with design tokens
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:44:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 c7e2d237e7 Block library proposal: use the agreed design token names
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:44:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 4ece5a5823 Block library proposal (design only)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:44:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 500c534bc9 Design tokens proposal: fluid-wide in the styles.css example
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:44:55 +01:00
Radosław SmolińskiandClaude Opus 5.5 18075bb7df Design tokens proposal: record approved decisions
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:44:55 +01:00
Radosław SmolińskiandClaude Opus 5.5 9286468ce9 Design tokens proposal: inverse surface scope
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:44:55 +01:00
Radosław SmolińskiandClaude Opus 5.5 655b12a232 Design-token standard proposal (draft for approval)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:44:55 +01:00
Radosław Smoliński 0ed3898370 Merge claude/db-names-seed-after-launch: database name rule, seeding after launch
Database name rule <domain without dots>_prod / _dev; ipalEnvRules({ databaseName })
warns only (default off); databaseNamesFor, databaseNameFromUri, checkDatabaseName.
createSeeder only / SEED_ONLY: a run touches named records only; a full seed of
production or a non-local database is refused unless IPAL_SEED_ALLOW_FULL=1 or
guard.allowFull (dry runs never refused, guard: false turns guards off).

Merge additions: CHANGELOG "## Unreleased" with Requires project changes;
guard.allowFull and guard: false in ipal-reference SKILL.md and api.md.
2026-10-29 13:29:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 af7d96f0e3 Database naming rule; seeding after launch touches named records only
- Rule (VERY IMPORTANT): databases are named <domain without dots>_prod /
  _dev (intecion.com → intecioncom_prod / intecioncom_dev) on MongoDB and
  Postgres — AGENT.md top rules, deployment.md §4.2a (Coolify), env.md,
  ipal-setup architecture questions (derive, then confirm), AGENTS.md
  template. ipalEnvRules({ databaseName }) warns (never fails) on a
  mismatch, domain from NEXT_PUBLIC_SERVER_URL or { domain }, { warn }
  overridable; helpers databaseNamesFor, databaseNameFromUri,
  checkDatabaseName from the root and /env.
- Rule (VERY IMPORTANT): after launch never re-seed everything — AGENT.md,
  seeding.md, ipal-site, ipal-form, ipal-reference. createSeeder gains
  `only` / SEED_ONLY (pages:slug, forms:title, global:slug, collection:*;
  the rest → "skip (not listed)") and refuses a run with no record list
  against a production / non-local database unless IPAL_SEED_ALLOW_FULL=1
  (guard.allowFull; dry runs allowed). Seed templates carry an ONLY list;
  the form seed touches only its own form.
- Tests: seed only/full-run guard, database-name helpers and warning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 13:27:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 9ecab39783 1.14.6 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade and PROGRAMISTA §6 item 54 point at 1.14.6 (1.14.5 never
published), with the 1.14.5 steps kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:21:21 +01:00
Radosław SmolińskiandClaude Opus 5.5 c407ed33fc 1.14.6
Version bump and CHANGELOG entry: the admin link-preview hook fix; 1.14.5 was
tagged but never published, projects go from 1.14.4 to 1.14.6 with the 1.14.5
steps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:21:21 +01:00
Radosław SmolińskiandClaude Opus 5.5 71f7108cb8 Admin link-preview hook never throws without a Payload instance
syncAdminMeta returned to payload.logger in its catch even when payload was
undefined, so the Site settings afterChange hook threw with req: {} (an
unhandled rejection that made vitest, and npm publish for 1.14.5, exit 1).
Return early without payload, log through payload?.logger, skip the call in the
hook without req.payload; the fillEmptyLocales hooks get the same guard. Tests:
sync without payload, and every plugin global afterChange hook with req: {}.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:21:21 +01:00
Radosław SmolińskiandClaude Opus 5.5 838a2f70b2 1.14.5 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade: one "→ 1.14.5" section with the 7 steps (replaces the two
unversioned notes). PROGRAMISTA §6: item 54. seo.md points at 1.14.5.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:13:57 +01:00
Radosław SmolińskiandClaude Opus 5.5 53f9010910 1.14.5
Version bump; the Unreleased section becomes 1.14.5: GraphQL 500 fix (title
separator enum names), theme key 'theme', cookie storage type, admin link
previews (adminMeta, agency), graphql-scalars override, agent rules and
external skills; what projects update (7 steps incl. Postgres titleSeparatorSql).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:13:57 +01:00
Radosław Smoliński 8c61951a26 Merge claude/agent-rules-arch: architecture questions first, ipal-kit first, external skills
Agent guide and skills: ask architecture questions before building, use ipal-kit
first (report a gap and wait), code rules. Five vendored third-party skills (text
only, pinned SHAs, licences, sha256 manifest in docs/agent/external), copied only
with ipal-skills --external. scripts/vendor-external-skills.mjs is a maintainer
script and is not shipped.
2026-10-29 12:11:28 +01:00
Radosław Smoliński 0fc9add2b6 Merge claude/graphql-enum-names: fix /api/graphql 500 (title separator enum names)
Site settings -> Title separator values are GraphQL enum names (pipe, endash,
hyphen, middot, slash); legacy stored characters map on read and write, MongoDB
is rewritten on init, Postgres projects add titleSeparatorSql() to the generated
migration. test/graphqlSchema.test.ts builds the full schema.

Merge resolution, docs/CHANGELOG.md (one Unreleased section): both new
"What projects must update" items kept — 5 graphql-scalars override, 6 title
separator SQL, plus a note that code reading settings.titleSeparator gets a name
(titleSeparatorChar).
2026-10-29 12:11:21 +01:00
Radosław Smoliński 6702553e69 Merge claude/deps-graphql-scalars: override graphql-scalars to ^2.0.1
Repo-only pnpm override "graphql-scalars@<2.0.1": "^2.0.1" (GHSA-x8rm-f576-gq67,
high, via @payloadcms/graphql); the docs recommend it to projects on payload
3.90.x-3.92.x. pnpm audit --prod: only the deepmerge low.
2026-10-29 12:11:00 +01:00
Radosław SmolińskiandClaude Opus 5.5 bb10fb10fd Fix /api/graphql 500: Site settings title separator values are GraphQL enum names
The titleSeparator select stored '|', '–', '-', '·', '/'. Select values become
GraphQL enum names; '|', '–', '·' are invalid and '-' and '/' collide on '_', so
every project's /api/graphql answered 500 since 1.0.1 (admin/REST unaffected).

- Values are now pipe/endash/hyphen/middot/slash (same labels); TITLE_SEPARATORS
  and titleSeparatorChar map them to the character; titles accept old characters
  and custom project values literally
- Field afterRead/beforeChange turn an old stored character into its name
- MongoDB: rewritten at start (migrateTitleSeparator); Postgres: titleSeparatorSql()
  for the generated migration (verified up/down/up against Postgres 16)
- Test builds the full plugin GraphQL schema and fails on invalid or duplicate
  enum names; unit tests for the mapping, hooks, SQL and Mongo rewrite
- CHANGELOG Unreleased (Fixed + upgrade step 5), seo.md, ipal-upgrade, api.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:06:55 +01:00
Radosław SmolińskiandClaude Opus 5.5 e1f82ce387 ipal-skills --external: vendored third-party agent skills, pinned
- docs/agent/external: Vercel react-best-practices and composition-patterns
  (MIT), Addy Osmani accessibility (MIT), Anthropic frontend-design
  (Apache-2.0), official Payload skill at v3.92.1 (MIT) — text only, each
  with its licence, SOURCE.md (repo, commit) and an override note in front
  of the SKILL.md (ipal-kit first, Payload fetching over swr, DESIGN.md
  tokens, Payload 3 not 4); manifest.json with sha256 per file
- scripts/vendor-external-skills.mjs (maintainer, not shipped): fetches by
  full commit SHA only, rejects non-text or executable files, regenerates
  the manifest; --check verifies it
- ipal-skills --external [names]: copies ext-* after checking every file
  against the manifest, downloads nothing, never touches ext-* folders
  without ipal-kit's SOURCE.md, removes only retired ones it installed;
  an unknown name stops the run before anything is copied
- AGENT.md §14, ipal-setup stage 2 (optional step), README: usage,
  overrides, how to update the pins
- test/externalSkills.test.ts: pins are SHAs, no branch fetch, checksums,
  text only, licences, override note, installer leaves other folders alone

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:54:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 927798105e Security: override graphql-scalars to ^2.0.1 (GHSA-x8rm-f576-gq67)
@payloadcms/graphql pins graphql-scalars 1.22.2 up to the latest Payload
(3.92.1), so no Payload upgrade fixes the high PhoneNumber ReDoS advisory.
Repo-only pnpm.overrides entry "graphql-scalars@<2.0.1": "^2.0.1" (not passed
to projects). Payload only imports DateTimeResolver and EmailAddressResolver;
checked against the dev app's /api/graphql: login, DateTime and EmailAddress
as input and output, a JSON field, and an invalid e-mail rejected.

pnpm audit --prod: 1 high + 1 low -> 1 low (deepmerge, no fix published).
Docs: AGENT.md §4 item 12, ipal-setup, ipal-upgrade, README, CHANGELOG
Unreleased recommend the same override to projects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:50:51 +01:00
Radosław SmolińskiandClaude Opus 5.5 25719ae7ec Agent guide: ask architecture questions first, ipal-kit first, code rules
- AGENT.md: "Ask before you build" (languages, styling, content, forms,
  analytics/consent, SEO/GEO, database + media, admin, hosting/DNS) —
  answers go to AGENTS.md "Project decisions", never guessed; "ipal-kit
  first" hard rule — a gap is reported to the owner and the agent waits
  for the decision, no hand-built replacements or silent workarounds;
  short "Code rules" (SRP, small files, no duplicates, typed, i18n texts,
  checks) pointing to §8
- ipal-setup stage 0 and ipal-site phase 0: the architecture question
  list, answered before building; content questions keep defaults
- ipal-plugin-gap: report, offer options, wait, record the decision;
  ipal-block/collection/form/debug and vibe aligned; AGENTS.md template
  and the ipal-skills pointer block carry the rules
- docsConsistency: the rules reach every site-building skill

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:46:50 +01:00
Radosław Smoliński f57d089f55 Merge claude/admin-white-label-meta: admin link previews, agency option
adminMeta (default on): panel title suffix, description, og:site_name, preview
image (/api/ipal/admin-og) and icon (/api/ipal/admin-icon) from Site settings,
robots noindex,nofollow on /admin; per-piece overrides, adminMeta: false, the
project's admin.meta wins. agency option (default Intecion.com, false = none).

Merge resolution:
- docs/CHANGELOG.md: one Unreleased section covering storage-keys and this
  branch (Changed: credit text; New: adminMeta, agency; upgrade step 4).
- dev importMap.js: regenerated with IPAL_DEV_2FA=1, so it keeps the TOTP
  entries (2FA fix) and adds AdminIcon, AdminLogo, IntecionCredit (whiteLabel).
2026-10-29 11:38:17 +01:00
Radosław Smoliński 3d16db5c22 Merge claude/storage-keys: theme key 'theme', storage types in the cookie list
Theme choice stored under 'theme' (theme.storageKey to change it); a choice under
the old 'ipal-theme' key moves once, before paint, and only into an empty key.
Cookie scanner integration "Theme choice" for the localStorage key. A storage
select on Cookies -> Cookie list rows and in the detail labels, with a Type
column in <CookieTable> (Postgres: enum + cookie_settings_cookies.storage +
detail_labels_storage).
2026-10-29 11:37:15 +01:00
Radosław SmolińskiandClaude Opus 5.5 0629cf7595 Cookie scanner: Polish names of the storage types match the cookie list
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:31:58 +01:00
Radosław SmolińskiandClaude Opus 5.5 3c828d963d Admin link previews: site name, description, preview image, noindex; technology support credit
- adminMeta (default on, with or without whiteLabel): robots noindex/nofollow,
  title suffix "— <site> | Panel", og:site_name and en/pl description from
  Site settings, preview image GET /api/ipal/admin-og (next/og, from the logo
  or name, no external service) and icon GET /api/ipal/admin-icon
- the site name sits in a process-wide store read through getters, so link
  previews stay current after a Site settings save and across config loads
- agency option (default Intecion.com) feeds the credit, description and image;
  credit reads "Technology support: Intecion.com" (pl: Wsparcie technologiczne)
- the project's own admin.meta keys always win; adminMeta: false / agency: false
- dev: whiteLabel on; docs: white-label.md, AGENT.md, ipal-reference/setup/upgrade

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:31:42 +01:00
Radosław SmolińskiandClaude Opus 5.5 b5368cdc61 Theme key 'theme', storage keys in the cookie scanner, type in the cookie list
- Theme choice in localStorage under 'theme' (next-themes' key and values)
  instead of 'ipal-theme'. ThemeScript moves an old choice before the first
  paint and removes the old key; useTheme / ThemeSwitcher do the same
  without the script. ipalKit({ theme: { storageKey } }) sets an own key,
  which reaches ThemeScript through getSiteShell().theme and <html
  data-theme-storage>.
- The cookie scanner declares the theme key (Theme choice: local storage,
  necessary, until changed or site data is cleared) when the theme switch
  is on, so Scan cookies finds it without a crawl.
- Cookies -> Cookie list rows get a Type (cookie / local storage / session
  storage, default cookie, shared by every language), filled by scan, review
  and approval. The detailed settings window and <CookieTable> show it with
  English and Polish defaults; the approval page marks storage entries.
- Migration: adds cookie_settings_cookies.storage (DEFAULT 'cookie') and
  cookie_settings_locales.detail_labels_storage, nothing else.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:29:56 +01:00
Radosław SmolińskiandClaude Opus 5.5 6998b44431 1.14.4 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade: "→ 1.14.4" section. PROGRAMISTA §6: item 53.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 23:02:00 +01:00
Radosław SmolińskiandClaude Opus 5.5 e1f42615f3 1.14.4
Version bump and CHANGELOG entry: fillEmptyLocales (empty languages of the
cookie texts filled, own text never overwritten), cookieScanner.adminLayout
'combined' (one Cookies entry with Review and approve / Site check tabs), Cookie
banner renamed Cookies, known issue, what projects update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 23:02:00 +01:00
Radosław Smoliński eab26c98ca Merge claude/cookie-admin-merge: fill empty languages, one Cookies entry in the admin
fillEmptyLocales (default on): text written in one language fills the empty
languages of cookie-list and cookie-review purpose/duration; a language with its
own text is never overwritten (false or per-slug fields to change it).
cookieScanner.adminLayout (default 'combined'): the Cookie banner global is
"Cookies" with "Review and approve" and "Site check" tabs; cookie-review and
cookie-crawl leave the navigation, their data, API and /admin/cookie-approval
stay ('separate' keeps the old entries). No schema change (Postgres
migrate:create: no schema changes).
2026-10-28 23:00:41 +01:00
Radosław SmolińskiandClaude Opus 5.5 cad299c132 Remove a local dev-server launch file committed by mistake
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:57:35 +01:00
Radosław SmolińskiandClaude Opus 5.5 49e27175ae Dev app: import map entries for the Cookies tabs
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:57:24 +01:00
Radosław SmolińskiandClaude Opus 5.5 b10c2dc0e3 Cookies: fill empty languages, and one Cookies entry in the admin
Every language filled (fillEmptyLocales, default on): text saved in one
language goes to every language where the same field is still empty, never
over a language's own text. Applies to the cookie list (purpose, duration)
and the cookie review (purpose, duration). Scanner and approval writes give
a language without its own text the default language's text. Building
blocks: buildFillEmptyLocalesGlobalHook / CollectionHook, fillEmptyLocales,
withFillLocales.

One Cookies entry (cookieScanner.adminLayout, default combined): the
Cookie banner global is now labelled Cookies and gets Review and approve
(scan box and approval list inline) and Site check tabs, built from ui
fields. Cookie review and Cookie check leave the navigation
(admin.group false) but keep their pages, data and API. This is
presentation only: no schema change and no migration, only
generate:importmap. adminLayout separate keeps the old layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:55:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 a9e1adc03b 1.14.3 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade: "→ 1.14.3" section for the cookie approval flow. PROGRAMISTA §6:
item 52.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:26:53 +01:00
Radosław SmolińskiandClaude Opus 5.5 44598bbef2 1.14.3
Version bump and CHANGELOG entry: Approve cookies page with one Approve and add,
New/Changed/Needs description/No longer found markers, unknownCategory,
dashboard and e-mail reminders, approval: false, new exports, the lookup change
for hand-typed rows, and what projects with cookieScanner update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:26:53 +01:00
Radosław Smoliński 5f4f2a07ab Merge claude/cookie-approve: one approval for everything a cookie scan finds
/admin/cookie-approval (Approve cookies): one "Approve and add" for the ticked
cookies into Cookie banner -> Cookies in every locale; statuses New, Changed,
Needs description, No longer found; never overwrites editor text, never
duplicates or deletes. Unknown cookies -> approval.unknownCategory (default
marketing). Dashboard and e-mail reminders. cookieScanner.approval: false keeps
the per-entry review. New cookie-review fields change and needsDescription
(Postgres: one enum column + index, one boolean).
2026-10-28 22:23:24 +01:00
Radosław SmolińskiandClaude Opus 5.5 9b9c5fc872 Dev app: import map entry for the cookie approval view
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:20:51 +01:00
Radosław SmolińskiandClaude Opus 5.5 86ff3f5ff7 Cookie scanner: one approval for everything a scan finds
After "Scan cookies" or a site check, the new Approve cookies view
(/admin/cookie-approval) lists what waits, grouped by consent category, with
provider, purpose and duration and New / Changed / Needs description markers.
One "Approve and add" puts every ticked cookie into Cookie banner -> Cookie
list in every locale. That list feeds the cookie policy table and the
detailed settings window.

- Never overwrites editor text or categories, never adds a second row (a
  pattern and a concrete name are the same cookie), never deletes.
- Unknown cookies are approved into a category that needs consent
  (approval.unknownCategory, default marketing) and flagged Needs
  description; writing a purpose clears the flag.
- Cookies a scan or crawl no longer finds are flagged No longer found, for
  review only.
- The dashboard and the crawl e-mail say how many cookies wait and link to
  the view; nothing is added without approval.
- Optional: cookieScanner.approval false keeps per-entry review.
- Migration: cookie-review gains change and needsDescription.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 22:17:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 0e7966dfbb 1.14.2 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade, PROGRAMISTA §6 item 51 and security.md point at 1.14.2 instead of
"after 1.14.1".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 21:34:09 +01:00
Radosław SmolińskiandClaude Opus 5.5 2cadb425d6 1.14.2
Version bump; the Unreleased section becomes 1.14.2: 2FA setup-loop fix
(TotpRedirectProvider), twoFactor.provider, totpRedirectTarget/totpAdminPath,
known issue (low deepmerge advisory via payload), what projects with 2FA update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 21:34:09 +01:00
Radosław Smoliński 41065940e8 Merge claude/recursing-wright-be31dd: fix the 2FA setup loop
ipal-kit swaps @clocklimited/payload-2fa's TOTPProvider (it read the path from an
x-pathname header nothing sets on /admin, so setup-totp?back=null redirected to
itself) for TotpRedirectProvider (/admin), which reads the path in the browser.
twoFactor.provider: own component, or false to keep the package's. Pure rules:
totpRedirectTarget, totpAdminPath. Server-side TOTP enforcement (the package's
access wrapper) is unchanged. Dev app: IPAL_DEV_2FA=1 turns 2FA on.
2026-10-28 21:30:03 +01:00
Radosław SmolińskiandClaude Opus 5.5 60f744e3ad Fix the 2FA setup loop: setup-totp?back=null redirected to itself
@clocklimited/payload-2fa's admin provider reads the current path from an
x-pathname request header. Nothing sets it on /admin (the createProxy matcher
skips /admin), so the path was null: every admin page, the setup screen too,
redirected to /admin/setup-totp?back=null, forever. Every new admin on a site
with 2FA got stuck.

ipalKit now swaps that provider for its own TotpRedirectProvider
(@intecion/ipal-kit/admin, client-side): it reads the path in the browser,
never redirects away from the setup/verify screens or logout, and renders
nothing while redirecting. twoFactor.provider takes a project component, or
false to keep the package's. totpRedirectTarget / totpAdminPath export the
rules. Projects run generate:importmap.

Test: test/totpRedirect.test.ts (redirect walk, provider swap). Dev app:
IPAL_DEV_2FA=1 turns 2FA on. Docs: security.md, CHANGELOG (Unreleased),
AGENT.md, ipal-setup/-upgrade/-debug/-reference, PROGRAMISTA item 51.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 21:27:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 4e254057f9 1.14.1 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade: the X-Powered-By/CSP section is now "→ 1.14.1". PROGRAMISTA §6:
item 50 for 1.14.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 21:53:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 cdf80744ea 1.14.1
Version bump and CHANGELOG entry: withSecurityConfig (hide X-Powered-By),
opt-in CSP through buildSecurityHeaders({ csp }) with report-only/enforce and
reports, createCspReportRoute, buildAdminCspHeaders, opt-in nonces, new buildCsp
flags with extra/override, ipal-audit header check; nothing required on upgrade.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 21:53:22 +01:00
Radosław Smoliński 86ff9e3df0 Merge claude/csp-powered-by-ee307c: hide X-Powered-By, opt-in CSP with reports, admin policy, nonces
withSecurityConfig hides X-Powered-By (hidePoweredBy: false to keep it).
buildSecurityHeaders({ csp }) is off unless passed; report-only first, then
enforce, with reportUri / Reporting-Endpoints. buildCsp flags with extra and
override, buildAdminCsp(Headers), createCspReportRoute. Nonces only with
createProxy({ csp }) + SiteProviders nonce, so static and ISR pages stay static.
2026-10-27 21:37:39 +01:00
Radosław SmolińskiandClaude Opus 5.5 ff4c595b91 Security: hide X-Powered-By, CSP report-only with reports, admin policy and nonces
- withSecurityConfig: poweredByHeader false + strips X-Powered-By from headers()
  (Next's and withPayload's), works on either side of withPayload
- buildSecurityHeaders({ csp }): CSP + Reporting-Endpoints; mode switches
  report-only → enforce
- buildCsp: reportUri/reportGroup, nonce + strict-dynamic, dev unsafe-eval,
  metaPixel/linkedIn/tiktok/clarity flags, media-src for R2, override
- buildAdminCsp(Headers): looser policy for Payload admin (Monaco CDN, blob workers)
- createCspReportRoute + parseCspReports: report collector for both formats
- createProxy({ csp }) + createCspNonce: per-request nonce, x-nonce header;
  SiteProviders/ThemeScript/Analytics/ConsentScript accept nonce
- docs: security.md, AGENT.md, ipal-setup/reference/upgrade; ipal-audit checks

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 21:28:11 +01:00
Radosław SmolińskiandClaude Opus 5.5 771dda1c6f 1.14.0 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade: the 1.14.0 section walks through the 8 "What projects must
update" items. PROGRAMISTA §6: item 48 marked 1.14.0, new item 49.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 16:52:47 +01:00
Radosław SmolińskiandClaude Opus 5.5 2051a01190 1.14.0
Version bump and CHANGELOG entry: image lightbox, cookie scanner (scan and
browser crawl), admin in English and Polish, admin follow-ups, Next 16.4.3 and
sharp 0.35.5 in dev, nodemailer 10 and Node >=20.9, test/dev generate:types fix,
and what projects must update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 16:52:47 +01:00
Radosław Smoliński 117d5c642d Merge claude/deps-audit-nodemailer-2fa: dependency advisories
nodemailer ^8 -> ^10.2.1 (ships its own types; @types/nodemailer removed),
engines.node >=20.9.0. Repo-only pnpm.overrides for Payload's transitive
dependencies (undici, dompurify, fast-uri, js-yaml, browserslist, source-map-js,
fast-copy, baseline-browser-mapping); consumers are not bound by them, and the
docs recommend the dompurify/undici overrides for projects on payload 3.90.x.
pnpm audit --prod: no known vulnerabilities. New emailTransports and twoFactor tests.
2026-10-27 16:45:07 +01:00
Radosław SmolińskiandClaude Opus 5.5 007a0a3ae6 Dependency advisories: nodemailer 10, overrides for Payload's pinned deps
- nodemailer ^8.0.1 -> ^10.2.1 (advisories up to 10.1.3); drop @types/nodemailer,
  nodemailer 10 ships its own types. Node engines >=20.9.0 (nodemailer 10 needs 20+).
- pnpm.overrides (repo only, not passed to projects) for packages in payload 3.90.2's
  tree: undici and dompurify are exact-pinned upstream; fast-uri, js-yaml,
  browserslist, source-map-js, fast-copy, baseline-browser-mapping raised to fixed
  minimums. pnpm audit --prod: 19 high / 35 moderate / 11 low -> 0.
- Tests: SMTP over a local SMTP socket with real nodemailer (panelSmtpAdapter,
  sendEmail, unreachable server status), Microsoft Graph and Graph->SMTP fallback
  via mailAdapter; real payloadTotp through ipalKit, plus a check that payload-2fa
  resolves the project's payload.
- Docs: email.md, AGENT.md §4 item 12, ipal-setup, ipal-upgrade, README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 16:42:05 +01:00
Radosław Smoliński 54fb57b7a9 Merge claude/relaxed-joliot-25dcb3: Next 16.4.3 and admin follow-ups
Dev dependencies: next and eslint-config-next 16.4.3, sharp 0.35.5 (fixes the
Next 16.0.0-16.4.0 advisories: 2 critical RCE, 1 high DoS); minimum safe Next
16.4.1 documented; peer range next >=15 unchanged.
Admin follow-ups: localised stats tab title (DocumentTitle), Polish cookie-scanner
integration names, construction notice close label, FaviconCheck hint under
Site settings -> Site icon (new import-map entry @intecion/ipal-kit/admin#FaviconCheck).
2026-10-27 16:34:01 +01:00
Radosław SmolińskiandClaude Opus 5.5 546806fe39 Admin follow-ups: localised stats tab title, scanner names, close label, favicon hint
- Statistics view: the browser-tab title follows the admin language.
  Payload's custom-view meta.title is one plain string and its custom-view
  metadata ignores i18n, so the view renders <DocumentTitle> (/admin) with the
  translated title; it re-applies the title while the view is open because
  Next streams the English metadata in after hydration. adminDocumentTitle()
  adds admin.meta.titleSuffix the way Payload does.
- Cookie scanner: CookieIntegration.label may be { en, pl, ... }. The built-in
  names without a product name come from the shared admin texts
  (cookieIntegration*, cookieSourceProject); the scan endpoint answers in the
  request's admin language and stored source names use the scanning editor's.
- Maintenance notice: getConstructionMode(locale) returns `locale`; the "x"
  close button gets a screen-reader name "Close" / "Zamknij" (locale and
  closeLabel props; constructionCloseLabel exported).
- Favicon: FaviconCheck (/admin, afterInput on Site settings -> Site icon)
  warns in the admin language when the image is under 48x48 or not square,
  without blocking the save; validateFaviconField shares faviconProblems().
- Docs, AGENT.md and skills: the above, plus Next.js 16.4.1 or later as the
  minimum safe version (AGENT.md 4.11, ipal-setup, ipal-upgrade).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 16:31:46 +01:00
Radosław SmolińskiandClaude Opus 5.5 6f32ea4cdb Dev dependencies: next and eslint-config-next 16.4.3, sharp 0.35.5
Next 16.0.0-16.4.0 is affected by GHSA-2464-fhr4-w9xw (RCE in image
optimization with SVG, fixed with sharp 0.35.5), GHSA-673q-mjm6-r5xr
(RCE in use cache) and GHSA-p3m5-59mp-jv5r (Server Actions DoS); all
fixed in 16.4.1. The peer range stays open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 16:20:13 +01:00
Radosław Smoliński e475f476d3 Merge claude/admin-ux-wording-9e043e: admin in English and Polish, reworded
Admin languages default to English + Polish unless the project sets
i18n.supportedLanguages; plugin texts under the ipal namespace, project
translations win key by key. All admin wording rewritten and fields regrouped
per docs/dev/admin-ux.md, without changing slugs, field names or the schema
(Postgres migrate:create: no schema changes). Dev app no longer leaks
generate:types; test/adminUx.test.ts.
2026-10-27 16:18:41 +01:00
Radosław SmolińskiandClaude Opus 5.5 2dafcd0852 Tests: fix test-project typecheck (casts, Rule arity) and base-to-string lint warnings
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 16:17:40 +01:00
Radosław SmolińskiandClaude Opus 5.5 a92bc51814 Admin wording follow-ups from the browser check
- stats nav link reads "Statistics overview" (it renders after all nav groups)
- form-builder e-mails array labelled in en + pl
- dev import map: RowLabel (cookie banner rows)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:49:37 +01:00
Radosław SmolińskiandClaude Opus 5.5 0a2374db18 Docs: admin languages and texts, wording rule for agents, new screen names
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:46:25 +01:00
Radosław SmolińskiandClaude Opus 5.5 6b46bc0c14 Admin panel in English and Polish, reworded per docs/dev/admin-ux.md
- admin-i18n module: AdminText { en, pl }, component texts under the ipal
  namespace (project translations win), en + pl admin languages when the
  project sets none (project's supportedLanguages wins)
- every plugin label, description, option, tab and group as { en, pl };
  explicit labels instead of auto-labels; sentence case; glossary terms
- visible renames (slugs, names, data unchanged): Cookie banner, Form
  messages, Privacy group, Search engines, Maintenance, Spam protection,
  E-mail sending, stats nav link Overview (hidden without access)
- Polish visitor defaults by page locale: cookie banner, form messages,
  validators, lightbox, accessibility widget; {field} uses the label
- fixes: e-mail status banner used Turnstile wording; developer words and
  env var names out of editor messages; stats numbers/dates in the admin
  language; test e-mail no longer says ipal-kit
- test/adminUx.test.ts: length limits, en + pl present, no developer words

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:46:25 +01:00
Radosław Smoliński eeac33ed2f Merge commit '77b826e' into claude/admin-ux-wording-9e043e 2026-10-27 15:29:39 +01:00
Radosław SmolińskiandClaude Opus 5.5 839c34ab6f dev: stop Payload spawning generate:types on every dev start (orphan leak)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:29:39 +01:00
Radosław Smoliński 77b826e6d8 Merge claude/cookie-scanner-eef8a8: cookie scanner phases 1 and 2
cookieScanner option: cookie-review collection, Scan cookies (declarations +
bundled Open Cookie Database), opt-in browser crawl through
services/cookie-crawler with the cookie-crawl global and dashboard alert.

Overlap with claude/test-no-typegen, resolved here: one test-config fix.
- the six real-Payload tests keep buildTestConfig and drop the branch's
  duplicate typescript: { autoGenerate: false } lines;
- cookieScannerIntegration and cookieCrawlIntegration use buildTestConfig
  instead of buildConfig + their own flag (testConfig.test.ts guard passes).
2026-10-27 15:26:44 +01:00
Radosław Smoliński cb7e21de20 Merge claude/image-lightbox-15eabd: shared image lightbox
LightboxProvider / LightboxTrigger / LightboxDialog and lightboxImage from
/client, RenderRichText lightbox, SiteProviders lightbox, opt-in Notifications
labels (ipalKit lightbox: true), docs/lightbox.md and agent guide.
2026-10-27 15:26:31 +01:00
Radosław Smoliński 5d587760de Merge claude/test-no-typegen: tests boot Payload without type generation
buildTestConfig (test/helpers.ts) turns typescript.autoGenerate off for the six
real-Payload tests; test/testConfig.test.ts fails if a test calls buildConfig
directly.
2026-10-27 15:26:31 +01:00
Radosław SmolińskiandClaude Opus 5.5 433984e1e1 Cookie scanner: fixes from the browser test in the dev app
- The admin box uses Payload's Button (plain <button class="btn"> rendered
  unstyled), shows "Never run" before the first crawl and the note on a
  finished crawl (e.g. "Accept all" not found).
- The dashboard warning puts its link on its own line.
- Dev sandbox: cookieScanner { crawl: true } and the regenerated import map.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:21:17 +01:00
Radosław SmolińskiandClaude Opus 5.5 4bb9c663fd Cookie scanner, phase 2: browser crawl through a shared scanner service
cookieScanner.crawl (opt-in) adds "Crawl site" to the Cookie review box. The
site asks the shared scanner service (services/cookie-crawler: Node +
Playwright, Dockerfile, deployed once on Coolify) to crawl its sitemap pages
twice, with no consent and after "Accept all". The service posts cookies,
storage keys and third-party hosts back to POST /api/ipal/cookie-crawl/results
(bearer token, running job only). No browser in the site.

Findings land as drafts through the same merge rules. Anything stored before
consent that is not necessary, and tracker requests before consent, are
violations, flagged on the review entries from the latest crawl only. The
cookie-crawl global keeps the latest result (no history). A dashboard warning
(CookieCrawlAlert) and an opt-in e-mail through the project's mail adapter
follow a crawl with violations or new unknown cookies. Scheduled crawls: a
Coolify scheduled task with the token. ipalEnvRules({ cookieCrawl: true }).

Also: the six older real-Payload tests no longer leave an orphaned
payload generate:types process (typescript.autoGenerate: false).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:14:01 +01:00
Radosław SmolińskiandClaude Opus 5.5 c7c8c819ac admin-ux guide: Privacy group, label naming, default admin languages
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:13:22 +01:00
Radosław SmolińskiandClaude Opus 5.5 4c55d7aeff Admin wording and layout guide (docs/dev/admin-ux.md); dev editor login
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 15:10:49 +01:00
Radosław SmolińskiandClaude Opus 5.5 53a8920564 Tests: boot Payload without type generation, guard against the leak
Outside production getPayload() spawns a detached generate:types child.
With no PAYLOAD_CONFIG_PATH it never finds a config (tsconfig rootDir
'./' sends Payload's findUpSync into an endless loop), so every full
vitest run left six processes spinning at ~40% CPU.

- test/helpers.ts: buildTestConfig() = buildConfig with
  typescript.autoGenerate false
- the six tests that boot Payload use it
- test/testConfig.test.ts: fails if a test calls buildConfig directly

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 14:59:41 +01:00
Radosław SmolińskiandClaude Opus 5.5 4f69f6ed20 Cookie scanner test: no generate:types child on Payload init
Outside production, getPayload() spawns `payload generate:types` in the
background and that process never exits, leaving one orphan per test file
per run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 14:57:21 +01:00
Radosław SmolińskiandClaude Opus 5.5 a0545b6716 Cookie scanner, phase 1: declarations, database lookup, review list
ipalKit({ cookieScanner }) (opt-in) adds the cookie-review collection, a
"Scan cookies" box above its list and GET/POST /api/ipal/cookie-scan. A scan
lists the cookies of every integration the project switches on (consent,
admin login, locale, stats, GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok,
Turnstile), the project's own declarations, and extra names looked up in the
bundled Open Cookie Database, as drafts. Editors accept (→ Cookie Settings →
Cookies, every locale, only empty text filled), edit or reject. A rescan never
deletes, never changes status and never overwrites edited text.

Everything is overridable (access, collectionOverrides, integrations,
declarations, databaseCategories, labels, syncAccepted) and the building
blocks are exported. Admin labels in en + pl. Docs: cookie-scanner.md,
consent.md, AGENT.md, ipal-reference, ipal-consent-check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 14:55:20 +01:00
Radosław SmolińskiandClaude Opus 5.5 ab45cf48be Bundle the Open Cookie Database (Apache-2.0) with a refresh script
scripts/refresh-cookie-database.mjs (pnpm cookie-db:refresh) downloads the CSV
and license at a pinned commit, refuses a non-Apache license, and writes
src/modules/consent/scanner/data/openCookieDatabase.ts (source commit and
change notice in the header) plus docs/licenses/open-cookie-database-LICENSE.txt.
Nothing is fetched at runtime.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 14:55:19 +01:00
Radosław SmolińskiandClaude Opus 5.5 7eacf1e713 Docs: image lightbox page, agent guide, skills, audit check, upgrade note
- docs/lightbox.md: setup, sizes, styling, overrides, migration from a
  hand-made modal or glightbox
- AGENT.md (§6.9, §7 catalog, §7.1, §12), ipal-reference (option, wiring,
  api.md section), ipal-site and ipal-block steps, PROGRAMISTA §6 row 48
- ipal-audit warns about lightbox libraries
- notifications.md, richtext.md, media.md, frontend.md, README index

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 14:49:38 +01:00
Radosław SmolińskiandClaude Opus 5.5 476c3ac1df Shared image lightbox: LightboxProvider, LightboxTrigger, LightboxDialog, lightboxImage
Opt-in click-to-enlarge for small images (cards, galleries, rich text):
- /client: LightboxProvider (one viewer per site), LightboxTrigger (button
  around any thumbnail, works without a provider), LightboxDialog
  (controlled viewer), useLightbox / useOptionalLightbox
- accessible dialog: aria-modal, focus trap and return, Esc, arrows,
  Home/End, swipe, counter, caption, scroll lock, reduced motion
- lightboxImage builds src + srcSet from Payload image sizes
- labels: ipalKit({ lightbox: true }) adds Notifications -> Lightbox;
  getNotificationTexts().lightbox and getSiteShell().lightboxTexts,
  English fallbacks otherwise
- RenderRichText lightbox / withLightboxUploads wrap image uploads
- SiteProviders lightbox mounts the provider
- styling from --ipal-lightbox-* variables; unstyled + classNames,
  renderImage, renderDialog, icons, loop overrides
- tests with happy-dom (vitest's pinned optional peer)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 14:49:38 +01:00
Radosław SmolińskiandClaude Opus 5.5 e53d09b720 1.13.0 upgrade notes
CI / check (push) Canceled after 0s
ipal-upgrade: the 1.13.0 section walks through the 7 "What projects must
update" items with checks. PROGRAMISTA §6: item 47 for 1.13.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 19:17:26 +02:00
Radosław SmolińskiandClaude Opus 5.5 72c059515d 1.13.0
Version bump and CHANGELOG entry: security and access, performance, SEO/GEO and
Search Console, @intecion/ipal-kit/seed, English docs and agent guide, small and
gap fixes, and what projects must update (behaviour change without access).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 19:15:35 +02:00
Radosław SmolińskiandClaude Opus 5.5 03fb6602fc ipal-reference: state how searchSettings and seo.searchSettings switch off the Search & AI tab
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 19:01:16 +02:00
Radosław SmolińskiandClaude Opus 5.5 5a07c42f76 Gap fixes: top-level searchSettings, public shouldLoadGoogle, consent/stats collection overrides
- ipalKit({ searchSettings }): switches off / reshapes Site Settings → Search & AI
  without `seo`; read as options.searchSettings ?? options.seo?.searchSettings.
- shouldLoadGoogle moved to a pure module (analytics/shouldLoadGoogle.ts) and
  exported from @intecion/ipal-kit and /client.
- consentLog.collectionOverrides and stats.collectionOverrides (object merges
  access/admin/hooks key by key, function takes over), via the new exported
  applyCollectionOverride / CollectionOverride. The stats view and dashboard
  chart now follow the stats-visits read access, so overrides narrow them too.

All additive; defaults unchanged. Docs: AGENT.md, ipal-reference, consent,
stats, seo, analytics, ipal-setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 18:54:08 +02:00
Radosław SmolińskiandClaude Opus 5.5 4911da7112 Small fixes: optional R2_PUBLIC_URL, seo.uploadsCollection, staff features without roles
- ipalEnvRules({ storage: true }): R2_PUBLIC_URL optional (media served by
  the app); storage: { requirePublicUrl: true } requires it again.
- seo.uploadsCollection: upload collection of the meta image (default media).
- userMeetsRole(req, minimum): the plugin's admin/editor features (Site
  Integrations, settings globals, test e-mail, stats, consent records, form
  submissions) stay reachable when `access` is omitted — without a roles
  field every logged-in account passes, as in Payload's default.
- IndexNow skip for seed writes is covered by test/seed.test.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 18:33:35 +02:00
Radosław SmolińskiandClaude Opus 5.5 cff76c2a69 Seed helper: @intecion/ipal-kit/seed (createSeeder + building blocks)
createSeeder(payload, { dryRun, update, force, guard, editCheck, context, ... })
returns upsertBySlug, upsertBy, fillGlobal and summary(); building blocks
isLocalDatabase, writeLocales, seedHash, projectOnto, editedSinceSeed.
Behaviour follows docs/seeding.md: create-only by default, natural keys,
never deletes, globals get empty fields only, every locale written with
fallbackLocale: false onto the same row ids, records edited since seeding
skipped, update refused on production / non-local DB unless
IPAL_SEED_ALLOW_PROD_UPDATE=1, context.ipalSkipIndexNow on every write.

Both seed templates now use the helper. Node-only entry (no 'server-only',
which throws under `payload run`). SQLite integration tests cover the
production guard, the edited-record skip, the hash field, row ids and
the IndexNow skip. Agent guide (AGENT.md, ipal-reference, ipal-site,
ipal-form) and seeding.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 18:33:34 +02:00
Radosław SmolińskiandClaude Opus 5.5 b61b753ec2 Merge main (security-perf + SEO) into docs; finish English docs and agent guide
- Resolve conflicts in analytics, consent, content, i18n, mcp and stats,
  keeping the docs fixes and the new code behaviour, verified against src
- Translate the remaining 14 module pages, ipal-seo-check skill and script
- Integrate the security-perf and SEO agent-guide text: getRobots,
  isPathVisible, Search & AI (DNS verification first, meta fields optional),
  sitemap index/cache/503, consentMode basic/advanced, policyVersion,
  globalOverrides, revalidatePath / buildGlobalRevalidateHook, authAccess,
  firstUserAdmin, allowCollectionMismatch, unknown-IP rate limit; stale
  claims fixed across AGENT.md, skills, frontend, developer guide, vibe
- docsConsistency: pending list removed (all docs English); relative links
  now also check #anchors

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:59:52 +02:00
Radosław SmolińskiandClaude Opus 5.5 8646585b7e CLAUDE.md: main rule (the plugin helps projects, never limits them) and complete agent guide rule
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:48:26 +02:00
Radosław Smoliński 24a98ff836 Merge SEO, GEO and Search Console track
Conflict in createContentHelpers.ts resolved by keeping both: isPathVisible (per-path, security track) and constructionPaths (per-list, SEO track).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

# Conflicts:
#	src/modules/frontend/createContentHelpers.ts
2026-10-22 17:48:22 +02:00
Radosław SmolińskiandClaude Opus 5.5 924d4564e5 Merge security and performance track (audit fixes, secure defaults with overrides)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:48:17 +02:00
Radosław SmolińskiandClaude Opus 5.5 54c9d3ec10 isPathVisible shares one construction-mode read per list
MCP and search call it once per result; React cache doesn't dedupe in
route handlers, so a 50-result list read Site Settings 300 times.
Concurrent calls now share one in-flight read per locale (6 reads).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:40:02 +02:00
Radosław SmolińskiandClaude Opus 5.5 2d9f3e15d4 Docs in English (part 1), seeding guide, Coolify deployment
- Translate to English every doc the code branches did not touch: AGENT.md,
  developer guide, vibe, CHANGELOG, docs index, module pages, all skills
  except ipal-seo-check (14 pages follow after the security/SEO merge).
  Placeholder marker is now [TO FILL: …]; skill resources renamed to
  section-code.md / nav-code.md. AGENT.md and the ipal-skills pointer
  block say the docs are in English.
- docs/seeding.md: create-only, natural keys, never delete, no users or
  secrets, empty-field globals, fallbackLocale: false, dry run, backup and
  restore, production update guard, seeds vs migrations, Coolify Terminal.
  Seed templates gain --dry-run, the SEED_UPDATE production guard
  (IPAL_SEED_ALLOW_PROD_UPDATE), skip of edited records and a summary.
  "Seeding on production" rule block in AGENT.md.
- Coolify is the single deployment path (deployment, env, developer guide,
  ipal-setup): build vs runtime env, migrations on container start
  (prodMigrations), health check and rolling updates, rollback, backups and
  restore, DNS/Let's Encrypt/CAA. R2: custom domain needs a Cloudflare zone;
  default is media served by the app (R2_PUBLIC_URL empty).
- docsConsistency: no Polish prose outside code/quoted data (pending pages
  listed); IPAL_* names may also be read by shipped skill templates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:39:03 +02:00
Radosław SmolińskiandClaude Opus 5.5 d45175739f Docs: forms, security, access, construction and others match the branch
Applies the docs session's forms.md diff and fixes, corrected for this
branch; adds the override sections and new options.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:35:08 +02:00
Radosław SmolińskiandClaude Opus 5.5 7d835bdc49 Locale cookie honours consent saved under a bumped policy version
The proxy parsed the consent cookie as version 1, so after an editor
bumped the policy version NEXT_LOCALE was never saved. It now accepts the
stored record's own version; policyVersion pins one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:35:08 +02:00
Radosław SmolińskiandClaude Opus 5.5 0fd57c1d6a Opt-outs for the secure defaults; isPathVisibleIn in construction/logic
- setUnknownIpFactor (0 = old free pass), UNKNOWN_IP_FACTOR exported
- createContentHelpers({ settingsDepth }) and markdown/mcp isPathVisible overrides
- <RenderRichText safeLinks={false}>
- resolveRedirect({ draft: true }) for preview
- isPathVisibleIn(mode, path), pathOf, PathVisibility exported; page route uses it

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:35:08 +02:00
Radosław SmolińskiandClaude Opus 5.5 4585e0fc69 submitForm reads forms.consentFieldName from ipalKit options
The option was typed but never read. An explicit argument still wins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:35:08 +02:00
Radosław SmolińskiandClaude Opus 5.5 38c1d9215e enabled: false keeps the plugin's schema, drops only its behaviour
Returning the incoming config dropped the plugin's collections and globals,
so a Postgres migration would drop their tables. Now collections, globals
and fields stay; endpoints, onInit and admin components are left out.
Also: ipalKit({ forms: { consentFieldName } }) is stored in config.custom.ipal.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:35:08 +02:00
Radosław SmolińskiandClaude Opus 5.5 f65c6580e1 SEO: sitemap construction filter uses isPathAllowed + pathOf (same rule as isPathVisibleIn)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:29:49 +02:00
Radosław SmolińskiandClaude Opus 5.5 a87742621a Access defaults overridable; unlock admin-only; 2FA target validated
- access.authAccess merges over the injected auth collection's access;
  unlock is admin-only by default
- access.firstUserAdmin (default true) makes the first-register promotion optional
- globalOverrides: object merges access/admin/hooks, function takes over
- form Emails protection is applied before formOverrides.fields, so a
  project can change it there
- 2FA defaults to admin.user and fails at init when the target is not an
  auth collection or differs from admin.user (twoFactor.allowCollectionMismatch)
- buildRolesField, injectRoles, applyGlobalOverrides exported

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:23:14 +02:00
Radosław SmolińskiandClaude Opus 5.5 6e3979bae6 Docs: DNS records checklist (deployment §6, ipal-setup, ipal-reference)
Site, www, CAA, Search Console TXT, Bing, SPF/DKIM/DMARC for the From
domain (SMTP vs Graph), R2 custom domain; dig checks; plugin automates
nothing in DNS; meta-tag verification fields stay empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:22:23 +02:00
Radosław SmolińskiandClaude Opus 5.5 da3a0c9a85 SEO docs: DNS verification notes in English
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:22:02 +02:00
Radosław SmolińskiandClaude Opus 5.5 b15e82546e SEO: DNS domain verification is the default path; seo-check reports a missing verification tag as INFO only
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:21:43 +02:00
Radosław SmolińskiandClaude Opus 5.5 104cdbfd4c SEO: use construction/visibility pathOf (identical to security-perf branch) for the sitemap filter
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:20:37 +02:00
Radosław SmolińskiandClaude Opus 5.5 465c5706f8 Agent guide: complete plugin coverage, full ipal-setup, pointer block
- New skill ipal-reference: every ipalKit option (incl. nested keys) with
  default and how to turn it off/override it, what the plugin injects
  (collections, globals, endpoints, import-map components), every file the
  project wires with a minimal example and a check, every env var;
  resources/api.md indexes all 432 exports with import path and purpose
- ipal-setup rewritten as a complete start-to-finish install: steps, code,
  verification and off/override per stage
- ipal-skills writes a marked <!-- ipal-kit:start/end --> pointer block into
  AGENTS.md (creates it if missing) and CLAUDE.md (or creates CLAUDE.md with
  @AGENTS.md); only the marked block is ever rewritten; --no-pointer skips.
  tsconfig exclude check now matches whole entries
- AGENT.md, PROGRAMISTA, README, docs index: point at ipal-reference and run
  `pnpm exec ipal-skills` right after install
- docsConsistency: the agent guide must mention every export (runtime and
  types), every plugin option incl. nested keys, every env var the code
  reads and every @/lib/content helper

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:19:50 +02:00
Radosław SmolińskiandClaude Opus 5.5 14fd2c497f Server entries no longer load 'use client' modules
The main entry and next/middleware re-exported module barrels that also
export React client components (LanguageSwitcher, AlternateLinks*,
AccessibilityWidget), so payload.config, the CLI and the proxy bundle
evaluated React UI. They now import concrete files; i18n client
components moved to modules/i18n/client.ts. test/entryGraph guards it.
Also lint fixes in tests added on this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:17:42 +02:00
Radosław SmolińskiandClaude Opus 5.5 e5d86b8afe Promote to admin only on the first-register screen, not any first create
An open sign-up on an empty collection would otherwise become admin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:17:42 +02:00
Radosław SmolińskiandClaude Opus 5.5 dc761164d9 SEO: project overrides (sitemapEntries, sitemapOptions, underConstructionSeo, searchSettings fn); seo-check follows sitemap index
- createContentHelpers: sitemapEntries transform has the last word,
  sitemapOptions passes maxUrls/cacheControl/memoSeconds to sitemapRoute,
  underConstructionSeo: false turns the construction filter off
- seo.searchSettings accepts a function over the default fields
- ipal-seo-check: reads sitemap index parts, reports 503 sitemap, warns on
  missing Google/Bing verification (skip key: verification)
- docs/seo.md updated

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:13:57 +02:00
Radosław SmolińskiandClaude Opus 5.5 4c199acdfd Old-slug redirects skip never-published drafts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:11:13 +02:00
Radosław SmolińskiandClaude Opus 5.5 67e9655376 Hooks run Local API calls with req; cross-locale sync restores req.locale
buildCrossLocaleFieldSync read other locales outside the save's transaction
and its update(req) left req.locale on the last target locale.
buildPreventDeleteSystemPage now reads Site Settings with req.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:10:42 +02:00
Radosław SmolińskiandClaude Opus 5.5 1beb0edb7f RenderRichText neutralises unsafe link URLs (safeHref)
Payload's link converter rendered fields.url as is; javascript:/data: URLs
stored via import or API reached the href. They now become '#'.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:09:44 +02:00
Radosław SmolińskiandClaude Opus 5.5 94e563055f SEO/GEO/GSC: sitemap index + caching, Search & AI settings, getRobots
- Sitemap: batched reads (500), published-only where, field select; sitemap
  index over maxUrls (default 10k) with ?part=N; Cache-Control; in-process
  memo; runtime errors → 503 Retry-After (empty urlset only during next build)
- Site Settings → Search & AI tab (seo.searchSettings: false removes it):
  Google/Bing/Yandex verification (paste code or whole meta tag) added to
  page metadata; AI crawler policy + per-bot exceptions; llms.txt note
- buildRobots aiBotRules; getRobots helper reads the panel; more AI agents
- Under construction: sitemap and llms.txt list only open pages
- collectSiteIndex: no silent 1000 cap; llms routes send Cache-Control
- IndexNow: nothing sent with IPAL_NOINDEX
- Unknown route metadata is noindex
- Tests (unit + SQLite integration) and docs/seo.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:09:01 +02:00
Radosław SmolińskiandClaude Opus 5.5 7967453f57 Revalidate the site layout when a global is saved
buildGlobalRevalidateHook + ipalKit({ revalidatePath }) wires it into the
plugin's globals; menus, consent texts and analytics IDs no longer stay
stale for the whole ISR window.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:09:00 +02:00
Radosław SmolińskiandClaude Opus 5.5 d39bbd01a8 docsConsistency: lint fixes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:08:15 +02:00
Radosław SmolińskiandClaude Opus 5.5 7c05a1dba9 Construction mode hides pages from Markdown, MCP and search; MCP rejects non-object messages
createContentHelpers exposes isPathVisible (built from getConstructionMode)
and passes it to markdownRoute and mcpPOST; createSearchRoute,
createMcpRoute and createMarkdownRoute accept it. A null/number/string
JSON-RPC message now gets -32600 instead of crashing the route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:07:45 +02:00
Radosław SmolińskiandClaude Opus 5.5 6e0f59c62b Docs: reconcile agent, developer and module docs with the code
- AGENT.md, skills, PROGRAMISTA, vibe, README and module pages checked
  against src/ and package.json; every mismatch fixed (consent/analytics
  loading, revalidation scope, generateStaticParams, construction gating,
  Turnstile fail modes, email/Graph, MCP, i18n, links, slug, hooks, ...)
- New pages: frontend.md, media.md, integrations.md; docs/README.md now
  indexes every page
- Main rule (plugin helps, never limits) at the top of AGENT.md,
  PROGRAMISTA.md, docs/README.md, README and the setup/plugin-gap skills;
  module pages gain a "Wyłączenie, nadpisanie, rozszerzenie" section
- README/PROGRAMISTA: stop telling projects to install packages ipal-kit
  already depends on; peer table; publish flow matches prepublishOnly
- ipal-skills: refuse --dest without a value or pointing at the project
  root (previously could delete ipal-* folders in cwd)
- docsConsistency: option keys, IPAL_* env names, relative links, README
  index, AGENT.md section refs, skill frontmatter, frontend.md helper keys,
  no `pnpm add` of own dependencies

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:06:52 +02:00
Radosław SmolińskiandClaude Opus 5.5 9a72ebfaff Analytics: consentMode 'basic' keeps Google tags out until consent
Opt-in; the default stays 'advanced' (tag loads with denied signals).
shouldLoadGoogle holds the rule so it is testable without a DOM.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:05:14 +02:00
Radosław SmolińskiandClaude Opus 5.5 0bfc509102 Run stats and consent-log retention purges off the request
The daily purge was awaited inside the visitor's request via payload.delete,
which loads and deletes expired documents one by one. It now runs as one
db.deleteMany in the background; failures are logged and retried.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:04:09 +02:00
Radosław SmolińskiandClaude Opus 5.5 78f4f5c16b First account of the auth collection always becomes admin
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:02:25 +02:00
Radosław SmolińskiandClaude Opus 5.5 561a9e2bb7 Site Settings read at depth 1; archive page re-fetched at page depth
getSettings ran findGlobal at depth 2 on every request, pulling the
relations of every page a project field links to (menus). Depth 1 keeps
slug/title. The archive page itself was rendered from the settings copy,
which maxDepth caps at 1, so its media never populated; resolveRoute now
re-fetches it at depth 2 like the homepage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:02:07 +02:00
Radosław SmolińskiandClaude Opus 5.5 8e10232765 Rate limit: no IP shares a capped bucket; optional Turnstile hostname check
A request without a usable client IP used to skip every limiter. It now
counts against one shared 'unknown-ip' bucket at 20x the limit. submitForm,
createSubmitAction and verifyTurnstile accept turnstileHostnames/hostnames
to reject tokens solved on another domain.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 16:59:51 +02:00
Radosław SmolińskiandClaude Opus 5.5 10da62ea4c Lock down injected users, 2FA slug, forms and globals writes
- Injected auth collection with roles: admins manage all accounts, others
  only themselves (Payload's default let any account edit or delete any other)
- 2FA defaults to the resolved auth collection instead of 'users'
- SiteSettings, CookieSettings, Notifications, Forms: write needs editor+;
  form Emails tab readable by editor+ only

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 16:58:00 +02:00
Radosław Smoliński 12fbd424a5 1.12.3
CI / check (push) Canceled after 0s
2026-10-21 18:16:31 +02:00
Radosław SmolińskiandClaude Opus 5.5 6b4336f961 Detailed cookie settings window (CookieBanner settings="detailed")
A third settings mode next to 'inline' and 'modal': a large dialog where every consent
category is a card with its on/off control, description and an expandable list of the
cookies it covers (name, provider, purpose, duration), taken from Cookie Settings → Cookies
— the same rows as <CookieTable>. The developer picks the mode with one prop; the
component default stays 'inline', so existing sites are unchanged.

Cookie Settings gets a localized detailLabels group (list labels, English fallback);
getConsentTexts passes texts.cookies and texts.details, sharing the row mapping with
getCookieTable. New classNames slots and data-ipal handles for the cards and lists.

Docs for devs and agents: consent.md (modes compared, which to pick — new projects default
to 'detailed' when the cookie list is filled), AGENT.md, PROGRAMISTA §2.8/§2.11/§6, skills
ipal-setup, ipal-site, ipal-upgrade, ipal-locale-add, ipal-consent-check. Postgres/SQLite
projects need migrate:create for the new fields.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 18:16:30 +02:00
Radosław Smoliński 1413e96731 1.12.2
CI / check (push) Canceled after 0s
2026-10-21 16:45:03 +02:00
Radosław SmolińskiandClaude Opus 5.5 e1431a7c49 Stable admin import map without R2 env, read-only media, Cookie Settings save-button migration
buildR2Storage registered nothing without R2_* env, so `pnpm dev` / generate:importmap in dev
wrote an importMap.js without S3ClientUploadHandler — committed, the production admin (R2 on)
rendered a blank page with no console error (hit vanstev.pl). The injected s3Storage is now
always registered (enabled: false without R2 → local disk); storage-s3 still adds its client
handler, so the import map is identical in every environment. ipal-audit flags an import map
without the handler.

R2_PUBLIC_URL alone (absolute, outside production) = read-only media: URLs from the media
domain, upload/delete refused with 403 — local dev against a production database without
bucket keys. ipalEnvRules allows it in development.

Cookie Settings (MongoDB): the 1.11.1 rename buttons.save → savePreferences lost the texts on
the first save; onInit copies the old value (all locales) when the new field is missing.
getConsentTexts read the old field as a string, Mongo returns the raw { pl, en } map.

Also: context.ipalSkipAutoFill (SKIP_AUTO_FILL) — save without meta / aiSummary auto-fill;
createPageRoute redirects the homepage under its own slug (homeAlias, default 'redirect');
ipal-audit: multi-line tsconfig exclude, numeronyms (a11y) not "numbered fields",
`${prefix}/${slug}` links and slugs typed into links detected, clearer panel-language message.
Docs: fallback-on-save in i18n.md, `pnpm up --latest` and the stale-token 401 in PROGRAMISTA §1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 16:45:03 +02:00
Radosław Smoliński 2c3195c4e1 1.12.1
CI / check (push) Canceled after 0s
2026-10-21 15:11:04 +02:00
Radosław SmolińskiandClaude Opus 5.5 4ec27d9ef0 Built-in statistics (cookieless, consent-gated visitor history); per-page meta descriptions, NoSnippet
Stats: ipalKit({ stats: true }) adds the stats-visits collection, POST /api/ipal/hit, the
/admin/stats view (30-day visits chart, top/entry pages, referrers, devices), a dashboard card
and a nav link. <PageStats> (or <SiteProviders stats>) sends one beacon per page view. Without
consent nothing is stored on the device and no IP is kept: page views are joined by a hash with
an in-memory salt replaced daily. With analytics consent an ipal_vid cookie links visits across
days (server re-checks the consent cookie and policy version; withdrawal deletes the cookie).
Bots, logged-in panel users and prefetches aren't counted. Retention 90 days.
@payloadcms/next added to peerDependencies (DefaultTemplate). Docs: stats.md with privacy text.

Also in this release: meta.description auto-filled from page blocks, <NoSnippet>,
MetaDescriptionCheck in the SEO tab, data-nosnippet on banner/language switcher, GA4 CSP
wildcards, consent version passed to Analytics' default consent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 15:10:55 +02:00
Radosław Smoliński 305c564d13 1.12.0
CI / check (push) Canceled after 0s
2026-10-20 00:46:44 +02:00
Radosław SmolińskiandClaude Opus 5.5 166bf51e53 Lazy 404: createNotFoundPage({ load }) + renderNotFoundView, NotFoundLoader
Next puts a layout's not-found tree into the RSC payload of every page under it. The eager
createNotFoundPage({ blocks }) rendered the panel's 404 page there in every locale, so with
404 = homepage each page shipped the homepage twice (homepage HTML 195 -> 146 KB gzip).
With { load } only <NotFoundLoader> is in the payload; the content comes from the project's
server action (renderNotFoundView, locale checked against configured locales) when a 404 shows.
The eager variant is unchanged. Docs: pages.md, i18n.md, AGENT.md, PROGRAMISTA, ipal-setup, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 00:46:44 +02:00
Radosław SmolińskiandClaude Opus 5.5 8b35986635 1.11.1
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 21:32:40 +02:00
Radosław SmolińskiandClaude Opus 5.5 faa4ad679c Theme switcher, table of contents, missing-page redirect, form placeholders and time field; audit and revalidate fixes
- buildRevalidateHook skips outside Next (no NEXT_RUNTIME) and with context.disableRevalidate
- BuilderForm focuses only on a real step change (no scroll to the form on remount)
- mediaImageProps: placeholder colour only for JPEG (placeholderColor); hook stores no colour for transparent images
- buildLinkField: interface name per shape (CmsLink, CmsLinkPlain, CmsLinkNoLabel) + interfaceName option
- Cookie Settings: buttons.save -> buttons.savePreferences (Mongoose reserved name)
- ThemeScript, ThemeSwitcher, useTheme; Site Settings defaultTheme 'system' + themeToggleLabel; Turnstile follows page theme
- extractHeadings, RenderRichText headingIds, TableOfContents, buildTableOfContentsField
- createPageRoute onMissing: 'redirectHome'
- Form builder: localized placeholder on text/email/textarea/number, new time field
- ipal-audit: no false positive for object keys between JSX elements; /md route not reported as dynamic

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 21:32:40 +02:00
Radosław SmolińskiandClaude Opus 5.5 23e033d7d7 1.11.0
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:38:28 +02:00
Radosław SmolińskiandClaude Opus 5.5 f809526f1d Page-filled form fields, links to entries, entry JSON-LD, R2-optional dev
Forms: `values` on RenderForm / BuilderForm / useBuilderForm fills fields the
page knows (chosen product variant, category) — read-only <output>, in the
SSR HTML, sent and validated like any field. prepareBuilderForm (/rsc) is the
server half of RenderForm for client components whose values change in the
browser; publicForm is exported so projects stop copying it.

Links: buildLinkField({ relationTo: ['pages', 'categories', …] }) — a
polymorphic relation; resolveLinkHref builds /{locale}/{archive}/{entry} from
`archives`, which getLinkOptions in createContentHelpers fills from Site
Settings.

SEO: pageJsonLd.entries — the main JSON-LD node per content collection
instead of BlogPosting; buildProductJsonLd emits an Offer only for a real
price from the panel.

Pages: createPageRoute / createNotFoundPage pass isFirst to blocks, so the
first section carries the page's only h1.

Fixes: ipalEnvRules({ storage: true }) requires R2_* in production only
(development: optional, all or none); buildImagesConfig allows the app's own
media on localhost outside production.

Docs, CHANGELOG, PROGRAMISTA §6 (34–37), ipal-form and ipal-upgrade skills.
Tests: builderForm, links, drafts (entries + archives), seo, media, env.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:38:28 +02:00
Radosław Smoliński 46d30d4ecd 1.10.1
CI / check (push) Canceled after 0s
2026-10-19 00:07:40 +02:00
Radosław SmolińskiandClaude Opus 5.5 a6eda2e3a3 Pass siteDescription to page metadata; document media cache rule
createPageMetadata read Site Settings → siteDescription but never passed it to
buildMetadata, so pages without their own meta description had no
<meta name="description"> or og:description. Regression test in seo.test.ts.

storage.md: Cloudflare Cache Rule for the media domain (R2 objects carry no
Cache-Control; storage-s3 cannot set it, Cloudflare defaults to 4 h).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 00:07:28 +02:00
radoslaw.smolinski d28cbe2570 1.10.0
CI / check (push) Canceled after 0s
2026-10-17 03:20:12 +02:00
radoslaw.smolinskiandClaude Opus 5.5 2bd9d60822 Cookie banner layout options; keep admin UI out of /client
CookieBanner: order, settings="modal", controls="switch",
settingsActions, icon and a class slot for every element. Cookie
Settings gains eyebrow, title, settingsDescription, alwaysActiveLabel
and buttons.close.

MaskedField, TestEmailButton and IntegrationStatusBanner import
@payloadcms/ui and moved from /client to /admin; with sideEffects in
package.json the site bundle no longer ships ~235 KB gz of admin code.
A test walks the /client import graph to keep it that way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 03:20:11 +02:00
radoslaw.smolinski 0f6a43ad12 1.9.9
CI / check (push) Canceled after 0s
2026-10-17 01:29:01 +02:00
radoslaw.smolinskiandClaude Opus 5.5 14d71bcc3a Readable form emails (forms.emailLayout)
{{*:table}} renders a readable submission summary (questions, option labels,
grouped by step, empty fields skipped) inside an email template with logo,
accent colour and footer from Site Settings → Emails. submitForm stores the
submission in the page language, so emails follow the visitor's locale.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-17 01:29:00 +02:00
radoslaw.smolinski 78e4e0f8e6 1.9.8
CI / check (push) Canceled after 0s
2026-10-16 22:15:57 +02:00
radoslaw.smolinskiandClaude Opus 5.5 8f8b79d003 Under construction mode (developer tool)
Site Settings -> Under construction: a switch, 'Pages still available' and
notice texts. When on, only the homepage and the chosen pages open (every
language); other addresses redirect to the homepage with the notice
(createPageRoute redirect option), and <ConstructionNotice> cancels clicks
on links to blocked pages and shows the notice. getConstructionMode(locale).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 22:15:57 +02:00
radoslaw.smolinski 91d5e986c5 1.9.7
CI / check (push) Canceled after 0s
2026-10-16 20:53:26 +02:00
radoslaw.smolinskiandClaude Opus 5.5 080086adfe Forms: conditional fields and steps (Show only when)
Every form block (built-in, Checkbox group, Step, message) gets a showWhen
group: visible only when another field has one of the given values. A hidden
Step drops out with its fields; browser and server share visibleFields, so a
hidden field is neither required nor stored. GDPR consent is always enforced.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 20:53:25 +02:00
radoslaw.smolinski 8c1a8b0e8e 1.9.6
CI / check (push) Canceled after 0s
2026-10-16 13:51:33 +02:00
radoslaw.smolinskiandClaude Opus 5.5 002eef56d1 Changelog 1.9.6
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:51:31 +02:00
radoslaw.smolinskiandClaude Opus 5.5 924b5cf8be Markdown route: type-safe locale code read
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 13:42:17 +02:00
818 changed files with 103268 additions and 8695 deletions
+78
View File
@@ -25,3 +25,81 @@ jobs:
- run: pnpm lint
- run: pnpm test:int
- run: pnpm build
# The reference site (reference/, docs/dev/reference-site-proposal.md). Fast part on every push and PR:
# install against the freshly built plugin, committed generated files current, typecheck.
reference:
runs-on: ubuntu-latest
needs: check
env:
PAYLOAD_SECRET: ci-reference-secret-0123456789abcdef
DATABASE_URI: mongodb://127.0.0.1:27017/example-studiopl_dev
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 10
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile --ignore-scripts
- run: pnpm build
# file:.. + injected: the site gets a copy of the built plugin with its peers from the site (README.md)
- run: pnpm --dir reference install --frozen-lockfile --ignore-workspace
- run: pnpm --dir reference exec ipal-tokens --check
- run: pnpm --dir reference generate:importmap && git diff --exit-code reference/src/app
- run: pnpm --dir reference generate:types && git diff --exit-code reference/src/payload-types.ts
- run: pnpm --dir reference typecheck
# ipal-doctor (static, docs/doctor.md): the reference site is the zero-findings example — any unsilenced finding fails
- run: node bin/ipal-doctor.mjs reference --strict --offline
# Full run on main (and before a release): MongoDB, seed, production build, smoke tests.
reference-full:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
needs: reference
services:
mongo:
image: mongo:7
ports: ['27017:27017']
env:
CI: '1'
DATABASE_URI: mongodb://127.0.0.1:27017/example-studiopl_dev
PAYLOAD_SECRET: ci-reference-secret-0123456789abcdef
NEXT_PUBLIC_SERVER_URL: http://localhost:3100
IPAL_IP_HEADER: x-forwarded-for
# cookieScanner.crawl → ipalEnvRules({ cookieCrawl }) requires both in production; CI never starts a crawl
IPAL_COOKIE_SCAN_URL: http://127.0.0.1:9/crawl
IPAL_COOKIE_SCAN_TOKEN: ci-cookie-scan-token-0123456789
NEXT_PUBLIC_TURNSTILE_SITE_KEY: 1x00000000000000000000AA
TURNSTILE_SECRET_KEY: 1x0000000000000000000000000000000AA
ALLOW_LOCAL_MEDIA: '1'
E2E_BASE_URL: http://localhost:3100
E2E_ADMIN_EMAIL: [email protected]
E2E_ADMIN_PASSWORD: ci-e2e-password-not-secret
E2E_TOTP_SECRET: JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 10
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm
- run: pnpm install --frozen-lockfile --ignore-scripts
- run: pnpm build
- run: pnpm --dir reference install --frozen-lockfile --ignore-workspace
- run: pnpm --dir reference seed
# the documented production seed path (Coolify Terminal): one named record, dry run
- run: SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm --dir reference seed
- run: pnpm --dir reference payload run e2e/create-test-admin.ts
- run: pnpm --dir reference build
- run: pnpm --dir reference exec playwright install --with-deps chromium
- run: pnpm --dir reference test:e2e
# ipal-doctor (deep + HTTP): read-only database counts, the import map, the env rules, and the running site
- run: |
PORT=3100 pnpm --dir reference start &
for i in $(seq 1 60); do curl -sf http://localhost:3100/api/health >/dev/null && break; sleep 2; done
node bin/ipal-doctor.mjs reference --strict --offline --deep --url http://localhost:3100
+3
View File
@@ -53,3 +53,6 @@ next-env.d.ts
# build output — produced by `pnpm build` (prepare/prepublishOnly), not committed
/dist
# pnpm starter:gate work folder
.starter-gate/
+17
View File
@@ -2,3 +2,20 @@
This project uses the Payload CMS skill at `.claude/skills/payload/`.
Start with `.claude/skills/payload/SKILL.md` for a quick reference, then see `.claude/skills/payload/reference/` for detailed docs.
## Main rule: the plugin helps projects, never limits them
ipal-kit is a plugin. Every change must leave the consuming project free to adapt it.
- Every module and feature can be turned off on its own. Turning one off never takes away anything the project still needs.
- Every default can be overridden: access rules, fields, hooks, labels, routes, collections and globals. The project's own config is merged with the plugin's and wins.
- Secure defaults are welcome. They come with an option to loosen or extend them, never as a hard lock.
- Export the building blocks (helpers, builders, hooks), not only finished features.
- Never force a dependency, route, UI or data shape where an option or an exported piece would do.
## Rule: an agent that adds the plugin gets the complete guide
When an agent adds ipal-kit to a project, `docs/agent/AGENT.md` and the `ipal-*` skills (installed by `ipal-skills`) must tell it how to set up and use every function the plugin supports.
- Every export, option, env var, route, middleware, layout component, admin import-map entry and hook a project must wire is documented, with steps and a way to verify it.
- A change that adds or alters a feature updates the agent guide and the matching skill in the same change.
+84 -15
View File
@@ -7,6 +7,12 @@ SEO (metadata, canonical, sitemap, robots), forms (Turnstile, rate limiting,
validation), consent management (consent mode), analytics (GA4/GTM), and a
blog/archive system (collections under an archive page, listing, pagination).
**Principle:** ipal-kit helps projects, never limits them — every module can be
turned off on its own, every default (access, fields, hooks, labels, routes,
collections, globals) can be overridden and the project's config wins, and the
building blocks are exported, not only the finished features. Where the code
doesn't meet this yet, the module's doc says so.
**Repository:** https://git.intecion.net/IntecionSoftware/ipal-kit
---
@@ -55,21 +61,78 @@ quick throwaway test it works. But prefer the registry for real projects:
Keep the git install only for pulling a specific unreleased commit during
plugin development.
### A new site in one command
```bash
pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create intecion.com
```
Asks the architecture questions (or reads `--answers answers.json`), generates the site from the reference
site with every team convention, installs it from a shipped lockfile and makes the first commit. Needs the
`@intecion` registry line in `~/.npmrc`. Details: [docs/project-starter.md](./docs/project-starter.md).
---
## Finish setting up your project
The plugin doesn't pull in the dependencies it shares with Payload — add them
yourself, in a version matching your Payload:
`nodemailer`, `lucide-react`, `slugify` and `server-only` are regular
`dependencies` of the plugin — they install with it; don't add them yourself.
The plugin's `nodemailer` 10 needs **Node.js 20 or later**; Payload 3.94 itself needs **Node.js 22.23.5 or later**
on the 22 line.
What you provide are the **peer dependencies** — packages the plugin shares with
your project — in a version matching your Payload. The plugin accepts Payload `^3.90.2`; the reference site and the starter use
**3.94.1** (with `react` / `react-dom` 19.3.1, which Payload 3.94 requires):
| Peer | Range | Notes |
|---|---|---|
| `payload`, `@payloadcms/next`, `@payloadcms/ui`, `@payloadcms/richtext-lexical` | `^3.90.2` | already in a `create-payload-app` project |
| `next`, `react` | `>=15`, `^19.0.0` | already in a `create-payload-app` project |
| `@payloadcms/plugin-seo`, `@payloadcms/plugin-form-builder` | `^3.90.2` | **add these** |
| `@clocklimited/payload-2fa` | `^3.0.0-0` | optional peer, but **needed by default**: 2FA is enforced and `ipalKit()` throws at startup unless you pass `twoFactor: { issuer, plugin: payloadTotp }` (or opt out with `twoFactor: false`) |
| `@payloadcms/storage-s3` | `^3.90.2` | optional — only when media go to Cloudflare R2 ([docs/storage.md](./docs/storage.md)) |
```bash
pnpm add @payloadcms/[email protected]0.2 @payloadcms/[email protected]0.2 \
nodemailer lucide-react slugify server-only
pnpm add @payloadcms/[email protected]4.1 @payloadcms/[email protected]4.1 \
@clocklimited/payload-2fa
pnpm add @payloadcms/[email protected] # only with R2 media
```
> **Match `lucide-react` to the plugin.** The plugin uses `lucide-react@^0.400.0`.
> If your project pulls a different major (e.g. `1.x`), you end up with two copies
> and confusing type errors. Pin your project to the same range.
Keep every `@payloadcms/*` at exactly the same version as `payload`
(`pnpm.overrides` — see PROGRAMISTA.md §1). Then run `pnpm audit --prod`: even
Payload 3.94.1 brings a vulnerable `happy-dom` (via Lexical) and `dompurify` — add
the two overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md); an older Payload
also needs the `mongoose` (MongoDB adapter, up to 3.93) and `undici` (up to 3.91)
ones listed there (recommended, not required by the plugin). Upload optimization and image
placeholders also use the `sharp` you pass to `buildConfig({ sharp })`
(standard in a `create-payload-app` project).
> **`lucide-react` comes with the plugin, at `^0.400.0`.** For a `0.x` version
> the caret means **`0.400.x` only** — not "0.400 or newer". If your project also
> uses `lucide-react` at another version (e.g. `0.5xx` or `1.x`), you end up with two
> copies and confusing type errors. Pin your project to `~0.400.0` too.
**Working with an AI agent?** Run this right after installing (and after every upgrade):
```bash
pnpm exec ipal-skills
```
It copies the `ipal-*` agent skills into `.agents/skills/` and adds a marked
`<!-- ipal-kit:start -->` block to `AGENTS.md` (plus a `CLAUDE.md` that imports it, if you
have none) pointing the agent at the full guide: `AGENT.md`, the `ipal-reference` skill
(every option, env var, route and export) and the `ipal-setup` skill. Only the text between
the markers is ever rewritten. `--no-pointer` skips that step. There is no `postinstall` script.
`pnpm exec ipal-skills --external` also adds a few well-known third-party skills as `ext-*` folders — Vercel's
React best practices and composition patterns, Addy Osmani's accessibility skill, Anthropic's frontend-design
skill and the official Payload 3 skill. They are vendored into the package at pinned commits (text only, each
with its licence and source), so nothing is downloaded, and each starts with a note that ipal-kit's rules win.
Pick some with `--external ext-accessibility,ext-payload`.
*Updating the pins (plugin maintainers):* change the commit in `scripts/vendor-external-skills.mjs`, run
`node scripts/vendor-external-skills.mjs`, review `git diff docs/agent/external`, and run
`pnpm vitest run test/externalSkills.test.ts`.
From here, the guide takes over: **[docs/dev/PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** —
from an empty project to a working site.
@@ -96,14 +159,19 @@ scope `write:package`. Put it in the `GITEA_TOKEN` env var.
| Linux / Ubuntu | `~/.npmrc` |
| Windows | `%USERPROFILE%\.npmrc` |
Then build and publish:
Then version and publish (commit your changes first — `npm version` needs a
clean working tree):
```bash
pnpm clean && pnpm build
npm version patch # 1.0.0 → 1.0.1
npm publish
npm version patch # 1.0.0 → 1.0.1 (commit + tag)
npm publish # prepublishOnly runs: pnpm clean && pnpm build && pnpm build:starter && pnpm test:int && pnpm starter:gate
git push && git push --tags
```
`publishConfig.registry` in `package.json` already points at the Gitea registry,
so `npm publish` needs no `--registry` flag. A failing build or test aborts the
publish.
Full checklist and troubleshooting: **[docs/dev/PROGRAMISTA.md §8](./docs/dev/PROGRAMISTA.md)**.
---
@@ -112,10 +180,10 @@ Full checklist and troubleshooting: **[docs/dev/PROGRAMISTA.md §8](./docs/dev/P
Everything lives in the **[docs/](./docs)** directory. To get started:
- **[AGENT.md](./docs/agent/AGENT.md)** — rules for AI agents (Polish)
- **[PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** — setup, deployment, upgrades, releasing (Polish)
- **[AGENT.md](./docs/agent/AGENT.md)** — rules for AI agents
- **[PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** — setup, deployment, upgrades, releasing
- **[README.md](./docs/README.md)** — index of the plugin's modules
- **[CHANGELOG.md](./docs/CHANGELOG.md)** — what changed per version and what projects must update (Polish)
- **[CHANGELOG.md](./docs/CHANGELOG.md)** — what changed per version and what projects must update
---
@@ -125,7 +193,8 @@ Everything lives in the **[docs/](./docs)** directory. To get started:
|---|---|
| `404` on `pnpm add @intecion/...` | the `@intecion:registry` line is missing from `.npmrc` — the install went to public npm instead of Gitea |
| `Could not find the module … in the React Client Manifest` | installed from git, not the registry — reinstall from the registry (clean path) |
| two versions of `lucide-react` | your project pins a different major than the plugin's `^0.400.0` — align them |
| two versions of `lucide-react` | your project uses a `lucide-react` outside the plugin's `^0.400.0` (= `0.400.x`) — align them |
| `[ipal] 2FA is enforced but no 2FA plugin was injected` | install `@clocklimited/payload-2fa` and pass `twoFactor: { issuer, plugin: payloadTotp }` |
| `missing secret key … to secure Payload` | `PAYLOAD_SECRET` isn't set in the runtime environment (not a plugin issue) |
If you get stuck, see **[docs/dev/PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** or message the
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env node
// ipal-blocks — the block library's command line.
// pnpm exec ipal-blocks list → the library blocks
// pnpm exec ipal-blocks eject faq → src/blocks/Faq/{config.ts,Component.tsx}
// pnpm exec ipal-blocks eject faq --dest src/blocks --dry-run
// Eject copies one block's source into the project, with its imports pointing at the
// package entries, so the project owns it: same slug and data shape, no migration.
// Then: use the ejected builder in Pages.layout instead of the library one, pass the ejected
// component as createBlockRegistry({ components: { faq: FaqBlock } }), record it in AGENTS.md.
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const args = process.argv.slice(2)
const [command, slug] = args
const dryRun = args.includes('--dry-run')
const destArg = args.indexOf('--dest')
const dest = resolve(process.cwd(), destArg >= 0 ? args[destArg + 1] : 'src/blocks')
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const libRoot = join(pkgRoot, 'src/modules/block-library')
const blocksRoot = join(libRoot, 'blocks')
if (!command || command === '--help' || command === '-h') {
console.log('Usage: ipal-blocks list | ipal-blocks eject <block> [--dest src/blocks] [--dry-run]')
process.exit(0)
}
const slugs = existsSync(blocksRoot) ? readdirSync(blocksRoot).sort() : []
if (command === 'list') {
console.log(slugs.join('\n'))
process.exit(0)
}
if (command !== 'eject' || !slug) {
console.error('Usage: ipal-blocks eject <block>')
process.exit(1)
}
if (!slugs.includes(slug)) {
console.error(`Unknown block "${slug}". Blocks: ${slugs.join(', ')}`)
process.exit(1)
}
/**
* Where an import inside the library goes in a project, by the file it points at.
* Config files (no React) take the Payload-side entries; components take /rsc and /client.
*/
const ROOT = '@intecion/ipal-kit'
const BLOCKS = '@intecion/ipal-kit/blocks'
const RSC = '@intecion/ipal-kit/blocks/rsc'
function target(file, isComponent) {
const rel = relative(join(pkgRoot, 'src/modules'), file).replace(/\\/g, '/').replace(/\.js$/, '')
if (rel.startsWith('block-library/')) {
const inner = rel.slice('block-library/'.length)
if (/^(define|fields|options|shared|types|faq|library|manifest|thumbnails)$/.test(inner)) {return BLOCKS}
return RSC // context, data, texts, ui/*
}
if (rel === 'lightbox/LightboxProvider' || rel === 'richtext/TableOfContents') {return '@intecion/ipal-kit/client'}
if (rel === 'forms/RenderForm' || rel === 'richtext/RenderRichText') {return '@intecion/ipal-kit/rsc'}
if (rel === 'richtext/headings') {return isComponent ? '@intecion/ipal-kit/rsc' : ROOT}
return ROOT
}
/** Rewrites relative imports to package entries and merges imports of the same entry. */
function rewrite(source, file) {
const isComponent = file.endsWith('.tsx')
const merged = new Map()
const body = source.replace(/^import (type )?\{([^}]*)\} from '(\.[^']+)'\n/gm, (_, type, names, spec) => {
const entry = target(resolve(dirname(file), spec), isComponent)
const key = `${type ? 'type ' : ''}${entry}`
const set = merged.get(key) ?? new Set()
for (const n of names.split(',').map((s) => s.trim()).filter(Boolean)) {set.add(n)}
merged.set(key, set)
return ''
})
const lines = [...merged].map(([key, set]) => {
const [type, entry] = key.startsWith('type ') ? ['type ', key.slice(5)] : ['', key]
return `import ${type}{ ${[...set].sort().join(', ')} } from '${entry}'`
})
return body.replace(/^((?:import [^\n]*\n)*)/, (head) => `${head}${lines.join('\n')}\n`).replace(/\n{3,}/g, '\n\n')
}
const folder = slug[0].toUpperCase() + slug.slice(1)
const outDir = join(dest, folder)
const files = readdirSync(join(blocksRoot, slug)).filter((f) => /\.(ts|tsx)$/.test(f))
for (const name of files) {
const from = join(blocksRoot, slug, name)
const to = join(outDir, name)
if (existsSync(to)) {
console.error(`skip ${relative(process.cwd(), to)} (exists — delete it first to eject again)`)
continue
}
const out = `// Ejected from @intecion/ipal-kit (block library: ${slug}). The project owns this file now.\n${rewrite(readFileSync(from, 'utf8'), from)}`
console.log(`${dryRun ? 'would write' : 'write'} ${relative(process.cwd(), to)}`)
if (!dryRun) {
mkdirSync(outDir, { recursive: true })
writeFileSync(to, out)
}
}
console.log(`\nNext: Pages.layout → the ejected build${folder}Block; registry → components: { ${slug}: ${folder}Block }; AGENTS.md → "Project decisions".`)
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env node
// ipal-doctor — checks a site against the ipal-kit team rules and lists every gap with a fix hint
// (docs/doctor.md). Static by default: reads files, writes nothing (except a first-seen date in
// ipal-doctor.json outside CI).
// pnpm exec ipal-doctor → this project, human-readable
// pnpm exec ipal-doctor --strict --offline → CI on a new site: any finding fails
// pnpm exec ipal-doctor --deep --url http://localhost:3000
// pnpm exec ipal-doctor --json > doctor.json
// pnpm dlx --package=@intecion/ipal-kit@latest ipal-doctor → the newest rules
// Exit: 0 ok · 1 findings · 2 could not run · 3 a rule crashed.
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runDoctorCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'doctor', 'cli.js')).href)
process.exit(await runDoctorCli(process.argv.slice(2), { packageRoot: pkgRoot }))
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env node
// ipal-kit — the plugin's command line.
// pnpm dlx @intecion/ipal-kit@<version> create intecion.com → a new client site (docs/project-starter.md)
// pnpm exec ipal-kit create intecion.com --dir ../intecioncom-web --answers answers.json
// `pnpm dlx <package>` runs the bin named after the package, so every subcommand lives here.
// The other tools keep their own bins: ipal-skills, ipal-blocks, ipal-tokens, ipal-doctor.
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const USAGE = `Usage: ipal-kit <command> [options]
create <domain> a new client site from the reference site (ipal-kit create --help)
Other tools: ipal-skills, ipal-blocks, ipal-tokens, ipal-doctor`
const [command, ...args] = process.argv.slice(2)
if (command !== 'create') {
console.log(USAGE)
process.exit(command === undefined || command === '--help' || command === '-h' ? 0 : 1)
}
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runCreateCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'starter', 'cli.js')).href)
process.exit(await runCreateCli(args))
+122 -7
View File
@@ -1,23 +1,45 @@
#!/usr/bin/env node
// ipal-skills — copies the ipal-kit agent skills into the project.
// pnpm ipal-skills → ./.agents/skills/ipal-*
// pnpm ipal-skills --dry-run → show what would change
// pnpm ipal-skills --dest .claude/skills
// pnpm exec ipal-skills → ./.agents/skills/ipal-*
// pnpm exec ipal-skills --dry-run → show what would change
// pnpm exec ipal-skills --dest .claude/skills
// pnpm exec ipal-skills --no-pointer → skills only, leave AGENTS.md / CLAUDE.md alone
// pnpm exec ipal-skills --external → also the vendored third-party skills (ext-*, pinned, text only)
// pnpm exec ipal-skills --external ext-accessibility,ext-payload → only those
// Only folders named ipal-* are touched; the project's own skills stay as they are.
// ipal-* folders that no longer exist in the package are removed (renamed/retired skills).
// ext-* folders are touched only with --external, and only those carrying ipal-kit's SOURCE.md.
// AGENTS.md (and CLAUDE.md) get a marked ipal-kit block pointing at the guide — only the
// text between the markers is ever rewritten; the project's own content stays as it is.
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'
import { createHash } from 'node:crypto'
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const args = process.argv.slice(2)
if (args.includes('--help') || args.includes('-h')) {
console.log('Usage: ipal-skills [--dest <dir>] [--dry-run]\nDefault dest: .agents/skills')
console.log('Usage: ipal-skills [--dest <dir>] [--dry-run] [--no-pointer] [--external [ext-a,ext-b]]\nDefault dest: .agents/skills')
process.exit(0)
}
const dryRun = args.includes('--dry-run')
const pointer = !args.includes('--no-pointer')
const externalArg = args.indexOf('--external')
const externalPick = externalArg >= 0 && args[externalArg + 1] && !args[externalArg + 1].startsWith('-')
? args[externalArg + 1].split(',').map((n) => n.trim()).filter(Boolean)
: null
const destArg = args.indexOf('--dest')
const dest = resolve(process.cwd(), destArg >= 0 ? args[destArg + 1] ?? '' : '.agents/skills')
const destValue = destArg >= 0 ? args[destArg + 1] : '.agents/skills'
// A missing value would resolve to cwd and remove every ipal-* folder there.
if (!destValue || destValue.startsWith('-')) {
console.error('ipal-skills: --dest needs a directory, e.g. --dest .claude/skills')
process.exit(1)
}
const dest = resolve(process.cwd(), destValue)
if (dest === resolve(process.cwd())) {
console.error('ipal-skills: --dest must be a subdirectory, not the project root')
process.exit(1)
}
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const src = join(pkgRoot, 'docs', 'agent', 'skills')
@@ -26,6 +48,16 @@ if (!existsSync(src)) {
process.exit(1)
}
// Validate --external before anything is copied.
const extSrc = join(pkgRoot, 'docs', 'agent', 'external')
const manifest = externalArg >= 0 ? JSON.parse(readFileSync(join(extSrc, 'manifest.json'), 'utf8')) : { skills: [] }
const known = manifest.skills.map((skill) => skill.name)
const unknown = (externalPick ?? []).filter((name) => !known.includes(name))
if (unknown.length) {
console.error(`ipal-skills: unknown external skill(s): ${unknown.join(', ')} — available: ${known.join(', ')}`)
process.exit(1)
}
const isSkillDir = (base, name) => name.startsWith('ipal-') && statSync(join(base, name)).isDirectory()
const shipped = readdirSync(src).filter((n) => isSkillDir(src, n))
const existing = existsSync(dest) ? readdirSync(dest).filter((n) => isSkillDir(dest, n)) : []
@@ -46,6 +78,88 @@ for (const name of retired) {
}
console.log(`${dryRun ? '[dry-run] ' : ''}${shipped.length} skill(s) → ${dest}`)
// Third-party skills, vendored into the package at pinned commits (docs/agent/external,
// scripts/vendor-external-skills.mjs). Nothing is downloaded here: every file is checked
// against manifest.json before it is copied.
if (externalArg >= 0) {
const MARK = 'Vendored by @intecion/ipal-kit'
const ours = (name) => existsSync(join(dest, name, 'SOURCE.md')) && readFileSync(join(dest, name, 'SOURCE.md'), 'utf8').includes(MARK)
const filesOf = (dir) => readdirSync(dir).flatMap((n) => (statSync(join(dir, n)).isDirectory() ? filesOf(join(dir, n)).map((f) => `${n}/${f}`) : [n]))
for (const skill of manifest.skills.filter((s) => !externalPick || externalPick.includes(s.name))) {
const from = join(extSrc, skill.name)
const files = filesOf(from).sort()
const tampered = files.filter((f) => skill.files[f] !== createHash('sha256').update(readFileSync(join(from, f))).digest('hex'))
if (tampered.length || files.length !== Object.keys(skill.files).length) {
console.error(`ipal-skills: ${skill.name} does not match manifest.json (${tampered.join(', ') || 'file list'}) — skipped`)
process.exitCode = 1
continue
}
if (existsSync(join(dest, skill.name)) && !ours(skill.name)) {
console.warn(`skip ${skill.name} (a folder of that name exists and is not from ipal-kit)`)
continue
}
console.log(`${existsSync(join(dest, skill.name)) ? 'update' : 'add '} ${skill.name} (${skill.publisher}, ${skill.license}, ${skill.commit.slice(0, 12)})`)
if (!dryRun) {
rmSync(join(dest, skill.name), { recursive: true, force: true })
cpSync(from, join(dest, skill.name), { recursive: true })
}
}
const retiredExt = existsSync(dest)
? readdirSync(dest).filter((n) => n.startsWith('ext-') && !known.includes(n) && ours(n))
: []
for (const name of retiredExt) {
console.log(`remove ${name} (no longer in ipal-kit)`)
if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true })
}
}
// Pointer block: an agent opening the project must find the guide without being told.
// AGENTS.md is read by Codex/Cursor/Antigravity, CLAUDE.md by Claude Code (which also
// follows `@AGENTS.md` imports, so a CLAUDE.md that imports AGENTS.md needs no copy).
if (pointer) {
const START = '<!-- ipal-kit:start -->'
const END = '<!-- ipal-kit:end -->'
const version = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8')).version
const skillsDir = relative(process.cwd(), dest).split('\\').join('/')
const block = [
START,
`## ipal-kit ${version} — agent guide`,
'',
'<!-- Managed by `pnpm exec ipal-skills` — edits between the markers are overwritten. -->',
'This project is built on `@intecion/ipal-kit` (a Payload CMS 3 plugin). Before you write code:',
'',
'1. Rules: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`.',
`2. Everything the plugin provides (options, env vars, routes, layout, hooks, collections, globals, every export): the \`ipal-reference\` skill — \`${skillsDir}/ipal-reference/SKILL.md\`.`,
`3. New project or missing foundation: the \`ipal-setup\` skill; a whole site: \`ipal-site\`. All skills: \`${skillsDir}/\`.`,
'4. Module details: `node_modules/@intecion/ipal-kit/docs/<module>.md`.',
'5. ipal-kit first: if the plugin has it, use it. Broken or not enough → report it with the `ipal-plugin-gap` skill and wait for the owner — no hand-built replacement, never patch `node_modules`.',
'6. Before you set up a site: ask the owner the architecture questions (AGENT.md "Ask before you build") and wait for the answers; record them under "Project decisions".',
'7. ipal-kit docs, this guide and the skills are in English; write rules, AGENTS.md entries and gap reports in English.',
END,
].join('\n')
const upsert = (file, { create }) => {
const path = join(process.cwd(), file)
const text = existsSync(path) ? readFileSync(path, 'utf8') : null
let next
if (text === null) {
if (!create) return
next = create === 'import' ? '@AGENTS.md\n' : `# ${file.replace('.md', '')}\n\n${block}\n`
} else if (text.includes(START) && text.includes(END)) {
next = text.slice(0, text.indexOf(START)) + block + text.slice(text.indexOf(END) + END.length)
} else {
next = `${text.replace(/\s*$/, '')}\n\n${block}\n`
}
if (next === text) return console.log(`ok ${file}`)
console.log(`${text === null ? 'create' : 'update'} ${file}`)
if (!dryRun) writeFileSync(path, next)
}
upsert('AGENTS.md', { create: 'block' })
const claude = join(process.cwd(), 'CLAUDE.md')
const importsAgents = existsSync(claude) && /^@AGENTS\.md\s*$/m.test(readFileSync(claude, 'utf8'))
// CLAUDE.md that imports AGENTS.md already sees the block — don't duplicate it.
if (!importsAgents) upsert('CLAUDE.md', { create: 'import' })
}
// Skills ship .ts/.tsx templates and scripts. A Next tsconfig ("include": ["**/*.tsx"]) would
// type-check them as project code and break `tsc` / `next build` → they must be excluded.
const tsconfig = join(process.cwd(), 'tsconfig.json')
@@ -53,7 +167,8 @@ const top = relative(process.cwd(), dest).split(/[\\/]/)[0]
if (existsSync(tsconfig) && top && !top.startsWith('..')) {
const text = readFileSync(tsconfig, 'utf8')
const exclude = text.match(/"exclude"\s*:\s*\[([^\]]*)\]/)?.[1] ?? ''
if (!exclude.includes(top)) {
const entries = [...exclude.matchAll(/"([^"]*)"/g)].map((m) => m[1].replace(/^\.\//, '').replace(/\/(\*\*)?$/, ''))
if (!entries.includes(top)) {
console.warn(`\n⚠ tsconfig.json does not exclude "${top}" — skill templates would be type-checked and break the build.`)
console.warn(` Add it: "exclude": ["node_modules", "${top}"]`)
process.exitCode = 1
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env node
// ipal-tokens — the brand's design tokens: src/design/tokens.ts → src/design/tokens.css,
// plus a WCAG contrast check (docs/design-tokens.md).
// pnpm exec ipal-tokens → write src/design/tokens.css, print the contrast report
// pnpm exec ipal-tokens --check → fail when the CSS is out of date (CI, ipal-doctor)
// pnpm exec ipal-tokens --in x.ts --out y.css --warn-only
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runTokensCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'tokens', 'cli.js')).href)
process.exit(await runTokensCli(process.argv.slice(2)))
+7 -1
View File
@@ -13,8 +13,14 @@ export default async function LocaleLayout({ children, params }: Props) {
return (
<html lang={locale}>
<body>
<SiteProviders banner={<CookieBanner equalChoice />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)}>
<SiteProviders banner={<CookieBanner controls="switch" equalChoice settings="detailed" />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)} stats={{ locale }}>
<main>{children}</main>
{/* A footer with links in the bottom-left corner: CookieButton must not cover them. */}
<footer style={{ borderTop: '1px solid #e5e5e5', display: 'flex', gap: '1.5rem', marginTop: '60vh', padding: '1.5rem 1rem' }}>
<a href={`/${locale}`}>Home</a>
<a href={`/${locale}/kontakt`}>Kontakt</a>
<a href={`/${locale}/polityka-prywatnosci`}>Polityka prywatności</a>
</footer>
</SiteProviders>
</body>
</html>
+88 -6
View File
@@ -1,24 +1,106 @@
import { TOTPField as TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { OverviewComponent as OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaTitleComponent as MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaDescriptionComponent as MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
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 { IntegrationStatusBanner as IntegrationStatusBanner_630f031911beff97691b963f10a20a86 } from '@intecion/ipal-kit/client'
import { MaskedField as MaskedField_630f031911beff97691b963f10a20a86 } from '@intecion/ipal-kit/client'
import { TestEmailButton as TestEmailButton_630f031911beff97691b963f10a20a86 } from '@intecion/ipal-kit/client'
import { RscEntryLexicalCell as RscEntryLexicalCell_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { RscEntryLexicalField as RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { LexicalDiffComponent as LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { InlineToolbarFeatureClient as InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { HorizontalRuleFeatureClient as HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { UploadFeatureClient as UploadFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { BlockquoteFeatureClient as BlockquoteFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { RelationshipFeatureClient as RelationshipFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { LinkFeatureClient as LinkFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ChecklistFeatureClient as ChecklistFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { OrderedListFeatureClient as OrderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { UnorderedListFeatureClient as UnorderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { IndentFeatureClient as IndentFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { AlignFeatureClient as AlignFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { HeadingFeatureClient as HeadingFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ParagraphFeatureClient as ParagraphFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { InlineCodeFeatureClient as InlineCodeFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { SuperscriptFeatureClient as SuperscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { SubscriptFeatureClient as SubscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { StrikethroughFeatureClient as StrikethroughFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { CookieScanButton as CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { FaviconCheck as FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TestEmailButton as TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { RowLabel as RowLabel_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieReviewTab as CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieSiteCheckTab as CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { AdminIcon as AdminIcon_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { AdminLogo as AdminLogo_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntecionCredit as IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsNavLink as StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsWidget as StatsWidget_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TotpRedirectProvider as TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
import { CookieApprovalView as CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
/** @type import('payload').ImportMap */
export const importMap = {
"@clocklimited/payload-2fa/rsc#TOTPField": TOTPField_3eb2cc20d1a2569c2ccbafcee15bd128,
"@payloadcms/plugin-seo/client#OverviewComponent": OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#MetaTitleComponent": MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#MetaDescriptionComponent": MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@intecion/ipal-kit/admin#MetaDescriptionCheck": MetaDescriptionCheck_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/plugin-seo/client#MetaImageComponent": MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#PreviewComponent": PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@intecion/ipal-kit/client#IntegrationStatusBanner": IntegrationStatusBanner_630f031911beff97691b963f10a20a86,
"@intecion/ipal-kit/client#MaskedField": MaskedField_630f031911beff97691b963f10a20a86,
"@intecion/ipal-kit/client#TestEmailButton": TestEmailButton_630f031911beff97691b963f10a20a86,
"@payloadcms/richtext-lexical/rsc#RscEntryLexicalCell": RscEntryLexicalCell_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/rsc#RscEntryLexicalField": RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/rsc#LexicalDiffComponent": LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/client#InlineToolbarFeatureClient": InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#HorizontalRuleFeatureClient": HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#UploadFeatureClient": UploadFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#BlockquoteFeatureClient": BlockquoteFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#RelationshipFeatureClient": RelationshipFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#LinkFeatureClient": LinkFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ChecklistFeatureClient": ChecklistFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#OrderedListFeatureClient": OrderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#UnorderedListFeatureClient": UnorderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#IndentFeatureClient": IndentFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#AlignFeatureClient": AlignFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#HeadingFeatureClient": HeadingFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ParagraphFeatureClient": ParagraphFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#InlineCodeFeatureClient": InlineCodeFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#SuperscriptFeatureClient": SuperscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#SubscriptFeatureClient": SubscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#StrikethroughFeatureClient": StrikethroughFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#UnderlineFeatureClient": UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@intecion/ipal-kit/admin#CookieScanButton": CookieScanButton_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#FaviconCheck": FaviconCheck_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationStatusBanner": IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TestEmailButton": TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#RowLabel": RowLabel_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieReviewTab": CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieSiteCheckTab": CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#AdminIcon": AdminIcon_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#AdminLogo": AdminLogo_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntecionCredit": IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsNavLink": StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsWidget": StatsWidget_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23,
"@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128,
"@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128,
"@intecion/ipal-kit/admin#CookieApprovalView": CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
}
+6
View File
@@ -2,3 +2,9 @@ export const devUser = {
email: '[email protected]',
password: '[email protected]',
}
/** Second dev login with the editor role — for checking what editors see. */
export const devEditor = {
email: '[email protected]',
password: '[email protected]',
}
+305 -5
View File
@@ -213,6 +213,19 @@ export interface Form {
width?: number | null;
required?: boolean | null;
defaultValue?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'checkbox';
@@ -231,6 +244,23 @@ export interface Form {
label?: string | null;
width?: number | null;
required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'email';
@@ -251,6 +281,19 @@ export interface Form {
};
[k: string]: unknown;
} | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'message';
@@ -261,6 +304,23 @@ export interface Form {
width?: number | null;
defaultValue?: number | null;
required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'number';
@@ -279,6 +339,19 @@ export interface Form {
}[]
| null;
required?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'select';
@@ -298,6 +371,23 @@ export interface Form {
width?: number | null;
defaultValue?: string | null;
required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'text';
@@ -308,6 +398,23 @@ export interface Form {
width?: number | null;
defaultValue?: string | null;
required?: boolean | null;
/**
* Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.
*/
placeholder?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'textarea';
@@ -335,6 +442,19 @@ export interface Form {
* Empty = no limit.
*/
maxSelected?: number | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'checkboxGroup';
@@ -345,6 +465,19 @@ export interface Form {
width?: number | null;
required?: boolean | null;
defaultValue?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'date';
@@ -362,6 +495,19 @@ export interface Form {
}[]
| null;
required?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'radio';
@@ -372,10 +518,48 @@ export interface Form {
*/
title?: string | null;
description?: string | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'step';
}
| {
/**
* Technical name, e.g. "services" — no spaces.
*/
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
/**
* Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".
*/
showWhen?: {
/**
* Technical name of another field.
*/
field?: string | null;
/**
* Comma-separated option values. Empty = when that field is filled in or ticked.
*/
values?: string | null;
};
id?: string | null;
blockName?: string | null;
blockType: 'time';
}
)[]
| null;
submitButtonLabel?: string | null;
@@ -701,6 +885,12 @@ export interface FormsSelect<T extends boolean = true> {
width?: T;
required?: T;
defaultValue?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -721,6 +911,13 @@ export interface FormsSelect<T extends boolean = true> {
label?: T;
width?: T;
required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -728,6 +925,12 @@ export interface FormsSelect<T extends boolean = true> {
| T
| {
message?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -739,6 +942,13 @@ export interface FormsSelect<T extends boolean = true> {
width?: T;
defaultValue?: T;
required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -758,6 +968,12 @@ export interface FormsSelect<T extends boolean = true> {
id?: T;
};
required?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -779,6 +995,13 @@ export interface FormsSelect<T extends boolean = true> {
width?: T;
defaultValue?: T;
required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -790,6 +1013,13 @@ export interface FormsSelect<T extends boolean = true> {
width?: T;
defaultValue?: T;
required?: T;
placeholder?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -809,6 +1039,12 @@ export interface FormsSelect<T extends boolean = true> {
};
minSelected?: T;
maxSelected?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -820,6 +1056,12 @@ export interface FormsSelect<T extends boolean = true> {
width?: T;
required?: T;
defaultValue?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -838,6 +1080,12 @@ export interface FormsSelect<T extends boolean = true> {
id?: T;
};
required?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -846,6 +1094,28 @@ export interface FormsSelect<T extends boolean = true> {
| {
title?: T;
description?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
time?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
showWhen?:
| T
| {
field?: T;
values?: T;
};
id?: T;
blockName?: T;
};
@@ -968,7 +1238,7 @@ export interface SiteSetting {
/**
* Separates the page title from the site name in browser tabs.
*/
titleSeparator?: ('|' | '–' | '-' | '·' | '/') | null;
titleSeparator?: ('pipe' | 'endash' | 'hyphen' | 'middot' | 'slash') | null;
/**
* Primary site logo.
*/
@@ -991,13 +1261,17 @@ export interface SiteSetting {
*/
favicon?: (number | null) | Media;
/**
* Theme applied on a visitor’s first visit.
* Theme applied on a visitor’s first visit. System = the visitor’s device setting.
*/
defaultTheme: 'light' | 'dark';
defaultTheme: 'light' | 'dark' | 'system';
/**
* Show a light/dark switch on the site.
*/
allowThemeToggle?: boolean | null;
/**
* Name of the switch read by screen readers, e.g. "Dark mode".
*/
themeToggleLabel?: string | null;
updatedAt?: string | null;
createdAt?: string | null;
}
@@ -1092,6 +1366,14 @@ export interface CookieSetting {
* Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again.
*/
policyVersion: number;
/**
* Small label above the banner title, e.g. "Privacy & cookies". Empty → not shown.
*/
eyebrow?: string | null;
/**
* Banner heading, e.g. "We respect your privacy". Empty → not shown.
*/
title?: string | null;
/**
* Main consent message shown in the banner.
*/
@@ -1100,6 +1382,14 @@ export interface CookieSetting {
* Heading for the detailed settings panel.
*/
settingsTitle?: string | null;
/**
* Intro under the settings heading — what cookies are for and that the choice can be changed later.
*/
settingsDescription?: string | null;
/**
* Badge next to the Necessary category, e.g. "Always active". Empty → a disabled switch/checkbox is shown instead.
*/
alwaysActiveLabel?: string | null;
/**
* Text of the privacy-policy link in the banner, e.g. "Privacy policy". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used.
*/
@@ -1111,8 +1401,12 @@ export interface CookieSetting {
acceptAll?: string | null;
reject?: string | null;
settings?: string | null;
save?: string | null;
savePreferences?: string | null;
back?: string | null;
/**
* Screen-reader label of the ✕ button in the settings dialog.
*/
close?: string | null;
};
/**
* Per-category titles and descriptions.
@@ -1206,6 +1500,7 @@ export interface SiteSettingsSelect<T extends boolean = true> {
favicon?: T;
defaultTheme?: T;
allowThemeToggle?: T;
themeToggleLabel?: T;
updatedAt?: T;
createdAt?: T;
globalType?: T;
@@ -1259,8 +1554,12 @@ export interface SiteIntegrationsSelect<T extends boolean = true> {
*/
export interface CookieSettingsSelect<T extends boolean = true> {
policyVersion?: T;
eyebrow?: T;
title?: T;
message?: T;
settingsTitle?: T;
settingsDescription?: T;
alwaysActiveLabel?: T;
privacyLinkLabel?: T;
buttons?:
| T
@@ -1268,8 +1567,9 @@ export interface CookieSettingsSelect<T extends boolean = true> {
acceptAll?: T;
reject?: T;
settings?: T;
save?: T;
savePreferences?: T;
back?: T;
close?: T;
};
categories?:
| T
+11 -1
View File
@@ -1,3 +1,4 @@
import { payloadTotp } from '@clocklimited/payload-2fa'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { ipalKit } from '../src/index.js'
@@ -67,15 +68,24 @@ export default buildConfig({
access: { authCollection: 'users' },
i18n: i18nConfig,
consentLog: true,
// Cookie review + "Crawl site" (needs IPAL_COOKIE_SCAN_URL / IPAL_COOKIE_SCAN_TOKEN and a running services/cookie-crawler).
cookieScanner: { crawl: true },
forms: {},
seo: { collections: ['posts', 'pages'] },
stats: true,
// 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator.
twoFactor: false,
// IPAL_DEV_2FA=1 turns it on (first-login setup and verify screens).
twoFactor: process.env.IPAL_DEV_2FA ? { issuer: 'ipal-kit dev', plugin: payloadTotp } : false,
// Panel logo/icon from Site settings and the technology support credit.
whiteLabel: true,
}),
],
secret: process.env.PAYLOAD_SECRET || 'test-secret_key',
sharp,
typescript: {
// Payload's dev init spawns `payload generate:types` on every start/recompile and never
// reaps it, so each restart left an orphan. Run `pnpm generate:types` when types change.
autoGenerate: false,
outputFile: path.resolve(dirname, 'payload-types.ts'),
},
})
+6 -1
View File
@@ -1,6 +1,6 @@
import type { Payload } from 'payload'
import { devUser } from './helpers/credentials.js'
import { devEditor, devUser } from './helpers/credentials.js'
export const seed = async (payload: Payload) => {
const { totalDocs } = await payload.count({
@@ -23,6 +23,11 @@ export const seed = async (payload: Payload) => {
})
}
const editors = await payload.count({ collection: 'users', where: { email: { equals: devEditor.email } } })
if (!editors.totalDocs) {
await payload.create({ collection: 'users', data: { ...devEditor, roles: ['editor'] } })
}
await seedContactPage(payload)
}
+1711 -271
View File
File diff suppressed because it is too large Load Diff
+52 -29
View File
@@ -1,40 +1,63 @@
# Dokumentacja @intecion/ipal-kit
# @intecion/ipal-kit documentation
| Kim jesteś | Czytaj |
All ipal-kit docs, the agent guide and the agent skills are written in English.
**Main rule — the plugin helps, never limits:** ipal-kit is a plugin — it helps projects and never
limits them. Every module can be turned off on its own, every default can be overridden (the project
config wins), safe defaults have an option to relax them, and the plugin exports building blocks
(helpers, builders, hooks), not only finished features. Every module page has a "Turn off, override,
extend" section that describes the current code.
| Who you are | Read |
|---|---|
| **Agent AI** pracujący w projekcie | [AGENT.md](./agent/AGENT.md) — reguły, struktura, budowa sekcji, kontrole przed „gotowe” |
| **Agent AI — skille** | [agent/skills/](./agent/skills) — 14 skilli `ipal-*` dla Antigravity/Claude Code, w tym `ipal-site` (strona od briefu do raportu) i skrypty kontrolne (kopiowane do projektu: `pnpm ipal:skills`, AGENT.md §14) |
| **Programista** | [PROGRAMISTA.md](./dev/PROGRAMISTA.md) — instalacja, nowy projekt, env, wdrożenie, aktualizacja, publikacja pluginu, Gitea |
| **Osoba prowadząca agenta AI** | [vibe.md](./dev/vibe.md) — tryb autonomiczny (`/ipal-site`) i gotowe polecenia krok po kroku |
| **AI agent** working in a project | [AGENT.md](./agent/AGENT.md) — rules, structure, building sections, checks before "done" |
| **AI agent — skills** | [agent/skills/](./agent/skills) — 15 `ipal-*` skills for Antigravity/Claude Code, including `ipal-reference` (full map of the plugin and every export), `ipal-setup` (complete installation), `ipal-site` (a site from brief to report) and the check scripts (copied into the project: `pnpm exec ipal-skills`, AGENT.md §14) |
| **Developer** | [PROGRAMISTA.md](./dev/PROGRAMISTA.md) — installation, new project, env, deployment, upgrades, releasing the plugin, Gitea; deployment and health check: [deployment.md](./deployment.md) |
| **Person driving an AI agent** | [vibe.md](./dev/vibe.md) — autonomous mode (`/ipal-site`) and ready-made step-by-step prompts |
Szczegóły API — jeden plik na moduł:
API details — one file per module:
| Moduł | Plik |
| Module | File |
|---|---|
| Role i dostęp do panelu | [access.md](./access.md) |
| Widget dostępności (opcjonalny) | [accessibility.md](./accessibility.md) |
| Roles and admin panel access | [access.md](./access.md) |
| Accessibility widget (optional) | [accessibility.md](./accessibility.md) |
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Zgoda cookies, baner | [consent.md](./consent.md) |
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
| Blocks, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
| Block library: ready sections, page templates | [block-library.md](./block-library.md) |
| Cookie consent, banner, settings window (in the bar / modal / large with cookie details) | [consent.md](./consent.md) |
| Cookie scanner: review list of drafts, "Scan cookies", Open Cookie Database lookup (optional) | [cookie-scanner.md](./cookie-scanner.md) |
| Under construction — locks subpages behind a popup (developer tool) | [construction.md](./construction.md) |
| Routing, archives, redirects, Markdown, search | [content.md](./content.md) |
| Site frontend: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](./frontend.md) |
| New site in one command (`ipal-kit create`, `@intecion/ipal-kit/starter`) | [project-starter.md](./project-starter.md) |
| Deployment, production variables, health check | [deployment.md](./deployment.md) |
| Seeds: create-only, dry run, backup, production update guard | [seeding.md](./seeding.md) |
| Email SMTP / Graph | [email.md](./email.md) |
| Walidacja env | [env.md](./env.md) |
| Formularze, useForm, honeypot | [forms.md](./forms.md) |
| Hooki | [hooks.md](./hooks.md) |
| i18n, proxy, przełącznik języka | [i18n.md](./i18n.md) |
| Linki / CTA: buildLinkField, buildLinksField, resolveLinkHref, rowLabel | [links.md](./links.md) |
| Serwer MCP strony | [mcp.md](./mcp.md) |
| Komunikaty formularzy | [notifications.md](./notifications.md) |
| Strony systemowe, 404, generateStaticParams | [pages.md](./pages.md) |
| Helpery Payload | [payload-helpers.md](./payload-helpers.md) |
| Rich text | [richtext.md](./richtext.md) |
| Nagłówki, CSP, 2FA | [security.md](./security.md) |
| Env validation | [env.md](./env.md) |
| Forms, useForm, honeypot | [forms.md](./forms.md) |
| GA4 + Meta Pixel through GTM (form events) | [gtm-meta-pixel.md](./gtm-meta-pixel.md) |
| Hooks | [hooks.md](./hooks.md) |
| i18n, proxy, language switcher | [i18n.md](./i18n.md) |
| Integrations (`site-integrations` global, statuses, test email) | [integrations.md](./integrations.md) |
| Links / CTA: buildLinkField, buildLinksField, resolveLinkHref, rowLabel | [links.md](./links.md) |
| Media: collection, file names, optimization, placeholders, `mediaImageProps` | [media.md](./media.md) |
| Image lightbox: enlarge a thumbnail, galleries, rich text images | [lightbox.md](./lightbox.md) |
| Site MCP server | [mcp.md](./mcp.md) |
| Form messages | [notifications.md](./notifications.md) |
| System pages, 404, generateStaticParams | [pages.md](./pages.md) |
| Payload helpers | [payload-helpers.md](./payload-helpers.md) |
| Rich text, table of contents | [richtext.md](./richtext.md) |
| Headers, CSP, 2FA | [security.md](./security.md) |
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](./seo.md) |
| Stats in the admin panel (no cookies; visitor history with consent) | [stats.md](./stats.md) |
| Auto-slug | [slug.md](./slug.md) |
| Media, R2 | [storage.md](./storage.md) |
| Light / dark theme, switcher | [theme.md](./theme.md) |
| Design tokens (`--ipal-*`, `tokens.css`, `tailwind.css`, `ipal-tokens`, DESIGN.md) | [design-tokens.md](./design-tokens.md) |
| R2, `buildImagesConfig`, `MediaPreconnect`, `YouTubeEmbed` | [storage.md](./storage.md) |
| Turnstile | [turnstile.md](./turnstile.md) |
| White-label panelu | [white-label.md](./white-label.md) |
| ipal-doctor (the site against the team standard, `ipal-doctor.json`) | [doctor.md](./doctor.md) |
| Admin panel white-label | [white-label.md](./white-label.md) |
Zasada utrzymania: zmiana API modułu → aktualizacja jego pliku w tym samym
commicie. Nowe reguły pracy → AGENT.md. Nowy krok procesu → PROGRAMISTA.md. Nowy etap budowy → vibe.md.
Nie dodawaj kolejnych plików ogólnych.
Maintenance rule: a module's API changes → update its file in the same commit. New working rules →
AGENT.md. New process step → PROGRAMISTA.md. New build stage → vibe.md.
Do not add more general files.
+168 -28
View File
@@ -1,48 +1,160 @@
# access
Kontrola dostępu oparta na rolach: hierarchia **admin > editor > user**.
Plugin wstrzykuje sztywne pole `roles` do klienckiej kolekcji auth i dostarcza
predykaty oraz gotowe funkcje dostępu (collection-level i field-level).
Role-based access control: hierarchy **admin > editor > user**.
The plugin injects a fixed `roles` field into the client's auth collection and provides
predicates and ready access functions (collection-level and field-level).
## Config (payload.config.ts)
```ts
ipalKit({
access: {
authCollection: 'users', // slug Twojej kolekcji auth
// defaultRole: 'user', // rola nowych użytkowników, domyślnie 'user'
authCollection: 'users', // slug of your auth collection (required)
// defaultRole: 'user', // role of new accounts
// firstUserAdmin: true, // the account from "Create first user" → admin
// authAccess: { … }, // access of the injected auth collection (your keys win)
// staffCollections: ['partners'], // more auth collections whose accounts are staff
},
// globalOverrides: { … }, // access / admin / hooks / fields of the plugin's globals
})
```
| Option | Default | What it does |
|---|---|---|
| `access.authCollection` | — (required) | the auth collection that gets the `roles` field |
| `access.defaultRole` | `'user'` | role of a new account when an admin did not set one |
| `access.firstUserAdmin` | `true` | the account from the "Create first user" screen (`…/first-register` on an empty collection) gets `['admin']`, even when the form picked `user`; `false` = it gets what was submitted |
| `access.authAccess` | see the table below | `access` of the **injected** auth collection, merged over the default (your keys win) |
| `access.staffCollections` | `[]` | more auth collections whose accounts count as **staff**, besides the one the panel logs in with (`admin.user`); see "Who is staff" |
| `globalOverrides` | — | changes to the plugin's globals: an object merges `access` / `admin` key by key (your keys win) and appends `hooks` (yours run after the plugin's), other keys (label, fields, …) replace; a function `(global) => global` takes over the whole global |
The `roles` field (select hasMany, required, `saveToJWT`): readable without limits; only an admin
can set and change it — also on account creation, so an open sign-up cannot
push `roles: ['admin']` through. The first-user screen and the Local API (seed) run with
`overrideAccess`. An account without roles meets no threshold (not even `'user'`); `authenticated`
only checks that someone is logged in.
**Auth collection when the project has none.** The plugin adds a minimal collection (`auth: true`,
`admin.useAsTitle: 'email'`) with the slug `access.authCollection` (or `twoFactor.collectionSlug`,
`admin.user`, `'users'`). The project's own collection with that slug always wins whole.
## What the plugin locks down by itself
| Resource | Read | Write | How to change |
|---|---|---|---|
| auth collection **injected** by the plugin, with roles | admin: everyone; other accounts **of that collection**: only themselves (`adminOrSelfIn`) | `create` / `delete` / `unlock`: admin; `update`: admin or self | `access.authAccess`, or your own collection |
| Site settings, Cookie banner, Notifications | public | `editor+` | `globalOverrides` |
| Site integrations | admin | admin | `globalOverrides` |
| Forms | public (Emails tab only `editor+`) | `editor+` | `forms.formOverrides.access`, the Emails field in `formOverrides.fields` |
| Form submissions | `editor+` | REST `create`: logged-in users; `delete`: admin | `forms.formSubmissionOverrides.access` |
```ts
import { authenticated } from '@intecion/ipal-kit'
ipalKit({
access: { authCollection: 'users', authAccess: { read: authenticated } }, // editors see the account list
globalOverrides: {
notifications: { access: { update: authenticated } }, // any logged-in account edits the texts
'site-settings': (g) => ({ ...g, admin: { ...g.admin, group: 'Configuration' } }),
},
})
```
Wstrzykuje pole `roles` (select hasMany, `saveToJWT`, tylko admin może
nadawać i zmieniać role — także przy tworzeniu konta, więc otwarta rejestracja nie
przepuści `roles: ['admin']`; nie-admin dostaje `defaultRole`) do wskazanej kolekcji.
Ekran pierwszego użytkownika i Local API (seed) działają z `overrideAccess`, więc
pierwszego admina nadal da się utworzyć. Kolekcja należy do Ciebie
(create-payload-app) — plugin tylko dokłada pole.
The project's own auth collection keeps its own `access` — the plugin only adds the
`roles` field. Give it at least `update: adminOrSelfIn('users')`, `delete: adminOnly`, `create: adminOnly`,
`unlock: adminOnly`: Payload's default lets any logged-in account change the email and password
of another account and unlock any account. A collection injected **without** `access` (no roles)
keeps Payload's default rules — without roles all accounts are equal.
> Po dodaniu: zadbaj, by seed / pierwszy user miał `roles: ['admin']`, inaczej
> stracisz dostęp do zasobów admin-only (np. SiteIntegrations).
## Who is staff
## Predykaty (front / hooki / access)
**Staff collections** are the auth collections whose accounts work in the panel:
- the one the admin panel logs in with (`admin.user`; Payload's default is the **first** auth collection in the
list — set `admin: { user: 'users' }` yourself as soon as the project has two);
- the one that carries the plugin's roles (`access.authCollection`);
- the ones named in `access.staffCollections`.
An account of **any other auth collection** — `customers`, `members`, a client zone — is a visitor to the
plugin. **Nothing in the plugin counts a role for it**, also when its own collection has a `roles` field with
the value `admin`: not `userMeetsRole`, not `isAdmin` / `isEditor` / `hasMinimumRole`, not `adminOnly`,
`adminOrEditor`, `requireRole`, `adminOrSelf`, `adminOrSelfIn` or the `…Field` variants, not the `roles` field
itself. The staff-collection check always comes first.
The plugin's own staff features — Site integrations, the settings globals, form submissions, consent records,
stats, the cookie scanner, `/api/ipal/test-email` — check with `userMeetsRole(req, minimum)`, in this order:
1. the account belongs to a staff collection;
2. with 2FA on: an account that has TOTP set up has entered the code in this session
([security.md](./security.md) → "What the second factor covers");
3. it holds at least the role `minimum` — **or** its collection has no `roles` field at all. Then every account
of that staff collection passes, as in Payload's default (without roles all accounts are equal).
What follows:
- **Without `access`** there is no `roles` field, so `isAdmin` always returns `false` and rule 3 keeps the
staff features reachable: every account of the panel collection is admin to the plugin. To narrow that
without roles: `globalOverrides` for the globals, `forms.formSubmissionOverrides` for submissions, or add
`access` to get roles.
- **A second staff collection** (e.g. `partners` who edit content): name it in
`access.staffCollections`. That is the one switch that makes its roles count. Without a `roles` field every
partner passes every staff check, admin ones included; to tell them apart add the field:
`fields: [buildRolesField('editor')]` in that collection. **2FA covers one collection** (`twoFactor.collectionSlug`,
by default the panel's): accounts of a further staff collection are staff with a password alone. ipalKit says
so in the log at start (`[ipal] 2FA covers "users" only…`); name such a collection only when that is acceptable.
- **Payload's own default** for a collection or global without `access` is "any logged-in account" — an account
of a visitor collection included. In a project with a second auth collection give every collection and global
explicit `access` (`adminOrEditor`, `requireRole(…)`, …).
- **A visitor collection that should reach one thing** (e.g. customers read their own form submissions):
do not make it staff. Write that one rule yourself — `forms.formSubmissionOverrides.access.read`,
`globalOverrides`, `collectionOverrides` of the module — and check `req.user.collection` in it.
- **A user object you build yourself** (Local API with `overrideAccess: false`, a custom auth strategy) must
carry `collection`: `{ ...doc, collection: 'users' }`. Payload's own strategies and `payload.auth()` set it. An
account without it is not staff.
> **Changed in 1.16.4.** Before, a role or the "no roles field" rule counted for an account
> of any auth collection: an account of a second auth collection passed staff checks — every one when its
> collection had no `roles` field, and the matching ones when it had its own `roles` field. A project with one
> auth collection sees no difference. A project that relied on a second collection being staff sets
> `access.staffCollections`.
## Predicates (front end / hooks / access)
```ts
import { isAdmin, isEditor, hasMinimumRole } from '@intecion/ipal-kit'
import { isAdmin, isEditor, hasMinimumRole, staffCollectionSlugs, userMeetsRole } from '@intecion/ipal-kit'
isAdmin(user) // admin?
isEditor(user) // editor lub admin (hierarchia)
hasMinimumRole(user, 'editor') // co najmniej editor
isAdmin(req.user, req.payload) // a staff account with the admin role
isEditor(req.user, req.payload) // editor or admin (hierarchy)
hasMinimumRole(req.user, 'editor', req.payload) // at least editor
userMeetsRole(req, 'admin') // the plugin's staff check: staff collection, second factor, role ("Who is staff")
staffCollectionSlugs(req.payload) // ['users', …]
```
Przyjmują luźno typowanego usera (jak `req.user`), czytają `roles` defensywnie.
They take a loosely typed user (like `req.user`) and read `roles` defensively. The last argument tells them
which collections are staff:
## Gotowe funkcje dostępu
| Where you call it | Pass | Without it |
|---|---|---|
| access functions, hooks, endpoints (server, the config is loaded) | `req.payload` | works: the staff collections of the config `ipalKit` built in this process. With two different configs in one process, only collections that are staff in **both** count — pass `req.payload` to get that config's own answer |
| client components | the config from `useConfig()` (it has `admin.user`), or `{ staffCollections: ['users', …] }` | **always `false`** — the browser bundle has no config |
| Next middleware / `proxy.ts`, the edge runtime | `{ staffCollections: ['users'] }` | **always `false`** — the config is not loaded there |
### Collection-level (zwracają boolean | Where)
```tsx
'use client'
const { config } = useConfig()
const { user } = useAuth()
if (isAdmin(user, config)) { /* show the button — a hint only, the server decides */ }
```
They fail closed: where the staff collections are not known, nobody is staff, and an account without
`collection` is nobody. `isAdmin` and the others do **not** check the second factor; `userMeetsRole` and every
`access` function in the config do.
## Ready access functions
### Collection-level (return boolean | Where)
```ts
import { adminOnly, adminOrEditor, adminOrSelf, requireRole, authenticated } from '@intecion/ipal-kit'
import { adminOnly, adminOrEditor, adminOrSelf, adminOrSelfIn, requireRole, authenticated } from '@intecion/ipal-kit'
export const Articles = {
slug: 'articles',
@@ -55,14 +167,18 @@ export const Articles = {
// ...
}
// Users: każdy widzi siebie, admin widzi wszystkich
access: { read: adminOrSelf }
// Users: everyone sees themselves, an admin sees everyone.
// adminOrSelfIn(slug): "self" = an account of THAT collection. Use it for an auth collection whenever
// the project has more than one: adminOrSelf only compares ids, and with numeric ids (Postgres, SQLite)
// customer no. 5 would match staff account no. 5.
access: { read: adminOrSelfIn('users') }
access: { read: adminOrSelf } // fine with a single auth collection
// dowolny minimalny próg
// any minimum threshold
access: { update: requireRole('editor') }
```
### Field-level (zwracają boolean)
### Field-level (return boolean)
```ts
import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/ipal-kit'
@@ -74,9 +190,33 @@ import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/
}
```
## Hierarchia
## Hierarchy
```ts
import { ROLE_HIERARCHY } from '@intecion/ipal-kit'
// ['user', 'editor', 'admin'] — wyższa rola spełnia wymóg niższej
// ['user', 'editor', 'admin'] — a higher role meets a lower role's requirement
```
## Building blocks: buildRolesField, injectRoles, applyGlobalOverrides
```ts
import { applyGlobalOverrides, buildRolesField, injectRoles } from '@intecion/ipal-kit'
buildRolesField('user', { firstUserAdmin: true }) // just the roles field — for your own collection
injectRoles(config, { authCollection: 'members' }) // add the field to a collection in a finished config
applyGlobalOverrides(globals, { notifications: { … } }) // the same logic as the globalOverrides option
```
Types: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug`.
## Turn off, override, extend
- **Turn off:** leave out `access` — no `roles` field, the auth collection keeps Payload's rules
(or yours). `access.firstUserAdmin: false` stops giving admin to the first account.
- **Override:** `access.staffCollections` (who is staff), `access.authAccess` (injected collection), your own auth collection (wins whole),
`globalOverrides` (globals), `forms.formOverrides` / `formSubmissionOverrides` (forms),
`defaultRole`. The role hierarchy (`ROLE_HIERARCHY`) is fixed.
- **Extend:** `requireRole` / `requireRoleField`, `adminOrSelfIn`, predicates (`userMeetsRole`, `staffCollectionSlugs`), `buildRolesField`, `injectRoles`,
`applyGlobalOverrides` in your own collections and globals.
- **Check:** log in with a `user` account → `PATCH /api/globals/site-settings` = 403,
`DELETE /api/users/<admin id>` = 403; the account from "Create first user" has the `admin` role.
+108 -69
View File
@@ -1,26 +1,27 @@
# Dostępność — widget a11y (WCAG)
# Accessibility — a11y widget (WCAG)
Widget dostępności: pływający przycisk otwierający panel z opcjami dla osób z
niepełnosprawnościami (rozmiar tekstu, kontrast, skala szarości, podkreślone
linki, czytelna czcionka, wyłączenie animacji, duży kursor).
Accessibility widget: a floating button that opens a panel with options for people
with disabilities (text size, contrast, grayscale, underlined links, readable font,
no animations, big cursor).
> **OPCJONALNY — nie dodawaj domyślnie.** Widget a11y jest wymagany prawnie
> TYLKO dla niektórych stron (podmioty publiczne, część e-commerce/usług objętych
> European Accessibility Act). Dla większości stron komercyjnych to OPCJA, nie
> obowiązek. Dodawaj GDY klient/projekt tego wymaga — nie na każdej stronie z
> automatu. W razie wątpliwości: zapytaj, czy strona podlega wymogom dostępności.
> **OPTIONAL — do not add by default.** The a11y widget is legally required
> ONLY for some sites (public bodies, some e-commerce/services covered by the
> European Accessibility Act). For most commercial sites it is an OPTION, not a
> duty. Add it WHEN the client/project requires it — not on every site
> automatically. If in doubt: ask whether the site falls under accessibility rules.
Wzorzec jak CookieBanner: provider + widget, wpinasz raz. Preferencje w cookie
(bez flash), stosowane jako atrybuty `data-a11y-*` na `<html>`.
Same pattern as CookieBanner: provider + widget, wired once. Preferences live in a
cookie (no flash) and are applied as `data-a11y-*` attributes on `<html>`.
> **Granica plugin/projekt:** plugin dostarcza MECHANIZM (widget, stan, cookie,
> atrybuty na html). Projekt dostarcza CSS reagujący na atrybuty — bo style
> zależą od designu projektu (kolory, czcionki, Tailwind). Plugin NIE narzuca
> stylów, żeby nie kolidować. Gotowy CSS do skopiowania niżej.
> **Plugin/project boundary:** the plugin provides the MECHANISM (widget, state,
> cookie, attributes on html). The project provides the CSS that reacts to the
> attributes — because styles depend on the project design (colors, fonts,
> Tailwind). The plugin does NOT impose styles, so nothing clashes. Ready-to-copy
> CSS is below.
---
## 1. Wpięcie — Provider + Widget
## 1. Wiring — Provider + Widget
```tsx
// app/(frontend)/[locale]/layout.tsx
@@ -40,19 +41,19 @@ import { AccessibilityProvider, AccessibilityWidget } from '@intecion/ipal-kit/c
resetButton: 'a11y-reset',
closeButton: 'a11y-close',
}}
texts={A11Y[locale]} // etykiety per locale; domyślnie ANGIELSKI
texts={A11Y[locale]} // labels per locale; ENGLISH by default
/>
</body>
</AccessibilityProvider>
```
Widget jest bez stylów (jak CookieBanner) — classNames dopasowujesz do designu.
The widget is unstyled (like CookieBanner) — match the classNames to your design.
## Etykiety — domyślnie angielski, konfiguracja per locale
## Labels — English by default, configured per locale
Domyślne etykiety są **angielskie** (plugin jest wielojęzyczny, neutralny bazowo).
Tłumaczenia trzymasz w projekcie i podajesz zestaw dla aktywnego języka przez
`texts` (`A11yTexts`). Plugin pozostaje content-agnostyczny:
Default labels are **English** (the plugin is multilingual, neutral at its base).
Keep translations in the project and pass the set for the active language through
`texts` (`A11yTexts`). The plugin stays content-agnostic:
```tsx
import type { A11yTexts } from '@intecion/ipal-kit/client'
@@ -65,56 +66,62 @@ const A11Y: Record<string, A11yTexts> = {
<AccessibilityWidget texts={A11Y[locale]} classNames={{ /* … */ }} />
```
Podajesz tylko te klucze, które chcesz nadpisać — reszta spadnie na angielski
default. Możesz też trzymać etykiety w zlokalizowanym globalu i czytać je z panelu
(spójne z „zarządzanie z panelu"), ale to już decyzja projektu — plugin wymaga
tylko `A11yTexts` dla bieżącego locale.
Pass only the keys you want to override — the rest falls back to the English
default. You can also keep the labels in a localized global and read them from the
panel (consistent with "managed from the panel"), but that is a project decision —
the plugin only needs `A11yTexts` for the current locale.
---
## 2. CSS reagujący na atrybuty (OBOWIĄZKOWE — projekt)
## 2. CSS that reacts to the attributes (MANDATORY — project)
Widget ustawia atrybuty na `<html>`. Bez tego CSS nic się nie dzieje. Skopiuj do
globalnego CSS projektu (dostosuj do designu):
The widget sets attributes on `<html>`. Without CSS for them nothing happens.
**Ready file (1.15.0):** `@import "@intecion/ipal-kit/a11y.css";` in `styles.css` — the rules below, working through
the design tokens ([design-tokens.md](./design-tokens.md)): the readable font swaps `--ipal-font-body/-heading` (set
`--ipal-font-readable` to change it), "no animations" zeroes the `--ipal-duration-*` tokens, contrast + grayscale
combine, the big cursor is built in. Check: tick each option in the widget and see the page change.
Or copy this into the project's global CSS (adapt it to the design):
```css
/* Rozmiar tekstu */
/* Text size */
html[data-a11y-text="1"] { font-size: 112.5%; }
html[data-a11y-text="2"] { font-size: 125%; }
html[data-a11y-text="3"] { font-size: 150%; }
/* Odstęp między liniami */
/* Line spacing */
html[data-a11y-line="1"] * { line-height: 1.8 !important; }
html[data-a11y-line="2"] * { line-height: 2.2 !important; }
/* Kontrast wysoki */
/* High contrast */
html[data-a11y-contrast="high"] {
filter: contrast(1.4);
}
/* Kontrast odwrócony */
/* Inverted contrast */
html[data-a11y-contrast="inverted"] {
filter: invert(1) hue-rotate(180deg);
}
html[data-a11y-contrast="inverted"] img,
html[data-a11y-contrast="inverted"] video {
filter: invert(1) hue-rotate(180deg); /* przywróć media */
filter: invert(1) hue-rotate(180deg); /* restore media */
}
/* Skala szarości */
/* Grayscale */
html[data-a11y-grayscale="on"] { filter: grayscale(1); }
/* Uwaga: filter na html nie kumuluje się — jeśli łączysz kontrast+szarość,
zastosuj na body albo połącz w jednej regule. */
/* Note: filter on html does not stack — if you combine contrast+grayscale,
apply it on body or merge it into one rule. */
/* Podkreślone linki */
/* Underlined links */
html[data-a11y-underline="on"] a { text-decoration: underline !important; }
/* Czytelna czcionka (podmień na swoją dyslexia-friendly / prostą) */
/* Readable font (swap in your own dyslexia-friendly / simple font) */
html[data-a11y-font="readable"] * {
font-family: Verdana, Tahoma, sans-serif !important;
letter-spacing: 0.02em;
}
/* Wyłączenie animacji */
/* No animations */
html[data-a11y-motion="reduce"] *,
html[data-a11y-motion="reduce"] *::before,
html[data-a11y-motion="reduce"] *::after {
@@ -123,31 +130,31 @@ html[data-a11y-motion="reduce"] *::after {
scroll-behavior: auto !important;
}
/* Duży kursor */
/* Big cursor */
html[data-a11y-cursor="big"] * {
cursor: url('/cursors/big.svg') 4 4, auto !important;
}
```
Dostosuj wartości do projektu (kolory kontrastu, czcionka, kursor). To Twój CSS —
plugin tylko ustawia atrybuty.
Adapt the values to the project (contrast colors, font, cursor). This is your CSS —
the plugin only sets the attributes.
> **Kontrast + filter:** wiele opcji używa `filter` na `<html>`. CSS `filter` na
> jednym elemencie NIE kumuluje wielu wartości z różnych reguł — ostatnia wygrywa.
> Jeśli chcesz łączyć (np. szarość + kontrast), zastosuj filtry na `body` z
> pełną wartością, albo zbuduj reguły kombinowane. Dla pojedynczych opcji działa
> bez problemu.
> **Contrast + filter:** several options use `filter` on `<html>`. CSS `filter` on
> one element does NOT stack values from different rules — the last one wins.
> If you want to combine them (e.g. grayscale + contrast), apply the filters on
> `body` with the full value, or build combined rules. Single options work
> without issues.
---
## 3. Bez flash (SSR) — opcjonalne
## 3. No flash (SSR) — optional
Domyślnie widget stosuje atrybuty po hydratacji (krótki flash przy ładowaniu,
jeśli użytkownik miał ustawienia). Żeby tego uniknąć, odczytaj cookie server-side
i ustaw atrybuty na `<html>` w SSR:
By default the widget applies the attributes after hydration (a short flash on load
if the user had settings). To avoid it, read the cookie server-side and set the
attributes on `<html>` during SSR:
```tsx
// layout.tsx (server) — odczytaj cookie i ustaw atrybuty od razu
// layout.tsx (server) — read the cookie and set the attributes right away
import { cookies } from 'next/headers'
import { A11Y_COOKIE, parseA11y, a11yAttributes } from '@intecion/ipal-kit'
@@ -160,34 +167,66 @@ const htmlAttrs = Object.fromEntries(
return <html lang={locale} {...htmlAttrs}>...</html>
```
Provider i tak re-aplikuje na kliencie i synchronizuje. To tylko eliminuje flash.
The provider re-applies and syncs on the client anyway. This only removes the flash.
### State and attributes (`A11yState`)
Cookie `a11y-prefs` (`A11Y_COOKIE`, JSON, `path=/`, `max-age` 1 year, `samesite=lax`).
It is written only when the visitor changes a setting, with no consent check: a preference the visitor
chose, no tracking (the same reasoning as the theme choice, theme.md). List it as **necessary** in the
cookie list — the scanner does not declare it, add it with `declarations` (cookie-scanner.md).
Widget texts: `texts` prop wins, otherwise `A11Y_DEFAULT_TEXTS[locale]` (`en`, `pl`; prop `locale`,
incl. `texts.on` / `texts.off` for the switches).
The helpers `A11Y_COOKIE`, `A11Y_DEFAULT`, `parseA11y`, `serializeA11y`, `a11yAttributes`
are in `@intecion/ipal-kit` (not in `/client`). The `A11yState` type is in both entries.
| State key | Values | Attribute on `<html>` (none = default) |
|---|---|---|
| `textSize` | `0`–`3` | `data-a11y-text="1..3"` |
| `lineHeight` | `0`–`2` | `data-a11y-line="1..2"` |
| `contrast` | `'default' \| 'high' \| 'inverted'` | `data-a11y-contrast="high\|inverted"` |
| `grayscale` | boolean | `data-a11y-grayscale="on"` |
| `underlineLinks` | boolean | `data-a11y-underline="on"` |
| `readableFont` | boolean | `data-a11y-font="readable"` |
| `reduceMotion` | boolean | `data-a11y-motion="reduce"` |
| `bigCursor` | boolean | `data-a11y-cursor="big"` |
---
## 4. Osobny przycisk otwierający (opcjonalnie)
## 4. Separate open button (optional)
Widget ma wbudowany pływający przycisk. Jeśli chcesz otwierać panel z innego
miejsca (np. stopka „Dostępność"), użyj hooka:
The widget has a built-in floating button. If you want to open the panel from
somewhere else (e.g. an "Accessibility" link in the footer), use the hook:
```tsx
'use client'
import { useAccessibility } from '@intecion/ipal-kit/client'
// stan otwarcia trzymaj sam, albo rozbuduj widget — hook daje state/set/reset
// keep the open state yourself, or extend the widget — the hook gives state/set/reset
```
---
## 5. Compliance — kiedy dostępność jest wymagana
## 5. Compliance — when accessibility is required
Dostępność (WCAG) jest wymagana prawnie TYLKO dla części stron:
- **Podmioty publiczne** (urzędy, szkoły, instytucje) — ustawa o dostępności cyfrowej
- **Duże e-commerce / usługi** objęte European Accessibility Act (2019/882, od 2025)
- Strony, gdzie klient sam tego wymaga (polityka firmy, przetarg)
Accessibility (WCAG) is legally required ONLY for some sites:
- **Public bodies** (government offices, schools, institutions) — the Polish digital accessibility act
- **Large e-commerce / services** covered by the European Accessibility Act (2019/882, from 2025)
- Sites where the client requires it (company policy, public tender)
Dla **większości stron komercyjnych** (wizytówka, mała firma, katalog) widget a11y
to **opcja, nie obowiązek** — dodawaj gdy klient wymaga, nie z automatu.
For **most commercial sites** (business card site, small company, catalog) the a11y
widget is **an option, not a duty** — add it when the client requires it, not
automatically.
Gdy dodajesz: widget sam w sobie NIE czyni strony w pełni dostępną — to pomoc dla
użytkownika. Pełna dostępność to też semantyczny HTML, alt teksty, nawigacja
klawiaturą, kontrast bazowy. Widget uzupełnia, nie zastępuje. Nie sprzedawaj
klientowi „mamy widget = jesteśmy zgodni z WCAG". Patrz PROGRAMISTA.md §5.
When you add it: the widget by itself does NOT make the site fully accessible — it
helps the user. Full accessibility also means semantic HTML, alt texts, keyboard
navigation, baseline contrast. The widget complements, it does not replace. Do not
sell the client "we have a widget = we are WCAG compliant". See [dev/PROGRAMISTA.md](dev/PROGRAMISTA.md) §5.
## Turn off, override, extend
- **Turn off:** the module is opt-in — without `AccessibilityProvider` / `AccessibilityWidget` nothing happens
(no option in `ipalKit`, no fields in the panel).
- **Override:** the widget's `classNames` and `texts`; the whole look of the effects is project CSS.
- **Extend:** your own UI on `useAccessibility()` (`state`, `set`, `reset`); SSR helpers
`parseA11y` / `a11yAttributes` / `serializeA11y` / `A11Y_DEFAULT`. The option set (`A11yState`) currently
cannot be extended without changes in the plugin.
+1207 -800
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Addy Osmani
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+475
View File
@@ -0,0 +1,475 @@
---
name: ext-accessibility
description: Audit and improve web accessibility following WCAG 2.2 guidelines. Use when asked to "improve accessibility", "a11y audit", "WCAG compliance", "screen reader support", "keyboard navigation", or "make accessible".
license: MIT
metadata:
author: web-quality-skills
version: "2.0"
---
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
> Never add a dependency this skill suggests without the owner's decision.
>
> **Tools:** never run `npx lighthouse` / `npx @axe-core/cli` unpinned — add them as devDependencies at fixed versions
> first. Use the ipal-kit components (CookieBanner, AccessibilityWidget, RenderForm…) and fix their markup through
> their props or a plugin gap report, not by copying them.
# Accessibility (a11y)
Comprehensive accessibility guidelines based on WCAG 2.2 and Lighthouse accessibility audits. Goal: make content usable by everyone, including people with disabilities.
## Evidence-led audit workflow
When a rendered page is available:
1. Run a live Lighthouse Accessibility audit when that capability is available; with Chrome DevTools MCP, use `lighthouse_audit`. Use mobile navigation mode for a general public page or snapshot mode when reloading would lose authenticated or user-created state.
2. Use failed audit nodes to localize the relevant component or template instead of searching the whole repository for generic patterns.
3. Inspect a rendered accessibility-tree snapshot for names, roles, states, landmarks, and heading structure; with Chrome DevTools MCP, use `take_snapshot`. Exercise the affected flow with the keyboard.
4. Fix the source, then re-run the same audit and manual interaction.
If the live tools are unavailable, use Lighthouse CLI or axe for automated coverage and complete the same manual checks. Automated tools detect only a subset of accessibility barriers: a score of 100 is not WCAG conformance, and a low score does not replace issue-level evidence.
## WCAG Principles: POUR
| Principle | Description |
|-----------|-------------|
| **P**erceivable | Content can be perceived through different senses |
| **O**perable | Interface can be operated by all users |
| **U**nderstandable | Content and interface are understandable |
| **R**obust | Content works with assistive technologies |
## Conformance levels
| Level | Requirement | Target |
|-------|-------------|--------|
| **A** | Minimum accessibility | Must pass |
| **AA** | Standard compliance | Should pass (legal requirement in many jurisdictions) |
| **AAA** | Enhanced accessibility | Nice to have |
---
## Perceivable
### Text alternatives (1.1)
**Images require alt text:**
```html
<!-- ❌ Missing alt -->
<img src="chart.png">
<!-- ✅ Descriptive alt -->
<img src="chart.png" alt="Bar chart showing 40% increase in Q3 sales">
<!-- ✅ Decorative image (empty alt) -->
<img src="decorative-border.png" alt="" role="presentation">
<!-- ✅ Complex image with longer description -->
<figure>
<img src="infographic.png" alt="2024 market trends infographic"
aria-describedby="infographic-desc">
<figcaption id="infographic-desc">
<!-- Detailed description -->
</figcaption>
</figure>
```
**Icon buttons need accessible names:**
```html
<!-- ❌ No accessible name -->
<button><svg><!-- menu icon --></svg></button>
<!-- ✅ Using aria-label -->
<button aria-label="Open menu">
<svg aria-hidden="true"><!-- menu icon --></svg>
</button>
<!-- ✅ Using visually hidden text -->
<button>
<svg aria-hidden="true"><!-- menu icon --></svg>
<span class="visually-hidden">Open menu</span>
</button>
```
**Visually hidden class:**
```css
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
```
### Color contrast (1.4.3, 1.4.6)
| Text Size | AA minimum | AAA enhanced |
|-----------|------------|--------------|
| Normal text (< 18px / < 14px bold) | 4.5:1 | 7:1 |
| Large text (≥ 18px / ≥ 14px bold) | 3:1 | 4.5:1 |
| UI components & graphics | 3:1 | 3:1 |
```css
/* ❌ Low contrast (2.5:1) */
.low-contrast {
color: #999;
background: #fff;
}
/* ✅ Sufficient contrast (7:1) */
.high-contrast {
color: #333;
background: #fff;
}
/* ✅ Focus states need contrast too (3:1 against background, WCAG 1.4.11) */
:focus-visible {
outline: 2px solid currentColor;
outline-offset: 2px;
}
```
**Don't rely on color alone:**
```html
<!-- ❌ Only color indicates error -->
<input class="error-border">
<style>.error-border { border-color: red; }</style>
<!-- ✅ Color + icon + text -->
<div class="field-error">
<input aria-invalid="true" aria-describedby="email-error">
<span id="email-error" class="error-message">
<svg aria-hidden="true"><!-- error icon --></svg>
Please enter a valid email address
</span>
</div>
```
### Media alternatives (1.2)
```html
<!-- Video with captions -->
<video controls>
<source src="video.mp4" type="video/mp4">
<track kind="captions" src="captions.vtt" srclang="en" label="English" default>
<track kind="descriptions" src="descriptions.vtt" srclang="en" label="Descriptions">
</video>
<!-- Audio with transcript -->
<audio controls>
<source src="podcast.mp3" type="audio/mp3">
</audio>
<details>
<summary>Transcript</summary>
<p>Full transcript text...</p>
</details>
```
---
## Operable
### Keyboard accessible (2.1)
**All functionality must be keyboard accessible.** Prefer native interactive elements — `<button>`, `<a href>`, and form controls handle Enter/Space activation, focus, and assistive-tech semantics for free. Only add manual keyboard handling when you cannot use a native element.
```html
<!-- ❌ Non-interactive element with click only: not focusable, no keyboard activation -->
<div class="card" onclick="handleAction()">Open</div>
<!-- ✅ Best: use a native button -->
<button type="button" onclick="handleAction()">Open</button>
```
```javascript
// ✅ When you MUST use a non-interactive element (e.g. div with role="button"),
// make it focusable AND handle keyboard activation. Do NOT add this to a native
// <button> — Enter/Space already fire click, so you'd double-trigger.
element.setAttribute('role', 'button');
element.setAttribute('tabindex', '0');
element.addEventListener('click', handleAction);
element.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleAction();
}
});
```
**No keyboard traps.** Users must be able to Tab into and out of every component. Use the [modal focus trap pattern](references/A11Y-PATTERNS.md#modal-focus-trap) for dialogs—the native `<dialog>` element handles this automatically.
### Focus visible (2.4.7)
```css
/* ❌ Never remove focus outlines */
*:focus { outline: none; }
/* ✅ Use :focus-visible for keyboard-only focus */
:focus {
outline: none;
}
:focus-visible {
outline: 2px solid currentColor; /* inherits text color → already contrast-checked */
outline-offset: 2px;
}
/* ✅ Or pick a brand color and verify ≥3:1 contrast against every background it lands on */
button:focus-visible {
box-shadow: 0 0 0 3px rgba(0, 95, 204, 0.5);
}
```
### Focus not obscured (2.4.11) — new in 2.2
When an element receives keyboard focus, it must not be entirely hidden by other author-created content such as sticky headers, footers, or overlapping panels. At Level AAA (2.4.12), no part of the focused element may be hidden.
```css
/* ✅ Account for sticky headers when scrolling to focused elements */
:target {
scroll-margin-top: 80px;
}
/* ✅ Ensure focused items clear fixed/sticky bars */
:focus {
scroll-margin-top: 80px;
scroll-margin-bottom: 60px;
}
```
### Skip links (2.4.1)
Provide a skip link so keyboard users can bypass repetitive navigation. See the [skip link pattern](references/A11Y-PATTERNS.md#skip-link) for full markup and styles.
### Target size (2.5.8) — new in 2.2
Interactive targets must be at least **24 × 24 CSS pixels** (AA). Exceptions: inline text links, elements where the browser controls the size, and targets where a 24px circle centered on the bounding box does not overlap another target.
```css
/* ✅ Minimum target size */
button,
[role="button"],
input[type="checkbox"] + label,
input[type="radio"] + label {
min-width: 24px;
min-height: 24px;
}
/* ✅ Comfortable target size (recommended 44×44) */
.touch-target {
min-width: 44px;
min-height: 44px;
display: inline-flex;
align-items: center;
justify-content: center;
}
```
### Dragging movements (2.5.7) — new in 2.2
Any action that requires dragging must have a single-pointer alternative (e.g., buttons, inputs). See the [dragging movements pattern](references/A11Y-PATTERNS.md#dragging-movements) for a sortable-list example.
### Timing (2.2)
```javascript
// Allow users to extend time limits
function showSessionWarning() {
const modal = createModal({
title: 'Session Expiring',
content: 'Your session will expire in 2 minutes.',
actions: [
{ label: 'Extend session', action: extendSession },
{ label: 'Log out', action: logout }
],
timeout: 120000
});
}
```
### Motion (2.3)
```css
/* Respect reduced motion preference */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
```
---
## Understandable
### Page language (3.1.1)
```html
<!-- ❌ No language specified -->
<html>
<!-- ✅ Language specified -->
<html lang="en">
<!-- ✅ Language changes within page -->
<p>The French word for hello is <span lang="fr">bonjour</span>.</p>
```
### Consistent navigation (3.2.3)
```html
<!-- Navigation should be consistent across pages -->
<nav aria-label="Main">
<ul>
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/products">Products</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
```
### Consistent help (3.2.6) — new in 2.2
If a help mechanism (contact info, chat widget, FAQ link, self-help option) is repeated across multiple pages, it must appear in the **same relative order** each time. Users who rely on consistent placement shouldn't have to hunt for help on every page.
### Form labels (3.3.2)
Every input needs a programmatically associated label. See the [form labels pattern](references/A11Y-PATTERNS.md#form-labels) for explicit, implicit, and instructional examples.
### Error handling (3.3.1, 3.3.3)
Announce errors to screen readers with `role="alert"` or `aria-live`, set `aria-invalid="true"` on invalid fields, and focus the first error on submit. See the [error handling pattern](references/A11Y-PATTERNS.md#error-handling) for full markup and JS.
### Redundant entry (3.3.7) — new in 2.2
Don't force users to re-enter information they already provided in the same session. Auto-populate from earlier steps, or let users select from previously entered values. Exceptions: security re-confirmation and content that has expired.
```html
<!-- ✅ Auto-fill shipping address from billing -->
<fieldset>
<legend>Shipping address</legend>
<label>
<input type="checkbox" id="same-as-billing" checked>
Same as billing address
</label>
<!-- Fields auto-populated when checked -->
</fieldset>
```
### Accessible authentication (3.3.8) — new in 2.2
Login flows must not rely on cognitive function tests (e.g., remembering a password, solving a puzzle) unless at least one of:
- A copy-paste or autofill mechanism is available
- An alternative method exists (e.g., passkey, SSO, email link)
- The test uses object recognition or personal content (AA only; AAA removes this exception)
```html
<!-- ✅ Allow paste in password fields -->
<input type="password" id="password" autocomplete="current-password">
<!-- ✅ Offer passwordless alternatives -->
<button type="button">Sign in with passkey</button>
<button type="button">Email me a login link</button>
```
---
## Robust
### ARIA usage (4.1.2)
**Prefer native elements:**
```html
<!-- ❌ ARIA role on div -->
<div role="button" tabindex="0">Click me</div>
<!-- ✅ Native button -->
<button>Click me</button>
<!-- ❌ ARIA checkbox -->
<div role="checkbox" aria-checked="false">Option</div>
<!-- ✅ Native checkbox -->
<label><input type="checkbox"> Option</label>
```
**When ARIA is needed,** use the correct roles and states. See the [ARIA tabs pattern](references/A11Y-PATTERNS.md#aria-tabs) for a complete tablist example.
### Live regions (4.1.3)
Use `aria-live` regions to announce dynamic content changes without moving focus. See the [live regions pattern](references/A11Y-PATTERNS.md#live-regions-and-notifications) for markup and a `showNotification()` helper.
---
## Testing checklist
### Automated testing
Prefer a live Lighthouse audit that returns failing rendered nodes directly to the agent. With Chrome DevTools MCP, this is `lighthouse_audit`. Otherwise:
```bash
# Lighthouse accessibility audit
npx lighthouse https://example.com --only-categories=accessibility
# axe-core
npm install @axe-core/cli -g
axe https://example.com
```
### Manual testing
- [ ] **Keyboard navigation:** Tab through entire page, use Enter/Space to activate
- [ ] **Screen reader:** Test with VoiceOver (Mac), NVDA (Windows), or TalkBack (Android)
- [ ] **Zoom:** Content usable at 200% zoom
- [ ] **High contrast:** Test with Windows High Contrast Mode
- [ ] **Reduced motion:** Test with `prefers-reduced-motion: reduce`
- [ ] **Focus order:** Logical and follows visual order
- [ ] **Target size:** Interactive elements meet 24×24px minimum
See the [screen reader commands reference](references/A11Y-PATTERNS.md#screen-reader-commands) for VoiceOver and NVDA shortcuts.
---
## Common issues by impact
### Critical (fix immediately)
1. Missing form labels
2. Missing image alt text
3. Insufficient color contrast
4. Keyboard traps
5. No focus indicators
### Serious (fix before launch)
1. Missing page language
2. Missing heading structure
3. Non-descriptive link text
4. Auto-playing media
5. Missing skip links
### Moderate (fix soon)
1. Missing ARIA labels on icons
2. Inconsistent navigation
3. Missing error identification
4. Timing without controls
5. Missing landmark regions
## References
- [WCAG 2.2 Quick Reference](https://www.w3.org/WAI/WCAG22/quickref/)
- [WAI-ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/)
- [Deque axe Rules](https://dequeuniversity.com/rules/axe/)
- [Web Quality Audit](../web-quality-audit/SKILL.md)
- [WCAG criteria reference](references/WCAG.md)
- [Accessibility code patterns](references/A11Y-PATTERNS.md)
+14
View File
@@ -0,0 +1,14 @@
# ext-accessibility
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
| | |
|---|---|
| Publisher | Addy Osmani |
| Source | https://github.com/addyosmani/web-quality-skills/tree/afa8da942115f2961fdbfa80807ea0b232ff6c00/skills/accessibility |
| Commit | `afa8da942115f2961fdbfa80807ea0b232ff6c00` |
| Licence | MIT (see the LICENSE file in this folder) |
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-accessibility`, and an
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
@@ -0,0 +1,233 @@
# Accessibility Code Patterns
Practical, copy-paste-ready patterns for common accessibility requirements. Each pattern is self-contained and linked from the main [SKILL.md](../SKILL.md).
---
## Modal focus trap
Trap keyboard focus inside a modal dialog so Tab/Shift+Tab cycle through its focusable elements and Escape closes it.
```javascript
function openModal(modal) {
const focusableElements = modal.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
modal.addEventListener('keydown', (e) => {
if (e.key === 'Tab') {
if (e.shiftKey && document.activeElement === firstElement) {
e.preventDefault();
lastElement.focus();
} else if (!e.shiftKey && document.activeElement === lastElement) {
e.preventDefault();
firstElement.focus();
}
}
if (e.key === 'Escape') {
closeModal();
}
});
firstElement.focus();
}
```
The native `<dialog>` element handles focus trapping automatically—prefer it when browser support allows.
---
## Skip link
Allows keyboard users to bypass repetitive navigation and jump straight to main content.
```html
<body>
<a href="#main-content" class="skip-link">Skip to main content</a>
<header><!-- navigation --></header>
<main id="main-content" tabindex="-1">
<!-- main content -->
</main>
</body>
```
```css
.skip-link {
position: absolute;
top: -40px;
left: 0;
background: #000;
color: #fff;
padding: 8px 16px;
z-index: 100;
}
.skip-link:focus {
top: 0;
}
```
---
## Error handling
Announce errors to screen readers and focus the first invalid field on submit.
```html
<form novalidate>
<div class="field" aria-live="polite">
<label for="email">Email</label>
<input type="email" id="email"
aria-invalid="true"
aria-describedby="email-error">
<p id="email-error" class="error" role="alert">
Please enter a valid email address (e.g., name@example.com)
</p>
</div>
</form>
```
```javascript
form.addEventListener('submit', (e) => {
const firstError = form.querySelector('[aria-invalid="true"]');
if (firstError) {
e.preventDefault();
firstError.focus();
const errorSummary = document.getElementById('error-summary');
errorSummary.textContent =
`${errors.length} errors found. Please fix them and try again.`;
errorSummary.focus();
}
});
```
---
## Form labels
Every input needs an associated label—either explicit (`for`/`id`) or implicit (wrapping `<label>`).
```html
<!-- ❌ No label association -->
<input type="email" placeholder="Email">
<!-- ✅ Explicit label -->
<label for="email">Email address</label>
<input type="email" id="email" name="email"
autocomplete="email" required>
<!-- ✅ Implicit label -->
<label>
Email address
<input type="email" name="email" autocomplete="email" required>
</label>
<!-- ✅ With instructions -->
<label for="password">Password</label>
<input type="password" id="password"
aria-describedby="password-requirements">
<p id="password-requirements">
Must be at least 8 characters with one number.
</p>
```
---
## Dragging movements
Any action triggered by dragging must offer a single-pointer alternative (WCAG 2.5.7).
```html
<!-- ❌ Drag-only reorder -->
<ul class="sortable-list" draggable="true">
<li>Item 1</li>
<li>Item 2</li>
</ul>
<!-- ✅ Drag + button alternatives -->
<ul class="sortable-list">
<li>
<span>Item 1</span>
<button aria-label="Move Item 1 up">↑</button>
<button aria-label="Move Item 1 down">↓</button>
</li>
<li>
<span>Item 2</span>
<button aria-label="Move Item 2 up">↑</button>
<button aria-label="Move Item 2 down">↓</button>
</li>
</ul>
```
Also applies to sliders, map panning, colour pickers, and similar drag-based widgets—always provide an equivalent click/tap or keyboard path.
---
## ARIA tabs
Tabs require `role="tablist"`, `role="tab"`, and `role="tabpanel"` with proper `aria-selected`, `aria-controls`, and keyboard support.
```html
<div role="tablist" aria-label="Product information">
<button role="tab" id="tab-1" aria-selected="true"
aria-controls="panel-1">Description</button>
<button role="tab" id="tab-2" aria-selected="false"
aria-controls="panel-2" tabindex="-1">Reviews</button>
</div>
<div role="tabpanel" id="panel-1" aria-labelledby="tab-1">
<!-- Panel content -->
</div>
<div role="tabpanel" id="panel-2" aria-labelledby="tab-2" hidden>
<!-- Panel content -->
</div>
```
Arrow keys should move focus between tabs; the active tab receives `tabindex="0"` while inactive tabs use `tabindex="-1"`.
---
## Live regions and notifications
Use `aria-live` to announce dynamic content changes to screen readers without moving focus.
```html
<!-- Status updates (polite — waits for pause in speech) -->
<div aria-live="polite" aria-atomic="true" class="status">
<!-- Content updates announced to screen readers -->
</div>
<!-- Urgent alerts (assertive — interrupts) -->
<div role="alert" aria-live="assertive">
<!-- Interrupts current announcement -->
</div>
```
```javascript
function showNotification(message, type = 'polite') {
const container = document.getElementById(`${type}-announcer`);
container.textContent = '';
requestAnimationFrame(() => {
container.textContent = message;
});
}
```
Clear the container before writing to ensure the same message triggers a new announcement.
---
## Screen reader commands
Quick reference for the most common screen reader shortcuts.
| Action | VoiceOver (Mac) | NVDA (Windows) |
|--------|-----------------|----------------|
| Start/Stop | ⌘ + F5 | Ctrl + Alt + N |
| Next item | VO + → | ↓ |
| Previous item | VO + ← | ↑ |
| Activate | VO + Space | Enter |
| Headings list | VO + U, then arrows | H / Shift + H |
| Links list | VO + U | K / Shift + K |
+191
View File
@@ -0,0 +1,191 @@
# WCAG 2.2 Quick Reference
## Success criteria by level
### Level A (minimum)
| Criterion | Description |
|-----------|-------------|
| **1.1.1** Non-text Content | All images, icons have text alternatives |
| **1.2.1** Audio-only/Video-only | Provide transcript or audio description |
| **1.2.2** Captions | Video with audio has captions |
| **1.2.3** Audio Description | Video has audio description |
| **1.3.1** Info and Relationships | Information conveyed through presentation is available programmatically |
| **1.3.2** Meaningful Sequence | Reading order is logical |
| **1.3.3** Sensory Characteristics | Instructions don't rely solely on shape, color, size, location, orientation, or sound |
| **1.4.1** Use of Color | Color is not the only visual means of conveying information |
| **1.4.2** Audio Control | Audio playing automatically can be paused/stopped |
| **2.1.1** Keyboard | All functionality available via keyboard |
| **2.1.2** No Keyboard Trap | Keyboard focus can be moved away from any component |
| **2.1.4** Character Key Shortcuts | Single-key shortcuts can be turned off or remapped |
| **2.2.1** Timing Adjustable | Time limits can be extended |
| **2.2.2** Pause, Stop, Hide | Moving/blinking content can be paused |
| **2.3.1** Three Flashes | Nothing flashes more than 3 times per second |
| **2.4.1** Bypass Blocks | Skip link or landmark navigation available |
| **2.4.2** Page Titled | Pages have descriptive titles |
| **2.4.3** Focus Order | Focus order preserves meaning |
| **2.4.4** Link Purpose | Link purpose clear from link text or context |
| **2.5.1** Pointer Gestures | Multi-point gestures have single-pointer alternatives |
| **2.5.2** Pointer Cancellation | Down-event doesn't trigger action (use up-event or click) |
| **2.5.3** Label in Name | Accessible name contains visible label text |
| **2.5.4** Motion Actuation | Motion-triggered functions have alternatives |
| **3.1.1** Language of Page | Default language specified in HTML |
| **3.2.1** On Focus | Focus doesn't trigger unexpected changes |
| **3.2.2** On Input | Input doesn't trigger unexpected changes |
| **3.2.6** Consistent Help | Help mechanisms appear in the same relative order across pages |
| **3.3.1** Error Identification | Input errors clearly described |
| **3.3.2** Labels or Instructions | Form inputs have labels or instructions |
| **3.3.7** Redundant Entry | Information previously entered is auto-populated or available to select |
| **4.1.2** Name, Role, Value | UI components have accessible names and correct roles |
### Level AA (standard)
| Criterion | Description |
|-----------|-------------|
| **1.2.4** Captions (Live) | Live audio has captions |
| **1.2.5** Audio Description | Pre-recorded video has audio description |
| **1.3.4** Orientation | Content doesn't restrict orientation |
| **1.3.5** Identify Input Purpose | Input purpose can be programmatically determined |
| **1.4.3** Contrast (Minimum) | 4.5:1 for normal text, 3:1 for large text |
| **1.4.4** Resize Text | Text can be resized to 200% without loss of functionality |
| **1.4.5** Images of Text | Text used instead of images of text |
| **1.4.10** Reflow | Content reflows at 320px width without horizontal scroll |
| **1.4.11** Non-text Contrast | UI components have 3:1 contrast |
| **1.4.12** Text Spacing | Content adapts to text spacing changes |
| **1.4.13** Content on Hover/Focus | Additional content is dismissible, hoverable, persistent |
| **2.4.5** Multiple Ways | Multiple ways to find pages |
| **2.4.6** Headings and Labels | Headings and labels are descriptive |
| **2.4.7** Focus Visible | Focus indicator is visible |
| **2.4.11** Focus Not Obscured (Minimum) | Focused element is not entirely hidden by author-created content |
| **2.5.7** Dragging Movements | Dragging actions have single-pointer alternatives |
| **2.5.8** Target Size (Minimum) | Interactive targets are at least 24×24 CSS pixels (with exceptions) |
| **3.1.2** Language of Parts | Language changes are marked |
| **3.2.3** Consistent Navigation | Navigation is consistent across pages |
| **3.2.4** Consistent Identification | Same functionality uses same labels |
| **3.3.3** Error Suggestion | Error corrections suggested when known |
| **3.3.4** Error Prevention (Legal) | Actions can be reversed or confirmed |
| **3.3.8** Accessible Authentication (Minimum) | No cognitive function test for login unless an alternative or assistance is provided |
| **4.1.3** Status Messages | Status messages announced to screen readers |
### Level AAA (enhanced)
| Criterion | Description |
|-----------|-------------|
| **1.4.6** Contrast (Enhanced) | 7:1 for normal text, 4.5:1 for large text |
| **1.4.8** Visual Presentation | Foreground/background colors can be selected |
| **1.4.9** Images of Text (No Exception) | No images of text |
| **2.1.3** Keyboard (No Exception) | All functionality keyboard accessible |
| **2.2.3** No Timing | No time limits |
| **2.2.4** Interruptions | Interruptions can be postponed |
| **2.2.5** Re-authenticating | Data preserved on re-authentication |
| **2.2.6** Timeouts | Users warned about data loss from inactivity |
| **2.3.2** Three Flashes | No content flashes more than 3 times |
| **2.3.3** Animation from Interactions | Motion animation can be disabled |
| **2.4.8** Location | User location within site is available |
| **2.4.9** Link Purpose (Link Only) | Link purpose clear from link text alone |
| **2.4.10** Section Headings | Sections have headings |
| **2.4.12** Focus Not Obscured (Enhanced) | No part of the focused element is hidden by author-created content |
| **2.4.13** Focus Appearance | Focus indicator has sufficient area, contrast, and is not obscured |
| **3.1.3** Unusual Words | Definitions available for unusual words |
| **3.1.4** Abbreviations | Abbreviations expanded |
| **3.1.5** Reading Level | Alternative content for complex text |
| **3.1.6** Pronunciation | Pronunciation available where needed |
| **3.2.5** Change on Request | Changes initiated only by user |
| **3.3.5** Help | Context-sensitive help available |
| **3.3.6** Error Prevention (All) | All form submissions can be reviewed |
| **3.3.9** Accessible Authentication (Enhanced) | No cognitive function test for login (no object or personal content recognition exceptions) |
## Common ARIA patterns
### Buttons
```html
<button>Label</button>
<!-- or -->
<button aria-label="Close dialog">×</button>
```
### Links
```html
<a href="/page">Descriptive link text</a>
<!-- External links -->
<a href="https://external.com" target="_blank" rel="noopener">
External site
<span class="visually-hidden">(opens in new tab)</span>
</a>
```
### Form fields
```html
<label for="email">Email address</label>
<input type="email" id="email" aria-describedby="email-hint">
<p id="email-hint">We'll never share your email.</p>
```
### Error states
```html
<label for="email">Email</label>
<input type="email" id="email" aria-invalid="true" aria-describedby="email-error">
<p id="email-error" role="alert">Please enter a valid email address.</p>
```
### Navigation
```html
<nav aria-label="Main">
<ul>
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
```
### Modals
```html
<div role="dialog" aria-modal="true" aria-labelledby="dialog-title">
<h2 id="dialog-title">Confirm Action</h2>
<!-- content -->
</div>
```
### Live regions
```html
<!-- Polite (waits for pause in speech) -->
<div aria-live="polite">Status update here</div>
<!-- Assertive (interrupts immediately) -->
<div aria-live="assertive" role="alert">Error message here</div>
<!-- Status (polite, implicit) -->
<div role="status">Loading complete</div>
```
## What changed from 2.1 to 2.2
| Change | Criterion | Level |
|--------|-----------|-------|
| **Removed** | 4.1.1 Parsing | A |
| **Added** | 2.4.11 Focus Not Obscured (Minimum) | AA |
| **Added** | 2.4.12 Focus Not Obscured (Enhanced) | AAA |
| **Added** | 2.4.13 Focus Appearance | AAA |
| **Added** | 2.5.7 Dragging Movements | AA |
| **Added** | 2.5.8 Target Size (Minimum) | AA |
| **Added** | 3.2.6 Consistent Help | A |
| **Added** | 3.3.7 Redundant Entry | A |
| **Added** | 3.3.8 Accessible Authentication (Minimum) | AA |
| **Added** | 3.3.9 Accessible Authentication (Enhanced) | AAA |
## Testing tools
| Tool | Type | URL |
|------|------|-----|
| axe DevTools | Browser extension | [deque.com/axe](https://www.deque.com/axe/) |
| WAVE | Browser extension | [wave.webaim.org](https://wave.webaim.org/) |
| Lighthouse | Built into Chrome | DevTools → Lighthouse |
| NVDA | Screen reader (Windows) | [nvaccess.org](https://www.nvaccess.org/) |
| VoiceOver | Screen reader (Mac) | Built into macOS |
| Colour Contrast Analyser | Desktop app | [tpgi.com](https://www.tpgi.com/color-contrast-checker/) |
## Sources
- [WCAG 2.2 W3C Recommendation](https://www.w3.org/TR/WCAG22/)
- [WCAG 2.2 Quick Reference](https://www.w3.org/WAI/WCAG22/quickref/)
- [What's New in WCAG 2.2](https://www.w3.org/WAI/standards-guidelines/wcag/new-in-22/)
+946
View File
@@ -0,0 +1,946 @@
# React Composition Patterns
**Version 1.0.0**
Engineering
January 2026
> **Note:**
> This document is mainly for agents and LLMs to follow when maintaining,
> generating, or refactoring React codebases using composition. Humans
> may also find it useful, but guidance here is optimized for automation
> and consistency by AI-assisted workflows.
---
## Abstract
Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.
---
## Table of Contents
1. [Component Architecture](#1-component-architecture) — **HIGH**
- 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation)
- 1.2 [Use Compound Components](#12-use-compound-components)
2. [State Management](#2-state-management) — **MEDIUM**
- 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui)
- 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection)
- 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components)
3. [Implementation Patterns](#3-implementation-patterns) — **MEDIUM**
- 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants)
- 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props)
4. [React 19 APIs](#4-react-19-apis) — **MEDIUM**
- 4.1 [React 19 API Changes](#41-react-19-api-changes)
---
## 1. Component Architecture
**Impact: HIGH**
Fundamental patterns for structuring components to avoid prop
proliferation and enable flexible composition.
### 1.1 Avoid Boolean Prop Proliferation
**Impact: CRITICAL (prevents unmaintainable component variants)**
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
component behavior. Each boolean doubles possible states and creates
unmaintainable conditional logic. Use composition instead.
**Incorrect: boolean props create exponential complexity**
```tsx
function Composer({
onSubmit,
isThread,
channelId,
isDMThread,
dmId,
isEditing,
isForwarding,
}: Props) {
return (
<form>
<Header />
<Input />
{isDMThread ? (
<AlsoSendToDMField id={dmId} />
) : isThread ? (
<AlsoSendToChannelField id={channelId} />
) : null}
{isEditing ? (
<EditActions />
) : isForwarding ? (
<ForwardActions />
) : (
<DefaultActions />
)}
<Footer onSubmit={onSubmit} />
</form>
)
}
```
**Correct: composition eliminates conditionals**
```tsx
// Channel composer
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Attachments />
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Thread composer - adds "also send to channel" field
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<AlsoSendToChannelField id={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Edit composer - different footer actions
function EditComposer() {
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
)
}
```
Each variant is explicit about what it renders. We can share internals without
sharing a single monolithic parent.
### 1.2 Use Compound Components
**Impact: HIGH (enables flexible composition without prop drilling)**
Structure complex components as compound components with a shared context. Each
subcomponent accesses shared state via context, not props. Consumers compose the
pieces they need.
**Incorrect: monolithic component with render props**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
showAttachments,
showFormatting,
showEmojis,
}: Props) {
return (
<form>
{renderHeader?.()}
<Input />
{showAttachments && <Attachments />}
{renderFooter ? (
renderFooter()
) : (
<Footer>
{showFormatting && <Formatting />}
{showEmojis && <Emojis />}
{renderActions?.()}
</Footer>
)}
</form>
)
}
```
**Correct: compound components with shared context**
```tsx
const ComposerContext = createContext<ComposerContextValue | null>(null)
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
return (
<ComposerContext value={{ state, actions, meta }}>
{children}
</ComposerContext>
)
}
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerInput() {
const {
state,
actions: { update },
meta: { inputRef },
} = use(ComposerContext)
return (
<TextInput
ref={inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
function ComposerSubmit() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Send</Button>
}
// Export as compound component
const Composer = {
Provider: ComposerProvider,
Frame: ComposerFrame,
Input: ComposerInput,
Submit: ComposerSubmit,
Header: ComposerHeader,
Footer: ComposerFooter,
Attachments: ComposerAttachments,
Formatting: ComposerFormatting,
Emojis: ComposerEmojis,
}
```
**Usage:**
```tsx
<Composer.Provider state={state} actions={actions} meta={meta}>
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</Composer.Provider>
```
Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
---
## 2. State Management
**Impact: MEDIUM**
Patterns for lifting state and managing shared context across
composed components.
### 2.1 Decouple State Management from UI
**Impact: MEDIUM (enables swapping state implementations without changing UI)**
The provider component should be the only place that knows how state is managed.
UI components consume the context interface—they don't know if state comes from
useState, Zustand, or a server sync.
**Incorrect: UI coupled to state implementation**
```tsx
function ChannelComposer({ channelId }: { channelId: string }) {
// UI component knows about global state implementation
const state = useGlobalChannelState(channelId)
const { submit, updateInput } = useChannelSync(channelId)
return (
<Composer.Frame>
<Composer.Input
value={state.input}
onChange={(text) => sync.updateInput(text)}
/>
<Composer.Submit onPress={() => sync.submit()} />
</Composer.Frame>
)
}
```
**Correct: state management isolated in provider**
```tsx
// Provider handles all state management details
function ChannelProvider({
channelId,
children,
}: {
channelId: string
children: React.ReactNode
}) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update, submit }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
// UI component only knows about the context interface
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Usage
function Channel({ channelId }: { channelId: string }) {
return (
<ChannelProvider channelId={channelId}>
<ChannelComposer />
</ChannelProvider>
)
}
```
**Different providers, same UI:**
```tsx
// Local state for ephemeral forms
function ForwardMessageProvider({ children }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
>
{children}
</Composer.Provider>
)
}
// Global synced state for channels
function ChannelProvider({ channelId, children }) {
const { state, update, submit } = useGlobalChannel(channelId)
return (
<Composer.Provider state={state} actions={{ update, submit }}>
{children}
</Composer.Provider>
)
}
```
The same `Composer.Input` component works with both providers because it only
depends on the context interface, not the implementation.
### 2.2 Define Generic Context Interfaces for Dependency Injection
**Impact: HIGH (enables dependency-injectable state across use-cases)**
Define a **generic interface** for your component context with three parts:
`state`, `actions`, and `meta`. This interface is a contract that any provider
can implement—enabling the same UI components to work with completely different
state implementations.
**Core principle:** Lift state, compose internals, make state
dependency-injectable.
**Incorrect: UI coupled to specific state implementation**
```tsx
function ComposerInput() {
// Tightly coupled to a specific hook
const { input, setInput } = useChannelComposerState()
return <TextInput value={input} onChangeText={setInput} />
}
```
**Correct: generic interface enables dependency injection**
```tsx
// Define a GENERIC interface that any provider can implement
interface ComposerState {
input: string
attachments: Attachment[]
isSubmitting: boolean
}
interface ComposerActions {
update: (updater: (state: ComposerState) => ComposerState) => void
submit: () => void
}
interface ComposerMeta {
inputRef: React.RefObject<TextInput>
}
interface ComposerContextValue {
state: ComposerState
actions: ComposerActions
meta: ComposerMeta
}
const ComposerContext = createContext<ComposerContextValue | null>(null)
```
**UI components consume the interface, not the implementation:**
```tsx
function ComposerInput() {
const {
state,
actions: { update },
meta,
} = use(ComposerContext)
// This component works with ANY provider that implements the interface
return (
<TextInput
ref={meta.inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
```
**Different providers implement the same interface:**
```tsx
// Provider A: Local state for ephemeral forms
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const inputRef = useRef(null)
const submit = useForwardMessage()
return (
<ComposerContext
value={{
state,
actions: { update: setState, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
// Provider B: Global synced state for channels
function ChannelProvider({ channelId, children }: Props) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<ComposerContext
value={{
state,
actions: { update, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
```
**The same composed UI works with both:**
```tsx
// Works with ForwardMessageProvider (local state)
<ForwardMessageProvider>
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ForwardMessageProvider>
// Works with ChannelProvider (global synced state)
<ChannelProvider channelId="abc">
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ChannelProvider>
```
**Custom UI outside the component can access state and actions:**
```tsx
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
{/* The composer UI */}
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
</Composer.Footer>
</Composer.Frame>
{/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
<MessagePreview />
{/* Actions at the bottom of the dialog */}
<DialogActions>
<CancelButton />
<ForwardButton />
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
function ForwardButton() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Forward</Button>
}
// This preview lives OUTSIDE Composer.Frame but can read composer's state!
function MessagePreview() {
const { state } = use(ComposerContext)
return <Preview message={state.input} attachments={state.attachments} />
}
```
The provider boundary is what matters—not the visual nesting. Components that
need shared state don't have to be inside the `Composer.Frame`. They just need
to be within the provider.
The `ForwardButton` and `MessagePreview` are not visually inside the composer
box, but they can still access its state and actions. This is the power of
lifting state into providers.
The UI is reusable bits you compose together. The state is dependency-injected
by the provider. Swap the provider, keep the UI.
### 2.3 Lift State into Provider Components
**Impact: HIGH (enables state sharing outside component boundaries)**
Move state management into dedicated provider components. This allows sibling
components outside the main UI to access and modify state without prop drilling
or awkward refs.
**Incorrect: state trapped inside component**
```tsx
function ForwardMessageComposer() {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer />
</Composer.Frame>
)
}
// Problem: How does this button access composer state?
function ForwardMessageDialog() {
return (
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Needs composer state */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Needs to call submit */}
</DialogActions>
</Dialog>
)
}
```
**Incorrect: useEffect to sync state up**
```tsx
function ForwardMessageDialog() {
const [input, setInput] = useState('')
return (
<Dialog>
<ForwardMessageComposer onInputChange={setInput} />
<MessagePreview input={input} />
</Dialog>
)
}
function ForwardMessageComposer({ onInputChange }) {
const [state, setState] = useState(initialState)
useEffect(() => {
onInputChange(state.input) // Sync on every change 😬
}, [state.input])
}
```
**Incorrect: reading state from ref on submit**
```tsx
function ForwardMessageDialog() {
const stateRef = useRef(null)
return (
<Dialog>
<ForwardMessageComposer stateRef={stateRef} />
<ForwardButton onPress={() => submit(stateRef.current)} />
</Dialog>
)
}
```
**Correct: state lifted to provider**
```tsx
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Custom components can access state and actions */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Custom components can access state and actions */}
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
function ForwardButton() {
const { actions } = use(Composer.Context)
return <Button onPress={actions.submit}>Forward</Button>
}
```
The ForwardButton lives outside the Composer.Frame but still has access to the
submit action because it's within the provider. Even though it's a one-off
component, it can still access the composer's state and actions from outside the
UI itself.
**Key insight:** Components that need shared state don't have to be visually
nested inside each other—they just need to be within the same provider.
---
## 3. Implementation Patterns
**Impact: MEDIUM**
Specific techniques for implementing compound components and
context providers.
### 3.1 Create Explicit Component Variants
**Impact: MEDIUM (self-documenting code, no hidden conditionals)**
Instead of one component with many boolean props, create explicit variant
components. Each variant composes the pieces it needs. The code documents
itself.
**Incorrect: one component, many modes**
```tsx
// What does this component actually render?
<Composer
isThread
isEditing={false}
channelId='abc'
showAttachments
showFormatting={false}
/>
```
**Correct: explicit variants**
```tsx
// Immediately clear what this renders
<ThreadComposer channelId="abc" />
// Or
<EditMessageComposer messageId="xyz" />
// Or
<ForwardMessageComposer messageId="123" />
```
Each implementation is unique, explicit and self-contained. Yet they can each
use shared parts.
**Implementation:**
```tsx
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<ThreadProvider channelId={channelId}>
<Composer.Frame>
<Composer.Input />
<AlsoSendToChannelField channelId={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</ThreadProvider>
)
}
function EditMessageComposer({ messageId }: { messageId: string }) {
return (
<EditMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
</EditMessageProvider>
)
}
function ForwardMessageComposer({ messageId }: { messageId: string }) {
return (
<ForwardMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Mentions />
</Composer.Footer>
</Composer.Frame>
</ForwardMessageProvider>
)
}
```
Each variant is explicit about:
- What provider/state it uses
- What UI elements it includes
- What actions are available
No boolean prop combinations to reason about. No impossible states.
### 3.2 Prefer Composing Children Over Render Props
**Impact: MEDIUM (cleaner composition, better readability)**
Use `children` for composition instead of `renderX` props. Children are more
readable, compose naturally, and don't require understanding callback
signatures.
**Incorrect: render props**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
}: {
renderHeader?: () => React.ReactNode
renderFooter?: () => React.ReactNode
renderActions?: () => React.ReactNode
}) {
return (
<form>
{renderHeader?.()}
<Input />
{renderFooter ? renderFooter() : <DefaultFooter />}
{renderActions?.()}
</form>
)
}
// Usage is awkward and inflexible
return (
<Composer
renderHeader={() => <CustomHeader />}
renderFooter={() => (
<>
<Formatting />
<Emojis />
</>
)}
renderActions={() => <SubmitButton />}
/>
)
```
**Correct: compound components with children**
```tsx
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerFooter({ children }: { children: React.ReactNode }) {
return <footer className='flex'>{children}</footer>
}
// Usage is flexible
return (
<Composer.Frame>
<CustomHeader />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<SubmitButton />
</Composer.Footer>
</Composer.Frame>
)
```
**When render props are appropriate:**
```tsx
// Render props work well when you need to pass data back
<List
data={items}
renderItem={({ item, index }) => <Item item={item} index={index} />}
/>
```
Use render props when the parent needs to provide data or state to the child.
Use children when composing static structure.
---
## 4. React 19 APIs
**Impact: MEDIUM**
React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
### 4.1 React 19 API Changes
**Impact: MEDIUM (cleaner component definitions and context usage)**
> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
**Incorrect: forwardRef in React 19**
```tsx
const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
return <TextInput ref={ref} {...props} />
})
```
**Correct: ref as a regular prop**
```tsx
function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
return <TextInput ref={ref} {...props} />
}
```
**Incorrect: useContext in React 19**
```tsx
const value = useContext(MyContext)
```
**Correct: use instead of useContext**
```tsx
const value = use(MyContext)
```
`use()` can also be called conditionally, unlike `useContext()`.
---
## References
1. [https://react.dev](https://react.dev)
2. [https://react.dev/learn/passing-data-deeply-with-context](https://react.dev/learn/passing-data-deeply-with-context)
3. [https://react.dev/reference/react/use](https://react.dev/reference/react/use)
+17
View File
@@ -0,0 +1,17 @@
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of
the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The upstream repository (https://github.com/vercel-labs/agent-skills) declares the MIT licence in its README and in
the SKILL.md frontmatter; it ships no LICENSE file with a copyright line. Copyright: Vercel.
+60
View File
@@ -0,0 +1,60 @@
# React Composition Patterns
A structured repository for React composition patterns that scale. These
patterns help avoid boolean prop proliferation by using compound components,
lifting state, and composing internals.
## Structure
- `rules/` - Individual rule files (one per rule)
- `_sections.md` - Section metadata (titles, impacts, descriptions)
- `_template.md` - Template for creating new rules
- `area-description.md` - Individual rule files
- `metadata.json` - Document metadata (version, organization, abstract)
- **`AGENTS.md`** - Compiled output (generated)
## Rules
### Component Architecture (CRITICAL)
- `architecture-avoid-boolean-props.md` - Don't add boolean props to customize
behavior
- `architecture-compound-components.md` - Structure as compound components with
shared context
### State Management (HIGH)
- `state-lift-state.md` - Lift state into provider components
- `state-context-interface.md` - Define clear context interfaces
(state/actions/meta)
- `state-decouple-implementation.md` - Decouple state management from UI
### Implementation Patterns (MEDIUM)
- `patterns-children-over-render-props.md` - Prefer children over renderX props
- `patterns-explicit-variants.md` - Create explicit component variants
## Core Principles
1. **Composition over configuration** — Instead of adding props, let consumers
compose
2. **Lift your state** — State in providers, not trapped in components
3. **Compose your internals** — Subcomponents access context, not props
4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer
with isThread
## Creating a New Rule
1. Copy `rules/_template.md` to `rules/area-description.md`
2. Choose the appropriate area prefix:
- `architecture-` for Component Architecture
- `state-` for State Management
- `patterns-` for Implementation Patterns
3. Fill in the frontmatter and content
4. Ensure you have clear examples with explanations
## Impact Levels
- `CRITICAL` - Foundational patterns, prevents unmaintainable code
- `HIGH` - Significant maintainability improvements
- `MEDIUM` - Good practices for cleaner code
+99
View File
@@ -0,0 +1,99 @@
---
name: ext-composition-patterns
description:
React composition patterns that scale. Use when refactoring components with
boolean prop proliferation, building flexible component libraries, or
designing reusable APIs. Triggers on tasks involving compound components,
render props, context providers, or component architecture. Includes React 19
API changes.
license: MIT
metadata:
author: vercel
version: '1.0.0'
---
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
> Never add a dependency this skill suggests without the owner's decision.
>
> **Blocks:** composition applies inside a block's own components; the block schema, shared fields and
> `RenderBlocks` follow AGENT.md §6.
# React Composition Patterns
Composition patterns for building flexible, maintainable React components. Avoid
boolean prop proliferation by using compound components, lifting state, and
composing internals. These patterns make codebases easier for both humans and AI
agents to work with as they scale.
## When to Apply
Reference these guidelines when:
- Refactoring components with many boolean props
- Building reusable component libraries
- Designing flexible component APIs
- Reviewing component architecture
- Working with compound components or context providers
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
| -------- | ----------------------- | ------ | --------------- |
| 1 | Component Architecture | HIGH | `architecture-` |
| 2 | State Management | MEDIUM | `state-` |
| 3 | Implementation Patterns | MEDIUM | `patterns-` |
| 4 | React 19 APIs | MEDIUM | `react19-` |
## Quick Reference
### 1. Component Architecture (HIGH)
- `architecture-avoid-boolean-props` - Don't add boolean props to customize
behavior; use composition
- `architecture-compound-components` - Structure complex components with shared
context
### 2. State Management (MEDIUM)
- `state-decouple-implementation` - Provider is the only place that knows how
state is managed
- `state-context-interface` - Define generic interface with state, actions, meta
for dependency injection
- `state-lift-state` - Move state into provider components for sibling access
### 3. Implementation Patterns (MEDIUM)
- `patterns-explicit-variants` - Create explicit variant components instead of
boolean modes
- `patterns-children-over-render-props` - Use children for composition instead
of renderX props
### 4. React 19 APIs (MEDIUM)
> **⚠️ React 19+ only.** Skip this section if using React 18 or earlier.
- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/architecture-avoid-boolean-props.md
rules/state-context-interface.md
```
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
+14
View File
@@ -0,0 +1,14 @@
# ext-composition-patterns
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
| | |
|---|---|
| Publisher | Vercel |
| Source | https://github.com/vercel-labs/agent-skills/tree/1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62/skills/composition-patterns |
| Commit | `1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62` |
| Licence | MIT (see the LICENSE file in this folder) |
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-composition-patterns`, and an
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
@@ -0,0 +1,11 @@
{
"version": "1.0.0",
"organization": "Engineering",
"date": "January 2026",
"abstract": "Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.",
"references": [
"https://react.dev",
"https://react.dev/learn/passing-data-deeply-with-context",
"https://react.dev/reference/react/use"
]
}
@@ -0,0 +1,29 @@
# Sections
This file defines all sections, their ordering, impact levels, and descriptions.
The section ID (in parentheses) is the filename prefix used to group rules.
---
## 1. Component Architecture (architecture)
**Impact:** HIGH
**Description:** Fundamental patterns for structuring components to avoid prop
proliferation and enable flexible composition.
## 2. State Management (state)
**Impact:** MEDIUM
**Description:** Patterns for lifting state and managing shared context across
composed components.
## 3. Implementation Patterns (patterns)
**Impact:** MEDIUM
**Description:** Specific techniques for implementing compound components and
context providers.
## 4. React 19 APIs (react19)
**Impact:** MEDIUM
**Description:** React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
@@ -0,0 +1,24 @@
---
title: Rule Title Here
impact: MEDIUM
impactDescription: brief description of impact
tags: composition, components
---
## Rule Title Here
Brief explanation of the rule and why it matters.
**Incorrect:**
```tsx
// Bad code example
```
**Correct:**
```tsx
// Good code example
```
Reference: [Link](https://example.com)
@@ -0,0 +1,100 @@
---
title: Avoid Boolean Prop Proliferation
impact: CRITICAL
impactDescription: prevents unmaintainable component variants
tags: composition, props, architecture
---
## Avoid Boolean Prop Proliferation
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
component behavior. Each boolean doubles possible states and creates
unmaintainable conditional logic. Use composition instead.
**Incorrect (boolean props create exponential complexity):**
```tsx
function Composer({
onSubmit,
isThread,
channelId,
isDMThread,
dmId,
isEditing,
isForwarding,
}: Props) {
return (
<form>
<Header />
<Input />
{isDMThread ? (
<AlsoSendToDMField id={dmId} />
) : isThread ? (
<AlsoSendToChannelField id={channelId} />
) : null}
{isEditing ? (
<EditActions />
) : isForwarding ? (
<ForwardActions />
) : (
<DefaultActions />
)}
<Footer onSubmit={onSubmit} />
</form>
)
}
```
**Correct (composition eliminates conditionals):**
```tsx
// Channel composer
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Attachments />
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Thread composer - adds "also send to channel" field
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<AlsoSendToChannelField id={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Edit composer - different footer actions
function EditComposer() {
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
)
}
```
Each variant is explicit about what it renders. We can share internals without
sharing a single monolithic parent.
@@ -0,0 +1,112 @@
---
title: Use Compound Components
impact: HIGH
impactDescription: enables flexible composition without prop drilling
tags: composition, compound-components, architecture
---
## Use Compound Components
Structure complex components as compound components with a shared context. Each
subcomponent accesses shared state via context, not props. Consumers compose the
pieces they need.
**Incorrect (monolithic component with render props):**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
showAttachments,
showFormatting,
showEmojis,
}: Props) {
return (
<form>
{renderHeader?.()}
<Input />
{showAttachments && <Attachments />}
{renderFooter ? (
renderFooter()
) : (
<Footer>
{showFormatting && <Formatting />}
{showEmojis && <Emojis />}
{renderActions?.()}
</Footer>
)}
</form>
)
}
```
**Correct (compound components with shared context):**
```tsx
const ComposerContext = createContext<ComposerContextValue | null>(null)
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
return (
<ComposerContext value={{ state, actions, meta }}>
{children}
</ComposerContext>
)
}
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerInput() {
const {
state,
actions: { update },
meta: { inputRef },
} = use(ComposerContext)
return (
<TextInput
ref={inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
function ComposerSubmit() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Send</Button>
}
// Export as compound component
const Composer = {
Provider: ComposerProvider,
Frame: ComposerFrame,
Input: ComposerInput,
Submit: ComposerSubmit,
Header: ComposerHeader,
Footer: ComposerFooter,
Attachments: ComposerAttachments,
Formatting: ComposerFormatting,
Emojis: ComposerEmojis,
}
```
**Usage:**
```tsx
<Composer.Provider state={state} actions={actions} meta={meta}>
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</Composer.Provider>
```
Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
@@ -0,0 +1,87 @@
---
title: Prefer Composing Children Over Render Props
impact: MEDIUM
impactDescription: cleaner composition, better readability
tags: composition, children, render-props
---
## Prefer Children Over Render Props
Use `children` for composition instead of `renderX` props. Children are more
readable, compose naturally, and don't require understanding callback
signatures.
**Incorrect (render props):**
```tsx
function Composer({
renderHeader,
renderFooter,
renderActions,
}: {
renderHeader?: () => React.ReactNode
renderFooter?: () => React.ReactNode
renderActions?: () => React.ReactNode
}) {
return (
<form>
{renderHeader?.()}
<Input />
{renderFooter ? renderFooter() : <DefaultFooter />}
{renderActions?.()}
</form>
)
}
// Usage is awkward and inflexible
return (
<Composer
renderHeader={() => <CustomHeader />}
renderFooter={() => (
<>
<Formatting />
<Emojis />
</>
)}
renderActions={() => <SubmitButton />}
/>
)
```
**Correct (compound components with children):**
```tsx
function ComposerFrame({ children }: { children: React.ReactNode }) {
return <form>{children}</form>
}
function ComposerFooter({ children }: { children: React.ReactNode }) {
return <footer className='flex'>{children}</footer>
}
// Usage is flexible
return (
<Composer.Frame>
<CustomHeader />
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<SubmitButton />
</Composer.Footer>
</Composer.Frame>
)
```
**When render props are appropriate:**
```tsx
// Render props work well when you need to pass data back
<List
data={items}
renderItem={({ item, index }) => <Item item={item} index={index} />}
/>
```
Use render props when the parent needs to provide data or state to the child.
Use children when composing static structure.
@@ -0,0 +1,100 @@
---
title: Create Explicit Component Variants
impact: MEDIUM
impactDescription: self-documenting code, no hidden conditionals
tags: composition, variants, architecture
---
## Create Explicit Component Variants
Instead of one component with many boolean props, create explicit variant
components. Each variant composes the pieces it needs. The code documents
itself.
**Incorrect (one component, many modes):**
```tsx
// What does this component actually render?
<Composer
isThread
isEditing={false}
channelId='abc'
showAttachments
showFormatting={false}
/>
```
**Correct (explicit variants):**
```tsx
// Immediately clear what this renders
<ThreadComposer channelId="abc" />
// Or
<EditMessageComposer messageId="xyz" />
// Or
<ForwardMessageComposer messageId="123" />
```
Each implementation is unique, explicit and self-contained. Yet they can each
use shared parts.
**Implementation:**
```tsx
function ThreadComposer({ channelId }: { channelId: string }) {
return (
<ThreadProvider channelId={channelId}>
<Composer.Frame>
<Composer.Input />
<AlsoSendToChannelField channelId={channelId} />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
</ThreadProvider>
)
}
function EditMessageComposer({ messageId }: { messageId: string }) {
return (
<EditMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.CancelEdit />
<Composer.SaveEdit />
</Composer.Footer>
</Composer.Frame>
</EditMessageProvider>
)
}
function ForwardMessageComposer({ messageId }: { messageId: string }) {
return (
<ForwardMessageProvider messageId={messageId}>
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
<Composer.Mentions />
</Composer.Footer>
</Composer.Frame>
</ForwardMessageProvider>
)
}
```
Each variant is explicit about:
- What provider/state it uses
- What UI elements it includes
- What actions are available
No boolean prop combinations to reason about. No impossible states.
@@ -0,0 +1,42 @@
---
title: React 19 API Changes
impact: MEDIUM
impactDescription: cleaner component definitions and context usage
tags: react19, refs, context, hooks
---
## React 19 API Changes
> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
**Incorrect (forwardRef in React 19):**
```tsx
const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
return <TextInput ref={ref} {...props} />
})
```
**Correct (ref as a regular prop):**
```tsx
function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
return <TextInput ref={ref} {...props} />
}
```
**Incorrect (useContext in React 19):**
```tsx
const value = useContext(MyContext)
```
**Correct (use instead of useContext):**
```tsx
const value = use(MyContext)
```
`use()` can also be called conditionally, unlike `useContext()`.
@@ -0,0 +1,191 @@
---
title: Define Generic Context Interfaces for Dependency Injection
impact: HIGH
impactDescription: enables dependency-injectable state across use-cases
tags: composition, context, state, typescript, dependency-injection
---
## Define Generic Context Interfaces for Dependency Injection
Define a **generic interface** for your component context with three parts:
`state`, `actions`, and `meta`. This interface is a contract that any provider
can implement—enabling the same UI components to work with completely different
state implementations.
**Core principle:** Lift state, compose internals, make state
dependency-injectable.
**Incorrect (UI coupled to specific state implementation):**
```tsx
function ComposerInput() {
// Tightly coupled to a specific hook
const { input, setInput } = useChannelComposerState()
return <TextInput value={input} onChangeText={setInput} />
}
```
**Correct (generic interface enables dependency injection):**
```tsx
// Define a GENERIC interface that any provider can implement
interface ComposerState {
input: string
attachments: Attachment[]
isSubmitting: boolean
}
interface ComposerActions {
update: (updater: (state: ComposerState) => ComposerState) => void
submit: () => void
}
interface ComposerMeta {
inputRef: React.RefObject<TextInput>
}
interface ComposerContextValue {
state: ComposerState
actions: ComposerActions
meta: ComposerMeta
}
const ComposerContext = createContext<ComposerContextValue | null>(null)
```
**UI components consume the interface, not the implementation:**
```tsx
function ComposerInput() {
const {
state,
actions: { update },
meta,
} = use(ComposerContext)
// This component works with ANY provider that implements the interface
return (
<TextInput
ref={meta.inputRef}
value={state.input}
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
/>
)
}
```
**Different providers implement the same interface:**
```tsx
// Provider A: Local state for ephemeral forms
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const inputRef = useRef(null)
const submit = useForwardMessage()
return (
<ComposerContext
value={{
state,
actions: { update: setState, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
// Provider B: Global synced state for channels
function ChannelProvider({ channelId, children }: Props) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<ComposerContext
value={{
state,
actions: { update, submit },
meta: { inputRef },
}}
>
{children}
</ComposerContext>
)
}
```
**The same composed UI works with both:**
```tsx
// Works with ForwardMessageProvider (local state)
<ForwardMessageProvider>
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ForwardMessageProvider>
// Works with ChannelProvider (global synced state)
<ChannelProvider channelId="abc">
<Composer.Frame>
<Composer.Input />
<Composer.Submit />
</Composer.Frame>
</ChannelProvider>
```
**Custom UI outside the component can access state and actions:**
The provider boundary is what matters—not the visual nesting. Components that
need shared state don't have to be inside the `Composer.Frame`. They just need
to be within the provider.
```tsx
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
{/* The composer UI */}
<Composer.Frame>
<Composer.Input placeholder="Add a message, if you'd like." />
<Composer.Footer>
<Composer.Formatting />
<Composer.Emojis />
</Composer.Footer>
</Composer.Frame>
{/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
<MessagePreview />
{/* Actions at the bottom of the dialog */}
<DialogActions>
<CancelButton />
<ForwardButton />
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
function ForwardButton() {
const {
actions: { submit },
} = use(ComposerContext)
return <Button onPress={submit}>Forward</Button>
}
// This preview lives OUTSIDE Composer.Frame but can read composer's state!
function MessagePreview() {
const { state } = use(ComposerContext)
return <Preview message={state.input} attachments={state.attachments} />
}
```
The `ForwardButton` and `MessagePreview` are not visually inside the composer
box, but they can still access its state and actions. This is the power of
lifting state into providers.
The UI is reusable bits you compose together. The state is dependency-injected
by the provider. Swap the provider, keep the UI.
@@ -0,0 +1,113 @@
---
title: Decouple State Management from UI
impact: MEDIUM
impactDescription: enables swapping state implementations without changing UI
tags: composition, state, architecture
---
## Decouple State Management from UI
The provider component should be the only place that knows how state is managed.
UI components consume the context interface—they don't know if state comes from
useState, Zustand, or a server sync.
**Incorrect (UI coupled to state implementation):**
```tsx
function ChannelComposer({ channelId }: { channelId: string }) {
// UI component knows about global state implementation
const state = useGlobalChannelState(channelId)
const { submit, updateInput } = useChannelSync(channelId)
return (
<Composer.Frame>
<Composer.Input
value={state.input}
onChange={(text) => sync.updateInput(text)}
/>
<Composer.Submit onPress={() => sync.submit()} />
</Composer.Frame>
)
}
```
**Correct (state management isolated in provider):**
```tsx
// Provider handles all state management details
function ChannelProvider({
channelId,
children,
}: {
channelId: string
children: React.ReactNode
}) {
const { state, update, submit } = useGlobalChannel(channelId)
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update, submit }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
// UI component only knows about the context interface
function ChannelComposer() {
return (
<Composer.Frame>
<Composer.Header />
<Composer.Input />
<Composer.Footer>
<Composer.Submit />
</Composer.Footer>
</Composer.Frame>
)
}
// Usage
function Channel({ channelId }: { channelId: string }) {
return (
<ChannelProvider channelId={channelId}>
<ChannelComposer />
</ChannelProvider>
)
}
```
**Different providers, same UI:**
```tsx
// Local state for ephemeral forms
function ForwardMessageProvider({ children }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
>
{children}
</Composer.Provider>
)
}
// Global synced state for channels
function ChannelProvider({ channelId, children }) {
const { state, update, submit } = useGlobalChannel(channelId)
return (
<Composer.Provider state={state} actions={{ update, submit }}>
{children}
</Composer.Provider>
)
}
```
The same `Composer.Input` component works with both providers because it only
depends on the context interface, not the implementation.
@@ -0,0 +1,125 @@
---
title: Lift State into Provider Components
impact: HIGH
impactDescription: enables state sharing outside component boundaries
tags: composition, state, context, providers
---
## Lift State into Provider Components
Move state management into dedicated provider components. This allows sibling
components outside the main UI to access and modify state without prop drilling
or awkward refs.
**Incorrect (state trapped inside component):**
```tsx
function ForwardMessageComposer() {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
return (
<Composer.Frame>
<Composer.Input />
<Composer.Footer />
</Composer.Frame>
)
}
// Problem: How does this button access composer state?
function ForwardMessageDialog() {
return (
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Needs composer state */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Needs to call submit */}
</DialogActions>
</Dialog>
)
}
```
**Incorrect (useEffect to sync state up):**
```tsx
function ForwardMessageDialog() {
const [input, setInput] = useState('')
return (
<Dialog>
<ForwardMessageComposer onInputChange={setInput} />
<MessagePreview input={input} />
</Dialog>
)
}
function ForwardMessageComposer({ onInputChange }) {
const [state, setState] = useState(initialState)
useEffect(() => {
onInputChange(state.input) // Sync on every change 😬
}, [state.input])
}
```
**Incorrect (reading state from ref on submit):**
```tsx
function ForwardMessageDialog() {
const stateRef = useRef(null)
return (
<Dialog>
<ForwardMessageComposer stateRef={stateRef} />
<ForwardButton onPress={() => submit(stateRef.current)} />
</Dialog>
)
}
```
**Correct (state lifted to provider):**
```tsx
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(initialState)
const forwardMessage = useForwardMessage()
const inputRef = useRef(null)
return (
<Composer.Provider
state={state}
actions={{ update: setState, submit: forwardMessage }}
meta={{ inputRef }}
>
{children}
</Composer.Provider>
)
}
function ForwardMessageDialog() {
return (
<ForwardMessageProvider>
<Dialog>
<ForwardMessageComposer />
<MessagePreview /> {/* Custom components can access state and actions */}
<DialogActions>
<CancelButton />
<ForwardButton /> {/* Custom components can access state and actions */}
</DialogActions>
</Dialog>
</ForwardMessageProvider>
)
}
function ForwardButton() {
const { actions } = use(Composer.Context)
return <Button onPress={actions.submit}>Forward</Button>
}
```
The ForwardButton lives outside the Composer.Frame but still has access to the
submit action because it's within the provider. Even though it's a one-off
component, it can still access the composer's state and actions from outside the
UI itself.
**Key insight:** Components that need shared state don't have to be visually
nested inside each other—they just need to be within the same provider.
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+81
View File
@@ -0,0 +1,81 @@
---
name: ext-frontend-design
description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
license: Complete terms in LICENSE.txt
---
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
> Never add a dependency this skill suggests without the owner's decision.
>
> **Design tokens:** the project's `DESIGN.md` tokens win. Use this skill to write or extend `DESIGN.md` (with the
> owner's approval); components never contain hex colours, font names or text — only Tailwind tokens and CMS text.
# Frontend Design
Approach this as the design lead at a design studio known for giving every client a distinct visual identity that is not mistaken for anyone else's. This client has already rejected proposals that felt cliché or templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take aesthetic risk if justified.
## Ground your designs in the subject matter
If the brief does not identify what the product or subject matter is, identify it yourself before designing, and confirm with the client. You can come up with one concrete subject, the design's audience, and the design's primary job, as a proposal. If there's any information in your memory about the client's preferences or context about what they're building, use that as a hint. The subject's industry, subject matter, materials, and vernacular are where distinctive visual choices come from — a design for a toy for girls aged 8–11 will be very aesthetically different from a dashboard for financial analysts. Build with the brief's real content and subject matter throughout.
## Design principles
For web designs, the hero is the first thing viewers will see. Open with the most characteristic thing in the subject's world, in the form that is most appropriate: a headline, an image, an animation, a live demo, an interactive moment, or other treatments. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the default treatment, so only use it if that's truly the best option.
Typography carries the personality of the page. You don't need a different typeface for display or headline text and body content: use one family or two, and if two, make them clearly distinct.
Choose your typefaces deliberately, not the default families you would reach for on any other project, and set a clear type scale following the default guidance of The Elements of Typographic Style with intentional weights, widths, and spacing. When type is used as a headline or visual element, use the type treatment itself as an active part of the design, not a neutral delivery vehicle for the content.
Default to line lengths of less than 80 characters. Serif typefaces can have slightly longer line lengths; give serif body text slightly more line-height than a sans-serif.
Avoid these default typographic treatments; they are the commonest tells of a generated page:
- Accenting just a single word or phrase in a headline, like putting one word in italic/bold or a different color.
- Using all caps for labels.
- Adding unnecessary typographic labels above content.
Visual structure is information. Structural devices like outlines, borders, numbering, eyebrows, dividers, labels, etc., encode useful information about the content rather than decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence — like a stepped process or a timeline. Before adding numbered markers, check the content really is a sequence.
Use non-user-triggered motion sparingly and deliberately, only to draw attention. A single orchestrated moment — one page-load sequence or one reveal — lands better than scattered effects; fade-and-slide-up entrances on each section and hover transitions on every card are the generic default and read as AI-generated. Motion that answers a person's action (opening, expanding, confirming) is welcome when it shows what changed.
Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy and placeholder content. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance.
## Process: plan, review against the brief, build, critique
For calibration, AI-generated design right now clusters around some traits:
1. a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta or warm-clay accent (often near #D97757 — Anthropic's own Claude-interaction accent, so on a user's brief it reads as a tell);
2. a near-black background with a single bright acid-green or vermilion accent;
3. a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns;
4. the SaaS-card kit: content chopped into identical rounded cards, one border-radius on everything regardless of hierarchy, the same soft grey shadow (rgba(0,0,0,.1)) under each, and gradient washes as decoration;
5. template chrome that appears whatever the subject: a tracked-out ALL-CAPS eyebrow label above every heading; meta strings joined with middle dots ('A · B · C'); labels built as 'WORD — fragment' with a spaced em dash; tinted near-black (#0B0B0B, #111) standing in for black; a monospace face for small data labels; a '→' appended to link and button text.
All traits are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. As with a hired human designer, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn.
Work in two passes. First, brainstorm a short design plan based on the client's design brief: create a compact token system with color, type, layout, and principles.
- Color: describe the core base palette as 4–6 named hex values.
- Type: the typefaces and their roles.
- Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Include alignment guidance; should the content be left aligned, center aligned, justified?
- Principles: the high-level guidance for what makes this page unique.
Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan.
When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and an element-based selector like .cta). This can happen often with padding/margin between sections.
## Restraint and self-critique
Spend your boldness in one place. Let one element be the memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected, visually accessible, harmonious color palettes. Critique your own work as you build, taking screenshots to review if your environment supports it — a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creatives have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes.
## More on writing in design
Words appear in a design for one reason: to make it easier to understand and use. They are design content, not decoration. Bring the same intentionality and minimalism to copywriting that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience.
Write from the end user's perspective. Name things by what users will understand in simple language, not by how the system is built. A user manages notifications, not webhook config. Describe what something is or does in plain terms rather than selling it. Being specific and legible to new users is always better than being clever.
Use active voice as default. A CTA says exactly what happens when it is used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around.
Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act.
Keep the tone conversational: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each written element do exactly one job.
+14
View File
@@ -0,0 +1,14 @@
# ext-frontend-design
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
| | |
|---|---|
| Publisher | Anthropic |
| Source | https://github.com/anthropics/skills/tree/ca45fc496a3436251f191354091d557da31c15b5/skills/frontend-design |
| Commit | `ca45fc496a3436251f191354091d557da31c15b5` |
| Licence | Apache-2.0 (see the LICENSE file in this folder) |
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-frontend-design`, and an
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2018-2025 Payload CMS, Inc. <info@payloadcms.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+459
View File
@@ -0,0 +1,459 @@
---
name: ext-payload
description: Use when working with Payload CMS projects (payload.config.ts, collections, fields, hooks, access control, Payload API). Use when debugging validation errors, security issues, relationship queries, transactions, or hook behavior.
---
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
> Never add a dependency this skill suggests without the owner's decision.
>
> **Reference only — Payload 3 (v3.92.1).** Never apply Payload 4 guidance. ipal-kit already provides users and roles,
> 2FA, SEO, forms, i18n, the site globals, revalidation and storage — check the `ipal-reference` skill before you
> write Payload config, hooks or access rules by hand.
# Payload CMS Application Development
Payload is a Next.js native CMS with TypeScript-first architecture, providing admin panel, database management, REST/GraphQL APIs, authentication, and file storage.
## Quick Reference
| Task | Solution | Details |
| ------------------------ | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Auto-generate slugs | `slugField()` | [FIELDS.md#slug-field-helper](reference/FIELDS.md#slug-field-helper) |
| Restrict content by user | Access control with query | [ACCESS-CONTROL.md#row-level-security-with-complex-queries](reference/ACCESS-CONTROL.md#row-level-security-with-complex-queries) |
| Local API user ops | `user` + `overrideAccess: false` | [QUERIES.md#access-control-in-local-api](reference/QUERIES.md#access-control-in-local-api) |
| Draft/publish workflow | `versions: { drafts: true }` | [COLLECTIONS.md#versioning--drafts](reference/COLLECTIONS.md#versioning--drafts) |
| Computed fields | `virtual: true` with afterRead | [FIELDS.md#virtual-fields](reference/FIELDS.md#virtual-fields) |
| Conditional fields | `admin.condition` | [FIELDS.md#conditional-fields](reference/FIELDS.md#conditional-fields) |
| Custom field validation | `validate` function | [FIELDS.md#validation](reference/FIELDS.md#validation) |
| Filter relationship list | `filterOptions` on field | [FIELDS.md#relationship](reference/FIELDS.md#relationship) |
| Select specific fields | `select` parameter | [QUERIES.md#field-selection](reference/QUERIES.md#field-selection) |
| Auto-set author/dates | beforeChange hook | [HOOKS.md#collection-hooks](reference/HOOKS.md#collection-hooks) |
| Prevent hook loops | `req.context` check | [HOOKS.md#context](reference/HOOKS.md#context) |
| Cascading deletes | beforeDelete hook | [HOOKS.md#collection-hooks](reference/HOOKS.md#collection-hooks) |
| Geospatial queries | `point` field with `near`/`within` | [FIELDS.md#point-geolocation](reference/FIELDS.md#point-geolocation) |
| Reverse relationships | `join` field type | [FIELDS.md#join-fields](reference/FIELDS.md#join-fields) |
| Next.js revalidation | Context control in afterChange | [HOOKS.md#nextjs-revalidation-with-context-control](reference/HOOKS.md#nextjs-revalidation-with-context-control) |
| Query by relationship | Nested property syntax | [QUERIES.md#nested-properties](reference/QUERIES.md#nested-properties) |
| Complex queries | AND/OR logic | [QUERIES.md#andor-logic](reference/QUERIES.md#andor-logic) |
| Transactions | Pass `req` to operations | [ADAPTERS.md#threading-req-through-operations](reference/ADAPTERS.md#threading-req-through-operations) |
| Background jobs | Jobs queue with tasks | [ADVANCED.md#jobs-queue](reference/ADVANCED.md#jobs-queue) |
| Custom API routes | Collection custom endpoints | [ADVANCED.md#custom-endpoints](reference/ADVANCED.md#custom-endpoints) |
| Cloud storage | Storage adapter plugins | [ADAPTERS.md#storage-adapters](reference/ADAPTERS.md#storage-adapters) |
| Multi-language | `localization` config + `localized: true` | [ADVANCED.md#localization](reference/ADVANCED.md#localization) |
| Create plugin | `(options) => (config) => Config` | [PLUGIN-DEVELOPMENT.md#plugin-architecture](reference/PLUGIN-DEVELOPMENT.md#plugin-architecture) |
| Plugin package setup | Package structure with SWC | [PLUGIN-DEVELOPMENT.md#plugin-package-structure](reference/PLUGIN-DEVELOPMENT.md#plugin-package-structure) |
| Add fields to collection | Map collections, spread fields | [PLUGIN-DEVELOPMENT.md#adding-fields-to-collections](reference/PLUGIN-DEVELOPMENT.md#adding-fields-to-collections) |
| Plugin hooks | Preserve existing hooks in array | [PLUGIN-DEVELOPMENT.md#adding-hooks](reference/PLUGIN-DEVELOPMENT.md#adding-hooks) |
| Check field type | Type guard functions | [FIELD-TYPE-GUARDS.md](reference/FIELD-TYPE-GUARDS.md) |
## Quick Start
```bash
npx create-payload-app@latest my-app
cd my-app
pnpm dev
```
### Minimal Config
```ts
import { buildConfig } from 'payload'
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import path from 'path'
import { fileURLToPath } from 'url'
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
export default buildConfig({
admin: {
user: 'users',
importMap: {
baseDir: path.resolve(dirname),
},
},
collections: [Users, Media],
editor: lexicalEditor(),
secret: process.env.PAYLOAD_SECRET,
typescript: {
outputFile: path.resolve(dirname, 'payload-types.ts'),
},
db: mongooseAdapter({
url: process.env.DATABASE_URL,
}),
})
```
## Essential Patterns
### Basic Collection
```ts
import type { CollectionConfig } from 'payload'
export const Posts: CollectionConfig = {
slug: 'posts',
admin: {
useAsTitle: 'title',
defaultColumns: ['title', 'author', 'status', 'createdAt'],
},
fields: [
{ name: 'title', type: 'text', required: true },
{ name: 'slug', type: 'text', unique: true, index: true },
{ name: 'content', type: 'richText' },
{ name: 'author', type: 'relationship', relationTo: 'users' },
],
timestamps: true,
}
```
For more collection patterns (auth, upload, drafts, live preview), see [COLLECTIONS.md](reference/COLLECTIONS.md).
### Common Fields
```ts
// Text field
{ name: 'title', type: 'text', required: true }
// Relationship
{ name: 'author', type: 'relationship', relationTo: 'users', required: true }
// Rich text
{ name: 'content', type: 'richText', required: true }
// Select
{ name: 'status', type: 'select', options: ['draft', 'published'], defaultValue: 'draft' }
// Upload
{ name: 'image', type: 'upload', relationTo: 'media' }
```
For all field types (array, blocks, point, join, virtual, conditional, etc.), see [FIELDS.md](reference/FIELDS.md).
### Hook Example
```ts
export const Posts: CollectionConfig = {
slug: 'posts',
hooks: {
beforeChange: [
async ({ data, operation }) => {
if (operation === 'create') {
data.slug = slugify(data.title)
}
return data
},
],
},
fields: [{ name: 'title', type: 'text' }],
}
```
For all hook patterns, see [HOOKS.md](reference/HOOKS.md). For access control, see [ACCESS-CONTROL.md](reference/ACCESS-CONTROL.md).
### Access Control with Type Safety
```ts
import type { Access } from 'payload'
import type { User } from '@/payload-types'
// Type-safe access control
export const adminOnly: Access = ({ req }) => {
const user = req.user as User
return user?.roles?.includes('admin') || false
}
// Row-level access control
export const ownPostsOnly: Access = ({ req }) => {
const user = req.user as User
if (!user) return false
if (user.roles?.includes('admin')) return true
return {
author: { equals: user.id },
}
}
```
### Query Example
```ts
// Local API
const posts = await payload.find({
collection: 'posts',
where: {
status: { equals: 'published' },
'author.name': { contains: 'john' },
},
depth: 2,
limit: 10,
sort: '-createdAt',
})
// Query with populated relationships
const post = await payload.findByID({
collection: 'posts',
id: '123',
depth: 2, // Populates relationships (default is 2)
})
// Returns: { author: { id: "user123", name: "John" } }
// Without depth, relationships return IDs only
const post = await payload.findByID({
collection: 'posts',
id: '123',
depth: 0,
})
// Returns: { author: "user123" }
```
For all query operators and REST/GraphQL examples, see [QUERIES.md](reference/QUERIES.md).
### Getting Payload Instance
```ts
// In API routes (Next.js)
import { getPayload } from 'payload'
import config from '@payload-config'
export async function GET() {
const payload = await getPayload({ config })
const posts = await payload.find({
collection: 'posts',
})
return Response.json(posts)
}
// In Server Components
import { getPayload } from 'payload'
import config from '@payload-config'
export default async function Page() {
const payload = await getPayload({ config })
const { docs } = await payload.find({ collection: 'posts' })
return <div>{docs.map(post => <h1 key={post.id}>{post.title}</h1>)}</div>
}
```
## Security Pitfalls
### 1. Local API Access Control (CRITICAL)
**By default, Local API operations bypass ALL access control**, even when passing a user.
```ts
// ❌ SECURITY BUG: Passes user but ignores their permissions
await payload.find({
collection: 'posts',
user: someUser, // Access control is BYPASSED!
})
// ✅ SECURE: Actually enforces the user's permissions
await payload.find({
collection: 'posts',
user: someUser,
overrideAccess: false, // REQUIRED for access control
})
```
**When to use each:**
- `overrideAccess: true` (default) - Server-side operations you trust (cron jobs, system tasks)
- `overrideAccess: false` - When operating on behalf of a user (API routes, webhooks)
See [QUERIES.md#access-control-in-local-api](reference/QUERIES.md#access-control-in-local-api).
### 2. Transaction Failures in Hooks
**Nested operations in hooks without `req` break transaction atomicity.**
```ts
// ❌ DATA CORRUPTION RISK: Separate transaction
hooks: {
afterChange: [
async ({ doc, req }) => {
await req.payload.create({
collection: 'audit-log',
data: { docId: doc.id },
// Missing req - runs in separate transaction!
})
},
]
}
// ✅ ATOMIC: Same transaction
hooks: {
afterChange: [
async ({ doc, req }) => {
await req.payload.create({
collection: 'audit-log',
data: { docId: doc.id },
req, // Maintains atomicity
})
},
]
}
```
See [ADAPTERS.md#threading-req-through-operations](reference/ADAPTERS.md#threading-req-through-operations).
### 3. Infinite Hook Loops
**Hooks triggering operations that trigger the same hooks create infinite loops.**
```ts
// ❌ INFINITE LOOP
hooks: {
afterChange: [
async ({ doc, req }) => {
await req.payload.update({
collection: 'posts',
id: doc.id,
data: { views: doc.views + 1 },
req,
}) // Triggers afterChange again!
},
]
}
// ✅ SAFE: Use context flag
hooks: {
afterChange: [
async ({ doc, req, context }) => {
if (context.skipHooks) return
await req.payload.update({
collection: 'posts',
id: doc.id,
data: { views: doc.views + 1 },
context: { skipHooks: true },
req,
})
},
]
}
```
See [HOOKS.md#context](reference/HOOKS.md#context).
## Project Structure
```txt
src/
├── app/
│ ├── (frontend)/
│ │ └── page.tsx
│ └── (payload)/
│ └── admin/[[...segments]]/page.tsx
├── collections/
│ ├── Posts.ts
│ ├── Media.ts
│ └── Users.ts
├── globals/
│ └── Header.ts
├── components/
│ └── CustomField.tsx
├── hooks/
│ └── slugify.ts
└── payload.config.ts
```
## Type Generation
```ts
// payload.config.ts
export default buildConfig({
typescript: {
outputFile: path.resolve(dirname, 'payload-types.ts'),
},
// ...
})
// Usage
import type { Post, User } from '@/payload-types'
```
## Common Gotchas
1. **Local API bypasses access control** unless you pass `overrideAccess: false`
2. **Missing `req` in nested operations** breaks transaction atomicity
3. **Hook loops** — operations in hooks can re-trigger the same hooks; use `req.context` flags
4. **Field-level access** returns boolean only, no query constraints
5. **Relationship depth** defaults to 2; set `depth: 0` for IDs only
6. **Draft status** — `_status` field is auto-injected when drafts are enabled
7. **Types are stale** until you run `generate:types`
8. **MongoDB transactions** require replica set configuration
9. **SQLite transactions** are disabled by default; enable with `transactionOptions: {}`
10. **Point fields** are not supported in SQLite
## Best Practices
### Security
- Default to restrictive access, gradually add permissions
- Use `overrideAccess: false` when passing `user` to Local API
- Field-level access only returns boolean (no query constraints)
- Never trust client-provided data
- Use `saveToJWT: true` for roles to avoid database lookups
### Performance
- Index frequently queried fields
- Use `select` to limit returned fields
- Set `maxDepth` on relationships to prevent over-fetching
- Prefer query constraints over async operations in access control
- Cache expensive operations in `req.context`
### Data Integrity
- Always pass `req` to nested operations in hooks
- Use context flags to prevent infinite hook loops
- Enable transactions for MongoDB (requires replica set) and Postgres
- Use `beforeValidate` for data formatting
- Use `beforeChange` for business logic
### Type Safety
- Run `generate:types` after schema changes
- Import types from generated `payload-types.ts`
- Type your user object: `import type { User } from '@/payload-types'`
- Use `as const` for field options
- Use field type guards for runtime type checking
### Organization
- Keep collections in separate files
- Extract access control to `access/` directory
- Extract hooks to `hooks/` directory
- Use reusable field factories for common patterns
- Document complex access control with comments
## Reference Documentation
- **[FIELDS.md](reference/FIELDS.md)** - All field types, validation, admin options
- **[FIELD-TYPE-GUARDS.md](reference/FIELD-TYPE-GUARDS.md)** - Type guards for runtime field type checking and narrowing
- **[COLLECTIONS.md](reference/COLLECTIONS.md)** - Collection configs, auth, upload, drafts, live preview
- **[HOOKS.md](reference/HOOKS.md)** - Collection hooks, field hooks, context patterns
- **[ACCESS-CONTROL.md](reference/ACCESS-CONTROL.md)** - Collection, field, global access control, RBAC, multi-tenant
- **[ACCESS-CONTROL-ADVANCED.md](reference/ACCESS-CONTROL-ADVANCED.md)** - Context-aware, time-based, subscription-based access, factory functions, templates
- **[QUERIES.md](reference/QUERIES.md)** - Query operators, Local/REST/GraphQL APIs
- **[ENDPOINTS.md](reference/ENDPOINTS.md)** - Custom API endpoints: authentication, helpers, request/response patterns
- **[ADAPTERS.md](reference/ADAPTERS.md)** - Database, storage, email adapters, transactions
- **[ADVANCED.md](reference/ADVANCED.md)** - Authentication, jobs, endpoints, components, plugins, localization
- **[PLUGIN-DEVELOPMENT.md](reference/PLUGIN-DEVELOPMENT.md)** - Plugin architecture, monorepo structure, patterns, best practices
## Resources
- llms-full.txt: <https://payloadcms.com/llms-full.txt>
- Docs: <https://payloadcms.com/docs>
- GitHub: <https://github.com/payloadcms/payload>
- Examples: <https://github.com/payloadcms/payload/tree/3.x/examples>
- Templates: <https://github.com/payloadcms/payload/tree/3.x/templates>
+14
View File
@@ -0,0 +1,14 @@
# ext-payload
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
| | |
|---|---|
| Publisher | Payload CMS |
| Source | https://github.com/payloadcms/payload/tree/9c396345dad3c831a34fd212299532e03dc4818f/tools/claude-plugin/skills/payload |
| Commit | `9c396345dad3c831a34fd212299532e03dc4818f` |
| Licence | MIT (see the LICENSE file in this folder) |
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-payload`, and an
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
@@ -0,0 +1,704 @@
# Payload CMS Access Control - Advanced Patterns
Advanced access control patterns including context-aware access, time-based restrictions, factory functions, and production templates.
## Context-Aware Access Patterns
### Locale-Specific Access
Control access based on user locale for internationalized content.
```ts
import type { Access } from 'payload'
export const localeSpecificAccess: Access = ({ req: { user, locale } }) => {
// Authenticated users can access all locales
if (user) return true
// Public users can only access English content
if (locale === 'en') return true
return false
}
// Usage in collection
export const Posts: CollectionConfig = {
slug: 'posts',
access: {
read: localeSpecificAccess,
},
fields: [{ name: 'title', type: 'text', localized: true }],
}
```
**Source**: `docs/access-control/overview.mdx` (req.locale argument)
### Device-Specific Access
Restrict access based on device type or user agent.
```ts
import type { Access } from 'payload'
export const mobileOnlyAccess: Access = ({ req: { headers } }) => {
const userAgent = headers?.get('user-agent') || ''
return /mobile|android|iphone/i.test(userAgent)
}
export const desktopOnlyAccess: Access = ({ req: { headers } }) => {
const userAgent = headers?.get('user-agent') || ''
return !/mobile|android|iphone/i.test(userAgent)
}
// Usage
export const MobileContent: CollectionConfig = {
slug: 'mobile-content',
access: {
read: mobileOnlyAccess,
},
fields: [{ name: 'title', type: 'text' }],
}
```
**Source**: Synthesized (headers pattern)
### IP-Based Access
Restrict access from specific IP addresses (requires middleware/proxy headers).
```ts
import type { Access } from 'payload'
export const restrictedIpAccess = (allowedIps: string[]): Access => {
return ({ req: { headers } }) => {
const ip = headers?.get('x-forwarded-for') || headers?.get('x-real-ip')
return allowedIps.includes(ip || '')
}
}
// Usage
const internalIps = ['192.168.1.0/24', '10.0.0.5']
export const InternalDocs: CollectionConfig = {
slug: 'internal-docs',
access: {
read: restrictedIpAccess(internalIps),
},
fields: [{ name: 'content', type: 'richText' }],
}
```
**Note**: Requires your server to pass IP address via headers (common with proxies/load balancers).
**Source**: Synthesized (headers pattern)
## Time-Based Access Patterns
### Today's Records Only
```ts
import type { Access } from 'payload'
export const todayOnlyAccess: Access = ({ req: { user } }) => {
if (!user) return false
const now = new Date()
const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const endOfDay = new Date(startOfDay.getTime() + 24 * 60 * 60 * 1000)
return {
createdAt: {
greater_than_equal: startOfDay.toISOString(),
less_than: endOfDay.toISOString(),
},
}
}
```
**Source**: `test/access-control/config.ts` (query constraint patterns)
### Recent Records (Last N Days)
```ts
import type { Access } from 'payload'
export const recentRecordsAccess = (days: number): Access => {
return ({ req: { user } }) => {
if (!user) return false
if (user.roles?.includes('admin')) return true
const cutoff = new Date()
cutoff.setDate(cutoff.getDate() - days)
return {
createdAt: {
greater_than_equal: cutoff.toISOString(),
},
}
}
}
// Usage: Users see only last 30 days, admins see all
export const Logs: CollectionConfig = {
slug: 'logs',
access: {
read: recentRecordsAccess(30),
},
fields: [{ name: 'message', type: 'text' }],
}
```
### Scheduled Content (Publish Date Range)
```ts
import type { Access } from 'payload'
export const scheduledContentAccess: Access = ({ req: { user } }) => {
// Editors see all content
if (user?.roles?.includes('admin') || user?.roles?.includes('editor')) {
return true
}
const now = new Date().toISOString()
// Public sees only content within publish window
return {
and: [
{ publishDate: { less_than_equal: now } },
{
or: [{ unpublishDate: { exists: false } }, { unpublishDate: { greater_than: now } }],
},
],
}
}
```
**Source**: Synthesized (query constraint + date patterns)
## Subscription-Based Access
### Active Subscription Required
```ts
import type { Access } from 'payload'
export const activeSubscriptionAccess: Access = async ({ req: { user } }) => {
if (!user) return false
if (user.roles?.includes('admin')) return true
try {
const subscription = await req.payload.findByID({
collection: 'subscriptions',
id: user.subscriptionId,
})
return subscription?.status === 'active'
} catch {
return false
}
}
// Usage
export const PremiumContent: CollectionConfig = {
slug: 'premium-content',
access: {
read: activeSubscriptionAccess,
},
fields: [{ name: 'title', type: 'text' }],
}
```
### Subscription Tier-Based Access
```ts
import type { Access } from 'payload'
export const tierBasedAccess = (requiredTier: string): Access => {
const tierHierarchy = ['free', 'basic', 'pro', 'enterprise']
return async ({ req: { user } }) => {
if (!user) return false
if (user.roles?.includes('admin')) return true
try {
const subscription = await req.payload.findByID({
collection: 'subscriptions',
id: user.subscriptionId,
})
if (subscription?.status !== 'active') return false
const userTierIndex = tierHierarchy.indexOf(subscription.tier)
const requiredTierIndex = tierHierarchy.indexOf(requiredTier)
return userTierIndex >= requiredTierIndex
} catch {
return false
}
}
}
// Usage
export const EnterpriseFeatures: CollectionConfig = {
slug: 'enterprise-features',
access: {
read: tierBasedAccess('enterprise'),
},
fields: [{ name: 'feature', type: 'text' }],
}
```
**Source**: Synthesized (async + cross-collection pattern)
## Factory Functions
Reusable functions that generate access control configurations.
### createRoleBasedAccess
Generate access control for specific roles.
```ts
import type { Access } from 'payload'
export function createRoleBasedAccess(roles: string[]): Access {
return ({ req: { user } }) => {
if (!user) return false
return roles.some((role) => user.roles?.includes(role))
}
}
// Usage
const adminOrEditor = createRoleBasedAccess(['admin', 'editor'])
const moderatorAccess = createRoleBasedAccess(['admin', 'moderator'])
export const Posts: CollectionConfig = {
slug: 'posts',
access: {
create: adminOrEditor,
update: adminOrEditor,
delete: moderatorAccess,
},
fields: [{ name: 'title', type: 'text' }],
}
```
**Source**: `test/access-control/config.ts`
### createOrgScopedAccess
Generate organization-scoped access with optional admin bypass.
```ts
import type { Access } from 'payload'
export function createOrgScopedAccess(allowAdmin = true): Access {
return ({ req: { user } }) => {
if (!user) return false
if (allowAdmin && user.roles?.includes('admin')) return true
return {
organizationId: { in: user.organizationIds || [] },
}
}
}
// Usage
const orgScoped = createOrgScopedAccess() // Admins bypass
const strictOrgScoped = createOrgScopedAccess(false) // Admins also scoped
export const Projects: CollectionConfig = {
slug: 'projects',
access: {
read: orgScoped,
update: orgScoped,
delete: strictOrgScoped,
},
fields: [
{ name: 'title', type: 'text' },
{ name: 'organizationId', type: 'text', required: true },
],
}
```
**Source**: `test/access-control/config.ts`
### createTeamBasedAccess
Generate team-scoped access with configurable field name.
```ts
import type { Access } from 'payload'
export function createTeamBasedAccess(teamField = 'teamId'): Access {
return ({ req: { user } }) => {
if (!user) return false
if (user.roles?.includes('admin')) return true
return {
[teamField]: { in: user.teamIds || [] },
}
}
}
// Usage with custom field name
const projectTeamAccess = createTeamBasedAccess('projectTeam')
export const Tasks: CollectionConfig = {
slug: 'tasks',
access: {
read: projectTeamAccess,
update: projectTeamAccess,
},
fields: [
{ name: 'title', type: 'text' },
{ name: 'projectTeam', type: 'text', required: true },
],
}
```
**Source**: Synthesized (org pattern variation)
### createTimeLimitedAccess
Generate access limited to records within specified days.
```ts
import type { Access } from 'payload'
export function createTimeLimitedAccess(daysAccess: number): Access {
return ({ req: { user } }) => {
if (!user) return false
if (user.roles?.includes('admin')) return true
const cutoff = new Date()
cutoff.setDate(cutoff.getDate() - daysAccess)
return {
createdAt: {
greater_than_equal: cutoff.toISOString(),
},
}
}
}
// Usage: Users see 90 days, admins see all
export const ActivityLogs: CollectionConfig = {
slug: 'activity-logs',
access: {
read: createTimeLimitedAccess(90),
},
fields: [{ name: 'action', type: 'text' }],
}
```
**Source**: Synthesized (time + query pattern)
## Configuration Templates
Complete collection configurations for common scenarios.
### Basic Authenticated Collection
```ts
import type { CollectionConfig } from 'payload'
export const BasicCollection: CollectionConfig = {
slug: 'basic-collection',
access: {
create: ({ req: { user } }) => Boolean(user),
read: ({ req: { user } }) => Boolean(user),
update: ({ req: { user } }) => Boolean(user),
delete: ({ req: { user } }) => Boolean(user),
},
fields: [
{ name: 'title', type: 'text', required: true },
{ name: 'content', type: 'richText' },
],
}
```
**Source**: `docs/access-control/collections.mdx`
### Public + Authenticated Collection
```ts
import type { CollectionConfig } from 'payload'
export const PublicAuthCollection: CollectionConfig = {
slug: 'posts',
access: {
// Only admins/editors can create
create: ({ req: { user } }) => {
return user?.roles?.some((role) => ['admin', 'editor'].includes(role)) || false
},
// Authenticated users see all, public sees only published
read: ({ req: { user } }) => {
if (user) return true
return { _status: { equals: 'published' } }
},
// Only admins/editors can update
update: ({ req: { user } }) => {
return user?.roles?.some((role) => ['admin', 'editor'].includes(role)) || false
},
// Only admins can delete
delete: ({ req: { user } }) => {
return user?.roles?.includes('admin') || false
},
},
versions: {
drafts: true,
},
fields: [
{ name: 'title', type: 'text', required: true },
{ name: 'content', type: 'richText', required: true },
{ name: 'author', type: 'relationship', relationTo: 'users' },
],
}
```
**Source**: `templates/website/src/collections/Posts/index.ts`
### Multi-User/Self-Service Collection
```ts
import type { CollectionConfig } from 'payload'
export const SelfServiceCollection: CollectionConfig = {
slug: 'users',
auth: true,
access: {
// Admins can create users
create: ({ req: { user } }) => user?.roles?.includes('admin') || false,
// Anyone can read user profiles
read: () => true,
// Users can update self, admins can update anyone
update: ({ req: { user }, id }) => {
if (!user) return false
if (user.roles?.includes('admin')) return true
return user.id === id
},
// Only admins can delete
delete: ({ req: { user } }) => user?.roles?.includes('admin') || false,
},
fields: [
{ name: 'name', type: 'text', required: true },
{ name: 'email', type: 'email', required: true },
{
name: 'roles',
type: 'select',
hasMany: true,
options: ['admin', 'editor', 'user'],
access: {
// Only admins can read/update roles
read: ({ req: { user } }) => user?.roles?.includes('admin') || false,
update: ({ req: { user } }) => user?.roles?.includes('admin') || false,
},
},
],
}
```
**Source**: `templates/website/src/collections/Users/index.ts`
## Debugging Tips
### Log Access Check Execution
```ts
export const debugAccess: Access = ({ req: { user }, id }) => {
console.log('Access check:', {
userId: user?.id,
userRoles: user?.roles,
docId: id,
timestamp: new Date().toISOString(),
})
return true
}
```
### Verify Arguments Availability
```ts
export const checkArgsAccess: Access = (args) => {
console.log('Available arguments:', {
hasReq: 'req' in args,
hasUser: args.req?.user ? 'yes' : 'no',
hasId: args.id ? 'provided' : 'undefined',
hasData: args.data ? 'provided' : 'undefined',
})
return true
}
```
### Measure Async Operation Timing
```ts
export const timedAsyncAccess: Access = async ({ req }) => {
const start = Date.now()
const result = await fetch('https://auth-service.example.com/validate', {
headers: { userId: req.user?.id },
})
console.log(`Access check took ${Date.now() - start}ms`)
return result.ok
}
```
### Test Access Without User
```ts
// In test/development
const testAccess = await payload.find({
collection: 'posts',
overrideAccess: false, // Enforce access control
user: undefined, // Simulate no user
})
console.log('Public access result:', testAccess.docs.length)
```
**Source**: Synthesized (debugging best practices)
## Performance Considerations
### Async Operations Impact
```ts
// ❌ Slow: Multiple sequential async calls
export const slowAccess: Access = async ({ req: { user } }) => {
const org = await req.payload.findByID({ collection: 'orgs', id: user.orgId })
const team = await req.payload.findByID({ collection: 'teams', id: user.teamId })
const subscription = await req.payload.findByID({ collection: 'subs', id: user.subId })
return org.active && team.active && subscription.active
}
// ✅ Fast: Use query constraints or cache in context
export const fastAccess: Access = ({ req: { user, context } }) => {
// Cache expensive lookups
if (!context.orgStatus) {
context.orgStatus = checkOrgStatus(user.orgId)
}
return context.orgStatus
}
```
### Query Constraint Optimization
```ts
// ❌ Avoid: Non-indexed fields in constraints
export const slowQuery: Access = () => ({
'metadata.internalCode': { equals: 'ABC123' }, // Slow if not indexed
})
// ✅ Better: Use indexed fields
export const fastQuery: Access = () => ({
status: { equals: 'active' }, // Indexed field
organizationId: { in: ['org1', 'org2'] }, // Indexed field
})
```
### Field Access on Large Arrays
```ts
// ❌ Slow: Complex access on array fields
const arrayField: ArrayField = {
name: 'items',
type: 'array',
fields: [
{
name: 'secretData',
type: 'text',
access: {
read: async ({ req }) => {
// Async call runs for EVERY array item
const result = await expensiveCheck()
return result
},
},
},
],
}
// ✅ Fast: Simple checks or cache result
const optimizedArrayField: ArrayField = {
name: 'items',
type: 'array',
fields: [
{
name: 'secretData',
type: 'text',
access: {
read: ({ req: { user }, context }) => {
// Cache once, reuse for all items
if (context.canReadSecret === undefined) {
context.canReadSecret = user?.roles?.includes('admin')
}
return context.canReadSecret
},
},
},
],
}
```
### Avoid N+1 Queries
```ts
// ❌ N+1 Problem: Query per access check
export const n1Access: Access = async ({ req, id }) => {
// Runs for EACH document in list
const doc = await req.payload.findByID({ collection: 'docs', id })
return doc.isPublic
}
// ✅ Better: Use query constraint to filter at DB level
export const efficientAccess: Access = () => {
return { isPublic: { equals: true } }
}
```
**Performance Best Practices:**
1. **Minimize Async Operations**: Use query constraints over async lookups when possible
2. **Cache Expensive Checks**: Store results in `req.context` for reuse
3. **Index Query Fields**: Ensure fields in query constraints are indexed
4. **Avoid Complex Logic in Array Fields**: Simple boolean checks preferred
5. **Use Query Constraints**: Let database filter rather than loading all records
**Source**: Synthesized (operational best practices)
## Enhanced Best Practices
Comprehensive security and implementation guidelines:
1. **Default Deny**: Start with restrictive access, gradually add permissions
2. **Type Guards**: Use TypeScript for user type safety and better IDE support
3. **Validate Data**: Never trust frontend-provided IDs or data
4. **Async for Critical Checks**: Use async operations for important security decisions
5. **Consistent Logic**: Apply same rules at field and collection levels
6. **Test Edge Cases**: Test with no user, wrong user, admin user scenarios
7. **Monitor Access**: Log failed access attempts for security review
8. **Regular Audit**: Review access rules quarterly or after major changes
9. **Cache Wisely**: Use `req.context` for expensive operations
10. **Document Intent**: Add comments explaining complex access rules
11. **Avoid Secrets in Client**: Never expose sensitive logic to client-side
12. **Rate Limit External Calls**: Protect against DoS on external validation services
13. **Handle Errors Gracefully**: Access functions should return `false` on error, not throw
14. **Use Environment Vars**: Store configuration (IPs, API keys) in env vars
15. **Test Local API**: Remember to set `overrideAccess: false` when testing
16. **Consider Performance**: Measure impact of async operations on login time
17. **Version Control**: Track access control changes in git history
18. **Principle of Least Privilege**: Grant minimum access required for functionality
**Sources**: `docs/access-control/*.mdx`, synthesized best practices
@@ -0,0 +1,697 @@
# Payload CMS Access Control Reference
Complete reference for access control patterns across collections, fields, and globals.
## At a Glance
| Feature | Scope | Returns | Use Case |
| --------------------- | --------------------------------------------------------- | ---------------------- | ---------------------------------- |
| **Collection Access** | create, read, update, delete, admin, unlock, readVersions | boolean \| Where query | Document-level permissions |
| **Field Access** | create, read, update | boolean only | Field-level visibility/editability |
| **Global Access** | read, update, readVersions | boolean \| Where query | Global document permissions |
## Three Layers of Access Control
Payload provides three distinct access control layers:
1. **Collection-Level**: Controls operations on entire documents (create, read, update, delete, admin, unlock, readVersions)
2. **Field-Level**: Controls access to individual fields (create, read, update)
3. **Global-Level**: Controls access to global documents (read, update, readVersions)
## Return Value Types
Access control functions can return:
- **Boolean**: `true` (allow) or `false` (deny)
- **Query Constraint**: `Where` object for row-level security (collection-level only)
Field-level access does NOT support query constraints - only boolean returns.
## Operation Decision Tree
```txt
User makes request
│
├─ Collection access check
│ ├─ Returns false? → Deny entire operation
│ ├─ Returns true? → Continue
│ └─ Returns Where? → Apply query constraint
│
├─ Field access check (if applicable)
│ ├─ Returns false? → Field omitted from result
│ └─ Returns true? → Include field
│
└─ Operation completed
```
## Collection Access Control
### Basic Patterns
```ts
import type { CollectionConfig, Access } from 'payload'
export const Posts: CollectionConfig = {
slug: 'posts',
access: {
// Boolean: Only authenticated users can create
create: ({ req: { user } }) => Boolean(user),
// Query constraint: Public sees published, users see all
read: ({ req: { user } }) => {
if (user) return true
return { status: { equals: 'published' } }
},
// User-specific: Admins or document owner
update: ({ req: { user }, id }) => {
if (user?.roles?.includes('admin')) return true
return { author: { equals: user?.id } }
},
// Async: Check related data
delete: async ({ req, id }) => {
const hasComments = await req.payload.count({
collection: 'comments',
where: { post: { equals: id } },
})
return hasComments === 0
},
// Admin panel visibility
admin: ({ req: { user } }) => {
return user?.roles?.includes('admin') || user?.roles?.includes('editor')
},
},
fields: [
{ name: 'title', type: 'text' },
{ name: 'status', type: 'select', options: ['draft', 'published'] },
{ name: 'author', type: 'relationship', relationTo: 'users' },
],
}
```
### Role-Based Access Control (RBAC) Pattern
Payload does NOT provide a roles system by default. The following is a commonly accepted pattern for implementing role-based access control in auth collections:
```ts
import type { CollectionConfig } from 'payload'
export const Users: CollectionConfig = {
slug: 'users',
auth: true,
fields: [
{ name: 'name', type: 'text', required: true },
{ name: 'email', type: 'email', required: true },
{
name: 'roles',
type: 'select',
hasMany: true,
options: ['admin', 'editor', 'user'],
defaultValue: ['user'],
required: true,
// Save roles to JWT for access control without database lookups
saveToJWT: true,
access: {
// Only admins can update roles
update: ({ req: { user } }) => user?.roles?.includes('admin'),
},
},
],
}
```
**Important Notes:**
1. **Not Built-In**: Payload does not provide a roles system out of the box. You must add a `roles` field to your auth collection.
2. **Save to JWT**: Use `saveToJWT: true` to include roles in the JWT token, enabling role checks without database queries.
3. **Default Value**: Set a `defaultValue` to automatically assign new users a default role.
4. **Access Control**: Restrict who can modify roles (typically only admins).
5. **Role Options**: Define your own role hierarchy based on your application needs.
**Using Roles in Access Control:**
```ts
import type { Access } from 'payload'
// Check for specific role
export const adminOnly: Access = ({ req: { user } }) => {
return user?.roles?.includes('admin')
}
// Check for multiple roles
export const adminOrEditor: Access = ({ req: { user } }) => {
return Boolean(user?.roles?.some((role) => ['admin', 'editor'].includes(role)))
}
// Role hierarchy check
export const hasMinimumRole: Access = ({ req: { user } }, minRole: string) => {
const roleHierarchy = ['user', 'editor', 'admin']
const userHighestRole = Math.max(...(user?.roles?.map((r) => roleHierarchy.indexOf(r)) || [-1]))
const requiredRoleIndex = roleHierarchy.indexOf(minRole)
return userHighestRole >= requiredRoleIndex
}
```
### Reusable Access Functions
```ts
import type { Access } from 'payload'
// Anyone (public)
export const anyone: Access = () => true
// Authenticated only
export const authenticated: Access = ({ req: { user } }) => Boolean(user)
// Authenticated or published content
export const authenticatedOrPublished: Access = ({ req: { user } }) => {
if (user) return true
return { _status: { equals: 'published' } }
}
// Admin only
export const admins: Access = ({ req: { user } }) => {
return user?.roles?.includes('admin')
}
// Admin or editor
export const adminsOrEditors: Access = ({ req: { user } }) => {
return Boolean(user?.roles?.some((role) => ['admin', 'editor'].includes(role)))
}
// Self or admin
export const adminsOrSelf: Access = ({ req: { user } }) => {
if (user?.roles?.includes('admin')) return true
return { id: { equals: user?.id } }
}
// Usage
export const Posts: CollectionConfig = {
slug: 'posts',
access: {
create: authenticated,
read: authenticatedOrPublished,
update: adminsOrEditors,
delete: admins,
},
fields: [{ name: 'title', type: 'text' }],
}
```
### Row-Level Security with Complex Queries
```ts
import type { Access } from 'payload'
// Organization-scoped access
export const organizationScoped: Access = ({ req: { user } }) => {
if (user?.roles?.includes('admin')) return true
// Users see only their organization's data
return {
organization: {
equals: user?.organization,
},
}
}
// Multiple conditions with AND
export const complexAccess: Access = ({ req: { user } }) => {
return {
and: [
{ status: { equals: 'published' } },
{ 'author.isActive': { equals: true } },
{
or: [{ visibility: { equals: 'public' } }, { author: { equals: user?.id } }],
},
],
}
}
// Team-based access
export const teamMemberAccess: Access = ({ req: { user } }) => {
if (!user) return false
if (user.roles?.includes('admin')) return true
return {
'team.members': {
contains: user.id,
},
}
}
```
### Header-Based Access (API Keys)
```ts
import type { Access } from 'payload'
export const apiKeyAccess: Access = ({ req }) => {
const apiKey = req.headers.get('x-api-key')
if (!apiKey) return false
// Validate against stored keys
return apiKey === process.env.VALID_API_KEY
}
// Bearer token validation
export const bearerTokenAccess: Access = async ({ req }) => {
const auth = req.headers.get('authorization')
if (!auth?.startsWith('Bearer ')) return false
const token = auth.slice(7)
const isValid = await validateToken(token)
return isValid
}
```
## Field Access Control
Field access does NOT support query constraints - only boolean returns.
### Basic Field Access
```ts
import type { NumberField, FieldAccess } from 'payload'
const salaryReadAccess: FieldAccess = ({ req: { user }, doc }) => {
// Self can read own salary
if (user?.id === doc?.id) return true
// Admin can read all salaries
return user?.roles?.includes('admin')
}
const salaryUpdateAccess: FieldAccess = ({ req: { user } }) => {
// Only admins can update salary
return user?.roles?.includes('admin')
}
const salaryField: NumberField = {
name: 'salary',
type: 'number',
access: {
read: salaryReadAccess,
update: salaryUpdateAccess,
},
}
```
### Sibling Data Access
```ts
import type { ArrayField, FieldAccess } from 'payload'
const contentReadAccess: FieldAccess = ({ req: { user }, siblingData }) => {
// Authenticated users see all
if (user) return true
// Public sees only if marked public
return siblingData?.isPublic === true
}
const arrayField: ArrayField = {
name: 'sections',
type: 'array',
fields: [
{
name: 'isPublic',
type: 'checkbox',
defaultValue: false,
},
{
name: 'content',
type: 'text',
access: {
read: contentReadAccess,
},
},
],
}
```
### Nested Field Access
```ts
import type { GroupField, FieldAccess } from 'payload'
const internalOnlyAccess: FieldAccess = ({ req: { user } }) => {
return user?.roles?.includes('admin') || user?.roles?.includes('internal')
}
const groupField: GroupField = {
name: 'internalMetadata',
type: 'group',
access: {
read: internalOnlyAccess,
update: internalOnlyAccess,
},
fields: [
{ name: 'internalNotes', type: 'textarea' },
{ name: 'priority', type: 'select', options: ['low', 'medium', 'high'] },
],
}
```
### Hiding Admin Fields
```ts
import type { CollectionConfig } from 'payload'
export const Users: CollectionConfig = {
slug: 'users',
auth: true,
fields: [
{ name: 'name', type: 'text', required: true },
{ name: 'email', type: 'email', required: true },
{
name: 'roles',
type: 'select',
hasMany: true,
options: ['admin', 'editor', 'user'],
access: {
// Hide from UI, but still saved/queried
read: ({ req: { user } }) => user?.roles?.includes('admin'),
// Only admins can update roles
update: ({ req: { user } }) => user?.roles?.includes('admin'),
},
},
],
}
```
## Global Access Control
```ts
import type { GlobalConfig, Access } from 'payload'
const adminOnly: Access = ({ req: { user } }) => {
return user?.roles?.includes('admin')
}
export const SiteSettings: GlobalConfig = {
slug: 'site-settings',
access: {
read: () => true, // Anyone can read settings
update: adminOnly, // Only admins can update
readVersions: adminOnly, // Only admins can see version history
},
fields: [
{ name: 'siteName', type: 'text' },
{ name: 'maintenanceMode', type: 'checkbox' },
],
}
```
## Multi-Tenant Access Control
```ts
import type { Access, CollectionConfig } from 'payload'
// Add tenant field to user type
interface User {
id: string
tenantId: string
roles?: string[]
}
// Tenant-scoped access
const tenantAccess: Access = ({ req: { user } }) => {
// No user = no access
if (!user) return false
// Super admin sees all
if (user.roles?.includes('super-admin')) return true
// Users see only their tenant's data
return {
tenant: {
equals: (user as User).tenantId,
},
}
}
export const Posts: CollectionConfig = {
slug: 'posts',
access: {
create: tenantAccess,
read: tenantAccess,
update: tenantAccess,
delete: tenantAccess,
},
fields: [
{ name: 'title', type: 'text' },
{
name: 'tenant',
type: 'text',
required: true,
access: {
// Tenant field hidden from non-admins
update: ({ req: { user } }) => user?.roles?.includes('super-admin'),
},
hooks: {
// Auto-set tenant on create
beforeChange: [
({ req, operation, value }) => {
if (operation === 'create' && !value) {
return (req.user as User)?.tenantId
}
return value
},
],
},
},
],
}
```
## Auth Collection Patterns
### Self or Admin Pattern
```ts
import type { CollectionConfig } from 'payload'
export const Users: CollectionConfig = {
slug: 'users',
auth: true,
access: {
// Anyone can read user profiles
read: () => true,
// Users can update themselves, admins can update anyone
update: ({ req: { user }, id }) => {
if (user?.roles?.includes('admin')) return true
return user?.id === id
},
// Only admins can delete
delete: ({ req: { user } }) => user?.roles?.includes('admin'),
},
fields: [
{ name: 'name', type: 'text' },
{ name: 'email', type: 'email' },
],
}
```
### Restrict Self-Updates
```ts
import type { CollectionConfig, FieldAccess } from 'payload'
const preventSelfRoleChange: FieldAccess = ({ req: { user }, id }) => {
// Admins can change anyone's roles
if (user?.roles?.includes('admin')) return true
// Users cannot change their own roles
if (user?.id === id) return false
return false
}
export const Users: CollectionConfig = {
slug: 'users',
auth: true,
fields: [
{
name: 'roles',
type: 'select',
hasMany: true,
options: ['admin', 'editor', 'user'],
access: {
update: preventSelfRoleChange,
},
},
],
}
```
## Cross-Collection Validation
```ts
import type { Access } from 'payload'
// Check if user is a project member before allowing access
export const projectMemberAccess: Access = async ({ req, id }) => {
const { user, payload } = req
if (!user) return false
if (user.roles?.includes('admin')) return true
// Check if document exists and user is member
const project = await payload.findByID({
collection: 'projects',
id: id as string,
depth: 0,
})
return project.members?.includes(user.id)
}
// Prevent deletion if document has dependencies
export const preventDeleteWithDependencies: Access = async ({ req, id }) => {
const { payload } = req
const dependencyCount = await payload.count({
collection: 'related-items',
where: {
parent: { equals: id },
},
})
return dependencyCount === 0
}
```
## Access Control Function Arguments
### Collection Create
```ts
create: ({ req, data }) => boolean | Where
// req: PayloadRequest
// - req.user: Authenticated user (if any)
// - req.payload: Payload instance for queries
// - req.headers: Request headers
// - req.locale: Current locale
// data: The data being created
```
### Collection Read
```ts
read: ({ req, id }) => boolean | Where
// req: PayloadRequest
// id: Document ID being read
// - undefined during Access Operation (login check)
// - string when reading specific document
```
### Collection Update
```ts
update: ({ req, id, data }) => boolean | Where
// req: PayloadRequest
// id: Document ID being updated
// data: New values being applied
```
### Collection Delete
```ts
delete: ({ req, id }) => boolean | Where
// req: PayloadRequest
// id: Document ID being deleted
```
### Field Create
```ts
access: {
create: ({ req, data, siblingData }) => boolean
}
// req: PayloadRequest
// data: Full document data
// siblingData: Adjacent field values at same level
```
### Field Read
```ts
access: {
read: ({ req, id, doc, siblingData }) => boolean
}
// req: PayloadRequest
// id: Document ID
// doc: Full document
// siblingData: Adjacent field values
```
### Field Update
```ts
access: {
update: ({ req, id, data, doc, siblingData }) => boolean
}
// req: PayloadRequest
// id: Document ID
// data: New values
// doc: Current document
// siblingData: Adjacent field values
```
## Important Notes
1. **Local API Default**: Access control is **skipped by default** in Local API (`overrideAccess: true`). When passing a `user` parameter, you almost always want to set `overrideAccess: false` to respect that user's permissions:
```ts
// ❌ WRONG: Passes user but bypasses access control (default behavior)
await payload.find({
collection: 'posts',
user: someUser, // User is ignored for access control!
})
// ✅ CORRECT: Respects the user's permissions
await payload.find({
collection: 'posts',
user: someUser,
overrideAccess: false, // Required to enforce access control
})
```
**Why this matters**: If you pass `user` without `overrideAccess: false`, the operation runs with admin privileges regardless of the user's actual permissions. This is a common security mistake.
2. **Field Access Limitations**: Field-level access does NOT support query constraints - only boolean returns.
3. **Admin Panel Visibility**: The `admin` access control determines if a collection appears in the admin panel for a user.
4. **Access Before Hooks**: Access control executes BEFORE hooks run, so hooks cannot modify access behavior.
5. **Query Constraints**: Only collection-level `read` access supports query constraints. All other operations and field-level access require boolean returns.
## Best Practices
1. **Reusable Functions**: Create named access functions for common patterns
2. **Fail Secure**: Default to `false` for sensitive operations
3. **Cache Checks**: Use `req.context` to cache expensive validation
4. **Type Safety**: Type your user object for better IDE support
5. **Test Thoroughly**: Write tests for complex access control logic
6. **Document Intent**: Add comments explaining access rules
7. **Audit Logs**: Track access control decisions for security review
8. **Performance**: Avoid N+1 queries in access functions
9. **Error Handling**: Access functions should not throw - return `false` instead
10. **Tenant Hooks**: Auto-set tenant fields in `beforeChange` hooks
## Advanced Patterns
For advanced access control patterns including context-aware access, time-based restrictions, subscription-based access, factory functions, configuration templates, debugging tips, and performance optimization, see [ACCESS-CONTROL-ADVANCED.md](ACCESS-CONTROL-ADVANCED.md).
+326
View File
@@ -0,0 +1,326 @@
# Payload CMS Adapters Reference
Complete reference for database, storage, and email adapters.
## Database Adapters
### MongoDB
```ts
import { mongooseAdapter } from '@payloadcms/db-mongodb'
export default buildConfig({
db: mongooseAdapter({
url: process.env.DATABASE_URL,
}),
})
```
### Postgres
```ts
import { postgresAdapter } from '@payloadcms/db-postgres'
export default buildConfig({
db: postgresAdapter({
pool: {
connectionString: process.env.DATABASE_URL,
},
push: false, // Don't auto-push schema changes
migrationDir: './migrations',
}),
})
```
### SQLite
```ts
import { sqliteAdapter } from '@payloadcms/db-sqlite'
export default buildConfig({
db: sqliteAdapter({
client: {
url: 'file:./payload.db',
},
transactionOptions: {}, // Enable transactions (disabled by default)
}),
})
```
## Transactions
Payload automatically uses transactions for all-or-nothing database operations. Pass `req` to include operations in the same transaction.
```ts
import type { CollectionAfterChangeHook } from 'payload'
const afterChange: CollectionAfterChangeHook = async ({ req, doc }) => {
// This will be part of the same transaction
await req.payload.create({
req, // Pass req to use same transaction
collection: 'audit-log',
data: { action: 'created', docId: doc.id },
})
}
// Manual transaction control
const transactionID = await payload.db.beginTransaction()
try {
await payload.create({
collection: 'orders',
data: orderData,
req: { transactionID },
})
await payload.update({
collection: 'inventory',
id: itemId,
data: { stock: newStock },
req: { transactionID },
})
await payload.db.commitTransaction(transactionID)
} catch (error) {
await payload.db.rollbackTransaction(transactionID)
throw error
}
```
**Note**: MongoDB requires replicaset for transactions. SQLite requires `transactionOptions: {}` to enable.
### Threading req Through Operations
**Critical**: When performing nested operations in hooks, always pass `req` to maintain transaction context. Failing to do so breaks atomicity and can cause partial updates.
```ts
import type { CollectionAfterChangeHook } from 'payload'
// ✅ CORRECT: Thread req through nested operations
const resaveChildren: CollectionAfterChangeHook = async ({ collection, doc, req }) => {
// Find children - pass req
const children = await req.payload.find({
collection: 'children',
where: { parent: { equals: doc.id } },
req, // Maintains transaction context
})
// Update each child - pass req
for (const child of children.docs) {
await req.payload.update({
id: child.id,
collection: 'children',
data: { updatedField: 'value' },
req, // Same transaction as parent operation
})
}
}
// ❌ WRONG: Missing req breaks transaction
const brokenHook: CollectionAfterChangeHook = async ({ collection, doc, req }) => {
const children = await req.payload.find({
collection: 'children',
where: { parent: { equals: doc.id } },
// Missing req - separate transaction or no transaction
})
for (const child of children.docs) {
await req.payload.update({
id: child.id,
collection: 'children',
data: { updatedField: 'value' },
// Missing req - if parent operation fails, these updates persist
})
}
}
```
**Why This Matters:**
- **MongoDB (with replica sets)**: Creates atomic session across operations
- **PostgreSQL**: All operations use same Drizzle transaction
- **SQLite (with transactions enabled)**: Ensures rollback on errors
- **Without req**: Each operation runs independently, breaking atomicity
**When req is Required:**
- All mutating operations in hooks (create, update, delete)
- Operations that must succeed/fail together
- When using MongoDB replica sets or Postgres
- Any operation that relies on `req.context` or `req.user`
**When req is Optional:**
- Read-only lookups independent of current transaction
- Operations with `disableTransaction: true`
- Administrative operations with `overrideAccess: true`
## Storage Adapters
Available storage adapters:
- **@payloadcms/storage-s3** - AWS S3
- **@payloadcms/storage-azure** - Azure Blob Storage
- **@payloadcms/storage-gcs** - Google Cloud Storage
- **@payloadcms/storage-r2** - Cloudflare R2
- **@payloadcms/storage-vercel-blob** - Vercel Blob
- **@payloadcms/storage-uploadthing** - Uploadthing
### AWS S3
```ts
import { s3Storage } from '@payloadcms/storage-s3'
export default buildConfig({
plugins: [
s3Storage({
collections: {
media: true,
},
bucket: process.env.S3_BUCKET,
config: {
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
},
region: process.env.S3_REGION,
},
}),
],
})
```
### Azure Blob Storage
```ts
import { azureStorage } from '@payloadcms/storage-azure'
export default buildConfig({
plugins: [
azureStorage({
collections: {
media: true,
},
connectionString: process.env.AZURE_STORAGE_CONNECTION_STRING,
containerName: process.env.AZURE_STORAGE_CONTAINER_NAME,
}),
],
})
```
### Google Cloud Storage
```ts
import { gcsStorage } from '@payloadcms/storage-gcs'
export default buildConfig({
plugins: [
gcsStorage({
collections: {
media: true,
},
bucket: process.env.GCS_BUCKET,
options: {
projectId: process.env.GCS_PROJECT_ID,
credentials: JSON.parse(process.env.GCS_CREDENTIALS),
},
}),
],
})
```
### Cloudflare R2
```ts
import { r2Storage } from '@payloadcms/storage-r2'
export default buildConfig({
plugins: [
r2Storage({
collections: {
media: true,
},
bucket: process.env.R2_BUCKET,
config: {
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
},
region: 'auto',
endpoint: process.env.R2_ENDPOINT,
},
}),
],
})
```
### Vercel Blob
```ts
import { vercelBlobStorage } from '@payloadcms/storage-vercel-blob'
export default buildConfig({
plugins: [
vercelBlobStorage({
collections: {
media: true,
},
token: process.env.BLOB_READ_WRITE_TOKEN,
}),
],
})
```
### Uploadthing
```ts
import { uploadthingStorage } from '@payloadcms/storage-uploadthing'
export default buildConfig({
plugins: [
uploadthingStorage({
collections: {
media: true,
},
options: {
token: process.env.UPLOADTHING_TOKEN,
acl: 'public-read',
},
}),
],
})
```
## Email Adapters
### Nodemailer (SMTP)
```ts
import { nodemailerAdapter } from '@payloadcms/email-nodemailer'
export default buildConfig({
email: nodemailerAdapter({
defaultFromAddress: 'noreply@example.com',
defaultFromName: 'My App',
transportOptions: {
host: process.env.SMTP_HOST,
port: 587,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
},
}),
})
```
### Resend
```ts
import { resendAdapter } from '@payloadcms/email-resend'
export default buildConfig({
email: resendAdapter({
defaultFromAddress: 'noreply@example.com',
defaultFromName: 'My App',
apiKey: process.env.RESEND_API_KEY,
}),
})
```
+386
View File
@@ -0,0 +1,386 @@
# Payload CMS Advanced Features
Complete reference for authentication, jobs, custom endpoints, components, plugins, and localization.
## Authentication
### Login
```ts
// REST API
const response = await fetch('/api/users/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'user@example.com',
password: 'password',
}),
})
// Local API
const result = await payload.login({
collection: 'users',
data: {
email: 'user@example.com',
password: 'password',
},
})
```
### Forgot Password
```ts
await payload.forgotPassword({
collection: 'users',
data: {
email: 'user@example.com',
},
})
```
### Custom Strategy
```ts
import type { CollectionConfig, Strategy } from 'payload'
const customStrategy: Strategy = {
name: 'custom',
authenticate: async ({ payload, headers }) => {
const token = headers.get('authorization')?.split(' ')[1]
if (!token) return { user: null }
const user = await verifyToken(token)
return { user }
},
}
export const Users: CollectionConfig = {
slug: 'users',
auth: {
strategies: [customStrategy],
},
fields: [],
}
```
### API Keys
```ts
import type { CollectionConfig } from 'payload'
export const APIKeys: CollectionConfig = {
slug: 'api-keys',
auth: {
disableLocalStrategy: true,
useAPIKey: true,
},
fields: [],
}
```
## Jobs Queue
Offload long-running or scheduled tasks to background workers.
### Tasks
```ts
import { buildConfig } from 'payload'
import type { TaskConfig } from 'payload'
export default buildConfig({
jobs: {
tasks: [
{
slug: 'sendWelcomeEmail',
inputSchema: [
{ name: 'userEmail', type: 'text', required: true },
{ name: 'userName', type: 'text', required: true },
],
outputSchema: [{ name: 'emailSent', type: 'checkbox', required: true }],
retries: 2, // Retry up to 2 times on failure
handler: async ({ input, req }) => {
await sendEmail({
to: input.userEmail,
subject: `Welcome ${input.userName}`,
})
return { output: { emailSent: true } }
},
} as TaskConfig<'sendWelcomeEmail'>,
],
},
})
```
### Queueing Jobs
```ts
// In a hook or endpoint
await req.payload.jobs.queue({
task: 'sendWelcomeEmail',
input: {
userEmail: 'user@example.com',
userName: 'John',
},
waitUntil: new Date('2024-12-31'), // Optional: schedule for future
})
```
### Workflows
Multi-step jobs that run in sequence:
```ts
{
slug: 'onboardUser',
inputSchema: [{ name: 'userId', type: 'text' }],
handler: async ({ job, req }) => {
const results = await job.runInlineTask({
task: async ({ input }) => {
// Step 1: Send welcome email
await sendEmail(input.userId)
return { output: { emailSent: true } }
},
})
await job.runInlineTask({
task: async () => {
// Step 2: Create onboarding tasks
await createTasks()
return { output: { tasksCreated: true } }
},
})
},
}
```
## Custom Endpoints
Add custom REST API routes to collections, globals, or root config. See [ENDPOINTS.md](ENDPOINTS.md) for detailed patterns, authentication, helpers, and real-world examples.
### Root Endpoints
```ts
import { buildConfig } from 'payload'
import type { Endpoint } from 'payload'
const helloEndpoint: Endpoint = {
path: '/hello',
method: 'get',
handler: () => {
return Response.json({ message: 'Hello!' })
},
}
const greetEndpoint: Endpoint = {
path: '/greet/:name',
method: 'get',
handler: (req) => {
return Response.json({
message: `Hello ${req.routeParams.name}!`,
})
},
}
export default buildConfig({
endpoints: [helloEndpoint, greetEndpoint],
collections: [],
secret: process.env.PAYLOAD_SECRET || '',
})
```
### Collection Endpoints
```ts
import type { CollectionConfig, Endpoint } from 'payload'
const featuredEndpoint: Endpoint = {
path: '/featured',
method: 'get',
handler: async (req) => {
const posts = await req.payload.find({
collection: 'posts',
where: { featured: { equals: true } },
})
return Response.json(posts)
},
}
export const Posts: CollectionConfig = {
slug: 'posts',
endpoints: [featuredEndpoint],
fields: [
{ name: 'title', type: 'text' },
{ name: 'featured', type: 'checkbox' },
],
}
```
## Custom Components
### Field Component (Client)
```tsx
'use client'
import { useField } from '@payloadcms/ui'
import type { TextFieldClientComponent } from 'payload'
export const CustomField: TextFieldClientComponent = () => {
const { value, setValue } = useField()
return <input value={value || ''} onChange={(e) => setValue(e.target.value)} />
}
```
### Custom View
```tsx
'use client'
import { DefaultTemplate } from '@payloadcms/next/templates'
export const CustomView = () => {
return (
<DefaultTemplate>
<h1>Custom Dashboard</h1>
{/* Your content */}
</DefaultTemplate>
)
}
```
### Admin Config
```ts
import { buildConfig } from 'payload'
export default buildConfig({
admin: {
components: {
beforeDashboard: ['/components/BeforeDashboard'],
beforeLogin: ['/components/BeforeLogin'],
views: {
custom: {
Component: '/views/Custom',
path: '/custom',
},
},
},
},
collections: [],
secret: process.env.PAYLOAD_SECRET || '',
})
```
## Plugins
### Available Plugins
- **@payloadcms/plugin-seo** - SEO fields with meta title/description, Open Graph, preview generation
- **@payloadcms/plugin-redirects** - Manage URL redirects (301/302) for Next.js apps
- **@payloadcms/plugin-nested-docs** - Hierarchical document structures with breadcrumbs
- **@payloadcms/plugin-form-builder** - Dynamic form builder with submissions and validation
- **@payloadcms/plugin-search** - Full-text search integration (Algolia support)
- **@payloadcms/plugin-stripe** - Stripe payments, subscriptions, webhooks
- **@payloadcms/plugin-ecommerce** - Complete ecommerce solution (products, variants, carts, orders)
- **@payloadcms/plugin-import-export** - Import/export data via CSV
- **@payloadcms/plugin-multi-tenant** - Multi-tenancy with tenant isolation
- **@payloadcms/plugin-sentry** - Sentry error tracking integration
- **@payloadcms/plugin-mcp** - Model Context Protocol for AI integrations
### Using Plugins
```ts
import { buildConfig } from 'payload'
import { seoPlugin } from '@payloadcms/plugin-seo'
import { redirectsPlugin } from '@payloadcms/plugin-redirects'
export default buildConfig({
plugins: [
seoPlugin({
collections: ['posts', 'pages'],
}),
redirectsPlugin({
collections: ['pages'],
}),
],
collections: [],
secret: process.env.PAYLOAD_SECRET || '',
})
```
### Creating Plugins
```ts
import type { Config } from 'payload'
interface PluginOptions {
enabled?: boolean
}
export const myPlugin =
(options: PluginOptions) =>
(config: Config): Config => ({
...config,
collections: [
...(config.collections || []),
{
slug: 'plugin-collection',
fields: [{ name: 'title', type: 'text' }],
},
],
onInit: async (payload) => {
if (config.onInit) await config.onInit(payload)
// Plugin initialization
},
})
```
## Localization
```ts
import { buildConfig } from 'payload'
import type { Field, Payload } from 'payload'
export default buildConfig({
localization: {
locales: ['en', 'es', 'de'],
defaultLocale: 'en',
fallback: true,
},
collections: [],
secret: process.env.PAYLOAD_SECRET || '',
})
// Localized field
const localizedField: TextField = {
name: 'title',
type: 'text',
localized: true,
}
// Query with locale
const posts = await payload.find({
collection: 'posts',
locale: 'es',
})
```
## TypeScript Type References
For complete TypeScript type definitions and signatures, reference these files from the Payload source:
### Core Configuration Types
- **[All Commonly-Used Types](https://github.com/payloadcms/payload/blob/3.x/packages/payload/src/index.ts)** - Check here first for commonly used types and interfaces. All core types are exported from this file.
### Database & Adapters
- **[Database Adapter Types](https://github.com/payloadcms/payload/blob/3.x/packages/payload/src/database/types.ts)** - Base adapter interface
- **[MongoDB Adapter](https://github.com/payloadcms/payload/blob/3.x/packages/db-mongodb/src/index.ts)** - MongoDB-specific options
- **[Postgres Adapter](https://github.com/payloadcms/payload/blob/3.x/packages/db-postgres/src/index.ts)** - Postgres-specific options
### Rich Text & Plugins
- **[Lexical Types](https://github.com/payloadcms/payload/blob/3.x/packages/richtext-lexical/src/exports/server/index.ts)** - Lexical editor configuration
When users need detailed type information, fetch these URLs to provide complete signatures and optional parameters.
+303
View File
@@ -0,0 +1,303 @@
# Payload CMS Collections Reference
Complete reference for collection configurations and patterns.
## Basic Collection
```ts
import type { CollectionConfig } from 'payload'
export const Posts: CollectionConfig = {
slug: 'posts',
labels: {
singular: 'Post',
plural: 'Posts',
},
admin: {
useAsTitle: 'title',
defaultColumns: ['title', 'author', 'status', 'createdAt'],
group: 'Content', // Organize in admin sidebar
description: 'Blog posts and articles',
listSearchableFields: ['title', 'slug'],
},
fields: [
{
name: 'title',
type: 'text',
required: true,
index: true,
},
{
name: 'slug',
type: 'text',
unique: true,
index: true,
admin: { position: 'sidebar' },
},
{
name: 'status',
type: 'select',
options: ['draft', 'published'],
defaultValue: 'draft',
},
],
defaultSort: '-createdAt',
timestamps: true,
}
```
## Auth Collection
```ts
export const Users: CollectionConfig = {
slug: 'users',
auth: {
tokenExpiration: 7200, // 2 hours
verify: true,
maxLoginAttempts: 5,
lockTime: 600000, // 10 minutes
useAPIKey: true,
},
admin: {
useAsTitle: 'email',
},
fields: [
{
name: 'roles',
type: 'select',
hasMany: true,
options: ['admin', 'editor', 'user'],
required: true,
defaultValue: ['user'],
saveToJWT: true,
},
{
name: 'name',
type: 'text',
required: true,
},
],
}
```
## Upload Collection
```ts
export const Media: CollectionConfig = {
slug: 'media',
upload: {
staticDir: 'media',
mimeTypes: ['image/*'],
imageSizes: [
{
name: 'thumbnail',
width: 400,
height: 300,
position: 'centre',
},
{
name: 'card',
width: 768,
height: 1024,
},
],
adminThumbnail: 'thumbnail',
focalPoint: true,
crop: true,
},
access: {
read: () => true,
},
fields: [
{
name: 'alt',
type: 'text',
required: true,
},
{
name: 'caption',
type: 'text',
localized: true,
},
],
}
```
## Live Preview
Enable real-time content preview during editing.
```ts
import type { CollectionConfig } from 'payload'
const generatePreviewPath = ({
slug,
collection,
req,
}: {
slug: string
collection: string
req: any
}) => {
const baseUrl = process.env.NEXT_PUBLIC_SERVER_URL
return `${baseUrl}/api/preview?slug=${slug}&collection=${collection}`
}
export const Pages: CollectionConfig = {
slug: 'pages',
admin: {
useAsTitle: 'title',
// Live preview during editing
livePreview: {
url: ({ data, req }) =>
generatePreviewPath({
slug: data?.slug as string,
collection: 'pages',
req,
}),
},
// Static preview button
preview: (data, { req }) =>
generatePreviewPath({
slug: data?.slug as string,
collection: 'pages',
req,
}),
},
fields: [
{ name: 'title', type: 'text' },
{ name: 'slug', type: 'text' },
],
}
```
## Versioning & Drafts
Payload maintains version history and supports draft/publish workflows.
```ts
import type { CollectionConfig } from 'payload'
// Basic versioning (audit log only)
export const Users: CollectionConfig = {
slug: 'users',
versions: true, // or { maxPerDoc: 100 }
fields: [{ name: 'name', type: 'text' }],
}
// Drafts enabled (draft/publish workflow)
export const Posts: CollectionConfig = {
slug: 'posts',
versions: {
drafts: true, // Enables _status field
maxPerDoc: 50,
},
fields: [{ name: 'title', type: 'text' }],
}
// Full configuration with autosave and scheduled publish
export const Pages: CollectionConfig = {
slug: 'pages',
versions: {
drafts: {
autosave: true, // Auto-save while editing
schedulePublish: true, // Schedule future publish/unpublish
validate: false, // Don't validate drafts (default)
},
maxPerDoc: 100, // Keep last 100 versions (0 = unlimited)
},
fields: [{ name: 'title', type: 'text' }],
}
```
### Draft API Usage
```ts
// Create draft
await payload.create({
collection: 'posts',
data: { title: 'Draft Post' },
draft: true, // Saves as draft, skips required field validation
})
// Update as draft
await payload.update({
collection: 'posts',
id: '123',
data: { title: 'Updated Draft' },
draft: true,
})
// Read with drafts (returns newest draft if available)
const post = await payload.findByID({
collection: 'posts',
id: '123',
draft: true, // Returns draft version if exists
})
// Query only published (REST API)
// GET /api/posts (returns only _status: 'published')
// Access control for drafts
export const Posts: CollectionConfig = {
slug: 'posts',
versions: { drafts: true },
access: {
read: ({ req: { user } }) => {
// Public can only see published
if (!user) return { _status: { equals: 'published' } }
// Authenticated can see all
return true
},
},
fields: [{ name: 'title', type: 'text' }],
}
```
### Document Status
The `_status` field is auto-injected when drafts are enabled:
- `draft` - Never published
- `published` - Published with no newer drafts
- `changed` - Published but has newer unpublished drafts
## Globals
Globals are single-instance documents (not collections).
```ts
import type { GlobalConfig } from 'payload'
export const Header: GlobalConfig = {
slug: 'header',
label: 'Header',
admin: {
group: 'Settings',
},
fields: [
{
name: 'logo',
type: 'upload',
relationTo: 'media',
required: true,
},
{
name: 'nav',
type: 'array',
maxRows: 8,
fields: [
{
name: 'link',
type: 'relationship',
relationTo: 'pages',
},
{
name: 'label',
type: 'text',
},
],
},
],
}
```
+634
View File
@@ -0,0 +1,634 @@
# Payload Custom API Endpoints Reference
Custom REST API endpoints extend Payload's auto-generated CRUD operations with custom logic, authentication flows, webhooks, and integrations.
## Quick Reference
### Endpoint Configuration
| Property | Type | Description |
| --------- | ------------------------------------------------- | --------------------------------------------------------------- |
| `path` | `string` | Route path after collection/global slug (e.g., `/:id/tracking`) |
| `method` | `'get' \| 'post' \| 'put' \| 'patch' \| 'delete'` | HTTP method (lowercase) |
| `handler` | `(req: PayloadRequest) => Promise<Response>` | Async function returning Web API Response |
| `custom` | `Record<string, any>` | Extension point for plugins/metadata |
### Request Context
| Property | Type | Description |
| ----------------- | ----------------------- | ------------------------------------------------------ |
| `req.user` | `User \| null` | Authenticated user (null if not authenticated) |
| `req.payload` | `Payload` | Payload instance for operations (find, create...) |
| `req.routeParams` | `Record<string, any>` | Path parameters (e.g., `:id`) |
| `req.url` | `string` | Full request URL |
| `req.method` | `string` | HTTP method |
| `req.headers` | `Headers` | Request headers |
| `req.json()` | `() => Promise<any>` | Parse JSON body |
| `req.text()` | `() => Promise<string>` | Read body as text |
| `req.data` | `any` | Parsed body (after `addDataAndFileToRequest()`) |
| `req.file` | `File` | Uploaded file (after `addDataAndFileToRequest()`) |
| `req.locale` | `string` | Request locale (after `addLocalesToRequestFromData()`) |
| `req.i18n` | `I18n` | i18n instance |
| `req.t` | `TFunction` | Translation function |
## Common Patterns
### Authentication Check
Custom endpoints are **not authenticated by default**. Check `req.user` to enforce authentication.
```ts
import { APIError } from 'payload'
export const authenticatedEndpoint = {
path: '/protected',
method: 'get',
handler: async (req) => {
if (!req.user) {
throw new APIError('Unauthorized', 401)
}
// User is authenticated
return Response.json({ message: 'Access granted' })
},
}
```
### Using Payload Operations
Use `req.payload` for database operations with access control and hooks.
```ts
export const getRelatedPosts = {
path: '/:id/related',
method: 'get',
handler: async (req) => {
const { id } = req.routeParams
// Find related posts
const posts = await req.payload.find({
collection: 'posts',
where: {
category: {
equals: id,
},
},
limit: 5,
sort: '-createdAt',
})
return Response.json(posts)
},
}
```
### Route Parameters
Access path parameters via `req.routeParams`.
```ts
export const getTrackingEndpoint = {
path: '/:id/tracking',
method: 'get',
handler: async (req) => {
const orderId = req.routeParams.id
const tracking = await getTrackingInfo(orderId)
if (!tracking) {
return Response.json({ error: 'not found' }, { status: 404 })
}
return Response.json(tracking)
},
}
```
### Request Body Handling
**Option 1: Manual JSON parsing**
```ts
export const createEndpoint = {
path: '/create',
method: 'post',
handler: async (req) => {
const data = await req.json()
const result = await req.payload.create({
collection: 'posts',
data,
})
return Response.json(result)
},
}
```
**Option 2: Using helper (handles JSON + files)**
```ts
import { addDataAndFileToRequest } from 'payload'
export const uploadEndpoint = {
path: '/upload',
method: 'post',
handler: async (req) => {
await addDataAndFileToRequest(req)
// req.data now contains parsed body
// req.file contains uploaded file (if multipart)
const result = await req.payload.create({
collection: 'media',
data: req.data,
file: req.file,
})
return Response.json(result)
},
}
```
### CORS Headers
Use `headersWithCors` helper to apply config CORS settings.
```ts
import { headersWithCors } from 'payload'
export const corsEndpoint = {
path: '/public-data',
method: 'get',
handler: async (req) => {
const data = await fetchPublicData()
return Response.json(data, {
headers: headersWithCors({
headers: new Headers(),
req,
}),
})
},
}
```
### Error Handling
Throw `APIError` with status codes for proper error responses.
```ts
import { APIError } from 'payload'
export const validateEndpoint = {
path: '/validate',
method: 'post',
handler: async (req) => {
const data = await req.json()
if (!data.email) {
throw new APIError('Email is required', 400)
}
// Validation passed
return Response.json({ valid: true })
},
}
```
### Query Parameters
Extract query params from URL.
```ts
export const searchEndpoint = {
path: '/search',
method: 'get',
handler: async (req) => {
const url = new URL(req.url)
const query = url.searchParams.get('q')
const limit = parseInt(url.searchParams.get('limit') || '10')
const results = await req.payload.find({
collection: 'posts',
where: {
title: {
contains: query,
},
},
limit,
})
return Response.json(results)
},
}
```
## Helper Functions
### addDataAndFileToRequest
Parses request body and attaches to `req.data` and `req.file`.
```ts
import { addDataAndFileToRequest } from 'payload'
export const endpoint = {
path: '/process',
method: 'post',
handler: async (req) => {
await addDataAndFileToRequest(req)
// req.data: parsed JSON or form data
// req.file: uploaded file (if multipart)
console.log(req.data) // { title: 'My Post' }
console.log(req.file) // File object or undefined
},
}
```
**Handles:**
- JSON bodies (`Content-Type: application/json`)
- Form data (`Content-Type: multipart/form-data`)
- File uploads
### addLocalesToRequestFromData
Extracts locale from request data and validates against config.
```ts
import { addLocalesToRequestFromData } from 'payload'
export const endpoint = {
path: '/translate',
method: 'post',
handler: async (req) => {
await addLocalesToRequestFromData(req)
// req.locale: validated locale string
// req.fallbackLocale: fallback locale string
const result = await req.payload.find({
collection: 'posts',
locale: req.locale,
})
return Response.json(result)
},
}
```
### headersWithCors
Applies CORS headers from Payload config.
```ts
import { headersWithCors } from 'payload'
export const endpoint = {
path: '/data',
method: 'get',
handler: async (req) => {
const data = { message: 'Hello' }
return Response.json(data, {
headers: headersWithCors({
headers: new Headers({
'Cache-Control': 'public, max-age=3600',
}),
req,
}),
})
},
}
```
## Real-World Examples
### Multi-Tenant Login Endpoint
From `examples/multi-tenant`:
```ts
import { APIError, generatePayloadCookie, headersWithCors } from 'payload'
export const externalUsersLogin = {
path: '/login-external',
method: 'post',
handler: async (req) => {
const { email, password, tenant } = await req.json()
if (!email || !password || !tenant) {
throw new APIError('Missing credentials', 400)
}
// Find user with tenant constraint
const userQuery = await req.payload.find({
collection: 'users',
where: {
and: [
{ email: { equals: email } },
{
or: [{ tenants: { equals: tenant } }, { 'tenants.tenant': { equals: tenant } }],
},
],
},
})
if (!userQuery.docs.length) {
throw new APIError('Invalid credentials', 401)
}
// Authenticate user
const result = await req.payload.login({
collection: 'users',
data: { email, password },
})
return Response.json(result, {
headers: headersWithCors({
headers: new Headers({
'Set-Cookie': generatePayloadCookie({
collectionAuthConfig: req.payload.config.collections.find((c) => c.slug === 'users')
.auth,
cookiePrefix: req.payload.config.cookiePrefix,
token: result.token,
}),
}),
req,
}),
})
},
}
```
### Webhook Handler (Stripe)
From `packages/plugin-ecommerce`:
```ts
export const webhookEndpoint = {
path: '/webhooks',
method: 'post',
handler: async (req) => {
const body = await req.text()
const signature = req.headers.get('stripe-signature')
try {
const event = stripe.webhooks.constructEvent(body, signature, webhookSecret)
// Process event
switch (event.type) {
case 'payment_intent.succeeded':
await handlePaymentSuccess(req.payload, event.data.object)
break
case 'payment_intent.failed':
await handlePaymentFailure(req.payload, event.data.object)
break
}
return Response.json({ received: true })
} catch (err) {
req.payload.logger.error(`Webhook error: ${err.message}`)
return Response.json({ error: err.message }, { status: 400 })
}
},
}
```
### Data Preview Endpoint
From `packages/plugin-import-export`:
```ts
import { addDataAndFileToRequest } from 'payload'
export const previewEndpoint = {
path: '/preview',
method: 'post',
handler: async (req) => {
if (!req.user) {
throw new APIError('Unauthorized', 401)
}
await addDataAndFileToRequest(req)
const { collection, where, limit = 10 } = req.data
// Validate collection exists
const collectionConfig = req.payload.config.collections.find((c) => c.slug === collection)
if (!collectionConfig) {
throw new APIError('Collection not found', 404)
}
// Preview data
const results = await req.payload.find({
collection,
where,
limit,
depth: 0,
})
return Response.json({
docs: results.docs,
totalDocs: results.totalDocs,
fields: collectionConfig.fields,
})
},
}
```
### Reindex Action Endpoint
From `packages/plugin-search`:
```ts
export const reindexEndpoint = (pluginConfig) => ({
path: '/reindex',
method: 'post',
handler: async (req) => {
if (!req.user) {
throw new APIError('Unauthorized', 401)
}
const { collection } = req.routeParams
// Reindex collection
const result = await reindexCollection(req.payload, collection, pluginConfig)
return Response.json({
message: `Reindexed ${result.count} documents`,
count: result.count,
})
},
})
```
## Endpoint Placement
### Collection Endpoints
Mounted at `/api/{collection-slug}/{path}`.
```ts
import type { CollectionConfig } from 'payload'
export const Orders: CollectionConfig = {
slug: 'orders',
fields: [
/* ... */
],
endpoints: [
{
path: '/:id/tracking',
method: 'get',
handler: async (req) => {
// Available at: /api/orders/:id/tracking
const orderId = req.routeParams.id
return Response.json({ orderId })
},
},
],
}
```
### Global Endpoints
Mounted at `/api/globals/{global-slug}/{path}`.
```ts
import type { GlobalConfig } from 'payload'
export const Settings: GlobalConfig = {
slug: 'settings',
fields: [
/* ... */
],
endpoints: [
{
path: '/clear-cache',
method: 'post',
handler: async (req) => {
// Available at: /api/globals/settings/clear-cache
await clearCache()
return Response.json({ message: 'Cache cleared' })
},
},
],
}
```
## Advanced Patterns
### Factory Functions
Create reusable endpoint factories for plugins.
```ts
export const createWebhookEndpoint = (config) => ({
path: '/webhook',
method: 'post',
handler: async (req) => {
const signature = req.headers.get('x-webhook-signature')
if (!verifySignature(signature, config.secret)) {
throw new APIError('Invalid signature', 401)
}
const data = await req.json()
await processWebhook(req.payload, data, config)
return Response.json({ received: true })
},
})
```
### Conditional Endpoints
Add endpoints based on config options.
```ts
export const MyCollection: CollectionConfig = {
slug: 'posts',
fields: [
/* ... */
],
endpoints: [
// Always included
{
path: '/public',
method: 'get',
handler: async (req) => Response.json({ data: [] }),
},
// Conditionally included
...(process.env.ENABLE_ANALYTICS
? [
{
path: '/analytics',
method: 'get',
handler: async (req) => Response.json({ analytics: [] }),
},
]
: []),
],
}
```
### OpenAPI Documentation
Use `custom` property for API documentation metadata.
```ts
export const endpoint = {
path: '/search',
method: 'get',
handler: async (req) => {
// Handler implementation
},
custom: {
openapi: {
summary: 'Search posts',
parameters: [
{
name: 'q',
in: 'query',
required: true,
schema: { type: 'string' },
},
],
responses: {
200: {
description: 'Search results',
content: {
'application/json': {
schema: { type: 'array' },
},
},
},
},
},
},
}
```
## Best Practices
1. **Always check authentication** - Custom endpoints are not authenticated by default
2. **Use `req.payload` for operations** - Ensures access control and hooks execute
3. **Use helpers for common tasks** - `addDataAndFileToRequest`, `headersWithCors`, etc.
4. **Throw `APIError` for errors** - Provides consistent error responses
5. **Return Web API `Response`** - Use `Response.json()` for consistent responses
6. **Validate input** - Check required fields, validate types
7. **Handle CORS** - Use `headersWithCors` for cross-origin requests
8. **Log errors** - Use `req.payload.logger` for debugging
9. **Document with `custom`** - Add OpenAPI metadata for API docs
10. **Factory pattern for reuse** - Create endpoint factories for plugins
## Resources
- REST API Overview: <https://payloadcms.com/docs/rest-api/overview>
- Custom Endpoints: <https://payloadcms.com/docs/rest-api/overview#custom-endpoints>
- Access Control: <https://payloadcms.com/docs/access-control/overview>
- Local API: <https://payloadcms.com/docs/local-api/overview>
@@ -0,0 +1,553 @@
# Payload Field Type Guards Reference
Complete reference with detailed examples and patterns. See [FIELDS.md](FIELDS.md#field-type-guards) for quick reference table of all guards.
## Structural Guards
### fieldHasSubFields
Checks if field contains nested fields (group, array, row, or collapsible).
```ts
import type { Field } from 'payload'
import { fieldHasSubFields } from 'payload'
function traverseFields(fields: Field[]): void {
fields.forEach((field) => {
if (fieldHasSubFields(field)) {
// Safe to access field.fields
traverseFields(field.fields)
}
})
}
```
**Signature:**
```ts
fieldHasSubFields<TField extends ClientField | Field>(
field: TField
): field is TField & (FieldWithSubFieldsClient | FieldWithSubFields)
```
**Common Pattern - Exclude Arrays:**
```ts
if (fieldHasSubFields(field) && !fieldIsArrayType(field)) {
// Groups, rows, collapsibles only (not arrays)
}
```
### fieldIsArrayType
Checks if field type is `'array'`.
```ts
import { fieldIsArrayType } from 'payload'
if (fieldIsArrayType(field)) {
// field.type === 'array'
console.log(`Min rows: ${field.minRows}`)
console.log(`Max rows: ${field.maxRows}`)
}
```
**Signature:**
```ts
fieldIsArrayType<TField extends ClientField | Field>(
field: TField
): field is TField & (ArrayFieldClient | ArrayField)
```
### fieldIsBlockType
Checks if field type is `'blocks'`.
```ts
import { fieldIsBlockType } from 'payload'
if (fieldIsBlockType(field)) {
// field.type === 'blocks'
field.blocks.forEach((block) => {
console.log(`Block: ${block.slug}`)
})
}
```
**Signature:**
```ts
fieldIsBlockType<TField extends ClientField | Field>(
field: TField
): field is TField & (BlocksFieldClient | BlocksField)
```
**Common Pattern - Distinguish Containers:**
```ts
if (fieldIsArrayType(field)) {
// Handle array rows
} else if (fieldIsBlockType(field)) {
// Handle block types
}
```
### fieldIsGroupType
Checks if field type is `'group'`.
```ts
import { fieldIsGroupType } from 'payload'
if (fieldIsGroupType(field)) {
// field.type === 'group'
console.log(`Interface: ${field.interfaceName}`)
}
```
**Signature:**
```ts
fieldIsGroupType<TField extends ClientField | Field>(
field: TField
): field is TField & (GroupFieldClient | GroupField)
```
## Capability Guards
### fieldSupportsMany
Checks if field can have multiple values (select, relationship, or upload with `hasMany`).
```ts
import { fieldSupportsMany } from 'payload'
if (fieldSupportsMany(field)) {
// field.type is 'select' | 'relationship' | 'upload'
// Safe to check field.hasMany
if (field.hasMany) {
console.log('Field accepts multiple values')
}
}
```
**Signature:**
```ts
fieldSupportsMany<TField extends ClientField | Field>(
field: TField
): field is TField & (FieldWithManyClient | FieldWithMany)
```
### fieldHasMaxDepth
Checks if field is relationship/upload/join with numeric `maxDepth` property.
```ts
import { fieldHasMaxDepth } from 'payload'
if (fieldHasMaxDepth(field)) {
// field.type is 'upload' | 'relationship' | 'join'
// AND field.maxDepth is number
const remainingDepth = field.maxDepth - currentDepth
}
```
**Signature:**
```ts
fieldHasMaxDepth<TField extends ClientField | Field>(
field: TField
): field is TField & (FieldWithMaxDepthClient | FieldWithMaxDepth)
```
### fieldShouldBeLocalized
Checks if field needs localization handling (accounts for parent localization).
```ts
import { fieldShouldBeLocalized } from 'payload'
function processField(field: Field, parentIsLocalized: boolean) {
if (fieldShouldBeLocalized({ field, parentIsLocalized })) {
// Create locale-specific table or index
}
}
```
**Signature:**
```ts
fieldShouldBeLocalized({
field,
parentIsLocalized,
}: {
field: ClientField | ClientTab | Field | Tab
parentIsLocalized: boolean
}): boolean
```
```ts
// Accounts for parent localization
if (fieldShouldBeLocalized({ field, parentIsLocalized: false })) {
/* ... */
}
```
### fieldIsVirtual
Checks if field is virtual (computed or virtual relationship).
```ts
import { fieldIsVirtual } from 'payload'
if (fieldIsVirtual(field)) {
// field.virtual is truthy
if (typeof field.virtual === 'string') {
// Virtual relationship path
console.log(`Virtual path: ${field.virtual}`)
} else {
// Computed virtual field (uses hooks)
}
}
```
**Signature:**
```ts
fieldIsVirtual(field: Field | Tab): boolean
```
## Data Guards
### fieldAffectsData
**Most commonly used guard.** Checks if field stores data (has name and is not UI-only).
```ts
import { fieldAffectsData } from 'payload'
function generateSchema(fields: Field[]) {
fields.forEach((field) => {
if (fieldAffectsData(field)) {
// Safe to access field.name
schema[field.name] = getFieldType(field)
}
})
}
```
**Signature:**
```ts
fieldAffectsData<TField extends ClientField | Field | TabAsField | TabAsFieldClient>(
field: TField
): field is TField & (FieldAffectingDataClient | FieldAffectingData)
```
**Pattern - Data Fields Only:**
```ts
const dataFields = fields.filter(fieldAffectsData)
```
### fieldIsPresentationalOnly
Checks if field is UI-only (type `'ui'`).
```ts
import { fieldIsPresentationalOnly } from 'payload'
if (fieldIsPresentationalOnly(field)) {
// field.type === 'ui'
// Skip in data operations, GraphQL schema, etc.
return
}
```
**Signature:**
```ts
fieldIsPresentationalOnly<TField extends ClientField | Field | TabAsField | TabAsFieldClient>(
field: TField
): field is TField & (UIFieldClient | UIField)
```
### fieldIsID
Checks if field name is exactly `'id'`.
```ts
import { fieldIsID } from 'payload'
if (fieldIsID(field)) {
// field.name === 'id'
// Special handling for ID field
}
```
**Signature:**
```ts
fieldIsID<TField extends ClientField | Field>(
field: TField
): field is { name: 'id' } & TField
```
### fieldIsHiddenOrDisabled
Checks if field is hidden or admin-disabled.
```ts
import { fieldIsHiddenOrDisabled } from 'payload'
const visibleFields = fields.filter((field) => !fieldIsHiddenOrDisabled(field))
```
**Signature:**
```ts
fieldIsHiddenOrDisabled<TField extends ClientField | Field | TabAsField | TabAsFieldClient>(
field: TField
): field is { admin: { hidden: true } } & TField
```
## Layout Guards
### fieldIsSidebar
Checks if field is positioned in sidebar.
```ts
import { fieldIsSidebar } from 'payload'
const [mainFields, sidebarFields] = fields.reduce(
([main, sidebar], field) => {
if (fieldIsSidebar(field)) {
return [main, [...sidebar, field]]
}
return [[...main, field], sidebar]
},
[[], []],
)
```
**Signature:**
```ts
fieldIsSidebar<TField extends ClientField | Field | TabAsField | TabAsFieldClient>(
field: TField
): field is { admin: { position: 'sidebar' } } & TField
```
## Tab & Group Guards
### tabHasName
Checks if tab is named (stores data under tab name).
```ts
import { tabHasName } from 'payload'
tabs.forEach((tab) => {
if (tabHasName(tab)) {
// tab.name exists
dataPath.push(tab.name)
}
// Process tab.fields
})
```
**Signature:**
```ts
tabHasName<TField extends ClientTab | Tab>(
tab: TField
): tab is NamedTab & TField
```
### groupHasName
Checks if group is named (stores data under group name).
```ts
import { groupHasName } from 'payload'
if (groupHasName(group)) {
// group.name exists
return data[group.name]
}
```
**Signature:**
```ts
groupHasName(group: Partial<NamedGroupFieldClient>): group is NamedGroupFieldClient
```
## Option & Value Guards
### optionIsObject
Checks if option is object format `{label, value}` vs string.
```ts
import { optionIsObject } from 'payload'
field.options.forEach((option) => {
if (optionIsObject(option)) {
console.log(`${option.label}: ${option.value}`)
} else {
console.log(option) // string value
}
})
```
**Signature:**
```ts
optionIsObject(option: Option): option is OptionObject
```
### optionsAreObjects
Checks if entire options array contains objects.
```ts
import { optionsAreObjects } from 'payload'
if (optionsAreObjects(field.options)) {
// All options are OptionObject[]
const labels = field.options.map((opt) => opt.label)
}
```
**Signature:**
```ts
optionsAreObjects(options: Option[]): options is OptionObject[]
```
### optionIsValue
Checks if option is string value (not object).
```ts
import { optionIsValue } from 'payload'
if (optionIsValue(option)) {
// option is string
const value = option
}
```
**Signature:**
```ts
optionIsValue(option: Option): option is string
```
### valueIsValueWithRelation
Checks if relationship value is polymorphic format `{relationTo, value}`.
```ts
import { valueIsValueWithRelation } from 'payload'
if (valueIsValueWithRelation(fieldValue)) {
// fieldValue.relationTo exists
// fieldValue.value exists
console.log(`Related to ${fieldValue.relationTo}: ${fieldValue.value}`)
}
```
**Signature:**
```ts
valueIsValueWithRelation(value: unknown): value is ValueWithRelation
```
## Common Patterns
### Recursive Field Traversal
```ts
import { fieldAffectsData, fieldHasSubFields } from 'payload'
function traverseFields(fields: Field[], callback: (field: Field) => void) {
fields.forEach((field) => {
if (fieldAffectsData(field)) {
callback(field)
}
if (fieldHasSubFields(field)) {
traverseFields(field.fields, callback)
}
})
}
```
### Filter Data-Bearing Fields
```ts
import { fieldAffectsData, fieldIsPresentationalOnly, fieldIsHiddenOrDisabled } from 'payload'
const dataFields = fields.filter(
(field) =>
fieldAffectsData(field) && !fieldIsPresentationalOnly(field) && !fieldIsHiddenOrDisabled(field),
)
```
### Container Type Switching
```ts
import { fieldIsArrayType, fieldIsBlockType, fieldHasSubFields } from 'payload'
if (fieldIsArrayType(field)) {
// Handle array-specific logic
} else if (fieldIsBlockType(field)) {
// Handle blocks-specific logic
} else if (fieldHasSubFields(field)) {
// Handle group/row/collapsible
}
```
### Safe Property Access
```ts
import { fieldSupportsMany, fieldHasMaxDepth } from 'payload'
// Without guard - TypeScript error
// if (field.hasMany) { /* ... */ }
// With guard - safe access
if (fieldSupportsMany(field) && field.hasMany) {
console.log('Multiple values supported')
}
if (fieldHasMaxDepth(field)) {
const depth = field.maxDepth // TypeScript knows this is number
}
```
## Type Preservation
All guards preserve the original type constraint:
```ts
import type { ClientField, Field } from 'payload'
import { fieldHasSubFields } from 'payload'
function processServerField(field: Field) {
if (fieldHasSubFields(field)) {
// field is Field & FieldWithSubFields (not ClientField)
}
}
function processClientField(field: ClientField) {
if (fieldHasSubFields(field)) {
// field is ClientField & FieldWithSubFieldsClient
}
}
```
+744
View File
@@ -0,0 +1,744 @@
# Payload CMS Field Types Reference
Complete reference for all Payload field types with examples.
## Text Field
```ts
import type { TextField } from 'payload'
const textField: TextField = {
name: 'title',
type: 'text',
required: true,
unique: true,
minLength: 5,
maxLength: 100,
index: true,
localized: true,
defaultValue: 'Default Title',
validate: (value) => Boolean(value) || 'Required',
admin: {
placeholder: 'Enter title...',
position: 'sidebar',
condition: (data) => data.showTitle === true,
},
}
```
### Slug Field Helper
Built-in helper for auto-generating slugs:
```ts
import { slugField } from 'payload'
import type { CollectionConfig } from 'payload'
export const Pages: CollectionConfig = {
slug: 'pages',
fields: [
{ name: 'title', type: 'text', required: true },
slugField({
name: 'slug', // defaults to 'slug'
useAsSlug: 'title', // defaults to 'title'
checkboxName: 'generateSlug', // defaults to 'generateSlug'
localized: true,
required: true,
overrides: (defaultField) => {
// Customize the generated fields if needed
return defaultField
},
}),
],
}
```
## Rich Text (Lexical)
```ts
import type { RichTextField } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { HeadingFeature, LinkFeature } from '@payloadcms/richtext-lexical'
const richTextField: RichTextField = {
name: 'content',
type: 'richText',
required: true,
localized: true,
editor: lexicalEditor({
features: ({ defaultFeatures }) => [
...defaultFeatures,
HeadingFeature({
enabledHeadingSizes: ['h1', 'h2', 'h3'],
}),
LinkFeature({
enabledCollections: ['posts', 'pages'],
}),
],
}),
}
```
### Advanced Lexical Configuration
```ts
import {
BoldFeature,
EXPERIMENTAL_TableFeature,
FixedToolbarFeature,
HeadingFeature,
IndentFeature,
InlineToolbarFeature,
ItalicFeature,
LinkFeature,
OrderedListFeature,
UnderlineFeature,
UnorderedListFeature,
lexicalEditor,
} from '@payloadcms/richtext-lexical'
// Global editor config with full features
export default buildConfig({
editor: lexicalEditor({
features: () => {
return [
UnderlineFeature(),
BoldFeature(),
ItalicFeature(),
OrderedListFeature(),
UnorderedListFeature(),
LinkFeature({
enabledCollections: ['pages'],
fields: ({ defaultFields }) => {
const defaultFieldsWithoutUrl = defaultFields.filter((field) => {
if ('name' in field && field.name === 'url') return false
return true
})
return [
...defaultFieldsWithoutUrl,
{
name: 'url',
type: 'text',
admin: {
condition: ({ linkType }) => linkType !== 'internal',
},
label: ({ t }) => t('fields:enterURL'),
required: true,
},
]
},
}),
IndentFeature(),
EXPERIMENTAL_TableFeature(),
]
},
}),
})
// Field-specific editor with custom toolbar
const richTextWithToolbars: RichTextField = {
name: 'richText',
type: 'richText',
editor: lexicalEditor({
features: ({ rootFeatures }) => {
return [
...rootFeatures,
HeadingFeature({ enabledHeadingSizes: ['h2', 'h3', 'h4'] }),
FixedToolbarFeature(),
InlineToolbarFeature(),
]
},
}),
label: false,
}
```
## Relationship
```ts
import type { RelationshipField } from 'payload'
// Single relationship
const singleRelationship: RelationshipField = {
name: 'author',
type: 'relationship',
relationTo: 'users',
required: true,
maxDepth: 2,
}
// Multiple relationships (hasMany)
const multipleRelationship: RelationshipField = {
name: 'categories',
type: 'relationship',
relationTo: 'categories',
hasMany: true,
filterOptions: {
active: { equals: true },
},
}
// Polymorphic relationship
const polymorphicRelationship: PolymorphicRelationshipField = {
name: 'relatedContent',
type: 'relationship',
relationTo: ['posts', 'pages'],
hasMany: true,
}
```
## Array
```ts
import type { ArrayField } from 'payload'
const arrayField: ArrayField = {
name: 'slides',
type: 'array',
minRows: 2,
maxRows: 10,
labels: {
singular: 'Slide',
plural: 'Slides',
},
fields: [
{
name: 'title',
type: 'text',
required: true,
},
{
name: 'image',
type: 'upload',
relationTo: 'media',
},
],
admin: {
initCollapsed: true,
},
}
```
## Blocks
```ts
import type { BlocksField, Block } from 'payload'
const HeroBlock: Block = {
slug: 'hero',
interfaceName: 'HeroBlock',
fields: [
{
name: 'heading',
type: 'text',
required: true,
},
{
name: 'background',
type: 'upload',
relationTo: 'media',
},
],
}
const ContentBlock: Block = {
slug: 'content',
fields: [
{
name: 'text',
type: 'richText',
},
],
}
const blocksField: BlocksField = {
name: 'layout',
type: 'blocks',
blocks: [HeroBlock, ContentBlock],
}
```
## Select
```ts
import type { SelectField } from 'payload'
const selectField: SelectField = {
name: 'status',
type: 'select',
options: [
{ label: 'Draft', value: 'draft' },
{ label: 'Published', value: 'published' },
],
defaultValue: 'draft',
required: true,
}
// Multiple select
const multiSelectField: SelectField = {
name: 'tags',
type: 'select',
hasMany: true,
options: ['tech', 'news', 'sports'],
}
```
## Upload
```ts
import type { UploadField } from 'payload'
const uploadField: UploadField = {
name: 'featuredImage',
type: 'upload',
relationTo: 'media',
required: true,
filterOptions: {
mimeType: { contains: 'image' },
},
}
```
## Point (Geolocation)
Point fields store geographic coordinates with automatic 2dsphere indexing for geospatial queries.
```ts
import type { PointField } from 'payload'
const locationField: PointField = {
name: 'location',
type: 'point',
label: 'Location',
required: true,
}
// Returns [longitude, latitude]
// Example: [-122.4194, 37.7749] for San Francisco
```
### Geospatial Queries
```ts
// Query by distance (sorted by nearest first)
const nearbyLocations = await payload.find({
collection: 'stores',
where: {
location: {
near: [10, 20], // [longitude, latitude]
maxDistance: 5000, // in meters
minDistance: 1000,
},
},
})
// Query within polygon area
const polygon: Point[] = [
[9.0, 19.0], // bottom-left
[9.0, 21.0], // top-left
[11.0, 21.0], // top-right
[11.0, 19.0], // bottom-right
[9.0, 19.0], // closing point
]
const withinArea = await payload.find({
collection: 'stores',
where: {
location: {
within: {
type: 'Polygon',
coordinates: [polygon],
},
},
},
})
// Query intersecting area
const intersecting = await payload.find({
collection: 'stores',
where: {
location: {
intersects: {
type: 'Polygon',
coordinates: [polygon],
},
},
},
})
```
**Note**: Point fields are not supported in SQLite.
## Join Fields
Join fields create reverse relationships, allowing you to access related documents from the "other side" of a relationship.
```ts
import type { JoinField } from 'payload'
// From Users collection - show user's orders
const ordersJoinField: JoinField = {
name: 'orders',
type: 'join',
collection: 'orders',
on: 'customer', // The field in 'orders' that references this user
admin: {
allowCreate: false,
defaultColumns: ['id', 'createdAt', 'total', 'currency', 'items'],
},
}
// From Users collection - show user's cart
const cartJoinField: JoinField = {
name: 'cart',
type: 'join',
collection: 'carts',
on: 'customer',
admin: {
allowCreate: false,
defaultColumns: ['id', 'createdAt', 'total', 'currency'],
},
}
```
## Virtual Fields
```ts
import type { TextField } from 'payload'
// Computed from siblings
const computedVirtualField: TextField = {
name: 'fullName',
type: 'text',
virtual: true,
hooks: {
afterRead: [({ siblingData }) => `${siblingData.firstName} ${siblingData.lastName}`],
},
}
// From relationship path
const pathVirtualField: TextField = {
name: 'authorName',
type: 'text',
virtual: 'author.name',
}
```
## Conditional Fields
```ts
import type { UploadField, CheckboxField } from 'payload'
// Simple boolean condition
const enableFeatureField: CheckboxField = {
name: 'enableFeature',
type: 'checkbox',
}
const conditionalField: TextField = {
name: 'featureText',
type: 'text',
admin: {
condition: (data) => data.enableFeature === true,
},
}
// Sibling data condition (from hero field pattern)
const typeField: SelectField = {
name: 'type',
type: 'select',
options: ['none', 'highImpact', 'mediumImpact', 'lowImpact'],
defaultValue: 'lowImpact',
}
const mediaField: UploadField = {
name: 'media',
type: 'upload',
relationTo: 'media',
admin: {
condition: (_, { type } = {}) => ['highImpact', 'mediumImpact'].includes(type),
},
required: true,
}
```
## Radio
Radio fields present options as radio buttons for single selection.
```ts
import type { RadioField } from 'payload'
const radioField: RadioField = {
name: 'priority',
type: 'radio',
options: [
{ label: 'Low', value: 'low' },
{ label: 'Medium', value: 'medium' },
{ label: 'High', value: 'high' },
],
defaultValue: 'medium',
admin: {
layout: 'horizontal', // or 'vertical'
},
}
```
## Row (Layout)
Row fields arrange fields horizontally in the admin panel (presentational only).
```ts
import type { RowField } from 'payload'
const rowField: RowField = {
type: 'row',
fields: [
{
name: 'firstName',
type: 'text',
admin: { width: '50%' },
},
{
name: 'lastName',
type: 'text',
admin: { width: '50%' },
},
],
}
```
## Collapsible (Layout)
Collapsible fields group fields in an expandable/collapsible section.
```ts
import type { CollapsibleField } from 'payload'
const collapsibleField: CollapsibleField = {
label: ({ data }) => data?.title || 'Advanced Options',
type: 'collapsible',
admin: {
initCollapsed: true,
},
fields: [
{ name: 'customCSS', type: 'textarea' },
{ name: 'customJS', type: 'code' },
],
}
```
## UI (Custom Components)
UI fields allow fully custom React components in the admin (no data stored).
```ts
import type { UIField } from 'payload'
const uiField: UIField = {
name: 'customMessage',
type: 'ui',
admin: {
components: {
Field: '/path/to/CustomFieldComponent',
Cell: '/path/to/CustomCellComponent', // For list view
},
},
}
```
## Tabs & Groups
```ts
import type { TabsField, GroupField } from 'payload'
// Tabs
const tabsField: TabsField = {
type: 'tabs',
tabs: [
{
label: 'Content',
fields: [
{ name: 'title', type: 'text' },
{ name: 'body', type: 'richText' },
],
},
{
label: 'SEO',
fields: [
{ name: 'metaTitle', type: 'text' },
{ name: 'metaDescription', type: 'textarea' },
],
},
],
}
// Group (named)
const groupField: GroupField = {
name: 'meta',
type: 'group',
fields: [
{ name: 'title', type: 'text' },
{ name: 'description', type: 'textarea' },
],
}
```
## Reusable Field Factories
Create composable field patterns that can be customized with overrides.
```ts
import type { Field, GroupField } from 'payload'
// Utility for deep merging
const deepMerge = <T>(target: T, source: Partial<T>): T => {
// Implementation would deeply merge objects
return { ...target, ...source }
}
// Reusable link field factory
type LinkType = (options?: {
appearances?: ('default' | 'outline')[] | false
disableLabel?: boolean
overrides?: Record<string, unknown>
}) => GroupField
export const link: LinkType = ({ appearances, disableLabel = false, overrides = {} } = {}) => {
const linkField: GroupField = {
name: 'link',
type: 'group',
admin: {
hideGutter: true,
},
fields: [
{
type: 'row',
fields: [
{
name: 'type',
type: 'radio',
options: [
{ label: 'Internal link', value: 'reference' },
{ label: 'Custom URL', value: 'custom' },
],
defaultValue: 'reference',
admin: {
layout: 'horizontal',
width: '50%',
},
},
{
name: 'newTab',
type: 'checkbox',
label: 'Open in new tab',
admin: {
width: '50%',
style: {
alignSelf: 'flex-end',
},
},
},
],
},
{
name: 'reference',
type: 'relationship',
relationTo: ['pages'],
required: true,
maxDepth: 1,
admin: {
condition: (_, siblingData) => siblingData?.type === 'reference',
},
},
{
name: 'url',
type: 'text',
label: 'Custom URL',
required: true,
admin: {
condition: (_, siblingData) => siblingData?.type === 'custom',
},
},
],
}
if (!disableLabel) {
linkField.fields.push({
name: 'label',
type: 'text',
required: true,
})
}
if (appearances !== false) {
linkField.fields.push({
name: 'appearance',
type: 'select',
defaultValue: 'default',
options: [
{ label: 'Default', value: 'default' },
{ label: 'Outline', value: 'outline' },
],
})
}
return deepMerge(linkField, overrides) as GroupField
}
// Usage
const navItem = link({ appearances: false })
const ctaButton = link({
overrides: {
name: 'cta',
admin: {
description: 'Call to action button',
},
},
})
```
## Field Type Guards
Type guards for runtime field type checking and safe type narrowing.
| Type Guard | Checks For | Use When |
| --------------------------- | ----------------------------------------------------------- | ---------------------------------------- |
| `fieldAffectsData` | Field stores data (has name, not UI-only) | Need to access field data or name |
| `fieldHasSubFields` | Field contains nested fields (group/array/row/collapsible) | Need to recursively traverse fields |
| `fieldIsArrayType` | Field is array type | Distinguish arrays from other containers |
| `fieldIsBlockType` | Field is blocks type | Handle blocks-specific logic |
| `fieldIsGroupType` | Field is group type | Handle group-specific logic |
| `fieldSupportsMany` | Field can have multiple values (select/relationship/upload) | Check for `hasMany` support |
| `fieldHasMaxDepth` | Field supports population depth control | Control relationship/upload/join depth |
| `fieldIsPresentationalOnly` | Field is UI-only (no data storage) | Exclude from data operations |
| `fieldIsSidebar` | Field positioned in sidebar | Separate sidebar rendering |
| `fieldIsID` | Field name is 'id' | Special ID field handling |
| `fieldIsHiddenOrDisabled` | Field is hidden or disabled | Filter from UI operations |
| `fieldShouldBeLocalized` | Field needs localization handling | Proper locale table checks |
| `fieldIsVirtual` | Field is virtual (computed/no DB column) | Skip in database transforms |
| `tabHasName` | Tab is named (stores data) | Distinguish named vs unnamed tabs |
| `groupHasName` | Group is named (stores data) | Distinguish named vs unnamed groups |
| `optionIsObject` | Option is `{label, value}` format | Access option properties safely |
| `optionsAreObjects` | All options are objects | Batch option processing |
| `optionIsValue` | Option is string value | Handle string options |
| `valueIsValueWithRelation` | Value is polymorphic relationship | Handle polymorphic relationships |
```ts
import { fieldAffectsData, fieldHasSubFields, fieldIsArrayType } from 'payload'
function processField(field: Field) {
if (fieldAffectsData(field)) {
// Safe to access field.name
console.log(field.name)
}
if (fieldHasSubFields(field)) {
// Safe to access field.fields
field.fields.forEach(processField)
}
}
```
See [FIELD-TYPE-GUARDS.md](FIELD-TYPE-GUARDS.md) for detailed usage patterns.
+186
View File
@@ -0,0 +1,186 @@
# Payload CMS Hooks Reference
Complete reference for collection hooks, field hooks, and hook context patterns.
## Collection Hooks
```ts
export const Posts: CollectionConfig = {
slug: 'posts',
hooks: {
// Before validation
beforeValidate: [
async ({ data, operation }) => {
if (operation === 'create') {
data.slug = slugify(data.title)
}
return data
},
],
// Before save
beforeChange: [
async ({ data, req, operation, originalDoc }) => {
if (operation === 'update' && data.status === 'published') {
data.publishedAt = new Date()
}
return data
},
],
// After save
afterChange: [
async ({ doc, req, operation, previousDoc }) => {
if (operation === 'create') {
await sendNotification(doc)
}
return doc
},
],
// After read
afterRead: [
async ({ doc, req }) => {
doc.viewCount = await getViewCount(doc.id)
return doc
},
],
// Before delete
beforeDelete: [
async ({ req, id }) => {
await cleanupRelatedData(id)
},
],
},
}
```
## Field Hooks
```ts
import type { EmailField, FieldHook } from 'payload'
const beforeValidateHook: FieldHook = ({ value }) => {
return value.trim().toLowerCase()
}
const afterReadHook: FieldHook = ({ value, req }) => {
// Hide email from non-admins
if (!req.user?.roles?.includes('admin')) {
return value.replace(/(.{2})(.*)(@.*)/, '$1***$3')
}
return value
}
const emailField: EmailField = {
name: 'email',
type: 'email',
hooks: {
beforeValidate: [beforeValidateHook],
afterRead: [afterReadHook],
},
}
```
## Hook Context
Share data between hooks or control hook behavior using request context:
```ts
import type { CollectionConfig } from 'payload'
export const Posts: CollectionConfig = {
slug: 'posts',
hooks: {
beforeChange: [
async ({ context }) => {
context.expensiveData = await fetchExpensiveData()
},
],
afterChange: [
async ({ context, doc }) => {
// Reuse from previous hook
await processData(doc, context.expensiveData)
},
],
},
fields: [{ name: 'title', type: 'text' }],
}
```
## Next.js Revalidation with Context Control
```ts
import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload'
import { revalidatePath } from 'next/cache'
import type { Page } from '../payload-types'
export const revalidatePage: CollectionAfterChangeHook<Page> = ({
doc,
previousDoc,
req: { payload, context },
}) => {
if (!context.disableRevalidate) {
if (doc._status === 'published') {
const path = doc.slug === 'home' ? '/' : `/${doc.slug}`
payload.logger.info(`Revalidating page at path: ${path}`)
revalidatePath(path)
}
// Revalidate old path if unpublished
if (previousDoc?._status === 'published' && doc._status !== 'published') {
const oldPath = previousDoc.slug === 'home' ? '/' : `/${previousDoc.slug}`
payload.logger.info(`Revalidating old page at path: ${oldPath}`)
revalidatePath(oldPath)
}
}
return doc
}
export const revalidateDelete: CollectionAfterDeleteHook<Page> = ({ doc, req: { context } }) => {
if (!context.disableRevalidate) {
const path = doc?.slug === 'home' ? '/' : `/${doc?.slug}`
revalidatePath(path)
}
return doc
}
```
## Date Field Auto-Set
Automatically set date when document is published:
```ts
import type { DateField } from 'payload'
const publishedOnField: DateField = {
name: 'publishedOn',
type: 'date',
admin: {
date: {
pickerAppearance: 'dayAndTime',
},
position: 'sidebar',
},
hooks: {
beforeChange: [
({ siblingData, value }) => {
if (siblingData._status === 'published' && !value) {
return new Date()
}
return value
},
],
},
}
```
## Hook Patterns Best Practices
- Use `beforeValidate` for data formatting
- Use `beforeChange` for business logic
- Use `afterChange` for side effects
- Use `afterRead` for computed fields
- Store expensive operations in `context`
- Pass `req` to nested operations for transaction safety (see [ADAPTERS.md#threading-req-through-operations](ADAPTERS.md#threading-req-through-operations))
File diff suppressed because it is too large Load Diff
+274
View File
@@ -0,0 +1,274 @@
# Payload CMS Querying Reference
Complete reference for querying data across Local API, REST, and GraphQL.
## Query Operators
```ts
import type { Where } from 'payload'
// Equals
const equalsQuery: Where = { color: { equals: 'blue' } }
// Not equals
const notEqualsQuery: Where = { status: { not_equals: 'draft' } }
// Greater/less than
const greaterThanQuery: Where = { price: { greater_than: 100 } }
const lessThanEqualQuery: Where = { age: { less_than_equal: 65 } }
// Contains (case-insensitive)
const containsQuery: Where = { title: { contains: 'payload' } }
// Like (all words present)
const likeQuery: Where = { description: { like: 'cms headless' } }
// In/not in
const inQuery: Where = { category: { in: ['tech', 'news'] } }
// Exists
const existsQuery: Where = { image: { exists: true } }
// Near (point fields)
const nearQuery: Where = { location: { near: '-122.4194,37.7749,10000' } }
```
## AND/OR Logic
```ts
import type { Where } from 'payload'
const complexQuery: Where = {
or: [
{ color: { equals: 'mint' } },
{
and: [{ color: { equals: 'white' } }, { featured: { equals: false } }],
},
],
}
```
## Nested Properties
```ts
import type { Where } from 'payload'
const nestedQuery: Where = {
'author.role': { equals: 'editor' },
'meta.featured': { exists: true },
}
```
## Local API
```ts
// Find documents
const posts = await payload.find({
collection: 'posts',
where: {
status: { equals: 'published' },
'author.name': { contains: 'john' },
},
depth: 2,
limit: 10,
page: 1,
sort: '-createdAt',
locale: 'en',
select: {
title: true,
author: true,
},
})
// Find by ID
const post = await payload.findByID({
collection: 'posts',
id: '123',
depth: 2,
})
// Create
const post = await payload.create({
collection: 'posts',
data: {
title: 'New Post',
status: 'draft',
},
})
// Update
await payload.update({
collection: 'posts',
id: '123',
data: {
status: 'published',
},
})
// Delete
await payload.delete({
collection: 'posts',
id: '123',
})
// Count
const count = await payload.count({
collection: 'posts',
where: {
status: { equals: 'published' },
},
})
```
### Threading req Parameter
When performing operations in hooks or nested operations, pass the `req` parameter to maintain transaction context:
```ts
// ✅ CORRECT: Pass req for transaction safety
const afterChange: CollectionAfterChangeHook = async ({ doc, req }) => {
await req.payload.create({
collection: 'audit-log',
data: { action: 'created', docId: doc.id },
req, // Maintains transaction atomicity
})
}
// ❌ WRONG: Missing req breaks transaction
const afterChange: CollectionAfterChangeHook = async ({ doc, req }) => {
await req.payload.create({
collection: 'audit-log',
data: { action: 'created', docId: doc.id },
// Missing req - runs in separate transaction
})
}
```
This is critical for MongoDB replica sets and Postgres. See [ADAPTERS.md#threading-req-through-operations](ADAPTERS.md#threading-req-through-operations) for details.
### Access Control in Local API
**Important**: Local API bypasses access control by default (`overrideAccess: true`). When passing a `user` parameter, you must explicitly set `overrideAccess: false` to respect that user's permissions.
```ts
// ❌ WRONG: User is passed but access control is bypassed
const posts = await payload.find({
collection: 'posts',
user: currentUser,
// Missing: overrideAccess: false
// Result: Operation runs with ADMIN privileges, ignoring user's permissions
})
// ✅ CORRECT: Respects user's access control permissions
const posts = await payload.find({
collection: 'posts',
user: currentUser,
overrideAccess: false, // Required to enforce access control
// Result: User only sees posts they have permission to read
})
// Administrative operation (intentionally bypass access control)
const allPosts = await payload.find({
collection: 'posts',
// No user parameter
// overrideAccess defaults to true
// Result: Returns all posts regardless of access control
})
```
**When to use `overrideAccess: false`:**
- Performing operations on behalf of a user
- Testing access control logic
- API routes that should respect user permissions
- Any operation where `user` parameter is provided
**When `overrideAccess: true` is appropriate:**
- Administrative operations (migrations, seeds, cron jobs)
- Internal system operations
- Operations explicitly intended to bypass access control
See [ACCESS-CONTROL.md#important-notes](ACCESS-CONTROL.md#important-notes) for more details.
## REST API
```ts
import { stringify } from 'qs-esm'
const query = {
status: { equals: 'published' },
}
const queryString = stringify(
{
where: query,
depth: 2,
limit: 10,
},
{ addQueryPrefix: true },
)
const response = await fetch(`https://api.example.com/api/posts${queryString}`)
const data = await response.json()
```
### REST Endpoints
```txt
GET /api/{collection} - Find documents
GET /api/{collection}/{id} - Find by ID
POST /api/{collection} - Create
PATCH /api/{collection}/{id} - Update
DELETE /api/{collection}/{id} - Delete
GET /api/{collection}/count - Count documents
GET /api/globals/{slug} - Get global
POST /api/globals/{slug} - Update global
```
## GraphQL
```graphql
query {
Posts(where: { status: { equals: published } }, limit: 10, sort: "-createdAt") {
docs {
id
title
author {
name
}
}
totalDocs
hasNextPage
}
}
mutation {
createPost(data: { title: "New Post", status: draft }) {
id
title
}
}
mutation {
updatePost(id: "123", data: { status: published }) {
id
status
}
}
mutation {
deletePost(id: "123") {
id
}
}
```
## Performance Best Practices
- Set `maxDepth` on relationships to prevent over-fetching
- Use `select` to limit returned fields
- Index frequently queried fields
- Use `virtual` fields for computed data
- Cache expensive operations in hook `context`
File diff suppressed because it is too large Load Diff
+17
View File
@@ -0,0 +1,17 @@
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of
the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The upstream repository (https://github.com/vercel-labs/agent-skills) declares the MIT licence in its README and in
the SKILL.md frontmatter; it ships no LICENSE file with a copyright line. Copyright: Vercel.
+123
View File
@@ -0,0 +1,123 @@
# React Best Practices
A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
## Structure
- `rules/` - Individual rule files (one per rule)
- `_sections.md` - Section metadata (titles, impacts, descriptions)
- `_template.md` - Template for creating new rules
- `area-description.md` - Individual rule files
- `src/` - Build scripts and utilities
- `metadata.json` - Document metadata (version, organization, abstract)
- __`AGENTS.md`__ - Compiled output (generated)
- __`test-cases.json`__ - Test cases for LLM evaluation (generated)
## Getting Started
1. Install dependencies:
```bash
pnpm install
```
2. Build AGENTS.md from rules:
```bash
pnpm build
```
3. Validate rule files:
```bash
pnpm validate
```
4. Extract test cases:
```bash
pnpm extract-tests
```
## Creating a New Rule
1. Copy `rules/_template.md` to `rules/area-description.md`
2. Choose the appropriate area prefix:
- `async-` for Eliminating Waterfalls (Section 1)
- `bundle-` for Bundle Size Optimization (Section 2)
- `server-` for Server-Side Performance (Section 3)
- `client-` for Client-Side Data Fetching (Section 4)
- `rerender-` for Re-render Optimization (Section 5)
- `rendering-` for Rendering Performance (Section 6)
- `js-` for JavaScript Performance (Section 7)
- `advanced-` for Advanced Patterns (Section 8)
3. Fill in the frontmatter and content
4. Ensure you have clear examples with explanations
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
## Rule File Structure
Each rule file should follow this structure:
```markdown
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description
tags: tag1, tag2, tag3
---
## Rule Title Here
Brief explanation of the rule and why it matters.
**Incorrect (description of what's wrong):**
```typescript
// Bad code example
```
**Correct (description of what's right):**
```typescript
// Good code example
```
Optional explanatory text after examples.
Reference: [Link](https://example.com)
## File Naming Convention
- Files starting with `_` are special (excluded from build)
- Rule files: `area-description.md` (e.g., `async-parallel.md`)
- Section is automatically inferred from filename prefix
- Rules are sorted alphabetically by title within each section
- IDs (e.g., 1.1, 1.2) are auto-generated during build
## Impact Levels
- `CRITICAL` - Highest priority, major performance gains
- `HIGH` - Significant performance improvements
- `MEDIUM-HIGH` - Moderate-high gains
- `MEDIUM` - Moderate performance improvements
- `LOW-MEDIUM` - Low-medium gains
- `LOW` - Incremental improvements
## Scripts
- `pnpm build` - Compile rules into AGENTS.md
- `pnpm validate` - Validate all rule files
- `pnpm extract-tests` - Extract test cases for LLM evaluation
- `pnpm dev` - Build and validate
## Contributing
When adding or modifying rules:
1. Use the correct filename prefix for your section
2. Follow the `_template.md` structure
3. Include clear bad/good examples with explanations
4. Add appropriate tags
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
6. Rules are automatically sorted by title - no need to manage numbers!
## Acknowledgments
Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
+159
View File
@@ -0,0 +1,159 @@
---
name: ext-react-best-practices
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
license: MIT
metadata:
author: vercel
version: "1.0.0"
---
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
> Never add a dependency this skill suggests without the owner's decision.
>
> **Data fetching:** ignore `client-swr-dedup` and any advice to add `swr`, `better-all`, `lru-cache` or another
> client-fetch library. Fetch in Server Components with the Payload Local API / `@/lib/content` helpers (React `cache()`).
# Vercel React Best Practices
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
## When to Apply
Reference these guidelines when:
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
- Reviewing code for performance issues
- Refactoring existing React/Next.js code
- Optimizing bundle size or load times
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
| 3 | Server-Side Performance | HIGH | `server-` |
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
| 6 | Rendering Performance | MEDIUM | `rendering-` |
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
| 8 | Advanced Patterns | LOW | `advanced-` |
## Quick Reference
### 1. Eliminating Waterfalls (CRITICAL)
- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
- `async-defer-await` - Move await into branches where actually used
- `async-parallel` - Use Promise.all() for independent operations
- `async-dependencies` - Use better-all for partial dependencies
- `async-api-routes` - Start promises early, await late in API routes
- `async-suspense-boundaries` - Use Suspense to stream content
### 2. Bundle Size Optimization (CRITICAL)
- `bundle-barrel-imports` - Import directly, avoid barrel files
- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
- `bundle-defer-third-party` - Load analytics/logging after hydration
- `bundle-conditional` - Load modules only when feature is activated
- `bundle-preload` - Preload on hover/focus for perceived speed
### 3. Server-Side Performance (HIGH)
- `server-auth-actions` - Authenticate server actions like API routes
- `server-cache-react` - Use React.cache() for per-request deduplication
- `server-cache-lru` - Use LRU cache for cross-request caching
- `server-dedup-props` - Avoid duplicate serialization in RSC props
- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level
- `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR
- `server-serialization` - Minimize data passed to client components
- `server-parallel-fetching` - Restructure components to parallelize fetches
- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all
- `server-after-nonblocking` - Use after() for non-blocking operations
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
- `client-swr-dedup` - Use SWR for automatic request deduplication
- `client-event-listeners` - Deduplicate global event listeners
- `client-passive-event-listeners` - Use passive listeners for scroll
- `client-localstorage-schema` - Version and minimize localStorage data
### 5. Re-render Optimization (MEDIUM)
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
- `rerender-memo` - Extract expensive work into memoized components
- `rerender-memo-with-default-value` - Hoist default non-primitive props
- `rerender-dependencies` - Use primitive dependencies in effects
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
- `rerender-derived-state-no-effect` - Derive state during render, not effects
- `rerender-functional-setstate` - Use functional setState for stable callbacks
- `rerender-lazy-state-init` - Pass function to useState for expensive values
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
- `rerender-split-combined-hooks` - Split hooks with independent dependencies
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
- `rerender-transitions` - Use startTransition for non-urgent updates
- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
- `rerender-no-inline-components` - Don't define components inside components
### 6. Rendering Performance (MEDIUM)
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
- `rendering-content-visibility` - Use content-visibility for long lists
- `rendering-hoist-jsx` - Extract static JSX outside components
- `rendering-svg-precision` - Reduce SVG coordinate precision
- `rendering-hydration-no-flicker` - Use inline script for client-only data
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
- `rendering-activity` - Use Activity component for show/hide
- `rendering-conditional-render` - Use ternary, not && for conditionals
- `rendering-usetransition-loading` - Prefer useTransition for loading state
- `rendering-resource-hints` - Use React DOM resource hints for preloading
- `rendering-script-defer-async` - Use defer or async on script tags
### 7. JavaScript Performance (LOW-MEDIUM)
- `js-batch-dom-css` - Group CSS changes via classes or cssText
- `js-index-maps` - Build Map for repeated lookups
- `js-cache-property-access` - Cache object properties in loops
- `js-cache-function-results` - Cache function results in module-level Map
- `js-cache-storage` - Cache localStorage/sessionStorage reads
- `js-combine-iterations` - Combine multiple filter/map into one loop
- `js-length-check-first` - Check array length before expensive comparison
- `js-early-exit` - Return early from functions
- `js-hoist-regexp` - Hoist RegExp creation outside loops
- `js-min-max-loop` - Use loop for min/max instead of sort
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
- `js-tosorted-immutable` - Use toSorted() for immutability
- `js-flatmap-filter` - Use flatMap to map and filter in one pass
- `js-request-idle-callback` - Defer non-critical work to browser idle time
### 8. Advanced Patterns (LOW)
- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps
- `advanced-event-handler-refs` - Store event handlers in refs
- `advanced-init-once` - Initialize app once per app load
- `advanced-use-latest` - useLatest for stable callback refs
## How to Use
Read individual rule files for detailed explanations and code examples:
```
rules/async-parallel.md
rules/bundle-barrel-imports.md
```
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
## Full Compiled Document
For the complete guide with all rules expanded: `AGENTS.md`
+14
View File
@@ -0,0 +1,14 @@
# ext-react-best-practices
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
| | |
|---|---|
| Publisher | Vercel |
| Source | https://github.com/vercel-labs/agent-skills/tree/1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62/skills/react-best-practices |
| Commit | `1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62` |
| Licence | MIT (see the LICENSE file in this folder) |
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-react-best-practices`, and an
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
@@ -0,0 +1,15 @@
{
"version": "1.0.0",
"organization": "Vercel Engineering",
"date": "January 2026",
"abstract": "Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.",
"references": [
"https://react.dev",
"https://nextjs.org",
"https://swr.vercel.app",
"https://github.com/shuding/better-all",
"https://github.com/isaacs/node-lru-cache",
"https://vercel.com/blog/how-we-optimized-package-imports-in-next-js",
"https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast"
]
}
@@ -0,0 +1,46 @@
# Sections
This file defines all sections, their ordering, impact levels, and descriptions.
The section ID (in parentheses) is the filename prefix used to group rules.
---
## 1. Eliminating Waterfalls (async)
**Impact:** CRITICAL
**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
## 2. Bundle Size Optimization (bundle)
**Impact:** CRITICAL
**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
## 3. Server-Side Performance (server)
**Impact:** HIGH
**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
## 4. Client-Side Data Fetching (client)
**Impact:** MEDIUM-HIGH
**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
## 5. Re-render Optimization (rerender)
**Impact:** MEDIUM
**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
## 6. Rendering Performance (rendering)
**Impact:** MEDIUM
**Description:** Optimizing the rendering process reduces the work the browser needs to do.
## 7. JavaScript Performance (js)
**Impact:** LOW-MEDIUM
**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.
## 8. Advanced Patterns (advanced)
**Impact:** LOW
**Description:** Advanced patterns for specific cases that require careful implementation.
@@ -0,0 +1,28 @@
---
title: Rule Title Here
impact: MEDIUM
impactDescription: Optional description of impact (e.g., "20-50% improvement")
tags: tag1, tag2
---
## Rule Title Here
**Impact: MEDIUM (optional impact description)**
Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
**Incorrect (description of what's wrong):**
```typescript
// Bad code example here
const bad = example()
```
**Correct (description of what's right):**
```typescript
// Good code example here
const good = example()
```
Reference: [Link to documentation or resource](https://example.com)
@@ -0,0 +1,56 @@
---
title: Do Not Put Effect Events in Dependency Arrays
impact: LOW
impactDescription: avoids unnecessary effect re-runs and lint errors
tags: advanced, hooks, useEffectEvent, dependencies, effects
---
## Do Not Put Effect Events in Dependency Arrays
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
**Incorrect (Effect Event added as a dependency):**
```tsx
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId, handleConnected])
}
```
Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
**Correct (depend on reactive values, not the Effect Event):**
```tsx
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId])
}
```
Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
@@ -0,0 +1,55 @@
---
title: Store Event Handlers in Refs
impact: LOW
impactDescription: stable subscriptions
tags: advanced, hooks, refs, event-handlers, optimization
---
## Store Event Handlers in Refs
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
**Incorrect (re-subscribes on every render):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
useEffect(() => {
window.addEventListener(event, handler)
return () => window.removeEventListener(event, handler)
}, [event, handler])
}
```
**Correct (stable subscription):**
```tsx
function useWindowEvent(event: string, handler: (e) => void) {
const handlerRef = useRef(handler)
useEffect(() => {
handlerRef.current = handler
}, [handler])
useEffect(() => {
const listener = (e) => handlerRef.current(e)
window.addEventListener(event, listener)
return () => window.removeEventListener(event, listener)
}, [event])
}
```
**Alternative: use `useEffectEvent` if you're on latest React:**
```tsx
import { useEffectEvent } from 'react'
function useWindowEvent(event: string, handler: (e) => void) {
const onEvent = useEffectEvent(handler)
useEffect(() => {
window.addEventListener(event, onEvent)
return () => window.removeEventListener(event, onEvent)
}, [event])
}
```
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
@@ -0,0 +1,42 @@
---
title: Initialize App Once, Not Per Mount
impact: LOW-MEDIUM
impactDescription: avoids duplicate init in development
tags: initialization, useEffect, app-startup, side-effects
---
## Initialize App Once, Not Per Mount
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
**Incorrect (runs twice in dev, re-runs on remount):**
```tsx
function Comp() {
useEffect(() => {
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
**Correct (once per app load):**
```tsx
let didInit = false
function Comp() {
useEffect(() => {
if (didInit) return
didInit = true
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
@@ -0,0 +1,39 @@
---
title: useEffectEvent for Stable Callback Refs
impact: LOW
impactDescription: prevents effect re-runs
tags: advanced, hooks, useEffectEvent, refs, optimization
---
## useEffectEvent for Stable Callback Refs
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
**Incorrect (effect re-runs on every callback change):**
```tsx
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
useEffect(() => {
const timeout = setTimeout(() => onSearch(query), 300)
return () => clearTimeout(timeout)
}, [query, onSearch])
}
```
**Correct (using React's useEffectEvent):**
```tsx
import { useEffectEvent } from 'react';
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
const onSearchEvent = useEffectEvent(onSearch)
useEffect(() => {
const timeout = setTimeout(() => onSearchEvent(query), 300)
return () => clearTimeout(timeout)
}, [query])
}
```
@@ -0,0 +1,38 @@
---
title: Prevent Waterfall Chains in API Routes
impact: CRITICAL
impactDescription: 2-10× improvement
tags: api-routes, server-actions, waterfalls, parallelization
---
## Prevent Waterfall Chains in API Routes
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
**Incorrect (config waits for auth, data waits for both):**
```typescript
export async function GET(request: Request) {
const session = await auth()
const config = await fetchConfig()
const data = await fetchData(session.user.id)
return Response.json({ data, config })
}
```
**Correct (auth and config start immediately):**
```typescript
export async function GET(request: Request) {
const sessionPromise = auth()
const configPromise = fetchConfig()
const session = await sessionPromise
const [config, data] = await Promise.all([
configPromise,
fetchData(session.user.id)
])
return Response.json({ data, config })
}
```
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
@@ -0,0 +1,37 @@
---
title: Check Cheap Conditions Before Async Flags
impact: HIGH
impactDescription: avoids unnecessary async work when a synchronous guard already fails
tags: async, await, feature-flags, short-circuit, conditional
---
## Check Cheap Conditions Before Async Flags
When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
**Incorrect:**
```typescript
const someFlag = await getFlag()
if (someFlag && someCondition) {
// ...
}
```
**Correct:**
```typescript
if (someCondition) {
const someFlag = await getFlag()
if (someFlag) {
// ...
}
}
```
This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
@@ -0,0 +1,82 @@
---
title: Defer Await Until Needed
impact: HIGH
impactDescription: avoids blocking unused code paths
tags: async, await, conditional, optimization
---
## Defer Await Until Needed
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
**Incorrect (blocks both branches):**
```typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
const userData = await fetchUserData(userId)
if (skipProcessing) {
// Returns immediately but still waited for userData
return { skipped: true }
}
// Only this branch uses userData
return processUserData(userData)
}
```
**Correct (only blocks when needed):**
```typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
if (skipProcessing) {
// Returns immediately without waiting
return { skipped: true }
}
// Fetch only when needed
const userData = await fetchUserData(userId)
return processUserData(userData)
}
```
**Another example (early return optimization):**
```typescript
// Incorrect: always fetches permissions
async function updateResource(resourceId: string, userId: string) {
const permissions = await fetchPermissions(userId)
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
// Correct: fetches only when needed
async function updateResource(resourceId: string, userId: string) {
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
const permissions = await fetchPermissions(userId)
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
```
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
@@ -0,0 +1,51 @@
---
title: Dependency-Based Parallelization
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, dependencies, better-all
---
## Dependency-Based Parallelization
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
**Incorrect (profile waits for config unnecessarily):**
```typescript
const [user, config] = await Promise.all([
fetchUser(),
fetchConfig()
])
const profile = await fetchProfile(user.id)
```
**Correct (config and profile run in parallel):**
```typescript
import { all } from 'better-all'
const { user, config, profile } = await all({
async user() { return fetchUser() },
async config() { return fetchConfig() },
async profile() {
return fetchProfile((await this.$.user).id)
}
})
```
**Alternative without extra dependencies:**
We can also create all the promises first, and do `Promise.all()` at the end.
```typescript
const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise
])
```
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
@@ -0,0 +1,28 @@
---
title: Promise.all() for Independent Operations
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, promises, waterfalls
---
## Promise.all() for Independent Operations
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
**Incorrect (sequential execution, 3 round trips):**
```typescript
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
```
**Correct (parallel execution, 1 round trip):**
```typescript
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
```
@@ -0,0 +1,99 @@
---
title: Strategic Suspense Boundaries
impact: HIGH
impactDescription: faster initial paint
tags: async, suspense, streaming, layout-shift
---
## Strategic Suspense Boundaries
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
**Incorrect (wrapper blocked by data fetching):**
```tsx
async function Page() {
const data = await fetchData() // Blocks entire page
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<DataDisplay data={data} />
</div>
<div>Footer</div>
</div>
)
}
```
The entire layout waits for data even though only the middle section needs it.
**Correct (wrapper shows immediately, data streams in):**
```tsx
function Page() {
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<Suspense fallback={<Skeleton />}>
<DataDisplay />
</Suspense>
</div>
<div>Footer</div>
</div>
)
}
async function DataDisplay() {
const data = await fetchData() // Only blocks this component
return <div>{data.content}</div>
}
```
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
**Alternative (share promise across components):**
```tsx
function Page() {
// Start fetch immediately, but don't await
const dataPromise = fetchData()
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<Suspense fallback={<Skeleton />}>
<DataDisplay dataPromise={dataPromise} />
<DataSummary dataPromise={dataPromise} />
</Suspense>
<div>Footer</div>
</div>
)
}
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Unwraps the promise
return <div>{data.content}</div>
}
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Reuses the same promise
return <div>{data.summary}</div>
}
```
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
**When NOT to use this pattern:**
- Critical data needed for layout decisions (affects positioning)
- SEO-critical content above the fold
- Small, fast queries where suspense overhead isn't worth it
- When you want to avoid layout shift (loading → content jump)
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
@@ -0,0 +1,63 @@
---
title: Prefer Statically Analyzable Paths
impact: HIGH
impactDescription: avoids accidental broad bundles and file traces
tags: bundle, nextjs, vite, webpack, rollup, esbuild, path
---
## Prefer Statically Analyzable Paths
Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.
Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.
When analysis becomes too broad, the cost is real:
- Larger server bundles
- Slower builds
- Worse cold starts
- More memory use
### Import Paths
**Incorrect (the bundler cannot tell what may be imported):**
```ts
const PAGE_MODULES = {
home: './pages/home',
settings: './pages/settings',
} as const
const Page = await import(PAGE_MODULES[pageName])
```
**Correct (use an explicit map of allowed modules):**
```ts
const PAGE_MODULES = {
home: () => import('./pages/home'),
settings: () => import('./pages/settings'),
} as const
const Page = await PAGE_MODULES[pageName]()
```
### File-System Paths
**Incorrect (a 2-value enum still hides the final path from static analysis):**
```ts
const baseDir = path.join(process.cwd(), 'content/' + contentKind)
```
**Correct (make each final path literal at the callsite):**
```ts
const baseDir =
kind === ContentKind.Blog
? path.join(process.cwd(), 'content/blog')
: path.join(process.cwd(), 'content/docs')
```
In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.
Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)
@@ -0,0 +1,60 @@
---
title: Avoid Barrel File Imports
impact: CRITICAL
impactDescription: 200-800ms import cost, slow builds
tags: bundle, imports, tree-shaking, barrel-files, performance
---
## Avoid Barrel File Imports
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
**Incorrect (imports entire library):**
```tsx
import { Check, X, Menu } from 'lucide-react'
// Loads 1,583 modules, takes ~2.8s extra in dev
// Runtime cost: 200-800ms on every cold start
import { Button, TextField } from '@mui/material'
// Loads 2,225 modules, takes ~4.2s extra in dev
```
**Correct - Next.js 13.5+ (recommended):**
```js
// next.config.js - automatically optimizes barrel imports at build time
module.exports = {
experimental: {
optimizePackageImports: ['lucide-react', '@mui/material']
}
}
```
```tsx
// Keep the standard imports - Next.js transforms them to direct imports
import { Check, X, Menu } from 'lucide-react'
// Full TypeScript support, no manual path wrangling
```
This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
**Correct - Direct imports (non-Next.js projects):**
```tsx
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
// Loads only what you use
```
> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
@@ -0,0 +1,31 @@
---
title: Conditional Module Loading
impact: HIGH
impactDescription: loads large data only when needed
tags: bundle, conditional-loading, lazy-loading
---
## Conditional Module Loading
Load large data or modules only when a feature is activated.
**Example (lazy-load animation frames):**
```tsx
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
const [frames, setFrames] = useState<Frame[] | null>(null)
useEffect(() => {
if (enabled && !frames && typeof window !== 'undefined') {
import('./animation-frames.js')
.then(mod => setFrames(mod.frames))
.catch(() => setEnabled(false))
}
}, [enabled, frames, setEnabled])
if (!frames) return <Skeleton />
return <Canvas frames={frames} />
}
```
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
@@ -0,0 +1,49 @@
---
title: Defer Non-Critical Third-Party Libraries
impact: MEDIUM
impactDescription: loads after hydration
tags: bundle, third-party, analytics, defer
---
## Defer Non-Critical Third-Party Libraries
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
**Incorrect (blocks initial bundle):**
```tsx
import { Analytics } from '@vercel/analytics/react'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
**Correct (loads after hydration):**
```tsx
import dynamic from 'next/dynamic'
const Analytics = dynamic(
() => import('@vercel/analytics/react').then(m => m.Analytics),
{ ssr: false }
)
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
@@ -0,0 +1,35 @@
---
title: Dynamic Imports for Heavy Components
impact: CRITICAL
impactDescription: directly affects TTI and LCP
tags: bundle, dynamic-import, code-splitting, next-dynamic
---
## Dynamic Imports for Heavy Components
Use `next/dynamic` to lazy-load large components not needed on initial render.
**Incorrect (Monaco bundles with main chunk ~300KB):**
```tsx
import { MonacoEditor } from './monaco-editor'
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
```
**Correct (Monaco loads on demand):**
```tsx
import dynamic from 'next/dynamic'
const MonacoEditor = dynamic(
() => import('./monaco-editor').then(m => m.MonacoEditor),
{ ssr: false }
)
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
```
@@ -0,0 +1,50 @@
---
title: Preload Based on User Intent
impact: MEDIUM
impactDescription: reduces perceived latency
tags: bundle, preload, user-intent, hover
---
## Preload Based on User Intent
Preload heavy bundles before they're needed to reduce perceived latency.
**Example (preload on hover/focus):**
```tsx
function EditorButton({ onClick }: { onClick: () => void }) {
const preload = () => {
if (typeof window !== 'undefined') {
void import('./monaco-editor')
}
}
return (
<button
onMouseEnter={preload}
onFocus={preload}
onClick={onClick}
>
Open Editor
</button>
)
}
```
**Example (preload when feature flag is enabled):**
```tsx
function FlagsProvider({ children, flags }: Props) {
useEffect(() => {
if (flags.editorEnabled && typeof window !== 'undefined') {
void import('./monaco-editor').then(mod => mod.init())
}
}, [flags.editorEnabled])
return <FlagsContext.Provider value={flags}>
{children}
</FlagsContext.Provider>
}
```
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
@@ -0,0 +1,74 @@
---
title: Deduplicate Global Event Listeners
impact: LOW
impactDescription: single listener for N components
tags: client, swr, event-listeners, subscription
---
## Deduplicate Global Event Listeners
Use `useSWRSubscription()` to share global event listeners across component instances.
**Incorrect (N instances = N listeners):**
```tsx
function useKeyboardShortcut(key: string, callback: () => void) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && e.key === key) {
callback()
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [key, callback])
}
```
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
**Correct (N instances = 1 listener):**
```tsx
import useSWRSubscription from 'swr/subscription'
// Module-level Map to track callbacks per key
const keyCallbacks = new Map<string, Set<() => void>>()
function useKeyboardShortcut(key: string, callback: () => void) {
// Register this callback in the Map
useEffect(() => {
if (!keyCallbacks.has(key)) {
keyCallbacks.set(key, new Set())
}
keyCallbacks.get(key)!.add(callback)
return () => {
const set = keyCallbacks.get(key)
if (set) {
set.delete(callback)
if (set.size === 0) {
keyCallbacks.delete(key)
}
}
}
}, [key, callback])
useSWRSubscription('global-keydown', () => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && keyCallbacks.has(e.key)) {
keyCallbacks.get(e.key)!.forEach(cb => cb())
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
})
}
function Profile() {
// Multiple shortcuts will share the same listener
useKeyboardShortcut('p', () => { /* ... */ })
useKeyboardShortcut('k', () => { /* ... */ })
// ...
}
```
@@ -0,0 +1,71 @@
---
title: Version and Minimize localStorage Data
impact: MEDIUM
impactDescription: prevents schema conflicts, reduces storage size
tags: client, localStorage, storage, versioning, data-minimization
---
## Version and Minimize localStorage Data
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
**Incorrect:**
```typescript
// No version, stores everything, no error handling
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
const data = localStorage.getItem('userConfig')
```
**Correct:**
```typescript
const VERSION = 'v2'
function saveConfig(config: { theme: string; language: string }) {
try {
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
} catch {
// Throws in incognito/private browsing, quota exceeded, or disabled
}
}
function loadConfig() {
try {
const data = localStorage.getItem(`userConfig:${VERSION}`)
return data ? JSON.parse(data) : null
} catch {
return null
}
}
// Migration from v1 to v2
function migrate() {
try {
const v1 = localStorage.getItem('userConfig:v1')
if (v1) {
const old = JSON.parse(v1)
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
localStorage.removeItem('userConfig:v1')
}
} catch {}
}
```
**Store minimal fields from server responses:**
```typescript
// User object has 20+ fields, only store what UI needs
function cachePrefs(user: FullUser) {
try {
localStorage.setItem('prefs:v1', JSON.stringify({
theme: user.preferences.theme,
notifications: user.preferences.notifications
}))
} catch {}
}
```
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
@@ -0,0 +1,48 @@
---
title: Use Passive Event Listeners for Scrolling Performance
impact: MEDIUM
impactDescription: eliminates scroll delay caused by event listeners
tags: client, event-listeners, scrolling, performance, touch, wheel
---
## Use Passive Event Listeners for Scrolling Performance
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
**Incorrect:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch)
document.addEventListener('wheel', handleWheel)
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**Correct:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch, { passive: true })
document.addEventListener('wheel', handleWheel, { passive: true })
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
@@ -0,0 +1,56 @@
---
title: Use SWR for Automatic Deduplication
impact: MEDIUM-HIGH
impactDescription: automatic deduplication
tags: client, swr, deduplication, data-fetching
---
## Use SWR for Automatic Deduplication
SWR enables request deduplication, caching, and revalidation across component instances.
**Incorrect (no deduplication, each instance fetches):**
```tsx
function UserList() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('/api/users')
.then(r => r.json())
.then(setUsers)
}, [])
}
```
**Correct (multiple instances share one request):**
```tsx
import useSWR from 'swr'
function UserList() {
const { data: users } = useSWR('/api/users', fetcher)
}
```
**For immutable data:**
```tsx
import { useImmutableSWR } from '@/lib/swr'
function StaticContent() {
const { data } = useImmutableSWR('/api/config', fetcher)
}
```
**For mutations:**
```tsx
import { useSWRMutation } from 'swr/mutation'
function UpdateButton() {
const { trigger } = useSWRMutation('/api/user', updateUser)
return <button onClick={() => trigger()}>Update</button>
}
```
Reference: [https://swr.vercel.app](https://swr.vercel.app)
@@ -0,0 +1,107 @@
---
title: Avoid Layout Thrashing
impact: MEDIUM
impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
tags: javascript, dom, css, performance, reflow, layout-thrashing
---
## Avoid Layout Thrashing
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
**This is OK (browser batches style changes):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Each line invalidates style, but browser batches the recalculation
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
}
```
**Incorrect (interleaved reads and writes force reflows):**
```typescript
function layoutThrashing(element: HTMLElement) {
element.style.width = '100px'
const width = element.offsetWidth // Forces reflow
element.style.height = '200px'
const height = element.offsetHeight // Forces another reflow
}
```
**Correct (batch writes, then read once):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Batch all writes together
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
// Read after all writes are done (single reflow)
const { width, height } = element.getBoundingClientRect()
}
```
**Correct (batch reads, then writes):**
```typescript
function avoidThrashing(element: HTMLElement) {
// Read phase - all layout queries first
const rect1 = element.getBoundingClientRect()
const offsetWidth = element.offsetWidth
const offsetHeight = element.offsetHeight
// Write phase - all style changes after
element.style.width = '100px'
element.style.height = '200px'
}
```
**Better: use CSS classes**
```css
.highlighted-box {
width: 100px;
height: 200px;
background-color: blue;
border: 1px solid black;
}
```
```typescript
function updateElementStyles(element: HTMLElement) {
element.classList.add('highlighted-box')
const { width, height } = element.getBoundingClientRect()
}
```
**React example:**
```tsx
// Incorrect: interleaving style changes with layout queries
function Box({ isHighlighted }: { isHighlighted: boolean }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current && isHighlighted) {
ref.current.style.width = '100px'
const width = ref.current.offsetWidth // Forces layout
ref.current.style.height = '200px'
}
}, [isHighlighted])
return <div ref={ref}>Content</div>
}
// Correct: toggle class
function Box({ isHighlighted }: { isHighlighted: boolean }) {
return (
<div className={isHighlighted ? 'highlighted-box' : ''}>
Content
</div>
)
}
```
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
@@ -0,0 +1,80 @@
---
title: Cache Repeated Function Calls
impact: MEDIUM
impactDescription: avoid redundant computation
tags: javascript, cache, memoization, performance
---
## Cache Repeated Function Calls
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
**Incorrect (redundant computation):**
```typescript
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// slugify() called 100+ times for same project names
const slug = slugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Correct (cached results):**
```typescript
// Module-level cache
const slugifyCache = new Map<string, string>()
function cachedSlugify(text: string): string {
if (slugifyCache.has(text)) {
return slugifyCache.get(text)!
}
const result = slugify(text)
slugifyCache.set(text, result)
return result
}
function ProjectList({ projects }: { projects: Project[] }) {
return (
<div>
{projects.map(project => {
// Computed only once per unique project name
const slug = cachedSlugify(project.name)
return <ProjectCard key={project.id} slug={slug} />
})}
</div>
)
}
```
**Simpler pattern for single-value functions:**
```typescript
let isLoggedInCache: boolean | null = null
function isLoggedIn(): boolean {
if (isLoggedInCache !== null) {
return isLoggedInCache
}
isLoggedInCache = document.cookie.includes('auth=')
return isLoggedInCache
}
// Clear cache when auth changes
function onAuthChange() {
isLoggedInCache = null
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
@@ -0,0 +1,28 @@
---
title: Cache Property Access in Loops
impact: LOW-MEDIUM
impactDescription: reduces lookups
tags: javascript, loops, optimization, caching
---
## Cache Property Access in Loops
Cache object property lookups in hot paths.
**Incorrect (3 lookups × N iterations):**
```typescript
for (let i = 0; i < arr.length; i++) {
process(obj.config.settings.value)
}
```
**Correct (1 lookup total):**
```typescript
const value = obj.config.settings.value
const len = arr.length
for (let i = 0; i < len; i++) {
process(value)
}
```
@@ -0,0 +1,70 @@
---
title: Cache Storage API Calls
impact: LOW-MEDIUM
impactDescription: reduces expensive I/O
tags: javascript, localStorage, storage, caching, performance
---
## Cache Storage API Calls
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
**Incorrect (reads storage on every call):**
```typescript
function getTheme() {
return localStorage.getItem('theme') ?? 'light'
}
// Called 10 times = 10 storage reads
```
**Correct (Map cache):**
```typescript
const storageCache = new Map<string, string | null>()
function getLocalStorage(key: string) {
if (!storageCache.has(key)) {
storageCache.set(key, localStorage.getItem(key))
}
return storageCache.get(key)
}
function setLocalStorage(key: string, value: string) {
localStorage.setItem(key, value)
storageCache.set(key, value) // keep cache in sync
}
```
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
**Cookie caching:**
```typescript
let cookieCache: Record<string, string> | null = null
function getCookie(name: string) {
if (!cookieCache) {
cookieCache = Object.fromEntries(
document.cookie.split('; ').map(c => c.split('='))
)
}
return cookieCache[name]
}
```
**Important (invalidate on external changes):**
If storage can change externally (another tab, server-set cookies), invalidate cache:
```typescript
window.addEventListener('storage', (e) => {
if (e.key) storageCache.delete(e.key)
})
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
storageCache.clear()
}
})
```
@@ -0,0 +1,32 @@
---
title: Combine Multiple Array Iterations
impact: LOW-MEDIUM
impactDescription: reduces iterations
tags: javascript, arrays, loops, performance
---
## Combine Multiple Array Iterations
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
**Incorrect (3 iterations):**
```typescript
const admins = users.filter(u => u.isAdmin)
const testers = users.filter(u => u.isTester)
const inactive = users.filter(u => !u.isActive)
```
**Correct (1 iteration):**
```typescript
const admins: User[] = []
const testers: User[] = []
const inactive: User[] = []
for (const user of users) {
if (user.isAdmin) admins.push(user)
if (user.isTester) testers.push(user)
if (!user.isActive) inactive.push(user)
}
```
@@ -0,0 +1,50 @@
---
title: Early Return from Functions
impact: LOW-MEDIUM
impactDescription: avoids unnecessary computation
tags: javascript, functions, optimization, early-return
---
## Early Return from Functions
Return early when result is determined to skip unnecessary processing.
**Incorrect (processes all items even after finding answer):**
```typescript
function validateUsers(users: User[]) {
let hasError = false
let errorMessage = ''
for (const user of users) {
if (!user.email) {
hasError = true
errorMessage = 'Email required'
}
if (!user.name) {
hasError = true
errorMessage = 'Name required'
}
// Continues checking all users even after error found
}
return hasError ? { valid: false, error: errorMessage } : { valid: true }
}
```
**Correct (returns immediately on first error):**
```typescript
function validateUsers(users: User[]) {
for (const user of users) {
if (!user.email) {
return { valid: false, error: 'Email required' }
}
if (!user.name) {
return { valid: false, error: 'Name required' }
}
}
return { valid: true }
}
```
@@ -0,0 +1,60 @@
---
title: Use flatMap to Map and Filter in One Pass
impact: LOW-MEDIUM
impactDescription: eliminates intermediate array
tags: javascript, arrays, flatMap, filter, performance
---
## Use flatMap to Map and Filter in One Pass
**Impact: LOW-MEDIUM (eliminates intermediate array)**
Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
**Incorrect (2 iterations, intermediate array):**
```typescript
const userNames = users
.map(user => user.isActive ? user.name : null)
.filter(Boolean)
```
**Correct (1 iteration, no intermediate array):**
```typescript
const userNames = users.flatMap(user =>
user.isActive ? [user.name] : []
)
```
**More examples:**
```typescript
// Extract valid emails from responses
// Before
const emails = responses
.map(r => r.success ? r.data.email : null)
.filter(Boolean)
// After
const emails = responses.flatMap(r =>
r.success ? [r.data.email] : []
)
// Parse and filter valid numbers
// Before
const numbers = strings
.map(s => parseInt(s, 10))
.filter(n => !isNaN(n))
// After
const numbers = strings.flatMap(s => {
const n = parseInt(s, 10)
return isNaN(n) ? [] : [n]
})
```
**When to use:**
- Transforming items while filtering some out
- Conditional mapping where some inputs produce no output
- Parsing/validating where invalid inputs should be skipped
@@ -0,0 +1,45 @@
---
title: Hoist RegExp Creation
impact: LOW-MEDIUM
impactDescription: avoids recreation
tags: javascript, regexp, optimization, memoization
---
## Hoist RegExp Creation
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
**Incorrect (new RegExp every render):**
```tsx
function Highlighter({ text, query }: Props) {
const regex = new RegExp(`(${query})`, 'gi')
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Correct (memoize or hoist):**
```tsx
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
function Highlighter({ text, query }: Props) {
const regex = useMemo(
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
[query]
)
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
```
**Warning (global regex has mutable state):**
Global regex (`/g`) has mutable `lastIndex` state:
```typescript
const regex = /foo/g
regex.test('foo') // true, lastIndex = 3
regex.test('foo') // false, lastIndex = 0
```
@@ -0,0 +1,37 @@
---
title: Build Index Maps for Repeated Lookups
impact: LOW-MEDIUM
impactDescription: 1M ops to 2K ops
tags: javascript, map, indexing, optimization, performance
---
## Build Index Maps for Repeated Lookups
Multiple `.find()` calls by the same key should use a Map.
**Incorrect (O(n) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
return orders.map(order => ({
...order,
user: users.find(u => u.id === order.userId)
}))
}
```
**Correct (O(1) per lookup):**
```typescript
function processOrders(orders: Order[], users: User[]) {
const userById = new Map(users.map(u => [u.id, u]))
return orders.map(order => ({
...order,
user: userById.get(order.userId)
}))
}
```
Build map once (O(n)), then all lookups are O(1).
For 1000 orders × 1000 users: 1M ops → 2K ops.
@@ -0,0 +1,49 @@
---
title: Early Length Check for Array Comparisons
impact: MEDIUM-HIGH
impactDescription: avoids expensive operations when lengths differ
tags: javascript, arrays, performance, optimization, comparison
---
## Early Length Check for Array Comparisons
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
**Incorrect (always runs expensive comparison):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Always sorts and joins, even when lengths differ
return current.sort().join() !== original.sort().join()
}
```
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
**Correct (O(1) length check first):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Early return if lengths differ
if (current.length !== original.length) {
return true
}
// Only sort when lengths match
const currentSorted = current.toSorted()
const originalSorted = original.toSorted()
for (let i = 0; i < currentSorted.length; i++) {
if (currentSorted[i] !== originalSorted[i]) {
return true
}
}
return false
}
```
This new approach is more efficient because:
- It avoids the overhead of sorting and joining the arrays when lengths differ
- It avoids consuming memory for the joined strings (especially important for large arrays)
- It avoids mutating the original arrays
- It returns early when a difference is found
@@ -0,0 +1,82 @@
---
title: Use Loop for Min/Max Instead of Sort
impact: LOW
impactDescription: O(n) instead of O(n log n)
tags: javascript, arrays, performance, sorting, algorithms
---
## Use Loop for Min/Max Instead of Sort
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
**Incorrect (O(n log n) - sort to find latest):**
```typescript
interface Project {
id: string
name: string
updatedAt: number
}
function getLatestProject(projects: Project[]) {
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
return sorted[0]
}
```
Sorts the entire array just to find the maximum value.
**Incorrect (O(n log n) - sort for oldest and newest):**
```typescript
function getOldestAndNewest(projects: Project[]) {
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
}
```
Still sorts unnecessarily when only min/max are needed.
**Correct (O(n) - single loop):**
```typescript
function getLatestProject(projects: Project[]) {
if (projects.length === 0) return null
let latest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt > latest.updatedAt) {
latest = projects[i]
}
}
return latest
}
function getOldestAndNewest(projects: Project[]) {
if (projects.length === 0) return { oldest: null, newest: null }
let oldest = projects[0]
let newest = projects[0]
for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
}
return { oldest, newest }
}
```
Single pass through the array, no copying, no sorting.
**Alternative (Math.min/Math.max for small arrays):**
```typescript
const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)
```
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
@@ -0,0 +1,105 @@
---
title: Defer Non-Critical Work with requestIdleCallback
impact: MEDIUM
impactDescription: keeps UI responsive during background tasks
tags: javascript, performance, idle, scheduling, analytics
---
## Defer Non-Critical Work with requestIdleCallback
**Impact: MEDIUM (keeps UI responsive during background tasks)**
Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
**Incorrect (blocks main thread during user interaction):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// These block the main thread immediately
analytics.track('search', { query })
saveToRecentSearches(query)
prefetchTopResults(results.slice(0, 3))
}
```
**Correct (defers non-critical work to idle time):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// Defer non-critical work to idle periods
requestIdleCallback(() => {
analytics.track('search', { query })
})
requestIdleCallback(() => {
saveToRecentSearches(query)
})
requestIdleCallback(() => {
prefetchTopResults(results.slice(0, 3))
})
}
```
**With timeout for required work:**
```typescript
// Ensure analytics fires within 2 seconds even if browser stays busy
requestIdleCallback(
() => analytics.track('page_view', { path: location.pathname }),
{ timeout: 2000 }
)
```
**Chunking large tasks:**
```typescript
function processLargeDataset(items: Item[]) {
let index = 0
function processChunk(deadline: IdleDeadline) {
// Process items while we have idle time (aim for <50ms chunks)
while (index < items.length && deadline.timeRemaining() > 0) {
processItem(items[index])
index++
}
// Schedule next chunk if more items remain
if (index < items.length) {
requestIdleCallback(processChunk)
}
}
requestIdleCallback(processChunk)
}
```
**With fallback for unsupported browsers:**
```typescript
const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))
scheduleIdleWork(() => {
// Non-critical work
})
```
**When to use:**
- Analytics and telemetry
- Saving state to localStorage/IndexedDB
- Prefetching resources for likely next actions
- Processing non-urgent data transformations
- Lazy initialization of non-critical features
**When NOT to use:**
- User-initiated actions that need immediate feedback
- Rendering updates the user is waiting for
- Time-sensitive operations
@@ -0,0 +1,24 @@
---
title: Use Set/Map for O(1) Lookups
impact: LOW-MEDIUM
impactDescription: O(n) to O(1)
tags: javascript, set, map, data-structures, performance
---
## Use Set/Map for O(1) Lookups
Convert arrays to Set/Map for repeated membership checks.
**Incorrect (O(n) per check):**
```typescript
const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))
```
**Correct (O(1) per check):**
```typescript
const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))
```
@@ -0,0 +1,57 @@
---
title: Use toSorted() Instead of sort() for Immutability
impact: MEDIUM-HIGH
impactDescription: prevents mutation bugs in React state
tags: javascript, arrays, immutability, react, state, mutation
---
## Use toSorted() Instead of sort() for Immutability
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
**Incorrect (mutates original array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Mutates the users prop array!
const sorted = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Correct (creates new array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Creates new sorted array, original unchanged
const sorted = useMemo(
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Why this matters in React:**
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
**Browser support (fallback for older browsers):**
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
```typescript
// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)
```
**Other immutable array methods:**
- `.toSorted()` - immutable sort
- `.toReversed()` - immutable reverse
- `.toSpliced()` - immutable splice
- `.with()` - immutable element replacement

Some files were not shown because too many files have changed in this diff Show More