From 8bb5ebd394c3edaa4f14c4c5aa1c79bc7ce95e0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 14:32:19 +0100 Subject: [PATCH 1/3] Reference site proposal (approved design, D1-D10) Co-Authored-By: Claude Opus 5.5 --- docs/dev/reference-site-proposal.md | 402 ++++++++++++++++++++++++++++ 1 file changed, 402 insertions(+) create mode 100644 docs/dev/reference-site-proposal.md diff --git a/docs/dev/reference-site-proposal.md b/docs/dev/reference-site-proposal.md new file mode 100644 index 0000000..ac289ff --- /dev/null +++ b/docs/dev/reference-site-proposal.md @@ -0,0 +1,402 @@ +# Reference site — proposal + +Status: **design approved.** The owner decided D1–D10 on 2026-10-29 (§10): D3 was revised to the team's +existing deploy process (no Dockerfile), D9 no longer applies, and D10 is MongoDB only. All four sibling +tracks have answered, and their designs are folded in. Nothing is built yet: building starts when the +coordinator confirms all five designs (starter, doctor, blocks, tokens, reference site) are in and +consistent. +Branch: `claude/reference-site-57ce26`. Written 2026-10-29 against ipal-kit 1.14.6. + +## 1. What it is + +The reference site is one complete, realistic client site built on `@intecion/ipal-kit`. It uses every +convention in `docs/agent/AGENT.md`. It is updated in the same change as each plugin release, so it is +never behind. It has three jobs: + +1. **Agents copy from it.** When AGENT.md or a skill says "do X", there is a working file that does X. +2. **The project starter is generated from it.** `ipal-kit create` = the reference site minus its demo + content (§6). +3. **It is the plugin's real-world test.** CI builds it, runs `ipal-doctor` on it and runs smoke tests + against it (§7). If a release breaks a real site, the release fails here first. + +The site belongs to a made-up company, so it never contains real client data (§5). + +## 2. Where it lives + +### Options + +| | A. Grow `dev/` into it | B. Separate repository | C. A folder in the plugin, not shipped | +|---|---|---|---| +| Plugin tests | `dev/` exists to test edge cases: SQLite, `twoFactor: false`, crawl on, a test email adapter, odd configs. A real site needs the opposite: 2FA on, a real email transport, the real DB. One app can't be both. Tests get slower and flakier. | Not affected | Not affected: `dev/` stays the test sandbox | +| Staying current | Same commit as the plugin | Lags behind. It needs a published version, a bump PR and a second CI. It drifts. | **Same commit as the plugin.** It uses the plugin through `link:..`, so a breaking change fails CI in the same PR. | +| Starter source | Messy: test-only config would leak into new sites | Clean, but the starter must fetch another repo | Clean: the starter copies one folder | +| Shipped in npm | `dev/` isn't shipped | — | Not shipped: `files` is `dist`, `docs`, `bin` | +| Agents in a client project | Can't see it | Need access to the repo | **Can't see it by default** (not in `node_modules`). Fixed with a pointer (§8). | + +### Recommendation: C — `reference/` in the plugin repo + +``` +ipal-kit/ + src/ dist/ docs/ bin/ # the plugin (shipped) + dev/ # test sandbox (unchanged; used by vitest and playwright) + reference/ # the reference site (NOT shipped) + services/cookie-crawler/ +``` + +- `reference/package.json` depends on `"@intecion/ipal-kit": "link:.."` in the repo. The starter + rewrites this to the released version (`"1.15.0"`, pinned exactly, as on the live sites). +- Install it with its own lockfile: `pnpm --dir reference install --ignore-workspace`. The repo has no + pnpm workspace today, so the plugin's install and lockfile don't change. +- It is a normal project: `src/`, `AGENTS.md`, `.env.example`, `docs/DEPLOY.md`, its own `README.md`. + No Dockerfile (D3). + `reference/` is the project root, so a file's path in `reference/` equals its path in a client project. +- **How agents reach it** (C's one gap): the docs ship a generated **file index with excerpts** + (`docs/agent/reference-site/INDEX.md`, §8). The full tree is at + `https://git.intecion.net/IntecionSoftware/ipal-kit/src/tag/v/reference`, one URL per release + tag. The doc pages link to the file for their module. + +Why not grow `dev/`: `dev/` is tuned for fast unit and integration tests. It turns 2FA off, uses SQLite +and has a single test page. Turning it into a showcase would make the plugin's own test suite slower +and would mix test hacks into code that agents copy. Keep both: **`dev/` tests the plugin, `reference/` +shows how a project uses it.** The e2e smoke tests move to `reference/` (§7). `dev/e2e.spec.ts` keeps +its admin-logo test. + +## 3. Stack and conventions (copies the live sites, decisions in §10) + +| | Reference site | Why | +|---|---|---| +| DB | **MongoDB only** (`@payloadcms/db-mongodb`): a local Mongo in dev, a separate Coolify MongoDB resource in production, a service container in CI | All 7 live sites use Mongo. **D2 + D10, accepted.** The adapter sits alone in `src/db.ts`, so a future Postgres client is one file, but v1 ships no Postgres files. | +| DB name | `example-studiopl_dev` locally, `example-studiopl_prod` in Coolify | the plugin's `databaseNamesFor()` (on `main` since 0ed3898): domain without dots, hyphens kept, + `_dev`/`_prod`. Never hand-written. | +| Next / Payload | Same versions as the plugin's devDependencies (Next 16.4.3, Payload 3.90.2) | One supported set per release | +| Styling | Tailwind 4 + the token standard (track "design tokens") | | +| Media | Local in dev, R2 (`@payloadcms/storage-s3`) in prod, through env | AGENT.md §0b | +| Email | `IPAL_*` transport env; in dev, a local mail catcher of the developer's choice; in CI, a Mailpit service container that the smoke test reads | Forms are tested end to end without a real inbox | +| Start | `node --disable-proto=throw node_modules/next/dist/bin/next start` | As intecioncom-web | +| Package manager | pnpm 10, Node 22 | As the plugin CI | + +## 4. What it shows + +The made-up company is **`Pracownia Przykład` / "Example Studio"**, a small Polish architecture and +interior-design studio with an English version. It has services, case studies and a blog, which are +the content types most client sites have. Domain: `example-studio.test` locally and in CI, and +`example.com`-style placeholders in copy. Mapped item by item: + +### 4.1 Languages +- `pl` (default) + `en`, URLs `/pl/...`, `/en/...`, `/` → default locale via the proxy. +- `src/i18n.config.ts` as the single source; localized slugs (`/pl/uslugi` ↔ `/en/services`). +- Every seeded record is filled in both languages; `locale-coverage` = 0 gaps (checked in CI). +- The admin panel in en/pl (plugin default). + +### 4.2 Pages, templates and blocks +Every page is a `Pages` document built from **library blocks only** (track "shared block library", +`docs/dev/block-library-proposal.md` on `claude/block-library-1152ba`, still pending the owner). +- The blocks are imported from the plugin, never copied: configs from `@intecion/ipal-kit/blocks` + (`libraryBlocks`), components and `createBlockRegistry` from `@intecion/ipal-kit/blocks/rsc`, and + page templates from `@intecion/ipal-kit/templates`. The reference site ejects nothing (eject is an + optional phase-2 tool of the block track). +- Phase-1 blocks: hero, textMedia, featureGrid, gallery, faq, cta, contact, team, pricing, logos, + testimonials, stats, richText, steps, entryList. Each has a `variant` select (pricing has none) and + `settings.background` default / muted / inverted. +- Page templates: home, about, services, service, contact, blogIndex, post, legal, cookiePolicy, + notFound. Pages are seeded from `pageTemplates` + `upsertBySlug`. +- Case studies are the one project-specific collection (`content.collections`, built per + ipal-collection). They're listed with entryList and gallery, so the site also shows how a project + adds its own collection next to the library. + +| Page (pl / en) | Shows | +|---|---| +| `Strona główna` / Home (`homepage` role) | Hero, feature grid, case-study cards, testimonials, CTA, FAQ (JSON-LD FAQPage) | +| `O nas` / About | Rich text, team, stats, timeline | +| `Usługi` / Services + 3 service pages | Archive vs detail template, `Service` JSON-LD | +| `Realizacje` / Case studies (collection with URLs) | `content.collections` archive + detail, gallery with the **lightbox** | +| Blog (collection `posts`) | Archive with pagination, post template, table of contents, author/date, `Article` JSON-LD | +| `Kontakt` / Contact | Contact form, opening hours, map/address from Company | +| `Wycena` / Quote | Multi-step form (the current `dev/` form, moved here) | +| `Polityka prywatności`, `Polityka cookies`, `Regulamin` | `privacyPolicy` / `cookiePolicy` / `termsOfService` roles; the cookie list comes from the scan | +| 404 | `notFound` role, `createNotFoundPage` | +| **`Bloki` / Blocks** (showcase) | Every block × every `variant` on one page, `noindex`. Each block appears at least once on the **inverted** background (and muted), which tests the token re-mapping inside inverse sections. The place to see the whole library. Phase-2 blocks (video, tabs, map, cookieTable, comparisonTable) are added when they ship. | +| **Design** (styleguide) | Every token: colours, type scale, spacing, radius, shadows, in light and dark side by side; `noindex` | +| Maintenance | Construction mode (toggle documented, off by default) | + +Globals: Header (with a mobile menu), Footer, Company (NAP, NIP placeholder, socials), Site settings +(name, description, logo, favicon, OG image, theme, search engines, system pages). + +### 4.3 Design tokens, light and dark +- Tokens from the token standard only (draft in `docs/dev/design-tokens-proposal.md` on + `claude/design-tokens-95806d`). The plugin exports `@intecion/ipal-kit/tokens.css` (neutral + defaults: light in `:root`, dark in `[data-theme=dark]`) and `@intecion/ipal-kit/tailwind.css` (a + Tailwind 4 `@theme inline` map plus the dark variant). Components use utilities such as `bg-surface`, + `text-fg`, `py-section` and `rounded-card`. No hex, no `dark:` for colours (they flip on their own), + and no raw size in any component (the doctor checks this). +- The project overrides only `src/design/tokens.css`, generated from `src/design/tokens.ts` by + `ipal-tokens` (the TS source is still the tokens track's open decision). It overrides the brand layer: + primary, secondary, accent, bg, fonts through next/font `--font-family-body` / `--font-family-heading`, and radius. + The files are built on `claude/design-tokens-build` (9511b12): `tokens.css`, `tailwind.css`, `a11y.css` and the `@intecion/ipal-kit/tokens` entry. The reference site imports them from the plugin and vendors nothing. +- The `/design` page lists the tokens from the token list the plugin exports, and shows the dark side in a + `data-theme="dark"` wrapper. +- Theme switcher + `Site settings → Theme` (theme.md), no flash of the wrong theme. Both themes appear + in the smoke test's screenshots. +- `DESIGN.md` in the project root describes the made-up brand. It shows what a real project's + `DESIGN.md` should contain. + +### 4.4 Forms, email, consent, cookies +- Contact + quote forms seeded with `ipal-form` templates: an email to the company **and** a + confirmation to the customer, in both languages; `createSubmitAction`; Turnstile (test keys in dev + and CI); rate limit. +- `CookieBanner` with detailed settings and consent log (`consentLog: true`); GTM/GA4/Meta Pixel wired + but **off** until IDs are entered (placeholder IDs only in an `.env.example` comment). +- Cookie scanner with `crawl: true` pointed at `services/cookie-crawler` (run on its own in dev; a service container in CI); + the seeded cookie list is in the **approved** state, plus one pending sample, so the review/approve + flow can be tried in the panel. + +### 4.5 SEO and GEO +- `generatePageMetadata`, hreflang, canonical from `NEXT_PUBLIC_SERVER_URL`. +- `sitemap.xml`, `robots.ts` (AI crawler policy from the panel), `llms.txt`, `llms-full.txt`, + `/md/[locale]/...`, `/api/mcp`, IndexNow key route, `manifest.ts`. +- JSON-LD: Organization (from Company), WebSite, BreadcrumbList, plus per template (§4.2). +- Every page has a meta title and description written by hand within limits, plus `aiSummary`; + `ipal-seo-check` = 0 errors in CI. +- Search Console: a DNS-verification note in the deploy notes (no API, per team rule). + +### 4.6 Security and admin +- CSP + security headers from the plugin through `next.config` / `proxy.ts`, no `X-Powered-By`, + a `csp-report` route. +- `adminMeta` on (noindex, OG image, icon); `whiteLabel: true` with the default Intecion credit. +- **2FA on** (`twoFactor: { issuer: 'Example Studio', plugin: payloadTotp }`). For CI and local + smoke tests a seeded test admin has a known TOTP secret from `.env.example`. The test computes the + code, so the real 2FA flow is tested, not skipped. +- `access` roles: admin + editor accounts seeded (test values only, in `.env.example`). +- `instrumentation.ts` with `assertEnv(ipalEnvRules(...))`. + +### 4.7 Seeding with named records +- `src/seed/` uses `createSeeder` (`@intecion/ipal-kit/seed`): `upsertBySlug`, `fillGlobal`, `summary`. +- **Two layers, two scripts:** + - `seed:base`: what every new site needs, kept by the starter (system pages, globals, forms, + cookie banner texts, notifications). + - `seed:demo`: the made-up company's content, removed by the starter. +- Named, targeted seeds for after launch use the plugin's keys (on `main` since 0ed3898): + `SEED_ONLY="pages:kontakt,forms:Wycena,global:header"` or `createSeeder({ only: [...] })`. This is the + rule "after launch only targeted seeds for named records, never a full seed", shown in code. +- `SEED_DRY_RUN=1` and production guards as in seeding.md. + +### 4.8 Deploy (Coolify): the team's existing process (D3, revised by the owner) +The reference site deploys exactly the way the team's sites already do. There is no Dockerfile and no +new image model: + +1. **Build and check locally:** `pnpm generate:types && pnpm build && pnpm start`, then `ipal-doctor`, + then push. +2. **Coolify builds and runs the app from the Git repo** with its default build pack (Nixpacks), as on + the five live sites without a Dockerfile (e.g. intecioncom-web): + - install: `pnpm install --frozen-lockfile`; + - build: `pnpm generate:types && pnpm build`; + - start: `pnpm start` = `node --disable-proto=throw node_modules/next/dist/bin/next start`, port 3000. + + Node comes from `engines` (`">=22 <23"`). +3. **MongoDB is a separate Coolify resource on the same server and Docker network.** `DATABASE_URI` + points at its internal hostname, with database `example-studiopl_prod` (`databaseNamesFor`). The + database is never exposed outside that network. +4. **Targeted seeds run from the app container's Terminal in Coolify.** The container is built from the + whole repo, so it has the sources, `node_modules` and the Payload CLI: + `SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm seed` (`seed` = `payload run src/seed/index.ts`), then + **Backup now** on the + Mongo resource, then the real run (`deployment.md` §4.7, `seeding.md` "Running a seed on Coolify"). + The CI job checks this: after `next build` it runs the same command against the built tree, so a + change that breaks the seed in the deployed container fails CI. + +No Dockerfile, no `docker-compose.yml` and no image model, in the reference site or in the starter's +output. In dev, the developer uses their own local MongoDB; the cookie crawler runs on its own from +`services/cookie-crawler` when crawl is being tested. + +`docs/DEPLOY.md` in the site is the short project-level runbook. It links to the plugin's +`docs/deployment.md` and doesn't repeat it: +- the local check before every push (build, start, `ipal-doctor --strict`, smoke tests); +- the Coolify app: Git source and branch, default build pack (Nixpacks), the install, build and start + commands above, port 3000, + domains (apex + www), the www ↔ apex redirect that matches `NEXT_PUBLIC_SERVER_URL`, health check + `/api/health`; +- the Coolify MongoDB resource: same server and network, internal `DATABASE_URI`, database + `example-studiopl_prod`, scheduled backups + **Backup now** before any seed; +- the env list with build/runtime flags (`NEXT_PUBLIC_*` at build time); +- targeted seeds from the app Terminal, with `SEED_ONLY`, a dry run first, and never a full seed after + launch; +- DNS records (A/AAAA, www, mail SPF/DKIM/DMARC, the Search Console TXT verification); +- rollback: redeploy the previous commit in Coolify; restore the Mongo backup only when data changed. + +### 4.9 AGENTS.md with filled "Project decisions" +`AGENTS.md` follows the §13 template, with every architecture answer filled in for the made-up client, +one line each. Examples: "languages: pl (default), en, prefixed URLs", "database: Mongo, db +`example-studiopl_prod`", "2FA: on, issuer Example Studio", "credit: Intecion default". It also has one +approved exception, to show the format. The starter blanks these lines into `<…>` prompts. +`CLAUDE.md` = `@AGENTS.md`; `.agents/skills/` installed by `ipal-skills` (committed, so the tree shows +what a real project contains). + +## 5. Placeholder content rules + +- A made-up company only. Names, addresses, NIP, phone numbers and e-mail addresses use reserved or + obviously fake values (`example.com`, `+48 000 000 000`, `NIP 000-000-00-00`, + `ul. Przykładowa 1, 00-000 Warszawa`). +- No real client names, logos, reviews or photos; nothing copied from the team's live sites. +- Images: a few generated or CC0 images (abstract architecture, interiors), WebP, each ≤ 300 kB, in + `reference/seed-media/` with a `LICENSES.md`. +- Texts are realistic in length and structure (headings, lists, FAQ), so SEO, GEO and layout checks + mean something. They are written for the site, never lorem ipsum. + +## 6. Reference site ⇄ starter — one source of truth + +**Proposal: the reference site is the only source of truth; the starter is generated from it.** + +- `reference/starter.manifest.json` marks each path as `keep`, `drop` (demo) or `template` (text with + `{{domain}}`, `{{dbBase}}`, `{{siteName}}`, `{{issuer}}`, `{{locales}}` placeholders). Demo = `seed/demo/`, + `seed-media/`, the case-study and blog demo records, the Blocks showcase page. The `/design` styleguide is kept (D5, accepted). +- The starter is a command of the plugin itself (owner decision, no separate package): + `pnpm dlx @intecion/ipal-kit@X.Y.Z create `. At `prepublishOnly`, `pnpm build:starter` reads + `reference/starter.manifest.json` and writes `dist/starter/template.json.gz` plus the gzipped + lockfile. `reference/` itself stays out of `files`. Nothing is fetched from git when a developer runs + it. The lockfile is the reference one with `link:..` rewritten to the exact version. +- Release gate (starter track): `pnpm pack` → `dlx` the packed tarball → install → build → + `ipal-doctor --strict`. +- `ipal-kit create` applies the variant flags, pins the plugin version, writes `AGENTS.md` decisions + from its prompts and runs `ipal-skills`. +- The starter keeps **no template files of its own**, so it can't drift. CI proves it (§7, job 3). + +Status: **agreed with the starter session** (2026-10-29). Its script copies `reference/`, swaps +placeholders and drops demo content. The contract is in the shared notes (`reference-site-for-starter.md`): +- placeholder names `{{projectName}}`, `{{domain}}`, `{{serverUrl}}`, `{{dbBase}}`, `{{siteName}}`, + `{{issuer}}`, `{{mcpName}}`, `{{locales}}` and `{{defaultLocale}}`; +- the fake values are **unique strings** (`example-studiopl`, `example-studio.pl`, `Example Studio`). + The generator fails when one of them is left in a file the manifest doesn't map, so a new file can't + leak the made-up client into a real site; +- variants inside a file use comment markers that keep the reference site runnable: + `// @starter:if ` … `// @starter:endif` (`{/* @starter:if */}` in TSX). Whole-file + variants go in the manifest (`{ "if": "theme" }`). The flags are `theme`, `cookieScanner`, `crawl`, + `graph`, `localBusiness`, `twoFactor`, `r2`, `singleLocale`, plus one CSP flag per analytics tool. The + reference site itself is the "everything on" build. The starter CI job also builds the "everything + off" output and `singleLocale`, so both ends of the flag range stay valid; +- the made-up company's NIP, address and phone live only in `src/seed/demo/`; +- the "Project decisions" block sits between `` markers; +- the database adapter is in `src/db.ts`. **D10, decided: MongoDB only in v1.** There is no + `db.postgres.ts`, no `src/migrations/` and no `--db postgres`; a Postgres client later means adding + one file next to `db.ts`. + +The owner confirmed it as D6 (2026-10-29). + +## 7. How it stays current + +### Plugin CI (`.gitea/workflows/ci.yml`), new job `reference` +1. Build the plugin (already done), then `pnpm --dir reference install --frozen-lockfile --ignore-workspace`. +2. `generate:types` + `generate:importmap` → `git diff --exit-code` (committed files are current). +3. `tsc --noEmit`, `next build`: page routes must be SSG (●), not dynamic. +4. Start it on Mongo (service container) + `seed:base` + `seed:demo`. Then run one targeted seed the way + Coolify's Terminal does (`SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm seed` + in the built tree), so the documented production seed path is tested. +5. **`ipal-doctor` on `reference/` → 0 findings, strict.** The CLI follows the doctor track's draft + (`docs/dev/ipal-doctor-proposal.md` on `claude/ipal-doctor-26c394`, pending the owner). It is a + zero-dependency bin in the plugin, linked into `reference/` through `link:..`. + - **Static pass, right after install** (needs `node_modules`, the committed `importMap.js` and the + `ipal-*` skills; no build, DB or server): + `node bin/ipal-doctor.mjs reference --strict --offline --json > doctor-static.json`. + `--offline` skips the registry lookups; with `link:..` the installed plugin is the repo version + anyway. + - **Deep + HTTP pass, after build, start and seed:** + `node bin/ipal-doctor.mjs reference --strict --offline --deep --url http://localhost:3000`. + `--deep` reads the DB read-only (users without TOTP, pending cookies, the exact import-map diff); + `--url` checks the headers, CSP, `/api/health`, admin noindex and link preview, and runs + ipal-seo-check. + - `--strict` = `--fail-on info`, so even info findings fail. Exit codes: 0 ok, 1 findings, 2 could not + run, 3 a rule crashed. The `--json` report is kept as a CI artifact. + - What the reference site needs for zero findings: + - `reference/ipal-doctor.json` `{ "domain": "example-studio.pl", "launched": false }`; the CI Mongo + database is named after it: `example-studiopl_dev` (from `databaseNamesFor('example-studio.pl')`); + - **CSP enforced, not report-only.** It is the example, so it has no silenced CSP entry; + - only conventional entries at the top of `src/`; `AGENTS.md` with a non-empty "Project + decisions" section; `CLAUDE.md` = `@AGENTS.md`; `engines.node` `">=22 <23"` + `.nvmrc` `22`; + - ipal-audit `--quick` (run inside the doctor) without warnings. + - `ipal-doctor.json` is a `template` file in the starter manifest (`{{domain}}`, `launched: false`). +6. `ipal-seo-check`, `ipal-consent-check`, `locale-coverage` → 0 errors. +7. **Playwright smoke tests** (`reference/e2e/`), each in pl and en where it applies: + - home renders, no console errors, both themes; + - every page in the sitemap returns 200, has a title, canonical, hreflang and JSON-LD; + - `robots.txt`, `llms.txt`, `/md/...`, `/api/mcp`, `/api/health` respond; + - the contact form sends, and Mailpit receives the company mail and the customer confirmation; + - the cookie banner: reject → no analytics cookie; accept → consent logged; + - security headers + CSP present, no `X-Powered-By`; + - admin login with the computed TOTP → dashboard, Intecion credit, `og:` tags on `/admin/login`; + - 404 page from the panel. +8. **Starter job:** generate a site from `reference/` with the manifest → install → build → + `ipal-doctor --strict --offline` (static). This proves the starter output is valid at every commit. + +Runtime: about 6–8 minutes. Steps 1–3 run on every PR; the full job runs on `main` and before each +release (**D4, accepted**). + +### Release checklist (`docs/dev/PROGRAMISTA.md`, release section), new steps +- [ ] Anything new or changed in this release is used in `reference/` (a new option set, a new + route wired, a new block shown). A PR that adds a feature without touching `reference/` gets a + reviewer question. A `test/docsConsistency` check will flag new exports that `reference/` never + imports (with an allow-list). +- [ ] `reference/` upgrade done the way `ipal-upgrade` tells client projects; the upgrade notes are + tested here first. +- [ ] CI `reference` job green, including the starter job. +- [ ] Regenerate `docs/agent/reference-site/INDEX.md` (script, part of `pnpm build`). +- [ ] Tag `v`: the tag URL is what the docs link to. + +## 8. How agents use it + +### `docs/agent/AGENT.md`, new short section after "ipal-kit first" +> **Reference site.** Every convention in this file is implemented in the reference site, a complete +> example project kept current with each release. Before writing a file the plugin expects you to wire +> (layout, catch-all page, `lib/content.ts`, proxy, SEO/GEO routes, forms, seeds, `DEPLOY.md`, +> AGENTS.md), look up the matching file in `node_modules/@intecion/ipal-kit/docs/agent/reference-site/INDEX.md` +> and copy its pattern. Change only the project's content, never the pattern. If the reference site +> and this file disagree, report it (ipal-plugin-gap): it's a plugin bug. + +### `docs/agent/reference-site/INDEX.md` (generated, shipped) +One row per file: path, what it shows, which AGENT.md section or doc page it implements. Short wiring +files (≤ 40 lines: routes, `proxy.ts`, `instrumentation.ts`, layout, `actions.ts`, `next.config`, +`DEPLOY.md`) are included **in full**, so an agent in a client project has them offline. Longer +files get an excerpt + the tag URL. + +### Skills +- **ipal-site**, phase 1 and phase 4: "copy the structure from the reference site (INDEX.md)"; phase 8: + "the reference site's `/design` page is the styleguide to reproduce". +- **ipal-setup**: new projects start with `ipal-kit create` (generated from the reference site); + existing projects compare their wiring files against INDEX.md. +- **ipal-reference**: each module row links its reference file. +- **ipal-upgrade**: "the reference site's diff between two tags shows exactly what a project must + change": `git diff v1.14.6 v1.15.0 -- reference/` (linked). +- **ipal-block**: the Blocks showcase page as the example of every block and variant. + +Per the CLAUDE.md rule, these texts land in the same change that builds the reference site. + +## 9. Build plan (after approval) + +One branch, one commit per phase, each phase green in CI before the next: + +1. Skeleton: `reference/` project, link to plugin, Mongo (local), i18n, proxy, layout, + catch-all, `lib/content`, system routes, instrumentation, 2FA, adminMeta, security headers. +2. Content model + base seed: Pages, Media, posts, case studies, globals, system pages, forms. +3. Blocks + tokens: wait for the block-library and token tracks to land on `main`; wire them, + showcase and styleguide pages. +4. Demo seed: the made-up company in pl/en, images. +5. Deploy: DEPLOY.md (the team's Coolify process), AGENTS.md with decisions. +6. CI job + Playwright smoke tests + doctor (once the doctor track lands). +7. Starter manifest + starter job (with the starter track). +8. Agent guide: AGENT.md section, INDEX.md generator, skill updates, release checklist. + +Dependencies: phase 3 needs the block library and tokens merged; phase 6 needs the doctor CLI; phase 7 +needs the starter. Phases 1–2 and 4–5 can start right away. + +## 10. Decisions (all made by the owner, 2026-10-29) + +| # | Decision | Accepted | +|---|---|---| +| D1 | Where it lives | **C: `reference/` in the plugin repo, not shipped**; `dev/` stays the test sandbox | +| D2 | Database of the reference site (and so the starter default) | **MongoDB**: all 7 live sites use it. The plugin's Postgres support stays tested by `dev/` + vitest. | +| D3 | Deploy style for every new site | **Revised by the owner: the team's existing process.** Build and check locally; Coolify builds and runs the app from the repo (no Dockerfile); MongoDB is a separate Coolify resource on the same Docker network; targeted seeds run from the app container's Terminal (§4.8). The first answer (a standalone Dockerfile) is withdrawn. | +| D4 | CI cost | Fast part on every PR; full job (start, seed, doctor, Playwright, starter) on `main` and before each release | +| D5 | Does the starter keep the `/design` styleguide page? | **Yes**, `noindex`; it helps the designer of each new site. Drop the Blocks showcase. | +| D6 | Source of truth with the starter | **Reference site is the source**, starter generated by manifest (agreed with the starter session, confirmed by the owner) | +| D7 | Made-up company | `Pracownia Przykład` / "Example Studio" (architecture studio): services, case studies, blog | +| D8 | Is the reference site deployed anywhere? | Optional: a Coolify app at `reference.` with `noindex`, redeployed per release. Useful for showing clients; not required. | + +| D9 | Dockerfile image type | **Doesn't apply**: there is no Dockerfile (D3 revised) | +| D10 | Postgres in v1 (= starter D12) | **MongoDB only.** No Postgres files or `--db postgres` in v1 | From 8adac41f92ba42bfe5adf546fb23156426e683ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 15:17:11 +0100 Subject: [PATCH 2/3] Reference site: Example Studio on ipal-kit (reference/), index for agents, CI job MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .gitea/workflows/ci.yml | 72 + docs/agent/AGENT.md | 11 + docs/agent/reference-site/INDEX.md | 1193 ++++ docs/agent/skills/ipal-block/SKILL.md | 2 + docs/agent/skills/ipal-reference/SKILL.md | 2 + docs/agent/skills/ipal-setup/SKILL.md | 4 + docs/agent/skills/ipal-site/SKILL.md | 8 +- docs/agent/skills/ipal-upgrade/SKILL.md | 3 + docs/dev/PROGRAMISTA.md | 22 + package.json | 1 + reference/.agents/skills/ipal-audit/SKILL.md | 57 + .../resources/smoke.spec.template.ts | 78 + .../skills/ipal-audit/scripts/audit.sh | 379 ++ .../skills/ipal-audit/scripts/html-check.mjs | 38 + .../skills/ipal-audit/scripts/jsx-text.mjs | 59 + .../skills/ipal-audit/scripts/panel-check.mjs | 55 + reference/.agents/skills/ipal-block/SKILL.md | 86 + .../ipal-block/resources/section-code.md | 342 + .../.agents/skills/ipal-collection/SKILL.md | 56 + .../skills/ipal-consent-check/SKILL.md | 133 + .../scripts/consent-check.mjs | 134 + .../scripts/cookie-scan.mjs | 178 + .../scripts/import-cookies.ts | 60 + reference/.agents/skills/ipal-debug/SKILL.md | 99 + reference/.agents/skills/ipal-form/SKILL.md | 161 + .../resources/CustomForm.example.tsx | 50 + .../skills/ipal-form/resources/FormBlock.tsx | 26 + .../skills/ipal-form/resources/actions.ts | 9 + .../skills/ipal-form/resources/formClasses.ts | 29 + .../ipal-form/resources/seed-form.template.ts | 152 + .../.agents/skills/ipal-locale-add/SKILL.md | 83 + .../scripts/locale-coverage.ts | 74 + .../skills/ipal-migrate-fields/SKILL.md | 106 + .../migrate-block-fields.template.ts | 121 + reference/.agents/skills/ipal-nav/SKILL.md | 38 + .../skills/ipal-nav/resources/nav-code.md | 177 + .../.agents/skills/ipal-plugin-gap/SKILL.md | 64 + .../.agents/skills/ipal-reference/SKILL.md | 259 + .../skills/ipal-reference/resources/api.md | 779 +++ .../.agents/skills/ipal-seo-check/SKILL.md | 50 + .../ipal-seo-check/scripts/seo-check.mjs | 295 + reference/.agents/skills/ipal-setup/SKILL.md | 594 ++ .../skills/ipal-setup/resources/DESIGN.md | 48 + .../skills/ipal-setup/resources/tokens.ts | 27 + reference/.agents/skills/ipal-site/SKILL.md | 168 + .../resources/seed-content.template.ts | 81 + .../.agents/skills/ipal-upgrade/SKILL.md | 217 + reference/.env.example | 43 + reference/.gitignore | 8 + reference/.npmrc | 2 + reference/.nvmrc | 1 + reference/AGENTS.md | 62 + reference/CLAUDE.md | 1 + reference/DESIGN.md | 49 + reference/README.md | 39 + reference/docs/DEPLOY.md | 74 + reference/e2e/create-test-admin.ts | 26 + reference/e2e/smoke.spec.ts | 140 + reference/e2e/totp.ts | 15 + reference/ipal-doctor.json | 4 + reference/next-env.d.ts | 7 + reference/next.config.ts | 37 + reference/package.json | 77 + reference/playwright.config.ts | 27 + reference/pnpm-lock.yaml | 5534 +++++++++++++++++ reference/postcss.config.mjs | 1 + .../(frontend)/[locale]/[[...slug]]/page.tsx | 37 + .../src/app/(frontend)/[locale]/actions.ts | 9 + .../app/(frontend)/[locale]/design/page.tsx | 32 + .../src/app/(frontend)/[locale]/layout.tsx | 60 + .../src/app/(frontend)/[locale]/not-found.tsx | 7 + .../app/(frontend)/[locale]/notFoundView.ts | 10 + reference/src/app/(frontend)/styles.css | 7 + .../admin/[[...segments]]/not-found.tsx | 25 + .../(payload)/admin/[[...segments]]/page.tsx | 25 + .../src/app/(payload)/admin/importMap.js | 102 + .../src/app/(payload)/api/[...slug]/route.ts | 19 + .../(payload)/api/graphql-playground/route.ts | 7 + .../src/app/(payload)/api/graphql/route.ts | 8 + reference/src/app/(payload)/custom.scss | 0 reference/src/app/(payload)/layout.tsx | 32 + reference/src/app/api/csp-report/route.ts | 4 + reference/src/app/api/health/route.ts | 3 + reference/src/app/api/mcp/route.ts | 3 + reference/src/app/indexnow-key.txt/route.ts | 3 + reference/src/app/llms-full.txt/route.ts | 3 + reference/src/app/llms.txt/route.ts | 3 + reference/src/app/manifest.ts | 2 + .../src/app/md/[locale]/[[...slug]]/route.ts | 3 + reference/src/app/robots.ts | 3 + reference/src/app/sitemap.xml/route.ts | 3 + reference/src/blocks/configs.ts | 30 + reference/src/blocks/registry.ts | 31 + reference/src/collections/CaseStudies.ts | 21 + reference/src/collections/Media.ts | 24 + reference/src/collections/Pages.ts | 36 + reference/src/collections/Posts.ts | 21 + reference/src/collections/entryFields.ts | 20 + .../src/components/design/TokenPanel.tsx | 84 + reference/src/components/forms/formClasses.ts | 31 + reference/src/components/layout/Footer.tsx | 60 + reference/src/components/layout/Header.tsx | 57 + .../src/components/layout/LocaleSwitcher.tsx | 22 + reference/src/components/layout/MobileNav.tsx | 40 + reference/src/content.config.ts | 12 + reference/src/db.ts | 5 + reference/src/design/tokens.css | 25 + reference/src/design/tokens.ts | 29 + reference/src/globals/Company.ts | 37 + reference/src/globals/Footer.ts | 31 + reference/src/globals/Header.ts | 33 + reference/src/i18n.config.ts | 12 + reference/src/instrumentation.ts | 14 + reference/src/lib/content.ts | 69 + reference/src/lib/globals.ts | 10 + reference/src/payload-types.ts | 3259 ++++++++++ reference/src/payload.config.ts | 58 + reference/src/proxy.ts | 10 + reference/src/seed/base.ts | 102 + reference/src/seed/demo.ts | 409 ++ reference/src/seed/forms.ts | 93 + reference/src/seed/index.ts | 54 + reference/src/seed/lib.ts | 33 + reference/src/seed/media.ts | 67 + reference/src/seed/showcase.ts | 90 + reference/starter.manifest.json | 54 + reference/tsconfig.json | 24 + scripts/reference-index.mjs | 176 + test/referenceIndex.test.ts | 21 + 129 files changed, 18440 insertions(+), 1 deletion(-) create mode 100644 docs/agent/reference-site/INDEX.md create mode 100644 reference/.agents/skills/ipal-audit/SKILL.md create mode 100644 reference/.agents/skills/ipal-audit/resources/smoke.spec.template.ts create mode 100644 reference/.agents/skills/ipal-audit/scripts/audit.sh create mode 100644 reference/.agents/skills/ipal-audit/scripts/html-check.mjs create mode 100644 reference/.agents/skills/ipal-audit/scripts/jsx-text.mjs create mode 100644 reference/.agents/skills/ipal-audit/scripts/panel-check.mjs create mode 100644 reference/.agents/skills/ipal-block/SKILL.md create mode 100644 reference/.agents/skills/ipal-block/resources/section-code.md create mode 100644 reference/.agents/skills/ipal-collection/SKILL.md create mode 100644 reference/.agents/skills/ipal-consent-check/SKILL.md create mode 100644 reference/.agents/skills/ipal-consent-check/scripts/consent-check.mjs create mode 100644 reference/.agents/skills/ipal-consent-check/scripts/cookie-scan.mjs create mode 100644 reference/.agents/skills/ipal-consent-check/scripts/import-cookies.ts create mode 100644 reference/.agents/skills/ipal-debug/SKILL.md create mode 100644 reference/.agents/skills/ipal-form/SKILL.md create mode 100644 reference/.agents/skills/ipal-form/resources/CustomForm.example.tsx create mode 100644 reference/.agents/skills/ipal-form/resources/FormBlock.tsx create mode 100644 reference/.agents/skills/ipal-form/resources/actions.ts create mode 100644 reference/.agents/skills/ipal-form/resources/formClasses.ts create mode 100644 reference/.agents/skills/ipal-form/resources/seed-form.template.ts create mode 100644 reference/.agents/skills/ipal-locale-add/SKILL.md create mode 100644 reference/.agents/skills/ipal-locale-add/scripts/locale-coverage.ts create mode 100644 reference/.agents/skills/ipal-migrate-fields/SKILL.md create mode 100644 reference/.agents/skills/ipal-migrate-fields/resources/migrate-block-fields.template.ts create mode 100644 reference/.agents/skills/ipal-nav/SKILL.md create mode 100644 reference/.agents/skills/ipal-nav/resources/nav-code.md create mode 100644 reference/.agents/skills/ipal-plugin-gap/SKILL.md create mode 100644 reference/.agents/skills/ipal-reference/SKILL.md create mode 100644 reference/.agents/skills/ipal-reference/resources/api.md create mode 100644 reference/.agents/skills/ipal-seo-check/SKILL.md create mode 100644 reference/.agents/skills/ipal-seo-check/scripts/seo-check.mjs create mode 100644 reference/.agents/skills/ipal-setup/SKILL.md create mode 100644 reference/.agents/skills/ipal-setup/resources/DESIGN.md create mode 100644 reference/.agents/skills/ipal-setup/resources/tokens.ts create mode 100644 reference/.agents/skills/ipal-site/SKILL.md create mode 100644 reference/.agents/skills/ipal-site/resources/seed-content.template.ts create mode 100644 reference/.agents/skills/ipal-upgrade/SKILL.md create mode 100644 reference/.env.example create mode 100644 reference/.gitignore create mode 100644 reference/.npmrc create mode 100644 reference/.nvmrc create mode 100644 reference/AGENTS.md create mode 100644 reference/CLAUDE.md create mode 100644 reference/DESIGN.md create mode 100644 reference/README.md create mode 100644 reference/docs/DEPLOY.md create mode 100644 reference/e2e/create-test-admin.ts create mode 100644 reference/e2e/smoke.spec.ts create mode 100644 reference/e2e/totp.ts create mode 100644 reference/ipal-doctor.json create mode 100644 reference/next-env.d.ts create mode 100644 reference/next.config.ts create mode 100644 reference/package.json create mode 100644 reference/playwright.config.ts create mode 100644 reference/pnpm-lock.yaml create mode 100644 reference/postcss.config.mjs create mode 100644 reference/src/app/(frontend)/[locale]/[[...slug]]/page.tsx create mode 100644 reference/src/app/(frontend)/[locale]/actions.ts create mode 100644 reference/src/app/(frontend)/[locale]/design/page.tsx create mode 100644 reference/src/app/(frontend)/[locale]/layout.tsx create mode 100644 reference/src/app/(frontend)/[locale]/not-found.tsx create mode 100644 reference/src/app/(frontend)/[locale]/notFoundView.ts create mode 100644 reference/src/app/(frontend)/styles.css create mode 100644 reference/src/app/(payload)/admin/[[...segments]]/not-found.tsx create mode 100644 reference/src/app/(payload)/admin/[[...segments]]/page.tsx create mode 100644 reference/src/app/(payload)/admin/importMap.js create mode 100644 reference/src/app/(payload)/api/[...slug]/route.ts create mode 100644 reference/src/app/(payload)/api/graphql-playground/route.ts create mode 100644 reference/src/app/(payload)/api/graphql/route.ts create mode 100644 reference/src/app/(payload)/custom.scss create mode 100644 reference/src/app/(payload)/layout.tsx create mode 100644 reference/src/app/api/csp-report/route.ts create mode 100644 reference/src/app/api/health/route.ts create mode 100644 reference/src/app/api/mcp/route.ts create mode 100644 reference/src/app/indexnow-key.txt/route.ts create mode 100644 reference/src/app/llms-full.txt/route.ts create mode 100644 reference/src/app/llms.txt/route.ts create mode 100644 reference/src/app/manifest.ts create mode 100644 reference/src/app/md/[locale]/[[...slug]]/route.ts create mode 100644 reference/src/app/robots.ts create mode 100644 reference/src/app/sitemap.xml/route.ts create mode 100644 reference/src/blocks/configs.ts create mode 100644 reference/src/blocks/registry.ts create mode 100644 reference/src/collections/CaseStudies.ts create mode 100644 reference/src/collections/Media.ts create mode 100644 reference/src/collections/Pages.ts create mode 100644 reference/src/collections/Posts.ts create mode 100644 reference/src/collections/entryFields.ts create mode 100644 reference/src/components/design/TokenPanel.tsx create mode 100644 reference/src/components/forms/formClasses.ts create mode 100644 reference/src/components/layout/Footer.tsx create mode 100644 reference/src/components/layout/Header.tsx create mode 100644 reference/src/components/layout/LocaleSwitcher.tsx create mode 100644 reference/src/components/layout/MobileNav.tsx create mode 100644 reference/src/content.config.ts create mode 100644 reference/src/db.ts create mode 100644 reference/src/design/tokens.css create mode 100644 reference/src/design/tokens.ts create mode 100644 reference/src/globals/Company.ts create mode 100644 reference/src/globals/Footer.ts create mode 100644 reference/src/globals/Header.ts create mode 100644 reference/src/i18n.config.ts create mode 100644 reference/src/instrumentation.ts create mode 100644 reference/src/lib/content.ts create mode 100644 reference/src/lib/globals.ts create mode 100644 reference/src/payload-types.ts create mode 100644 reference/src/payload.config.ts create mode 100644 reference/src/proxy.ts create mode 100644 reference/src/seed/base.ts create mode 100644 reference/src/seed/demo.ts create mode 100644 reference/src/seed/forms.ts create mode 100644 reference/src/seed/index.ts create mode 100644 reference/src/seed/lib.ts create mode 100644 reference/src/seed/media.ts create mode 100644 reference/src/seed/showcase.ts create mode 100644 reference/starter.manifest.json create mode 100644 reference/tsconfig.json create mode 100644 scripts/reference-index.mjs create mode 100644 test/referenceIndex.test.ts diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index ab92fa2..ccf49bb 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -25,3 +25,75 @@ 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 + # Doctor (static) — turn on when ipal-doctor ships (docs/dev/ipal-doctor-proposal.md): + # - run: node bin/ipal-doctor.mjs reference --strict --offline --json > doctor-static.json + + # 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 + NEXT_PUBLIC_TURNSTILE_SITE_KEY: 1x00000000000000000000AA + TURNSTILE_SECRET_KEY: 1x0000000000000000000000000000000AA + ALLOW_LOCAL_MEDIA: '1' + E2E_BASE_URL: http://localhost:3100 + E2E_ADMIN_EMAIL: e2e-admin@example.com + 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 + # Doctor (deep + HTTP) — turn on when ipal-doctor ships: + # - run: node bin/ipal-doctor.mjs reference --strict --offline --deep --url http://localhost:3100 diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 2789af8..3e6f8bd 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -95,6 +95,17 @@ the ready-to-send list is in **ipal-setup** stage 0 (ipal-site phase 0 uses the it, is marked `// WORKAROUND ipal-kit : docs/plugin-requests/` and is recorded in "Project decisions". +## Reference site — copy the pattern, not from memory + +Every convention in this file is implemented in the **reference site**: one complete client site on ipal-kit +("Example Studio", made up), kept current with each release and built, seeded and smoke-tested in the plugin's CI. +Before you write a file the plugin expects you to wire (payload.config, layout, catch-all page, `lib/content.ts`, +proxy, SEO/GEO routes, forms, seeds, `AGENTS.md`, `DESIGN.md`, deploy notes), open +`node_modules/@intecion/ipal-kit/docs/agent/reference-site/INDEX.md`, find the matching file and copy its pattern — +short wiring files are in the index in full, longer ones are linked at the tag of your plugin version. Change only the +project's content (names, texts, blocks the site map needs), never the pattern. The index and this file disagree → +report it with **ipal-plugin-gap**: it is a plugin bug. + ## Code rules Short version of §8 — every skill follows it. diff --git a/docs/agent/reference-site/INDEX.md b/docs/agent/reference-site/INDEX.md new file mode 100644 index 0000000..8a8f073 --- /dev/null +++ b/docs/agent/reference-site/INDEX.md @@ -0,0 +1,1193 @@ +# Reference site — file index + + + +The reference site is one complete client site on ipal-kit 1.14.6 ("Example Studio", made up) that uses +every convention in AGENT.md. It lives in the plugin repo (`reference/`, not in the npm package). Copy the +PATTERN of the file you need; change only the project's content. Files up to +40 lines are below in full; open the rest in the repo at the tag of your plugin version: +`https://git.intecion.net/IntecionSoftware/ipal-kit/src/tag/v/reference/`. +If this index and AGENT.md disagree, report it with ipal-plugin-gap — it is a plugin bug. + +## Project files + +Rules: AGENT.md §13, §0a. + +| File | What it shows | +|---|---| +| `.env.example` | every env var the site reads, with dev / test values and build vs runtime notes | +| `.gitignore` | what a project never commits (below) | +| `.npmrc` | the @intecion registry line (committed, no secret) (below) | +| `.nvmrc` | Node 22, the same as `engines` and the Coolify build pack (below) | +| `AGENTS.md` | the agent guide of the project: site map and filled "Project decisions" (AGENT.md §13) | +| `CLAUDE.md` | one line `@AGENTS.md` (Claude Code reads CLAUDE.md) | +| `DESIGN.md` | the human source of the look, matching src/design/tokens.ts | +| `README.md` | how to run the reference site and what is where | +| `docs/DEPLOY.md` | the Coolify runbook: local check, app settings, MongoDB resource, env, targeted seeds, DNS, rollback | +| `ipal-doctor.json` | the production domain and launch state for ipal-doctor (below) | +| `next.config.ts` | security headers, enforced CSP, admin CSP, upload headers, images, no X-Powered-By (below) | +| `package.json` | scripts (build, start, seed, tokens, generate), pinned Payload versions and overrides | +| `playwright.config.ts` | smoke tests against the built, seeded site (below) | +| `postcss.config.mjs` | Tailwind 4 through PostCSS (below) | +| `starter.manifest.json` | what `ipal-kit create` keeps, drops and turns into placeholders | +| `tsconfig.json` | paths @/ and @payload-config, .agents excluded (below) | + +### `.gitignore` + +``` +node_modules +.next +.env +media +test-results +playwright-report +*.tsbuildinfo +!next-env.d.ts +``` + +### `.npmrc` + +``` +legacy-peer-deps=true +@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/ +``` + +### `.nvmrc` + +``` +22 +``` + +### `ipal-doctor.json` + +```json +{ + "domain": "example-studio.pl", + "launched": false +} +``` + +### `next.config.ts` + +```ts +import type { NextConfig } from 'next' + +import { + buildAdminCspHeaders, + buildImagesConfig, + buildSecurityHeaders, + buildUploadSecurityHeaders, + withSecurityConfig, +} from '@intecion/ipal-kit' +import { withPayload } from '@payloadcms/next/withPayload' + +// CSP enforced: the reference site is the example after the report-only phase (security.md → "ROLL OUT CSP"). +// Flags = what the site loads: Turnstile on forms, Google analytics/GTM when IDs are set in Site integrations. +const csp = { mode: 'enforce', r2Url: process.env.R2_PUBLIC_URL, reportUri: '/api/csp-report' } as const + +const securityHeaders = buildSecurityHeaders({ + csp: { ...csp, analytics: true, turnstile: true }, + hsts: process.env.NODE_ENV === 'production', +}) + +const nextConfig: NextConfig = { + // ALLOW_LOCAL_MEDIA=1 (local / CI production checks only): let next/image optimize files the app serves on localhost + images: buildImagesConfig(process.env.ALLOW_LOCAL_MEDIA === '1' ? { production: false } : {}), + // Metadata in for crawlers (deployment.md §3a) + htmlLimitedBots: + /Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i, + async headers() { + return [ + { source: '/:path*', headers: securityHeaders }, + { source: '/admin/:path*', headers: buildAdminCspHeaders(csp) }, // after the site-wide rule + ...buildUploadSecurityHeaders(), + ] + }, +} + +// withSecurityConfig: no X-Powered-By (Next's and Payload's) +export default withPayload(withSecurityConfig(nextConfig)) +``` + +### `playwright.config.ts` + +```ts +import { defineConfig, devices } from '@playwright/test' + +// .env holds the E2E_* test values locally; CI passes them as env +try { + process.loadEnvFile('.env') +} catch { + // no .env (CI) +} + +/** Smoke tests against a built, seeded site: pnpm build && pnpm seed && pnpm payload run e2e/create-test-admin.ts. */ +const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:3100' + +export default defineConfig({ + forbidOnly: !!process.env.CI, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], + reporter: process.env.CI ? 'line' : 'list', + retries: process.env.CI ? 1 : 0, + testDir: './e2e', + use: { baseURL, trace: 'retain-on-failure' }, + webServer: { + command: 'pnpm start', + env: { PORT: new URL(baseURL).port || '3000' }, + reuseExistingServer: true, + url: `${baseURL}/api/health`, + }, + workers: 1, +}) +``` + +### `postcss.config.mjs` + +```js +export default { plugins: { '@tailwindcss/postcss': {} } } +``` + +### `tsconfig.json` + +```json +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "react-jsx", + "incremental": true, + "plugins": [{ "name": "next" }], + "paths": { + "@/*": ["./src/*"], + "@payload-config": ["./src/payload.config.ts"] + } + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"], + "exclude": ["node_modules", ".agents"] +} +``` + +## Configuration + +Rules: AGENT.md §3, ipal-setup stage 3. + +| File | What it shows | +|---|---| +| `src/content.config.ts` | collections with archive pages (below) | +| `src/db.ts` | the database adapter, alone in one file (MongoDB) (below) | +| `src/i18n.config.ts` | the ONLY source of languages (below) | +| `src/instrumentation.ts` | env validation at startup (assertEnv, database name rule) (below) | +| `src/payload.config.ts` | ipalKit with every module the site uses, R2, mail, 2FA, white-label | +| `src/proxy.ts` | the locale proxy with Markdown negotiation (not middleware.ts) (below) | + +### `src/content.config.ts` + +```ts +import type { ContentOption } from '@intecion/ipal-kit' + +/** + * Collections with an archive page (docs/content.md). The archive page is picked in + * Site settings → System pages, so `/pl/blog/` follows the page's slug. + */ +export const contentConfig: ContentOption = { + collections: [ + { slug: 'posts', label: 'Blog', perPage: 9 }, + { slug: 'caseStudies', label: 'Case studies', perPage: 9 }, + ], +} +``` + +### `src/db.ts` + +```ts +import { mongooseAdapter } from '@payloadcms/db-mongodb' + +// MongoDB only (AGENTS.md → Project decisions). Database name from databaseNamesFor('example-studio.pl'): +// example-studiopl_dev locally, example-studiopl_prod in the Coolify MongoDB resource. +export const db = mongooseAdapter({ url: process.env.DATABASE_URI ?? '' }) +``` + +### `src/i18n.config.ts` + +```ts +import type { I18nConfig } from '@intecion/ipal-kit' + +/** The ONLY source of languages (AGENT.md §3). Every language has a URL prefix: /pl/…, /en/…. */ +export const i18nConfig = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} as const satisfies I18nConfig + +export type Locale = (typeof i18nConfig.locales)[number]['code'] +``` + +### `src/instrumentation.ts` + +```ts +import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env' + +export function register() { + if (process.env.NEXT_RUNTIME !== 'nodejs') {return} + // storage: R2 is required in production. ALLOW_LOCAL_MEDIA=1 lets a production build run on local disk for + // local checks and CI only — never set it in Coolify. + // databaseName: DATABASE_URI must name example-studiopl_dev / example-studiopl_prod (databaseNamesFor). + // R2_PUBLIC_URL optional: media are served through the app by default (storage.md, env.md). + assertEnv( + ipalEnvRules({ databaseName: { domain: 'example-studio.pl' }, ipHeader: true, storage: process.env.ALLOW_LOCAL_MEDIA !== '1' }).map((rule) => + rule.name === 'R2_PUBLIC_URL' ? { ...rule, required: false } : rule, + ), + ) +} +``` + +### `src/proxy.ts` + +```ts +import { createProxy } from '@intecion/ipal-kit' +import { NextResponse } from 'next/server' + +import { i18nConfig } from '@/i18n.config' + +// markdown: true (GEO) — /md/… passes without a locale redirect; `Accept: text/markdown` gets the Markdown page +export const proxy = createProxy(i18nConfig, { markdown: true, NextResponse }) + +// Inline LITERAL — Next reads the matcher statically (importing DEFAULT_PROXY_MATCHER breaks /admin) +export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] } +``` + +## Collections and globals + +Rules: AGENT.md §5, ipal-nav, ipal-collection. + +| File | What it shows | +|---|---| +| `src/collections/CaseStudies.ts` | a project-specific archive collection (below) | +| `src/collections/Media.ts` | the full media collection (media.md) (below) | +| `src/collections/Pages.ts` | Pages: slug, blocks layout, AI summary, noindex, slug history, revalidation, system-page delete guard (below) | +| `src/collections/Posts.ts` | the blog collection (archive in System pages) (below) | +| `src/collections/entryFields.ts` | shared fields of archive collections (names the entry card reads) (below) | +| `src/globals/Company.ts` | company data (PL market): footer, contact details, LocalBusiness JSON-LD (below) | +| `src/globals/Footer.ts` | footer navigation global (below) | +| `src/globals/Header.ts` | header navigation global (below) | + +### `src/collections/CaseStudies.ts` + +```ts +import type { CollectionConfig } from 'payload' + +import { buildRevalidateHook } from '@intecion/ipal-kit' +import { revalidatePath } from 'next/cache' + +import { i18nConfig } from '@/i18n.config' + +import { entryFields } from './entryFields' + +const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath }) + +/** The project's own archive collection (skill ipal-collection) — the library has no case-study type. */ +export const CaseStudies: CollectionConfig = { + slug: 'caseStudies', + admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' }, + access: { read: () => true }, + defaultSort: '-publishedAt', + fields: entryFields, + hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] }, + labels: { plural: { en: 'Case studies', pl: 'Realizacje' }, singular: { en: 'Case study', pl: 'Realizacja' } }, +} +``` + +### `src/collections/Media.ts` + +```ts +import type { CollectionConfig } from 'payload' + +import { + buildMediaPlaceholderField, + buildMediaPlaceholderHook, + buildOptimizeUploadField, + buildOptimizeUploadHook, + normalizeFilenameHook, +} from '@intecion/ipal-kit' + +/** media.md "Full collection", 1:1. */ +export const Media: CollectionConfig = { + slug: 'media', + access: { read: () => true }, // public files; media are served by the app (/api/media/file/…) + upload: { focalPoint: true, mimeTypes: ['image/*', 'application/pdf', 'video/mp4', 'video/webm'] }, + hooks: { + beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()], + }, + fields: [ + { name: 'alt', type: 'text', localized: true, required: true }, + buildOptimizeUploadField(), + buildMediaPlaceholderField(), + ], +} +``` + +### `src/collections/Pages.ts` + +```ts +import type { CollectionConfig } from 'payload' + +import { + buildNoindexField, + buildPreventDeleteSystemPage, + buildRevalidateHook, + buildSlugField, + buildSummaryField, + trackSlugHistoryHook, +} from '@intecion/ipal-kit' +import { revalidatePath } from 'next/cache' + +import { pageBlocks } from '@/blocks/configs' +import { i18nConfig } from '@/i18n.config' + +const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath }) + +export const Pages: CollectionConfig = { + slug: 'pages', + admin: { defaultColumns: ['title', 'slug', 'updatedAt'], useAsTitle: 'title' }, + access: { read: () => true }, + fields: [ + { name: 'title', type: 'text', localized: true, required: true }, + buildSlugField({ from: 'title' }), + { name: 'layout', type: 'blocks', blocks: pageBlocks, minRows: 1 }, + buildSummaryField(), // aiSummary — GEO (llms.txt, MCP) + buildNoindexField(), + { name: 'slugHistory', type: 'array', admin: { readOnly: true }, fields: [{ name: 'slug', type: 'text' }] }, + ], + hooks: { + afterChange: [revalidate.afterChange], + afterDelete: [revalidate.afterDelete], + beforeChange: [trackSlugHistoryHook], + beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })], + }, +} +``` + +### `src/collections/Posts.ts` + +```ts +import type { CollectionConfig } from 'payload' + +import { buildRevalidateHook } from '@intecion/ipal-kit' +import { revalidatePath } from 'next/cache' + +import { i18nConfig } from '@/i18n.config' + +import { entryFields } from './entryFields' + +const revalidate = buildRevalidateHook({ config: i18nConfig, revalidatePath }) + +/** Blog entries — listed on the page assigned in Site settings → System pages → Blog (content.config.ts). */ +export const Posts: CollectionConfig = { + slug: 'posts', + admin: { defaultColumns: ['title', 'publishedAt', 'updatedAt'], useAsTitle: 'title' }, + access: { read: () => true }, + defaultSort: '-publishedAt', + fields: entryFields, + hooks: { afterChange: [revalidate.afterChange], afterDelete: [revalidate.afterDelete] }, + labels: { plural: { en: 'Blog posts', pl: 'Wpisy' }, singular: { en: 'Blog post', pl: 'Wpis' } }, +} +``` + +### `src/collections/entryFields.ts` + +```ts +import type { Field } from 'payload' + +import { buildNoindexField, buildSlugField, buildSummaryField } from '@intecion/ipal-kit' + +import { pageBlocks } from '@/blocks/configs' + +/** + * Fields every archive collection shares (posts, case studies). The entry card of the entry list block + * reads `title`, `excerpt`, `media` and `publishedAt` (defaultEntryCard), so the names follow it. + */ +export const entryFields: Field[] = [ + { name: 'title', type: 'text', localized: true, required: true }, + buildSlugField({ from: 'title' }), + { name: 'excerpt', type: 'textarea', localized: true, admin: { description: 'One or two sentences on the card in lists.' } }, + { name: 'media', type: 'upload', relationTo: 'media', admin: { description: 'Card and share image.' } }, + { name: 'publishedAt', type: 'date', admin: { position: 'sidebar' }, defaultValue: () => new Date().toISOString() }, + { name: 'layout', type: 'blocks', blocks: pageBlocks }, + buildSummaryField(), + buildNoindexField(), +] +``` + +### `src/globals/Company.ts` + +```ts +import type { GlobalConfig } from 'payload' + +import { buildGlobalRevalidateHook } from '@intecion/ipal-kit' +import { revalidatePath } from 'next/cache' + +/** Company data for a PL market site: footer, contact block details, LocalBusiness JSON-LD. */ +export const Company: GlobalConfig = { + slug: 'company', + access: { read: () => true }, + fields: [ + { name: 'name', type: 'text', required: true }, + { name: 'legalName', type: 'text' }, + { name: 'taxId', type: 'text', label: 'NIP' }, + { + name: 'address', + type: 'group', + fields: [ + { name: 'street', type: 'text' }, + { name: 'postalCode', type: 'text' }, + { name: 'city', type: 'text' }, + { name: 'country', type: 'text', defaultValue: 'PL' }, + ], + }, + { name: 'phone', type: 'text' }, + { name: 'email', type: 'email' }, + { name: 'hours', type: 'text', localized: true, admin: { description: 'Shown next to the contact form, e.g. "Mon–Fri 9:00–17:00".' } }, + { + name: 'socials', + type: 'array', + fields: [ + { name: 'label', type: 'text', required: true }, + { name: 'url', type: 'text', required: true }, + ], + }, + ], + hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] }, +} +``` + +### `src/globals/Footer.ts` + +```ts +import type { GlobalConfig } from 'payload' + +import { buildGlobalRevalidateHook, buildLinkField, rowLabel } from '@intecion/ipal-kit' +import { revalidatePath } from 'next/cache' + +/** ipal-nav: link columns and a note. Legal links come from System pages (getSystemLinks), not from here. */ +export const Footer: GlobalConfig = { + slug: 'footer', + access: { read: () => true }, + fields: [ + { + name: 'columns', + type: 'array', + admin: { components: rowLabel('heading', 'Column'), initCollapsed: true }, + fields: [ + { name: 'heading', type: 'text', localized: true }, + { + name: 'items', + type: 'array', + admin: { components: rowLabel('link.label', 'Link'), initCollapsed: true }, + fields: [buildLinkField({ appearances: false })], + labels: { plural: 'Links', singular: 'Link' }, + }, + ], + labels: { plural: 'Columns', singular: 'Column' }, + maxRows: 4, + }, + { name: 'note', type: 'textarea', localized: true }, + ], + hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] }, +} +``` + +### `src/globals/Header.ts` + +```ts +import type { GlobalConfig } from 'payload' + +import { buildGlobalRevalidateHook, buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit' +import { revalidatePath } from 'next/cache' + +/** ipal-nav: menu with one submenu level, a CTA button, the mobile menu label. Logo comes from Site settings. */ +export const Header: GlobalConfig = { + slug: 'header', + access: { read: () => true }, + fields: [ + { + name: 'navItems', + type: 'array', + admin: { components: rowLabel('link.label', 'Menu item'), initCollapsed: true }, + fields: [ + buildLinkField({ appearances: false }), + { + name: 'subItems', + type: 'array', + admin: { components: rowLabel('link.label', 'Submenu item'), initCollapsed: true }, + fields: [buildLinkField({ appearances: false })], + labels: { plural: 'Submenu', singular: 'Submenu item' }, + maxRows: 10, + }, + ], + labels: { plural: 'Menu items', singular: 'Menu item' }, + maxRows: 8, + }, + buildLinksField({ maxRows: 1 }), + { name: 'menuLabel', type: 'text', admin: { description: 'Accessible label of the mobile menu button, e.g. "Menu".' }, localized: true }, + ], + hooks: { afterChange: [buildGlobalRevalidateHook({ revalidatePath })] }, +} +``` + +## Blocks + +Rules: docs/block-library.md. + +| File | What it shows | +|---|---| +| `src/blocks/configs.ts` | the block library turned on in the Pages layout (libraryBlocks) (below) | +| `src/blocks/registry.ts` | createBlockRegistry with next/image, next/link, the form action and contact details (below) | + +### `src/blocks/configs.ts` + +```ts +import { libraryBlocks, type LibraryBlocksOptions } from '@intecion/ipal-kit/blocks' + +/** + * Every library block is on, because the reference site shows all of them (the Blocks showcase page). + * A client site turns on only what its site map needs (docs/block-library.md "Setup"). + */ +export const blockOptions = { + contact: true, + cta: true, + entryList: { + collections: [ + { label: { en: 'Blog posts', pl: 'Wpisy' }, value: 'posts' }, + { label: { en: 'Case studies', pl: 'Realizacje' }, value: 'caseStudies' }, + ], + }, + faq: true, + featureGrid: true, + gallery: true, + hero: true, + logos: true, + pricing: true, + richText: true, + stats: true, + steps: true, + team: true, + testimonials: true, + textMedia: true, +} satisfies LibraryBlocksOptions + +export const pageBlocks = [...libraryBlocks(blockOptions)] +``` + +### `src/blocks/registry.ts` + +```ts +import { createBlockRegistry } from '@intecion/ipal-kit/blocks/rsc' +import Image from 'next/image' +import Link from 'next/link' + +import { sendForm } from '@/app/(frontend)/[locale]/actions' +import { formClasses } from '@/components/forms/formClasses' +import * as content from '@/lib/content' +import { getCompany } from '@/lib/globals' + +/** Contact details beside the contact form — from the Company global, never from code. */ +async function contactDetails(locale: string) { + const company = await getCompany(locale) + const labels = locale === 'pl' ? { address: 'Adres', email: 'E-mail', hours: 'Godziny', phone: 'Telefon' } : { address: 'Address', email: 'E-mail', hours: 'Hours', phone: 'Phone' } + const address = [company.address?.street, [company.address?.postalCode, company.address?.city].filter(Boolean).join(' ')].filter(Boolean).join(', ') + return [ + ...(company.phone ? [{ href: `tel:${company.phone.replace(/[^\d+]/g, '')}`, label: labels.phone, value: company.phone }] : []), + ...(company.email ? [{ href: `mailto:${company.email}`, label: labels.email, value: company.email }] : []), + ...(address ? [{ label: labels.address, value: address }] : []), + ...(company.hours ? [{ label: labels.hours, value: company.hours }] : []), + ] +} + +/** blockType → component for every library block, bound to lib/content (docs/block-library.md "The registry"). */ +export const blockRegistry = createBlockRegistry(content, { + contactDetails, + formClassNames: formClasses, + Image, + Link, + noSnippet: ['cta'], // the same call to action closes most pages + sendForm, +}) +``` + +## Design tokens + +Rules: docs/design-tokens.md. + +| File | What it shows | +|---|---| +| `src/app/(frontend)/[locale]/design/page.tsx` | the design-token styleguide page (noindex) (below) | +| `src/components/design/TokenPanel.tsx` | one styleguide panel built from IPAL_TOKENS | +| `src/design/tokens.css` | GENERATED by `pnpm tokens` from tokens.ts — never edited by hand (below) | +| `src/design/tokens.ts` | the brand: the ONLY file edited to rebrand the site (below) | + +### `src/app/(frontend)/[locale]/design/page.tsx` + +```tsx +import type { Metadata } from 'next' + +import { Container } from '@intecion/ipal-kit/blocks/rsc' + +import { TokenPanel } from '@/components/design/TokenPanel' +import { i18nConfig } from '@/i18n.config' + +// The styleguide: every design token, in the current theme and in dark side by side. Technical page — +// noindex, not in the sitemap (it is not a Pages document), labels are token names (AGENTS.md → Project decisions). +export const metadata: Metadata = { robots: { follow: false, index: false }, title: 'Design tokens' } + +export default function DesignPage() { + return ( + +
+

ipal-kit

+

Design tokens

+

+ src/design/tokens.ts → pnpm tokens → src/design/tokens.css. The left panel follows the page theme; the right one is always dark + (data-theme="dark" on the panel). The bottom row is the inverse scope (data-surface="inverse"). +

+
+
+ + +
+ +
+ ) +} + +export const generateStaticParams = () => i18nConfig.locales.map(({ code }) => ({ locale: code })) +``` + +### `src/design/tokens.css` + +```css +/* + * GENERATED by `ipal-tokens` from src/design/tokens.ts — do not edit; change src/design/tokens.ts and run + * `pnpm exec ipal-tokens`. Import it in styles.css after @intecion/ipal-kit/tokens.css (and tailwind.css). + */ + +:root { + --ipal-bg: oklch(0.985 0.006 85); + --ipal-primary: oklch(0.47 0.09 160); + --ipal-surface-muted: oklch(0.955 0.012 85); + --ipal-accent: oklch(0.55 0.13 50); + --ipal-link-inverse: oklch(0.82 0.08 160); + --ipal-fw-heading: 600; + --ipal-radius: 0.25rem; + --ipal-radius-card: 0.25rem; +} + +:root[data-theme="dark"] { + --ipal-bg: oklch(0.2 0.01 160); + --ipal-primary: oklch(0.74 0.09 160); + --ipal-surface-muted: oklch(0.25 0.012 160); + --ipal-accent: oklch(0.76 0.12 55); + --ipal-accent-text: oklch(0.18 0.02 55); + --ipal-link-inverse: oklch(0.42 0.09 160); + --ipal-primary-text: oklch(0.18 0.02 160); +} +``` + +### `src/design/tokens.ts` + +```ts +// src/design/tokens.ts — the ONLY file edited to rebrand the site (docs/design-tokens.md). +// After every change: `pnpm tokens` → writes src/design/tokens.css (commit it) and prints the WCAG contrast check. +// Leave out anything the brand does not change: the neutral defaults in @intecion/ipal-kit/tokens.css apply. +import { defineTokens } from '@intecion/ipal-kit/tokens' + +export const tokens = defineTokens({ + theme: 'both', // must match Site settings → Theme (seeded: system, toggle on) + fluid: 'wide', + color: { + light: { + primary: 'oklch(0.47 0.09 160)', // deep sage green — the studio's brand colour (DESIGN.md §2) + accent: 'oklch(0.55 0.13 50)', // terracotta, for highlights only + 'link-inverse': 'oklch(0.82 0.08 160)', // links and accents on inverted sections + bg: 'oklch(0.985 0.006 85)', // warm paper white + 'surface-muted': 'oklch(0.955 0.012 85)', + }, + dark: { + primary: 'oklch(0.74 0.09 160)', + 'primary-text': 'oklch(0.18 0.02 160)', // dark text on the lighter dark-mode primary + accent: 'oklch(0.76 0.12 55)', + 'accent-text': 'oklch(0.18 0.02 55)', + 'link-inverse': 'oklch(0.42 0.09 160)', + bg: 'oklch(0.2 0.01 160)', + 'surface-muted': 'oklch(0.25 0.012 160)', + }, + }, + font: { fwHeading: 600 }, + radius: { card: '0.25rem', control: '0.25rem' }, // "sharp": architectural, precise +}) +``` + +## Data layer + +Rules: AGENT.md §3, PROGRAMISTA §2.7. + +| File | What it shows | +|---|---| +| `src/lib/content.ts` | createContentHelpers: the ONLY access to Payload, routes, links, JSON-LD | +| `src/lib/globals.ts` | cached getters for the project's own globals (below) | + +### `src/lib/globals.ts` + +```ts +import { cache } from 'react' + +import type { Locale } from '@/i18n.config' + +import { getCachedPayload } from './content' + +/** Cached getters for the project's own globals — the layout passes them down as props (ipal-nav). */ +export const getHeader = cache(async (locale: string) => (await getCachedPayload()).findGlobal({ slug: 'header', depth: 1, locale: locale as Locale })) +export const getFooter = cache(async (locale: string) => (await getCachedPayload()).findGlobal({ slug: 'footer', depth: 1, locale: locale as Locale })) +export const getCompany = cache(async (locale: string) => (await getCachedPayload()).findGlobal({ slug: 'company', locale: locale as Locale })) +``` + +## Layout and components + +Rules: AGENT.md §6.8, ipal-nav, ipal-form. + +| File | What it shows | +|---|---| +| `src/app/(frontend)/[locale]/[[...slug]]/page.tsx` | the catch-all page: createPageRoute, ISR, redirects, maintenance, the language switcher links (below) | +| `src/app/(frontend)/[locale]/actions.ts` | the ONE form server action (createSubmitAction) (below) | +| `src/app/(frontend)/[locale]/layout.tsx` | the locale layout: next/font slots, SiteProviders (theme, lightbox, consent), header, footer | +| `src/app/(frontend)/[locale]/not-found.tsx` | 404 from the panel (createNotFoundPage) (below) | +| `src/app/(frontend)/[locale]/notFoundView.ts` | the 404 view loaded only on a 404 (server action) (below) | +| `src/app/(frontend)/styles.css` | the standard styles.css: Tailwind, fluid-wide, tokens, preset, brand (below) | +| `src/components/forms/formClasses.ts` | the ONE place forms are styled, token utilities only (below) | +| `src/components/layout/Footer.tsx` | footer: columns, company data, legal links from System pages, NoSnippet | +| `src/components/layout/Header.tsx` | header: logo from Site settings, resolveNav menu, language and theme switch, CTA | +| `src/components/layout/LocaleSwitcher.tsx` | the language switcher in a client wrapper (function props) (below) | +| `src/components/layout/MobileNav.tsx` | the mobile menu (client, open state only) (below) | + +### `src/app/(frontend)/[locale]/[[...slug]]/page.tsx` + +```tsx +import { AlternateLinksUpdater } from '@intecion/ipal-kit/client' +import { createPageRoute } from '@intecion/ipal-kit/rsc' +import { notFound, permanentRedirect, redirect } from 'next/navigation' + +import { blockRegistry } from '@/blocks/registry' +import * as content from '@/lib/content' + +// ISR — a literal in the file (Next reads it statically) +export const revalidate = 3600 + +// Archive pages (Blog, Case studies) list their entries with an entry list block in their own layout, +// so the editor decides where the list goes; entries render their own `layout` like pages. +const route = createPageRoute(content, { + blocks: blockRegistry, + notFound, + permanentRedirect, + redirect, // Site settings → Maintenance: hidden pages → homepage with a notice + render: async ({ blocks, locale, segments }) => { + // This page's address in every language → the language switcher never leads to a 404 + const { alternates } = await content.generatePageMetadata(locale, segments) + const links = Object.fromEntries( + Object.entries(alternates?.languages ?? {}) + .filter(([code]) => code !== 'x-default') + .map(([code, href]) => [code, new URL(String(href)).pathname]), + ) + return ( + <> + + {blocks} + + ) + }, +}) + +export default route.Page +export const generateMetadata = route.generateMetadata +export const generateStaticParams = route.generateStaticParams +``` + +### `src/app/(frontend)/[locale]/actions.ts` + +```ts +'use server' +// ONE server action for every builder form: honeypot → client IP (IPAL_IP_HEADER) → submitForm +// (rate limit, Turnstile, validation, consent, save) → the message from Notifications. +import { createSubmitAction } from '@intecion/ipal-kit/server' +import { headers } from 'next/headers' + +import { getCachedPayload } from '@/lib/content' + +export const sendForm = createSubmitAction({ getCachedPayload, headers }) +``` + +### `src/app/(frontend)/[locale]/not-found.tsx` + +```tsx +import { createNotFoundPage } from '@intecion/ipal-kit/rsc' + +import * as content from '@/lib/content' + +import { loadNotFoundView } from './notFoundView' + +export default createNotFoundPage(content, { load: loadNotFoundView }) +``` + +### `src/app/(frontend)/[locale]/notFoundView.ts` + +```ts +'use server' +import { renderNotFoundView } from '@intecion/ipal-kit/rsc' + +import { blockRegistry } from '@/blocks/registry' +import * as content from '@/lib/content' + +/** 404 content from the panel (System pages → 404), in the URL's language. */ +export async function loadNotFoundView(locale: string) { + return renderNotFoundView(content, { blocks: blockRegistry }, locale) +} +``` + +### `src/app/(frontend)/styles.css` + +```css +/* The same on every site (design-tokens.md) — no brand values here; the brand lives in src/design/tokens.ts */ +@import "tailwindcss"; +@import "@intecion/ipal-kit/fluid-wide.css"; +@import "@intecion/ipal-kit/tokens.css"; +@import "@intecion/ipal-kit/tailwind.css"; +@import "../../design/tokens.css"; +@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js"; +``` + +### `src/components/forms/formClasses.ts` + +```ts +import type { BuilderFormClassNames } from '@intecion/ipal-kit/client' +import { buttonClass } from '@intecion/ipal-kit/blocks/rsc' + +const control = + 'w-full rounded-control border border-border bg-surface px-3 py-2 text-fg placeholder:text-fg-muted focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus' + +/** The ONLY place panel forms are styled (ipal-form). Token utilities only — no hex, no dark:. */ +export const formClasses: BuilderFormClassNames = { + actions: 'flex flex-wrap gap-3', + back: buttonClass('secondary'), + checkboxLabel: 'flex items-start gap-2 text-fg', + choice: 'flex items-center gap-2', + choices: 'grid gap-2', + error: 'mt-1 text-sm text-danger', + field: 'col-span-12', + fieldHalf: 'md:col-span-6', + fields: 'grid grid-cols-12 gap-4', + form: 'grid gap-6', + formError: 'rounded-control bg-danger-surface p-3 text-danger', + input: control, + label: 'mb-1 block font-medium text-fg-strong', + legend: 'mb-1 font-medium text-fg-strong', + progress: 'text-sm text-fg-muted', + select: control, + step: 'grid gap-4', + stepDescription: 'text-fg-muted', + stepTitle: 'font-heading text-h4 text-fg-strong', + submit: buttonClass('primary'), + success: 'rounded-card bg-success-surface p-6 text-fg', + textarea: `${control} min-h-32`, +} +``` + +### `src/components/layout/LocaleSwitcher.tsx` + +```tsx +'use client' +import type { I18nConfig } from '@intecion/ipal-kit' + +import { LanguageSwitcher } from '@intecion/ipal-kit/client' + +/** Client wrapper: renderLabel is a function, which a server component cannot pass to a client component. */ +export function LocaleSwitcher({ config, locale }: { config: I18nConfig; locale: string }) { + return ( + l.code.toUpperCase()} + /> + ) +} +``` + +### `src/components/layout/MobileNav.tsx` + +```tsx +'use client' +import type { NavItem } from '@intecion/ipal-kit' + +import Link from 'next/link' +import { useEffect, useState } from 'react' + +/** Mobile menu: open state only, data via props (ipal-nav). Esc closes it. */ +export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) { + const [open, setOpen] = useState(false) + useEffect(() => { + if (!open) {return} + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false) + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [open]) + return ( +
+ + {open ? ( +
    + {items.map((item) => ( +
  • + setOpen(false)}> + {item.label} + +
  • + ))} +
+ ) : null} +
+ ) +} +``` + +## SEO, GEO and ops routes + +Rules: AGENT.md §0b, ipal-setup stages 7–8. + +| File | What it shows | +|---|---| +| `src/app/api/csp-report/route.ts` | CSP violation reports (below) | +| `src/app/api/health/route.ts` | Coolify health check (below) | +| `src/app/api/mcp/route.ts` | public MCP server (GEO) (below) | +| `src/app/indexnow-key.txt/route.ts` | IndexNow key (below) | +| `src/app/llms-full.txt/route.ts` | llms-full.txt (GEO) (below) | +| `src/app/llms.txt/route.ts` | llms.txt (GEO) (below) | +| `src/app/manifest.ts` | web app manifest from Site settings (below) | +| `src/app/md/[locale]/[[...slug]]/route.ts` | every page as Markdown (GEO) (below) | +| `src/app/robots.ts` | robots.txt with the AI crawler policy from the panel (below) | +| `src/app/sitemap.xml/route.ts` | the one sitemap (below) | + +### `src/app/api/csp-report/route.ts` + +```ts +import { createCspReportRoute } from '@intecion/ipal-kit' + +// CSP violation reports → `[csp]` lines in the logs (security.md) +export const POST = createCspReportRoute() +``` + +### `src/app/api/health/route.ts` + +```ts +// Coolify health check: 200, or 503 without the database +export { healthRoute as GET } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +### `src/app/api/mcp/route.ts` + +```ts +// GEO: public MCP server (read-only) +export { mcpGET as GET, mcpPOST as POST } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +### `src/app/indexnow-key.txt/route.ts` + +```ts +// IndexNow key (Site integrations or INDEXNOW_KEY) +export { indexNowKeyRoute as GET } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +### `src/app/llms-full.txt/route.ts` + +```ts +// GEO: full page content for AI assistants +export { llmsFullRoute as GET } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +### `src/app/llms.txt/route.ts` + +```ts +// GEO: site summary for AI assistants +export { llmsRoute as GET } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +### `src/app/manifest.ts` + +```ts +export { manifest as default } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +### `src/app/md/[locale]/[[...slug]]/route.ts` + +```ts +// GEO: every page as Markdown (noindex, canonical to the HTML) +export { markdownRoute as GET } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +### `src/app/robots.ts` + +```ts +// robots.txt from code + the AI crawler policy from Site settings → Search engines +export { getRobots as default } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +### `src/app/sitemap.xml/route.ts` + +```ts +// sitemap: one only (no sitemap.ts), styled by the plugin +export { sitemapRoute as GET } from '@/lib/content' +export const dynamic = 'force-dynamic' +``` + +## Seeds + +Rules: docs/seeding.md, docs/block-library.md "Page templates". + +| File | What it shows | +|---|---| +| `src/seed/base.ts` | BASE seed: templates, system pages, navigation, banner texts — kept by the starter | +| `src/seed/demo.ts` | DEMO seed: the made-up company in pl and en — dropped by the starter | +| `src/seed/forms.ts` | forms seed: fields, confirmation, e-mail to the company and to the sender | +| `src/seed/index.ts` | the seed entry: layers, SEED_ONLY, the inbox rule | +| `src/seed/lib.ts` | seed value helpers (both languages side by side, rich text) (below) | +| `src/seed/media.ts` | generated placeholder images (no stock photos) | +| `src/seed/showcase.ts` | the Blocks showcase page from blockLibraryManifest (every variant, inverted too) | + +### `src/seed/lib.ts` + +```ts +/** Seed value helpers — every text written once, both languages side by side (docs/seeding.md). */ +export type L = { en: string; pl: string } + +export const tx = (pl: string, en: string): L => ({ en, pl }) + +const textNode = (t: string) => ({ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: t, version: 1 }) +const paragraph = (t: string) => ({ type: 'paragraph', children: [textNode(t)], direction: 'ltr', format: '', indent: 0, textFormat: 0, version: 1 }) +const heading = (t: string, tag: 'h2' | 'h3') => ({ type: 'heading', children: [textNode(t)], direction: 'ltr', format: '', indent: 0, tag, version: 1 }) +const root = (children: unknown[]) => ({ root: { type: 'root', children, direction: 'ltr', format: '', indent: 0, version: 1 } }) + +/** Rich text from paragraphs; a line starting with "## " is an h2, "### " an h3. One value per locale. */ +export function rich(pl: string[], en: string[]) { + const doc = (lines: string[]) => + root(lines.map((l) => (l.startsWith('### ') ? heading(l.slice(4), 'h3') : l.startsWith('## ') ? heading(l.slice(3), 'h2') : paragraph(l)))) + return { en: doc(en), pl: doc(pl) } +} + +/** Plain text (blank-line paragraphs, single newlines as line breaks) → rich text, as form-builder messages expect. */ +export function richMessage(text: string) { + return root( + text.split(/\n{2,}/).map((para) => ({ + ...paragraph(''), + children: para.split('\n').flatMap((line, i) => [...(i ? [{ type: 'linebreak', version: 1 }] : []), textNode(line)]), + })), + ) +} + +export const header = (heading: L, intro?: L, eyebrow?: L) => ({ ...(eyebrow ? { eyebrow } : {}), heading, ...(intro ? { intro } : {}) }) + +/** A button / link to a page by its default-locale (pl) slug. */ +export const pageLink = (label: L, slug: string, appearance: 'link' | 'primary' | 'secondary' = 'primary') => ({ + link: { type: 'internal', appearance, label, page: { $page: slug } }, +}) +``` + +## Smoke tests + +Rules: AGENT.md §8a. + +| File | What it shows | +|---|---| +| `e2e/create-test-admin.ts` | a test admin with a known TOTP secret (local / CI database only) (below) | +| `e2e/smoke.spec.ts` | the smoke tests every release must pass: pages, showcase, forms, sitemap, SEO/GEO, headers, consent, 2FA | +| `e2e/totp.ts` | RFC 6238 code generator for the 2FA sign-in in the smoke test (below) | + +### `e2e/create-test-admin.ts` + +```ts +/** + * Creates (or resets) the smoke-test admin with a known TOTP secret, so e2e/smoke.spec.ts signs in through + * the real 2FA screen instead of skipping it. LOCAL / CI database only: + * pnpm payload run e2e/create-test-admin.ts + * Values come from E2E_ADMIN_EMAIL / E2E_ADMIN_PASSWORD / E2E_TOTP_SECRET (.env.example). Not a seed: seeds + * never create users (docs/seeding.md). + */ +import config from '@payload-config' +import { isLocalDatabase } from '@intecion/ipal-kit/seed' +import { getPayload } from 'payload' + +const { E2E_ADMIN_EMAIL: email, E2E_ADMIN_PASSWORD: password, E2E_TOTP_SECRET: totpSecret } = process.env +if (!email || !password || !totpSecret) {throw new Error('Set E2E_ADMIN_EMAIL, E2E_ADMIN_PASSWORD and E2E_TOTP_SECRET (.env.example).')} +if (process.env.NODE_ENV === 'production' && !process.env.CI) {throw new Error('Refusing: NODE_ENV=production outside CI.')} +if (!isLocalDatabase(process.env.DATABASE_URI ?? '')) {throw new Error('Refusing: DATABASE_URI is not a local database.')} + +const payload = await getPayload({ config }) +const data = { email, hasTotp: true, password, roles: ['admin'], totpSecret } +const found = await payload.find({ collection: 'users', limit: 1, overrideAccess: true, where: { email: { equals: email } } }) +if (found.docs[0]) { + await payload.update({ id: found.docs[0].id, collection: 'users', data: data as never, overrideAccess: true }) +} else { + await payload.create({ collection: 'users', data: data as never, overrideAccess: true }) +} +console.log(`[e2e] test admin ready: ${email}`) +process.exit(0) +``` + +### `e2e/totp.ts` + +```ts +import { createHmac } from 'node:crypto' + +/** RFC 6238 TOTP (SHA-1, 6 digits, 30 s) — the code an authenticator app shows for `secret` (base32). */ +export function totp(secret: string, now = Date.now()): string { + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' + let bits = '' + for (const ch of secret.replace(/=+$/, '').toUpperCase()) {bits += alphabet.indexOf(ch).toString(2).padStart(5, '0')} + const key = Buffer.from((bits.match(/.{8}/g) ?? []).map((b) => parseInt(b, 2))) + const counter = Buffer.alloc(8) + counter.writeBigUInt64BE(BigInt(Math.floor(now / 1000 / 30))) + const hmac = createHmac('sha1', key).update(counter).digest() + const offset = hmac[hmac.length - 1] & 0xf + const code = (hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000 + return code.toString().padStart(6, '0') +} +``` diff --git a/docs/agent/skills/ipal-block/SKILL.md b/docs/agent/skills/ipal-block/SKILL.md index 91c9329..087eb45 100644 --- a/docs/agent/skills/ipal-block/SKILL.md +++ b/docs/agent/skills/ipal-block/SKILL.md @@ -14,6 +14,8 @@ One section per use of this skill. Details and ready code: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6. ## 0. Library block first (docs/block-library.md) +See every block and variant rendered (also on `muted` and `inverted`) on the reference site's Blocks page — seed +`src/seed/showcase.ts` in `docs/agent/reference-site/INDEX.md`; wiring: `src/blocks/configs.ts`, `src/blocks/registry.ts` there. The plugin ships 15 blocks: `hero`, `textMedia`, `featureGrid`, `cta`, `richText`, `faq`, `contact`, `gallery`, `testimonials`, `stats`, `steps`, `logos`, `team`, `pricing`, `entryList` (variants: `blockLibraryManifest`). 1. Does a library block or one of its variants fit the section? → turn it on in `src/blocks/configs.ts` diff --git a/docs/agent/skills/ipal-reference/SKILL.md b/docs/agent/skills/ipal-reference/SKILL.md index 0a9bf7c..15c5e0b 100644 --- a/docs/agent/skills/ipal-reference/SKILL.md +++ b/docs/agent/skills/ipal-reference/SKILL.md @@ -6,6 +6,8 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip # ipal-reference ## How to use +- **A working example of every row** is in the reference site: `docs/agent/reference-site/INDEX.md` (file → what it + shows; wiring files in full). - **Look here first**, then at the code. Looking for a function → `grep -n "" resources/api.md` (`resources/api.md` — every export: import, what it does). Module description: `node_modules/@intecion/ipal-kit/docs/.md` (the "details" column). diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index ecbf46f..35fde74 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -8,6 +8,10 @@ description: Complete start-to-finish install of @intecion/ipal-kit in a Payload **Goal: the MANDATORY SET from AGENT.md §0b (18 items), with nothing left "to discover".** Stage 11 checks everything; you do not finish with gaps (exception: an `ipal-audit-skip:` line from a client decision, AGENT.md §0b). +**Canonical code:** every stage's files exist, wired and tested, in the reference site — +`node_modules/@intecion/ipal-kit/docs/agent/reference-site/INDEX.md` (AGENT.md "Reference site"). When a snippet here +and the reference site differ, the reference site is the current one (and the difference is a plugin bug to report). + **Stage 0 first: ask the architecture questions and wait for the answers** (below). After that: **one stage = one commit** (`git commit -m "ipal-setup : "`), no waiting for an OK between stages (AGENT.md §0a). Missing *content data* (keys, IDs, company data) does not block you: wire the code, the value goes into `.env`/the panel diff --git a/docs/agent/skills/ipal-site/SKILL.md b/docs/agent/skills/ipal-site/SKILL.md index f8a832f..b56f016 100644 --- a/docs/agent/skills/ipal-site/SKILL.md +++ b/docs/agent/skills/ipal-site/SKILL.md @@ -45,7 +45,9 @@ decision on that part; no hand-built replacement, no silent workaround. **Code r decision (AGENT §0a) and on a plugin gap (ipal-plugin-gap — report, wait for the owner). ## Phase 1 — Foundation -- New project → **ipal-setup** (all of it, with `ipal-skills`, `AGENTS.md`). +- New project → **ipal-setup** (all of it, with `ipal-skills`, `AGENTS.md`). Every file you wire has its canonical + version in the reference site: `node_modules/@intecion/ipal-kit/docs/agent/reference-site/INDEX.md` (AGENT.md + "Reference site") — copy the pattern, change only the content. - Existing project on an older ipal-kit → **ipal-upgrade** before anything else. - Exit: `pnpm build` passes, `/admin` works, `ipal-audit --quick` = 0 errors — **including zero "missing: …"**, i.e. the full AGENT.md §0b set (SEO, GEO, R2, Turnstile, @@ -66,6 +68,8 @@ decision on that part; no hand-built replacement, no silent workaround. **Code r ## Phase 3 — Navigation and company data → **ipal-nav** ## Phase 4 — Sections → **ipal-block** for every block +The reference site's Blocks page (`/pl/bloki` on the reference site, seed `src/seed/showcase.ts` in the index) shows +every library block in every variant, also on the inverted background — pick the closest block × variant there. Library blocks need no code: `libraryBlocks(blockOptions)` in the Pages layout and `createBlockRegistry(content, { Image, Link, sendForm })` in `src/blocks/registry.ts` (docs/block-library.md "Setup"). Change looks through `classNames` / `ui`, never by copying a block; own it completely only with `ipal-blocks eject `. @@ -116,6 +120,8 @@ title/description of every page (≤ 60 / ≤ 155 characters, unique); `aiSummar keep the auto-fill or fix it when the summary is weak. ## Phase 8 — Design +The reference site's `/design` page (`src/components/design/TokenPanel.tsx` in the index) is the styleguide to reproduce: +every token from `IPAL_TOKENS`, light and dark, the inverse scope. The design-token standard (AGENT.md §6.11, `design-tokens.md`): `DESIGN.md` exists → its values go into `src/design/tokens.ts` (template `.agents/skills/ipal-setup/resources/tokens.ts`) → `pnpm exec ipal-tokens` (no ✗ contrast rows). None → copy the `DESIGN.md` template, keep the neutral defaults + the brand primary, and recommend diff --git a/docs/agent/skills/ipal-upgrade/SKILL.md b/docs/agent/skills/ipal-upgrade/SKILL.md index d7ab9ee..8b477c6 100644 --- a/docs/agent/skills/ipal-upgrade/SKILL.md +++ b/docs/agent/skills/ipal-upgrade/SKILL.md @@ -197,6 +197,9 @@ and the browser tab shows the same separator. consent: `pnpm exec ipal-skills --external`. ## 2. Inventory (no code changes) +**What changed for projects** between your old and new plugin version is exactly the reference site's diff — +`git diff v v -- reference/` in the ipal-kit repo (or the two `docs/agent/reference-site/INDEX.md` files): +every file a project must touch, already done once and tested in the plugin's CI. For **every** item in the PROGRAMISTA §6 table show evidence (grep / file) of whether it applies to the project. Run the **ipal-audit** skill (`--quick`) and attach the result. Result: a prioritised to-do list — carry it out right away. Stop diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 19e318a..f28189f 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -736,6 +736,28 @@ commit). `prepare` (`pnpm build`) builds the package on install from git and on `typecheck` and `lint` are **not** in `prepublishOnly` — before a commit: `pnpm typecheck && pnpm lint && pnpm test:int` (CI in `.gitea/workflows/ci.yml` runs typecheck, lint, test:int and build on push and PR). +### 8.1b The reference site (`reference/`) — part of every release + +`reference/` is one complete client site on the plugin ("Example Studio", made up; not in the npm package). Agents copy +from it (`docs/agent/reference-site/INDEX.md`, shipped) and the project starter is generated from it. A release is not +done until the reference site uses it. Before `npm version`: + +- [ ] Everything new or changed in this release is used in `reference/` — a new option set, a route wired, a block or + variant shown (the Blocks page picks up new blocks and variants from `blockLibraryManifest` by itself). +- [ ] `reference/` upgraded the way `ipal-upgrade` tells client projects; the upgrade notes are tried here first. +- [ ] Local run green: `pnpm build` (plugin) → `pnpm --dir reference install --ignore-workspace` (refreshes the injected + copy) → in `reference/`: `pnpm generate:types && pnpm generate:importmap` (no diff), `pnpm typecheck`, + `pnpm seed` on a throwaway MongoDB, `pnpm build`, `ALLOW_LOCAL_MEDIA=1 PORT=3100 pnpm start`, + `pnpm payload run e2e/create-test-admin.ts`, `pnpm test:e2e`. +- [ ] `pnpm reference:index` → `docs/agent/reference-site/INDEX.md` committed (`test/referenceIndex.test.ts` fails otherwise; + a new file in `reference/` needs its line in `scripts/reference-index.mjs` → `DESCRIPTIONS`). +- [ ] CI job `reference` green (`.gitea/workflows/ci.yml`), the starter check included once `ipal-kit create` ships. +- [ ] Tag `v` pushed — the index links to `reference/` at that tag, and `git diff v v -- reference/` is + the upgrade guide for projects. + +The site uses the plugin as `file:..` with `dependenciesMeta.injected`, so the plugin's peers (Payload, React, +`@payloadcms/ui`) resolve from the site — a plain `link:..` loads two copies of `@payloadcms/ui` and the admin crashes. + ### 8.1a Plugin tests `test/` (outside `src`, not shipped in `dist`), vitest: `pnpm test:int` (once), `pnpm test:watch`. diff --git a/package.json b/package.json index 0b1441e..2159b65 100644 --- a/package.json +++ b/package.json @@ -108,6 +108,7 @@ "lint:fix": "eslint ./src ./test --fix", "prepare": "pnpm build", "prepublishOnly": "pnpm clean && pnpm build && pnpm test:int", + "reference:index": "node scripts/reference-index.mjs", "test": "pnpm test:int && pnpm test:e2e", "test:e2e": "playwright test", "test:int": "vitest run", diff --git a/reference/.agents/skills/ipal-audit/SKILL.md b/reference/.agents/skills/ipal-audit/SKILL.md new file mode 100644 index 0000000..2498a0a --- /dev/null +++ b/reference/.agents/skills/ipal-audit/SKILL.md @@ -0,0 +1,57 @@ +--- +name: ipal-audit +description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — the mandatory feature set (SEO, JSON-LD, llms.txt, Markdown, MCP, R2, Turnstile, panel forms, consent, 2FA, health, env, security headers, X-Powered-By, CSP), forbidden replacements (own forms, nodemailer, reCAPTCHA, hand-written JSON-LD), hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project. +--- + +# ipal-audit + +The checks from AGENT.md §11 as a script — always the same, no interpretation. + +## Steps + +1. From the project root, run: + ```bash + bash .agents/skills/ipal-audit/scripts/audit.sh --quick # while working + bash .agents/skills/ipal-audit/scripts/audit.sh # before "done" (+ tsc + build) + ``` + Options: `--help`. Do not read the script source — the output is enough. +2. Show the user the **full output** (summary + list of violations). +3. Fix every `[ERROR]` or — if it is a deliberate exception — add a code comment + with the reason and list it in your answer. + Each violation names a section in + `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` — read it before fixing. +4. `[WARNING]` — assess it and tell the user what to do about it; do not fix it + blindly (e.g. `searchParams` is OK in a paginated archive route). +5. Run again until the output is `0 error(s)`. + +## "missing: …" — the mandatory set (AGENT.md §0b) +Every `[ERROR] missing: X` is an item of the set that the code lacks. Wire it +following the hint (PROGRAMISTA §2) — do not ask whether it is needed. The only exception: +a client decision recorded in `AGENTS.md` as `ipal-audit-skip: — ` (keys +in AGENT.md §0b). Never add that line yourself just to make the audit pass. + +## Design tokens (AGENT.md §6.11) +The script checks: hex in classes and inline styles (error), `dark:` on colour utilities and `var(--color-…)` in +classes (warnings), `styles.css` without `@intecion/ipal-kit/tokens.css` (warning — a site not yet migrated), +next/font in `--font-body` with the preset (warning), and with `src/design/tokens.ts`: no `DESIGN.md` (warning) and +`ipal-tokens --check` — a stale `src/design/tokens.css` or a WCAG AA contrast failure is an error. + +## What the script does not check (do it by hand) + +- **Editor test** (AGENT.md §11): every text, image, button, section, + menu, footer and SEO field can be changed in the panel, in every language. +- **Cookie consent:** in Network, before accepting, there are no requests to + google-analytics / googletagmanager (except Consent Mode), facebook.net, + clarity.ms, licdn, tiktok. +- **Content**: fallbacks contain no client data (`|| 'Firma X'`). +- **Response headers** (on a running build — `pnpm build && pnpm start`, or the deployed domain): + ```bash + U=http://localhost:3000 + for p in /pl /admin /api/health; do echo "== $p"; curl -sI "$U$p" | grep -iE 'x-powered-by|content-security-policy'; done + ``` + `x-powered-by` anywhere → ERROR (`withSecurityConfig`, security.md → "X-Powered-By"). No + `content-security-policy` / `content-security-policy-report-only` on `/pl` and `/admin` → WARNING (CSP not + rolled out). Report-only for more than a few weeks with clean reports → WARNING (switch to `mode: 'enforce'`). + Then open `/pl` and `/admin` in the browser: CSP lines in the console = missing sources (flags / `extra`). + +Do not say "done" until the full audit (without `--quick`) has no errors. diff --git a/reference/.agents/skills/ipal-audit/resources/smoke.spec.template.ts b/reference/.agents/skills/ipal-audit/resources/smoke.spec.template.ts new file mode 100644 index 0000000..12005ae --- /dev/null +++ b/reference/.agents/skills/ipal-audit/resources/smoke.spec.template.ts @@ -0,0 +1,78 @@ +/** + * Smoke tests of a client site (Playwright) — the few things that must never + * break: every language's homepage, a real 404, the form end to end, the + * language switch, the GEO routes. Copy to tests/smoke.spec.ts and run against + * a production build: + * + * pnpm add -D @playwright/test && pnpm exec playwright install chromium + * pnpm build && pnpm start & + * BASE_URL=http://localhost:3000 pnpm exec playwright test tests/smoke.spec.ts + * + * Content-agnostic on purpose: it reads locales from the sitemap and finds the + * form by its renderer, so it survives editors changing texts in the panel. + * Turnstile: run with the test keys in Site Integrations (1x00000000000000000000AA / + * 1x0000000000000000000000000000000AA) or without keys. + */ +import { expect, test } from '@playwright/test' + +const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '') + +async function sitemapUrls(): Promise { + const xml = await (await fetch(`${BASE}/sitemap.xml`)).text() + return [...xml.matchAll(/\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/^https?:\/\/[^/]+/, BASE)) +} + +test('every sitemap URL answers 200 with a title and one h1', async ({ page }) => { + const urls = (await sitemapUrls()).slice(0, 30) + expect(urls.length).toBeGreaterThan(0) + for (const url of urls) { + const res = await page.goto(url) + expect(res?.status(), url).toBe(200) + await expect(page, url).toHaveTitle(/\S/) + expect(await page.locator('h1').count(), `${url}: exactly one h1`).toBe(1) + } +}) + +test('unknown URL is a real 404', async ({ request }) => { + const res = await request.get(`${BASE}/this-page-does-not-exist-${Date.now()}`, { maxRedirects: 5 }) + expect(res.status()).toBe(404) +}) + +test('GEO routes answer', async ({ request }) => { + for (const path of ['/robots.txt', '/sitemap.xml', '/llms.txt', '/llms-full.txt', '/api/health']) { + expect((await request.get(`${BASE}${path}`)).status(), path).toBe(200) + } + const mcp = await request.post(`${BASE}/api/mcp`, { data: { id: 1, jsonrpc: '2.0', method: 'tools/list' } }) + expect(((await mcp.json()) as { result: { tools: unknown[] } }).result.tools.length).toBeGreaterThan(0) +}) + +test('cookie banner: reject hides it and survives a reload', async ({ page }) => { + await page.goto(BASE) + await page.locator('[data-ipal="reject"]').click() + await expect(page.locator('[data-ipal="banner"]')).toBeHidden() + await page.reload() + await expect(page.locator('[data-ipal="banner"]')).toBeHidden() +}) + +test('the first form on the site submits and shows the confirmation', async ({ page }) => { + const urls = await sitemapUrls() + let found = false + for (const url of urls) { + await page.goto(url) + const form = page.locator('form').filter({ has: page.locator('[type="submit"]') }).first() + if (!(await form.count())) {continue} + found = true + await page.locator('[data-ipal="reject"]').click().catch(() => {}) + for (const input of await form.locator('input:not([type=hidden]):not([type=checkbox]), textarea').all()) { + const type = await input.getAttribute('type') + if (await input.getAttribute('name') === 'company_url') {continue} // honeypot stays empty + await input.fill(type === 'email' ? 'smoke-test@example.com' : type === 'number' ? '1' : 'Smoke test') + } + for (const box of await form.locator('input[type=checkbox]').all()) {await box.check()} + for (const select of await form.locator('select').all()) {await select.selectOption({ index: 1 }).catch(() => {})} + await form.locator('[type="submit"]').click() + await expect(page.locator('[role="status"], [role="alert"]').first()).toBeVisible({ timeout: 15_000 }) + break + } + test.skip(!found, 'no form on the site') +}) diff --git a/reference/.agents/skills/ipal-audit/scripts/audit.sh b/reference/.agents/skills/ipal-audit/scripts/audit.sh new file mode 100644 index 0000000..0aa5888 --- /dev/null +++ b/reference/.agents/skills/ipal-audit/scripts/audit.sh @@ -0,0 +1,379 @@ +#!/usr/bin/env bash +# ipal-audit — deterministic checks of an ipal-kit project against AGENT.md. +# Run from the project root: +# bash .agents/skills/ipal-audit/scripts/audit.sh # all checks + tsc + build +# bash .agents/skills/ipal-audit/scripts/audit.sh --quick # static checks only +# bash .agents/skills/ipal-audit/scripts/audit.sh --help +# Exit code: 0 = no errors (warnings allowed), 1 = at least one error. + +set -u + +QUICK=0 +for arg in "$@"; do + case "$arg" in + --quick) QUICK=1 ;; + --help|-h) + sed -n '2,7p' "$0" | sed 's/^# \{0,1\}//' + exit 0 + ;; + esac +done + +if [ ! -d src ]; then + echo "ipal-audit: run from the project root (no ./src found)." >&2 + exit 2 +fi + +ERRORS=0 +WARNINGS=0 + +# report LEVEL "title" "rule" <<< "$matches" +report() { + local level="$1" title="$2" rule="$3" matches="$4" + [ -z "$matches" ] && return 0 + local count + count=$(printf '%s\n' "$matches" | grep -c .) + if [ "$level" = ERROR ]; then ERRORS=$((ERRORS + count)); else WARNINGS=$((WARNINGS + count)); fi + printf '\n[%s] %s (%s) — %s\n' "$level" "$title" "$count" "$rule" + printf '%s\n' "$matches" | head -20 | sed 's/^/ /' + [ "$count" -gt 20 ] && printf ' … and %s more\n' "$((count - 20))" +} + +g() { grep -rnE "$@" 2>/dev/null || true; } +# drop matches that sit inside a // or /* comment (keeps http:// URLs) +# (also a whole-line comment right after grep's "file:line:" prefix) +nc() { grep -vE "^[^:]+:[0-9]+:[[:space:]]*(//|/?\*)|(^|[^:])//.*$1|/\*.*$1" || true; } +dirs() { for d in "$@"; do [ -d "$d" ] && printf '%s ' "$d"; done; } + +BLOCKS=$(dirs src/blocks) +UI=$(dirs src/blocks src/components) + +echo "ipal-audit — $(pwd)" + +# --- Skill templates must not be compiled as project code --- +if [ -d .agents ] && [ -f tsconfig.json ]; then + report ERROR "tsconfig.json does not exclude .agents" "skill templates (.ts/.tsx) break tsc / next build — \"exclude\": [\"node_modules\", \".agents\"]" \ + "$(tr -d '\n' < tsconfig.json | grep -qE '"exclude"[^]]*\.agents' || echo tsconfig.json)" +fi + +# --- Sitemap: one route, look from the plugin (seo.md) --- +SM_TS=$(ls src/app/sitemap.ts 2>/dev/null) +SM_ROUTE=$(ls src/app/sitemap.xml/route.ts 2>/dev/null) +if [ -n "$SM_TS" ] && [ -n "$SM_ROUTE" ]; then + report ERROR "two sitemaps" "seo.md — keep src/app/sitemap.xml/route.ts (sitemapRoute), delete src/app/sitemap.ts" "$(printf '%s\n%s' "$SM_TS" "$SM_ROUTE")" +fi +report WARNING "project copy of the sitemap stylesheet" "seo.md — sitemapRoute serves the look from the plugin; delete it (and cssUrl)" \ + "$(ls public/sitemap.css 2>/dev/null)" + +# --- Architecture (AGENT.md §4) --- +report ERROR "middleware.ts exists" "§4.1 Next 16 uses proxy.ts only" \ + "$(ls src/middleware.ts middleware.ts 2>/dev/null)" + +report ERROR " in app" "§4.2 no explicit — metadata ends up in " \ + "$(g ']' src/app --include=*.tsx | nc '/dev/null) +for p in $PAGES; do + grep -q 'revalidate' "$p" || report ERROR "no ISR" "§4.3 export const revalidate" "$p" + grep -q 'generateStaticParams' "$p" || report ERROR "no generateStaticParams" "§4.4 without it the route is dynamic and metadata lands in " "$p" + report WARNING "searchParams in catch-all page" "§4.6 deoptimizes SSG/ISR — only for paginated archives" \ + "$(grep -n 'searchParams' "$p" | nc 'searchParams' | sed "s|^|$p:|")" +done + +for r in src/app/sitemap.ts src/app/manifest.ts src/app/llms.txt/route.ts src/app/sitemap.xml/route.ts src/app/api/health/route.ts; do + [ -f "$r" ] && ! grep -q "dynamic = 'force-dynamic'" "$r" && \ + report ERROR "DB route without force-dynamic" "§4.7 build without DB will crash" "$r" +done + +report ERROR "headers()/cookies() in blocks/components" "§4.6 forces dynamic rendering — pass locale via enhanceProps" \ + "$( [ -n "$UI" ] && g "from 'next/headers'" $UI)" + +report ERROR "headers()/cookies() in static page tree" "§4.6 SSG/ISR → 'Page changed from static to dynamic' — not-found: LocaleView (pages.md)" \ + "$(g "from 'next/headers'" src/app --include=page.tsx --include=layout.tsx --include=not-found.tsx --include=template.tsx | grep -v '/api/\|(payload)')" + +# --- Hardcoding & types (§2, §8) --- +report ERROR "hardcoded locale map / any / ts-ignore" "§2, §8" \ + "$(g 'localizedRoutes|as any\b|@ts-ignore|: any\b' src --include=*.ts --include=*.tsx | grep -v '/payload-types.ts:')" + +report ERROR "hardcoded locale list" "§2 languages come from i18n.config.ts" \ + "$(g "\[ *'(pl|en|de|fr|es|it)' *, *'(pl|en|de|fr|es|it)'" src --include=*.ts --include=*.tsx | grep -v 'i18n.config.ts')" + +# --- Sections (§6) --- +if [ -n "$BLOCKS" ]; then + report ERROR "forbidden field names" "§6.5 use links/link/media (linksField, linkField, upload)" \ + "$(g "name: *'[a-zA-Z]*([cC]ta|[bB]utton|Url|Href|[pP]df|[iI]mage)[a-zA-Z]*'" $BLOCKS --include=config.ts)" + + report ERROR "hardcoded href/src/file paths in blocks" "§2, §6 use CMSLink / Media" \ + "$(g 'href=\{?["`]/| (appearance from the panel)" \ + "$(g ']*className=[^>]*(bg-|rounded|px-[0-9])' $BLOCKS --include=*.tsx)" + + report ERROR "raw / in blocks" "§6.3 links from the panel render via CMSLink" \ + "$(g '<(a|Link)[ >]' $BLOCKS --include=*.tsx)" + + report ERROR "hardcoded text in blocks" "§2 every visible text comes from the panel (localized field)" \ + "$(node "$(dirname "$0")/jsx-text.mjs" $BLOCKS 2>/dev/null)" + + report WARNING "
outside the form renderer" "§0b — panel forms render via (a search box is fine)" \ + "$(g ']' src --include=*.tsx | grep -v 'components/forms/')" + +# Project copies of what the plugin now ships (import instead of code) +report WARNING "own form engine" "ipal-form §3 — / useBuilderForm (steps, choices, Turnstile, honeypot; Emails tab never reaches the browser)" \ + "$(g 'buildValidator|useForm\(' src --include=*.tsx | grep -v 'useBuilderForm')" +report WARNING "own image lightbox" "lightbox.md — + lightboxImage, one ; labels from Notifications → Lightbox" \ + "$(g "['\"](glightbox|photoswipe|yet-another-react-lightbox|react-medium-image-zoom|fslightbox-react)['\"]" src --include=*.ts --include=*.tsx)" +report WARNING "project copy of section fields / navigation" "blocks.md, links.md — buildSectionHeaderField, buildSectionSettingsField, resolveNav (lib/content)" \ + "$(ls src/fields/sectionHeader.ts src/fields/sectionSettings.ts src/lib/navigation.ts 2>/dev/null)" +if [ -n "$UI" ]; then + for c in $(grep -rlE "^['\"]use client['\"]" $UI 2>/dev/null); do + report ERROR "server entry in client component" "§6.9 '@intecion/ipal-kit' (root), '/rsc', '/server' pull Payload into the browser — client code imports '/client' (types: import type)" \ + "$(grep -nE "from '@intecion/ipal-kit(/rsc|/server)?'" "$c" | grep -v 'import type' | sed "s|^|$c:|")" + done +fi + +# --- Compile & build --- +if [ "$QUICK" -eq 0 ]; then + echo + echo "== pnpm generate:types && tsc --noEmit ==" + if ! (pnpm -s generate:types >/dev/null && pnpm -s exec tsc --noEmit); then + ERRORS=$((ERRORS + 1)); echo "[ERROR] type check failed" + fi + echo + echo "== pnpm build ==" + BUILD_LOG=$(mktemp) + if pnpm -s build >"$BUILD_LOG" 2>&1; then + # Only page routes under /[locale]: route handlers (/md/[locale]/…, sitemap, llms) are force-dynamic by design. + DYN=$(grep -E '^[│├└ ]*ƒ /\[locale\]' "$BUILD_LOG" || true) + report WARNING "page routes rendered dynamically (ƒ)" "§4 expected ● SSG — does the build see the DB?" "$DYN" + else + ERRORS=$((ERRORS + 1)); echo "[ERROR] build failed — last lines:"; tail -30 "$BUILD_LOG" | sed 's/^/ /' + fi + rm -f "$BUILD_LOG" +fi + +echo +echo "ipal-audit: $ERRORS error(s), $WARNINGS warning(s)$( [ "$QUICK" -eq 1 ] && echo ' (quick: no tsc/build)')" +[ "$ERRORS" -eq 0 ] diff --git a/reference/.agents/skills/ipal-audit/scripts/html-check.mjs b/reference/.agents/skills/ipal-audit/scripts/html-check.mjs new file mode 100644 index 0000000..39fc97f --- /dev/null +++ b/reference/.agents/skills/ipal-audit/scripts/html-check.mjs @@ -0,0 +1,38 @@ +#!/usr/bin/env node +// Raw HTML in JSX (dangerouslySetInnerHTML), classified — prints "LEVEL|rule|file:line", exit 0. +// node html-check.mjs src +// - inline JSON-LD (" typed in the panel breaks out of the tag) → JsonLdGraph from /rsc +// - inline JSON-LD with escaping → WARNING (works; JsonLdGraph is the shared version) +// - anything else → WARNING (rich text → RenderRichText; other HTML must be sanitized) +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join } from 'node:path' + +const files = [] +const walk = (p) => { + let st + try { st = statSync(p) } catch { return } + if (st.isDirectory()) { if (!/node_modules|\.next/.test(p)) for (const n of readdirSync(p)) walk(join(p, n)) } + else if (/\.(tsx|jsx)$/.test(p)) files.push(p) +} +process.argv.slice(2).forEach(walk) + +for (const file of files) { + // blank out comments (keeps offsets/line numbers) + const src = readFileSync(file, 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, ' ')) + .replace(/(^|[^:'"`])\/\/.*$/gm, (c, p) => p + ' '.repeat(c.length - p.length)) + for (const m of src.matchAll(/dangerouslySetInnerHTML/g)) { + // the element this prop belongs to: from its opening " from @intecion/ipal-kit/rsc (seo.md)|${at}`) + else console.log(`ERROR|unescaped JSON-LD in " in panel text; use from @intecion/ipal-kit/rsc|${at}`) + } else { + console.log(`WARNING|raw HTML (dangerouslySetInnerHTML) — rich text → RenderRichText; other HTML must be sanitized|${at}`) + } + } +} diff --git a/reference/.agents/skills/ipal-audit/scripts/jsx-text.mjs b/reference/.agents/skills/ipal-audit/scripts/jsx-text.mjs new file mode 100644 index 0000000..a5367c3 --- /dev/null +++ b/reference/.agents/skills/ipal-audit/scripts/jsx-text.mjs @@ -0,0 +1,59 @@ +#!/usr/bin/env node +// Finds user-visible text hardcoded in JSX (AGENT.md §2: everything visible comes from the panel). +// node jsx-text.mjs [ …] → prints "file:line: text" per finding, exit 0 +// Detects: +// - text between HTML text tags:

Nasze usługi

,

\n Lorem…\n

, więcej < +// - text attributes with words: alt="Logo firmy", placeholder="Twój e-mail", aria-label="Zamknij" +// Ignores comments, {expressions}, digits/punctuation/symbols only (404, →, ☰, ·). +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join } from 'node:path' + +const TEXT_TAGS = + 'h1|h2|h3|h4|h5|h6|p|span|a|button|li|label|strong|em|b|i|small|div|section|article|header|footer|main|nav|td|th|dt|dd|figcaption|blockquote|option|legend|summary|caption|q|cite|time|mark' +// Opening tags: HTML text tags or Capitalized components (), never preceded by an +// identifier char — that excludes TS generics like useState( … ). +const OPEN_OR_CLOSE = new RegExp( + `(?:(?]*)?>|)([^<>{}]*)(?=<|\\{)`, + 'g', +) +const ATTR = /\b(alt|title|placeholder|aria-label|label)=("([^"]*)"|'([^']*)')/g +const WORD = /\p{L}{2,}/u +// Text right after a closing/self-closing tag may be the JS that follows the JSX +// expression (` : null`, `) }`, `

\n const id = …`) — not visible text. +const JS_CODE = /(^|\s)(return|const|let|var|if|else|export|import|await|typeof)\b|=>|[=;`]|^\s*[:?)\]}]|&&|\|\|/ +// JSX elements as values in an object literal: `narrow:
,\n wide: ` leaves +// ", wide:" between the two elements — a property key, not visible text. +const OBJECT_KEY = /^\s*,\s*(?:[A-Za-z_$][\w$]*|'[^']*'|"[^"]*")\s*:\s*$/ + +const files = [] +const walk = (p) => { + let st + try { st = statSync(p) } catch { return } + if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n)) + else if (p.endsWith('.tsx')) files.push(p) +} +process.argv.slice(2).forEach(walk) + +// Blank out comments but keep line numbers. +const stripComments = (src) => + src + .replace(/\{\/\*[\s\S]*?\*\/\}/g, (m) => m.replace(/[^\n]/g, ' ')) + .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')) + .replace(/(^|[^:"'`])\/\/.*$/gm, (m, p) => p + ' '.repeat(m.length - p.length)) + +const lineOf = (src, idx) => src.slice(0, idx).split('\n').length + +for (const file of files) { + const src = stripComments(readFileSync(file, 'utf8')) + for (const m of src.matchAll(OPEN_OR_CLOSE)) { + const text = m[1].replace(/\s+/g, ' ').trim() + if (!text || !WORD.test(text) || JS_CODE.test(text) || OBJECT_KEY.test(text)) continue + if (/&[a-z]+;/.test(text) && !WORD.test(text.replace(/&[a-z]+;/g, ''))) continue + console.log(`${file}:${lineOf(src, m.index + m[0].length - m[1].length)}: ${text.slice(0, 80)}`) + } + for (const m of src.matchAll(ATTR)) { + const value = m[3] ?? m[4] ?? '' + if (!WORD.test(value)) continue + console.log(`${file}:${lineOf(src, m.index)}: ${m[1]}="${value.slice(0, 60)}"`) + } +} diff --git a/reference/.agents/skills/ipal-audit/scripts/panel-check.mjs b/reference/.agents/skills/ipal-audit/scripts/panel-check.mjs new file mode 100644 index 0000000..cacf2e5 --- /dev/null +++ b/reference/.agents/skills/ipal-audit/scripts/panel-check.mjs @@ -0,0 +1,55 @@ +#!/usr/bin/env node +// Editor-panel clarity checks (AGENT.md §6.5a): prints "LEVEL|rule|file:line: detail", exit 0. +// node panel-check.mjs src/blocks src/collections src/globals src/fields +import { readFileSync, readdirSync, statSync } from 'node:fs' +import { join } from 'node:path' + +const files = [] +const walk = (p) => { + let st + try { st = statSync(p) } catch { return } + if (st.isDirectory()) for (const n of readdirSync(p)) walk(join(p, n)) + else if (/\.ts$/.test(p) && !/Component|\.d\.ts$/.test(p)) files.push(p) +} +process.argv.slice(2).forEach(walk) + +const POLISH = /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/ +const lineOf = (src, i) => src.slice(0, i).split('\n').length +const out = (level, rule, file, src, i, detail) => console.log(`${level}|${rule}|${file}:${lineOf(src, i)}: ${detail}`) +const strip = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:])\/\/.*$/gm, (m, p) => p + ' '.repeat(m.length - p.length)) + +for (const file of files) { + const src = strip(readFileSync(file, 'utf8')) + + // numbered slots: cta1Label, feature2Title, image3, phone2 → array with "+ Add …" + // digits at the end or before a new word (cta1Label) — not numeronyms like a11y, i18n, l10n + for (const m of src.matchAll(/name:\s*['"]([a-zA-Z]+[0-9]+(?:[A-Z][a-zA-Z0-9]*)?)['"]/g)) { + if (/^(h[1-6]|x[0-9]|[a-z]?2fa)$/i.test(m[1])) continue + out('ERROR', 'numbered fields → one array field with labels {singular, plural} ("+ Add …")', file, src, m.index, m[1]) + } + + // panel text must be English and short + for (const m of src.matchAll(/\b(label|description|singular|plural|placeholder)\s*:\s*(['"`])((?:(?!\2).)*)\2/g)) { + const text = m[3] + if (POLISH.test(text)) out('WARNING', 'panel text in Polish — admin labels/descriptions are English', file, src, m.index, `${m[1]}: "${text.slice(0, 60)}"`) + else if (m[1] === 'description' && text.length > 120) out('WARNING', 'description over 120 chars — one short sentence: what it does / where it shows', file, src, m.index, `${text.length} chars`) + } + + // arrays: labels (→ "Add Feature" button) + rowLabel (→ readable rows) + for (const m of src.matchAll(/type:\s*['"]array['"]/g)) { + const before = src.slice(0, m.index) + const start = Math.max(before.lastIndexOf('name:'), before.lastIndexOf('{')) + const fieldsAt = src.indexOf('fields:', m.index) + const head = src.slice(start < 0 ? m.index : start, fieldsAt < 0 ? m.index + 400 : fieldsAt) + const name = head.match(/name:\s*['"](\w+)['"]/)?.[1] ?? '?' + if (!/\blabels\s*:/.test(head)) out('WARNING', 'array without labels {singular, plural} — panel shows "Add Row"', file, src, m.index, name) + if (!/rowLabel|RowLabel/.test(head)) out('WARNING', 'array without rowLabel() — rows read "Item 01" instead of their content', file, src, m.index, name) + } + + // too many fields in one block config → tabs / condition / arrays / variant + if (/\/blocks\/[^/]+\/config\.ts$/.test(file)) { + const n = (src.match(/name:\s*['"]/g) ?? []).length + const hasTabs = /type:\s*['"]tabs['"]/.test(src) + if (n > 14 && !hasTabs) out('WARNING', 'block has many fields and no tabs — tabs Content/Media/Settings, admin.condition, arrays', file, src, 0, `${n} fields`) + } +} diff --git a/reference/.agents/skills/ipal-block/SKILL.md b/reference/.agents/skills/ipal-block/SKILL.md new file mode 100644 index 0000000..91c9329 --- /dev/null +++ b/reference/.agents/skills/ipal-block/SKILL.md @@ -0,0 +1,86 @@ +--- +name: ipal-block +description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — first a block of the plugin's block library (libraryBlocks / createBlockRegistry, 15 ready sections) or its variant or options, and only when none fits an own block with a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short `{ en, pl }` labels per docs/dev/admin-ux.md, no empty spare fields), shared fields from the plugin (buildSectionHeaderField, buildLinksField, buildLinkField, buildSectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component. +--- + +# ipal-block + +**ipal-kit first (hard rule, AGENT.md "ipal-kit first"):** anything the plugin covers is built with the +plugin's feature. It does not work or is not enough → report it with **ipal-plugin-gap** and wait for the owner's +decision on that part; no hand-built replacement, no silent workaround. **Code rules:** AGENT.md "Code rules" +(one job per file/component/function, no duplicates, typed, texts from the panel, a check for new behaviour). + +One section per use of this skill. Details and ready code: +`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6. + +## 0. Library block first (docs/block-library.md) +The plugin ships 15 blocks: `hero`, `textMedia`, `featureGrid`, `cta`, `richText`, `faq`, `contact`, `gallery`, +`testimonials`, `stats`, `steps`, `logos`, `team`, `pricing`, `entryList` (variants: `blockLibraryManifest`). +1. Does a library block or one of its variants fit the section? → turn it on in `src/blocks/configs.ts` + (`blockOptions` → `libraryBlocks`), no component code. Done after step 3 below. +2. Almost fits → its options, not a copy: `fields: (defaults) => …` (`replaceField`, `removeField`), `variants` + (own `{ label: { en, pl }, value }` + `components` / `classNames` in the registry), `settings: { backgrounds }`, + `links`, `maxItems`. Another look of one part → `createBlockRegistry(content, { classNames: { faq: { item: '…' } } })`; + another primitive everywhere → `ui: { Media }`. +3. The project must own it completely → `pnpm exec ipal-blocks eject ` (same slug and data, no migration), + then the ejected builder in `pageBlocks` and `components: { : Block }` in the registry. +4. Nothing fits → an own block (below), with the library's builders (`buildItemsField`, `buildMediaField`, + `buildVariantField`, `buildContentField`, `defineLibraryBlock`) and primitives (`Section`, `SectionHeader`, `Media`, + `CMSLink`, `Card` from `@intecion/ipal-kit/blocks/rsc`), added to `extra` in `createBlockRegistry`. + Record the reason in AGENTS.md → "Project decisions" (`ipal-doctor` warns about own blocks that copy a library block). + +**Check (library block):** `pnpm generate:types` → `pnpm payload generate:importmap` → Postgres/SQLite +`pnpm payload migrate:create`; add the block to a page in the panel (en and pl labels, ≤ 6 fields), the page shows +the section with `data-ipal-block=""`. + +## 0a. Prerequisites (own block) +With `createBlockRegistry` the primitives come from `@intecion/ipal-kit/blocks/rsc` — import them, no project copies. +A project without it: check that these exist: `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`. +Old `src/fields/sectionHeader.ts` / `sectionSettings.ts` → replace with the plugin import and delete them (blocks.md, no migration). +Links (`buildLinkField`, `buildLinksField`, `resolveLink`) and section fields (`buildSectionHeaderField`, `buildSectionSettingsField`) come from the plugin — do not create them in the project. +Missing → first create them 1:1 from `resources/section-code.md` (this skill) +(and tell the user). Do not write your own versions. + +## 1. Plan (write 3–5 points, then go straight to code — AGENT.md §0a) +- block slug (camelCase), folder name (PascalCase), +- the field list, **only** from the AGENT.md §6.5 vocabulary: + `header`, `media`, `links`, `link`, `items` (+ `heading`, `text`, `content`), `settings`, +- whether `items` get a `Card.tsx` subcomponent, +- whether interaction is needed → a separate `'use client'` file (try `
`/`` first), +- whether the section is a variant of an existing block (then a `variant: select` field, not a new block). + +## 2. Code +File patterns (Hero, FeatureGrid + FeatureCard): `resources/section-code.md`. + +1. `src/blocks//config.ts` — `interfaceName: 'Block'`, fields from the plan, + always `buildSectionSettingsField()`. CTA = `buildLinksField()`, never `cta*`/`button*` fields. + A downloadable file = a link of type `file`. **Panel per AGENT.md §6.5a:** + - repeatable → an array with `labels: { singular, plural }` + `admin: { initCollapsed: true, components: rowLabel('heading', '') }`, `maxRows` from the design; + - no numbered fields (`cta1`, `feature2Title`, `image3`) and no spare fields "just in case"; + - EN labels of 1–3 words, `description` only when needed (≤ 80 chars, what/where, an example); + - dependent fields use `admin.condition`, a variant = a `variant` select, > ~10 fields → `tabs`; + - block: `labels: { singular: 'Feature grid', plural: 'Feature grids' }`. +2. `src/blocks//Component.tsx` — named export, type from `@/payload-types` + (`Block & { locale: string }`), structure: + `
` → `` → content with ``, ``, + `items.map()`. No text, `href`, ``, hex colors or inline SVG. Styles only through the design-token + utilities (`bg-surface`, `text-fg`, `rounded-card`, `py-section` — AGENT.md §6.11, design-tokens.md); no `dark:` for + colours; a different look per brand = a value in `src/design/tokens.ts`, never a change here. +3. Subcomponents go in the same folder; shared by 2+ sections → `src/components/ui/`. + An image the visitor can enlarge (gallery, card, product, certificate) → wrap the `` in + `-${id}`} image={lightboxImage(item.image, { size: 'hero' })}>` + (`@intecion/ipal-kit/client`; skip the trigger when `lightboxImage` returns `null`). No + `useState` dialog, no `glightbox` — lightbox.md. +4. Add `config.ts` to `pageBlocks` (`src/blocks/configs.ts`, used by `layout` in `src/collections/Pages.ts`), + and the component to `src/blocks/registry.ts` (`extra: { : Component }` in `createBlockRegistry`, key = slug). +5. `pnpm generate:types`. + +## 3. Check +- `Component.tsx` ≤ ~80 lines of JSX. +- **Empty block test** in the panel: ≤ 6 items at the start, every label and description + readable in English and Polish (switch the admin language in Account), + "+ Add Button / Add Feature", collapsed rows showing their content, every field shows something. + First `rowLabel` in the project → `pnpm payload generate:importmap`. +- Run the **ipal-audit** skill (`--quick`), fix every `[ERROR]`. +- Refactoring an existing block with renamed fields: **migrate the data first** + (old field → new), and only then remove the old fields (AGENT.md §6.7). diff --git a/reference/.agents/skills/ipal-block/resources/section-code.md b/reference/.agents/skills/ipal-block/resources/section-code.md new file mode 100644 index 0000000..c175bb8 --- /dev/null +++ b/reference/.agents/skills/ipal-block/resources/section-code.md @@ -0,0 +1,342 @@ +# Section code — ready files for the project + +> Resources of the **ipal-block** skill. The rules (why, and what not to do) are in +> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6 — this file is only the code +> to create in the project **1:1**. Links (`buildLinkField`, `buildLinksField`, +> `resolveLink`), section fields (`buildSectionHeaderField`, `buildSectionSettingsField`) and the menu +> (`resolveNav`) come from the plugin — do not copy them. + +## Layer 1 — shared fields + +**Link / CTA — from the plugin, do not copy the code** (`docs/links.md`): + +```ts +import { buildLinkField, buildLinksField } from '@intecion/ipal-kit' + +buildLinksField() // 0–2 section buttons → `links` field +buildLinksField({ maxRows: 3, appearances: ['primary', 'secondary'] }) +buildLinkField() // single link → `link` field +buildLinkField({ disableLabel: true, appearances: false }) // whole card clickable +``` + +One link shape: type (`internal` page / `external` URL, mailto, tel, #anchor / +`file` upload), `label` (localized), `newTab`, `appearance`. `payload-types.ts` +gets a `CmsLink` type (without style: `CmsLinkPlain`, without label: `CmsLinkNoLabel`; all +fit `CmsLink`; custom name: `interfaceName`). Options: `relationTo` (default `'pages'`), `uploadTo` +(default `'media'`), `required`. + + +**Files and images:** `{ name: 'media', type: 'upload', relationTo: 'media' }`. +The `media` collection accepts PDF (`upload.mimeTypes: ['image/*', 'application/pdf', +'video/mp4']`), has `alt` (required, localized) and `normalizeFilenameHook`. +"Download price list (PDF)" is a **link of type `file`**, not a separate `pdf`/`pdfUrl` field. + +**Section header and settings — from the plugin, do not copy the code** (`docs/blocks.md`): + +```ts +import { buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit' + +buildSectionHeaderField() // `header` group: eyebrow, heading, intro (localized) — type SectionHeaderData +buildSectionSettingsField() // sidebar `settings`: anchor, background (default/muted/inverted) — type SectionSettings +buildSectionSettingsField({ backgrounds: [{ label: 'Default', value: 'default' }, { label: 'Brand', value: 'brand' }] }) +``` + +Every section has `buildSectionSettingsField()` — no `bgColor`, `darkMode`, +`sectionId` in individual blocks. Field labels in English (the panel is EN). + +## Layer 2 — UI primitives + +`src/components/ui/CMSLink.tsx` — **every** link/button from the panel: + +```tsx +import Link from 'next/link' +import type { ReactNode } from 'react' +import type { CmsLink } from '@/payload-types' +import { resolveLink } from '@/lib/content' +import { buttonClass } from './Button' +import type { LinkAppearance } from '@intecion/ipal-kit' + +type Props = { + link: CmsLink | null | undefined + locale: string + className?: string + /** For wrapping links (cards): content instead of link.label. */ + children?: ReactNode +} + +// href, new tab, rel, internal/external — from the plugin. Here: the element and the classes. +export async function CMSLink({ link, locale, className, children }: Props) { + const l = await resolveLink(link, locale) + const content = children ?? l?.label + if (!l || !content) return null + const cls = [l.appearance ? buttonClass(l.appearance as LinkAppearance) : '', className].filter(Boolean).join(' ') || undefined + return l.internal + ? {content} + : {content} +} +``` + +`src/components/ui/Button.tsx` — variants as a map, not a ternary: + +```ts +import type { LinkAppearance } from '@intecion/ipal-kit' + +// design-token utilities only (design-tokens.md) — a brand changes src/design/tokens.ts, never this file +const BASE = 'inline-flex items-center gap-2 rounded-control px-5 py-2.5 font-medium transition-colors duration-fast ease-out' +const VARIANTS: Record = { + primary: `${BASE} bg-primary text-on-primary hover:bg-primary-hover`, + secondary: `${BASE} bg-secondary text-on-secondary hover:bg-secondary-hover`, + link: 'text-link underline-offset-4 hover:text-link-hover hover:underline', +} + +export function buttonClass(appearance: LinkAppearance): string { + return VARIANTS[appearance] +} +``` + +`src/components/ui/Media.tsx` — **every** image/video from the panel. The plugin handles speed +(`mediaImageProps`, `videoProps`), the look stays here: + +```tsx +import Image from 'next/image' +import { mediaImageProps, MEDIA_SIZES, videoProps, type VideoMode } from '@intecion/ipal-kit' +import type { Media as MediaDoc } from '@/payload-types' + +type Props = { + resource: MediaDoc | string | number | null | undefined + /** Width ON SCREEN — MEDIA_SIZES.half / .third / a custom string. Without it the full width downloads. */ + sizes?: string + /** Only the first visible image of the page (hero, LCP). The rest load lazily. */ + priority?: boolean + className?: string + /** Video: 'background' (muted loop) or 'player' (controls, loads on click). */ + videoMode?: VideoMode + /** Video poster — upload from the panel. */ + poster?: MediaDoc | string | number | null +} + +export function Media({ resource, sizes = MEDIA_SIZES.full, priority = false, className, videoMode = 'player', poster }: Props) { + const video = videoProps(resource, { mode: videoMode, poster }) + if (video) return