Docs in English (part 1), seeding guide, Coolify deployment

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 17:39:03 +02:00
co-authored by Claude Opus 5.5
parent 6e3979bae6
commit 2d9f3e15d4
47 changed files with 6102 additions and 5355 deletions
+845 -828
View File
File diff suppressed because it is too large Load Diff
+26 -26
View File
@@ -5,38 +5,38 @@ description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md r
# ipal-audit
Kontrole z AGENT.md §11 jako skrypt — zawsze te same, bez interpretacji.
The checks from AGENT.md §11 as a script — always the same, no interpretation.
## Kroki
## Steps
1. Z roota projektu uruchom:
1. From the project root, run:
```bash
bash .agents/skills/ipal-audit/scripts/audit.sh --quick # w trakcie pracy
bash .agents/skills/ipal-audit/scripts/audit.sh # przed „gotowe” (+ tsc + build)
bash .agents/skills/ipal-audit/scripts/audit.sh --quick # while working
bash .agents/skills/ipal-audit/scripts/audit.sh # before "done" (+ tsc + build)
```
Opcje: `--help`. Nie czytaj źródła skryptu — wynik wystarczy.
2. Pokaż użytkownikowi **pełny wynik** (podsumowanie + listę naruszeń).
3. Każde `[ERROR]` napraw albo — jeśli to świadomy wyjątek — dodaj w kodzie
komentarz z uzasadnieniem i wymień go w odpowiedzi.
Reguła przy każdym naruszeniu wskazuje sekcję w
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` — przeczytaj ją przed poprawką.
4. `[WARNING]` — oceń i powiedz użytkownikowi, co z nim zrobić; nie poprawiaj
na ślepo (np. `searchParams` jest OK w trasie archiwum z paginacją).
5. Uruchom ponownie, aż wynik to `0 error(s)`.
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: …” — obowiązkowy komplet (AGENT.md §0b)
Każde `[ERROR] missing: X` to pozycja kompletu, której nie ma w kodzie. Wpinasz ją
wg wskazówki (PROGRAMISTA §2) — nie pytasz, czy trzeba. Jedyny wyjątek: decyzja
klienta zapisana w `AGENTS.md` jako `ipal-audit-skip: <klucze> — <powód>` (klucze
w AGENT.md §0b). Nie dopisujesz tej linii sam, żeby „przeszło”.
## "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> — <reason>` (keys
in AGENT.md §0b). Never add that line yourself just to make the audit pass.
## Czego skrypt nie sprawdzi (zrób ręcznie)
## What the script does not check (do it by hand)
- **Test redaktora** (AGENT.md §11): czy każdy tekst, obraz, przycisk, sekcja,
menu, stopka i SEO zmienia się w panelu, w każdym języku.
- **Zgoda cookies:** w Network przed akceptacją brak żądań do
google-analytics / googletagmanager (poza Consent Mode), facebook.net,
- **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.
- **Treść**: czy fallbacki nie zawierają danych klienta (`|| 'Firma X'`).
- **Content**: fallbacks contain no client data (`|| 'Firma X'`).
Nie mów „gotowe”, dopóki pełny audyt (bez `--quick`) nie ma błędów.
Do not say "done" until the full audit (without `--quick`) has no errors.
@@ -297,7 +297,7 @@ fi
need WARNING r2 "R2 env in .env.example" ".env.example lists R2_BUCKET, R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_PUBLIC_URL" 'R2_BUCKET' .env.example
need WARNING '' "IPAL_IP_HEADER in .env.example" "header the rate limit trusts, e.g. cf-connecting-ip (forms.md)" 'IPAL_IP_HEADER' .env.example
# Plugin replacements (§0b "Zakazane zamienniki")
# Plugin replacements (§0b "Forbidden substitutes")
report ERROR "own form / mail / captcha stack" "§0b — forms come from the panel builder, mail from mailAdapter, bot check from Turnstile" \
"$(g "from '(nodemailer|resend|@sendgrid/[a-z]+|react-hook-form|formik|react-google-recaptcha|@hcaptcha/react-hcaptcha|@aws-sdk/client-s3)'" src --include=*.ts --include=*.tsx)"
report ERROR "own form/mail API route" "§0b — use the sendForm server action → submitForm" \
+38 -38
View File
@@ -5,49 +5,49 @@ description: Builds or refactors one page section (Payload block + React compone
# ipal-block
Jedna sekcja na jedno użycie skilla. Szczegóły i gotowy kod:
One section per use of this skill. Details and ready code:
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.
## 0. Warunki wstępne
Sprawdź, czy istnieją: `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
Stare `src/fields/sectionHeader.ts` / `sectionSettings.ts` → zamień na import z pluginu i usuń (blocks.md, bez migracji).
Linki (`buildLinkField`, `buildLinksField`, `resolveLink`) i pola sekcji (`buildSectionHeaderField`, `buildSectionSettingsField`) są w pluginie — nie twórz ich w projekcie.
Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
(i powiedz o tym użytkownikowi). Nie pisz własnych wersji.
## 0. Prerequisites
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 (zapisz w 3–5 punktach, potem od razu kod — AGENT.md §0a)
- slug bloku (camelCase), nazwa folderu (PascalCase),
- lista pól **tylko** ze słownika AGENT.md §6.5:
## 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`,
- czy elementy `items` dostają podkomponent `<Nazwa>Card.tsx`,
- czy potrzebna interakcja → osobny plik `'use client'` (najpierw `<details>`/`<dialog>`),
- czy sekcja to wariant istniejącego bloku (wtedy pole `variant: select`, nie nowy blok).
- whether `items` get a `<Name>Card.tsx` subcomponent,
- whether interaction is needed → a separate `'use client'` file (try `<details>`/`<dialog>` first),
- whether the section is a variant of an existing block (then a `variant: select` field, not a new block).
## 2. Kod
Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`.
## 2. Code
File patterns (Hero, FeatureGrid + FeatureCard): `resources/section-code.md`.
1. `src/blocks/<Nazwa>/config.ts` — `interfaceName: '<Nazwa>Block'`, pola z planu,
zawsze `buildSectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`.
Plik do pobrania = link typu `file`. **Panel wg AGENT.md §6.5a:**
- powtarzalne → tablica z `labels: { singular, plural }` + `admin: { initCollapsed: true, components: rowLabel('heading', '<Singular>') }`, `maxRows` z designu;
- zero numerowanych pól (`cta1`, `feature2Title`, `image3`) i pól „na zapas”;
- etykiety EN 1–3 słowa, `description` tylko gdy potrzebny (≤ 80 znaków, co/gdzie, przykład);
- pola zależne `admin.condition`, wariant = `variant` select, > ~10 pól → `tabs`;
- blok: `labels: { singular: 'Feature grid', plural: 'Feature grids' }`.
2. `src/blocks/<Nazwa>/Component.tsx` — nazwany eksport, typ z `@/payload-types`
(`<Nazwa>Block & { locale: string }`), struktura:
`<Section settings>` → `<SectionHeader header>` → treść z `<Media>`, `<CMSLink>`,
`items.map(<Card/>)`. Zero tekstu, `href`, `<img>`, hexów, inline SVG.
3. Podkomponenty w tym samym folderze; wspólne dla 2+ sekcji → `src/components/ui/`.
4. Dodaj `config.ts` do `layout` w `src/collections/Pages.ts`,
komponent do `src/blocks/registry.ts` (klucz = slug).
1. `src/blocks/<Name>/config.ts` — `interfaceName: '<Name>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', '<Singular>') }`, `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/<Name>/Component.tsx` — named export, type from `@/payload-types`
(`<Name>Block & { locale: string }`), structure:
`<Section settings>` → `<SectionHeader header>` → content with `<Media>`, `<CMSLink>`,
`items.map(<Card/>)`. No text, `href`, `<img>`, hex colors or inline SVG.
3. Subcomponents go in the same folder; shared by 2+ sections → `src/components/ui/`.
4. Add `config.ts` to `layout` in `src/collections/Pages.ts`,
and the component to `src/blocks/registry.ts` (key = slug).
5. `pnpm generate:types`.
## 3. Weryfikacja
- `Component.tsx` ≤ ~80 linii JSX.
- **Test pustego bloku** w panelu: ≤ 6 pozycji na starcie, wszystko po angielsku,
„+ Add Button / Add Feature”, zwinięte wiersze z treścią, każde pole coś wyświetla.
Pierwszy `rowLabel` w projekcie → `pnpm payload generate:importmap`.
- Uruchom skill **ipal-audit** (`--quick`), napraw wszystkie `[ERROR]`.
- Refaktor istniejącego bloku ze zmianą nazw pól: **najpierw migracja danych**
(stare pole → nowe), dopiero potem usunięcie starych pól (AGENT.md §6.7).
## 3. Check
- `Component.tsx` ≤ ~80 lines of JSX.
- **Empty block test** in the panel: ≤ 6 items at the start, everything in English,
"+ 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).
@@ -1,52 +1,52 @@
# Kod sekcji — gotowe pliki dla projektu
# Section code — ready files for the project
> Zasoby skilla **ipal-block**. Reguły (dlaczego tak, czego nie robić) są w
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6 — ten plik to tylko kod
> do utworzenia w projekcie **1:1**. Linki (`buildLinkField`, `buildLinksField`,
> `resolveLink`), pola sekcji (`buildSectionHeaderField`, `buildSectionSettingsField`) i menu
> (`resolveNav`) są w pluginie — nie twórz ich kopii.
> 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.
## Warstwa 1 — wspólne pola
## Layer 1 — shared fields
**Link / CTA — z pluginu, nie kopiuj kodu** (`docs/links.md`):
**Link / CTA — from the plugin, do not copy the code** (`docs/links.md`):
```ts
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
buildLinksField() // 0–2 przyciski sekcji → pole `links`
buildLinksField() // 0–2 section buttons → `links` field
buildLinksField({ maxRows: 3, appearances: ['primary', 'secondary'] })
buildLinkField() // pojedynczy link → pole `link`
buildLinkField({ disableLabel: true, appearances: false }) // klikalna cała karta
buildLinkField() // single link → `link` field
buildLinkField({ disableLabel: true, appearances: false }) // whole card clickable
```
Jeden kształt linku: typ (`internal` strona / `external` URL, mailto, tel, #anchor /
`file` upload), `label` (localized), `newTab`, `appearance`. W `payload-types.ts`
powstaje typ `CmsLink` (bez stylu: `CmsLinkPlain`, bez etykiety: `CmsLinkNoLabel`; wszystkie
pasują do `CmsLink`; własna nazwa: `interfaceName`). Opcje: `relationTo` (domyślnie `'pages'`), `uploadTo`
(domyślnie `'media'`), `required`.
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`.
**Pliki i obrazy:** `{ name: 'media', type: 'upload', relationTo: 'media' }`.
Kolekcja `media` dopuszcza PDF (`upload.mimeTypes: ['image/*', 'application/pdf',
'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`.
„Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`.
**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.
**Nagłówek i ustawienia sekcji — z pluginu, nie kopiuj kodu** (`docs/blocks.md`):
**Section header and settings — from the plugin, do not copy the code** (`docs/blocks.md`):
```ts
import { buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
buildSectionHeaderField() // grupa `header`: eyebrow, heading, intro (localized) — typ SectionHeaderData
buildSectionSettingsField() // sidebar `settings`: anchor, background (default/muted/inverted) — typ SectionSettings
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' }] })
```
Każda sekcja ma `buildSectionSettingsField()` — żadnych `bgColor`, `darkMode`,
`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN).
Every section has `buildSectionSettingsField()` — no `bgColor`, `darkMode`,
`sectionId` in individual blocks. Field labels in English (the panel is EN).
## Warstwa 2 — prymitywy UI
## Layer 2 — UI primitives
`src/components/ui/CMSLink.tsx` — **każdy** link/przycisk z panelu:
`src/components/ui/CMSLink.tsx` — **every** link/button from the panel:
```tsx
import Link from 'next/link'
@@ -76,7 +76,7 @@ export async function CMSLink({ link, locale, className, children }: Props) {
}
```
`src/components/ui/Button.tsx` — warianty jako mapa, nie ternary:
`src/components/ui/Button.tsx` — variants as a map, not a ternary:
```ts
import type { LinkAppearance } from '@intecion/ipal-kit'
@@ -92,8 +92,8 @@ export function buttonClass(appearance: LinkAppearance): string {
}
```
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu. Szybkość liczy plugin
(`mediaImageProps`, `videoProps`), wygląd zostaje tutaj:
`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'
@@ -102,14 +102,14 @@ import type { Media as MediaDoc } from '@/payload-types'
type Props = {
resource: MediaDoc | string | number | null | undefined
/** Szerokość NA EKRANIE — MEDIA_SIZES.half / .third / własny string. Bez tego pobiera się pełna szerokość. */
/** Width ON SCREEN — MEDIA_SIZES.half / .third / a custom string. Without it the full width downloads. */
sizes?: string
/** Tylko pierwszy widoczny obraz strony (hero, LCP). Reszta ładuje się leniwie. */
/** Only the first visible image of the page (hero, LCP). The rest load lazily. */
priority?: boolean
className?: string
/** Wideo: 'background' (pętla bez dźwięku) albo 'player' (kontrolki, ładowanie po kliknięciu). */
/** Video: 'background' (muted loop) or 'player' (controls, loads on click). */
videoMode?: VideoMode
/** Plakat wideo — upload z panelu. */
/** Video poster — upload from the panel. */
poster?: MediaDoc | string | number | null
}
@@ -117,17 +117,17 @@ export function Media({ resource, sizes = MEDIA_SIZES.full, priority = false, cl
const video = videoProps(resource, { mode: videoMode, poster })
if (video) return <video {...video} className={className} />
const img = mediaImageProps(resource, { priority, sizes })
if (!img) return null // PDF / plik — link typu 'file' (CMSLink), nie <Media>
if (!img) return null // PDF / file — a link of type 'file' (CMSLink), not <Media>
return <Image {...img} className={className} />
}
```
Media w kolekcji: `upload: { focalPoint: true, … }` (punkt ostrości → `object-position`) oraz
hooki z pluginu: `hooks.beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()]`,
pola `buildOptimizeUploadField()` (zgoda na optymalizację za dużego pliku) i
`buildMediaPlaceholderField()` (rozmyty podgląd + kolor podczas ładowania).
Media in the collection: `upload: { focalPoint: true, … }` (focal point → `object-position`) and
hooks from the plugin: `hooks.beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()]`,
fields `buildOptimizeUploadField()` (consent to optimize an oversized file) and
`buildMediaPlaceholderField()` (blurred preview + color while loading).
`Section.tsx` i `SectionHeader.tsx`:
`Section.tsx` and `SectionHeader.tsx`:
```tsx
// src/components/ui/Section.tsx
@@ -168,14 +168,14 @@ export function SectionHeader({ header, as: H = 'h2' }: { header?: SectionHeader
}
```
**`locale` dla każdego bloku — raz, w trasie strony:**
**`locale` for every block — once, in the page route:**
```tsx
const enhanceProps = () => ({ locale }) // Turnstile: <TurnstileProvider> w layoucie, nie props
const enhanceProps = () => ({ locale }) // Turnstile: <TurnstileProvider> in the layout, not props
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
```
## Warstwa 3 — sekcja = kompozycja
## Layer 3 — section = composition
```ts
// src/blocks/Hero/config.ts
@@ -197,7 +197,7 @@ export const HeroBlock: Block = {
```
```tsx
// src/blocks/Hero/Component.tsx — cały komponent
// src/blocks/Hero/Component.tsx — the whole component
import type { HeroBlock } from '@/payload-types'
import { Section } from '@/components/ui/Section'
import { SectionHeader } from '@/components/ui/SectionHeader'
@@ -223,7 +223,7 @@ export function Hero({ header, media, links, settings, locale }: HeroBlock & { l
}
```
Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
A section with repeatable items — an array item is a subcomponent:
```ts
// src/blocks/FeatureGrid/config.ts (fields) — import { buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
@@ -234,8 +234,8 @@ buildSectionHeaderField(),
interfaceName: 'FeatureItem',
labels: { singular: 'Feature', plural: 'Features' }, // panel: "+ Add Feature"
minRows: 1,
maxRows: 6, // ile mieści design
admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') }, // wiersz = nagłówek
maxRows: 6, // as many as the design fits
admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') }, // row = heading
fields: [
{ name: 'media', type: 'upload', relationTo: 'media' },
{ name: 'heading', type: 'text', localized: true, required: true },
@@ -274,21 +274,21 @@ export function FeatureGrid({ header, items, links, settings, locale }: FeatureG
}
```
**Wydziel podkomponent, gdy którekolwiek jest prawdą:** ten sam JSX 2+ razy;
element `items[]` ma >5 linii markupu; `Component.tsx` >80 linii JSX; jest stan/
interakcja (accordion, slider, tabs → osobny `'use client'`). Podkomponent
jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/components/ui/`.
Ikony: upload albo `select` z mapą w `src/components/icons` — nigdy SVG wklejone
w sekcję.
**Extract a subcomponent when any of these is true:** the same JSX 2+ times;
an `items[]` element has >5 lines of markup; `Component.tsx` >80 lines of JSX; there is state/
interaction (accordion, slider, tabs → a separate `'use client'`). A subcomponent of
one section → in its folder; used in 2+ sections → `src/components/ui/`.
Icons: upload or a `select` with a map in `src/components/icons` — never SVG pasted
into a section.
## Ikony
## Icons
Dwa źródła, nic pomiędzy:
- **Dowolna grafika od klienta** → upload do `media` + `<Media>` (także logo, ikony SVG marki).
- **Stały zestaw ikon UI** → pole `select` + mapa `lucide-react`:
Two sources, nothing in between:
- **Any graphic from the client** → upload to `media` + `<Media>` (also the logo, brand SVG icons).
- **A fixed set of UI icons** → a `select` field + a `lucide-react` map:
```ts
// src/components/icons/names.ts — same nazwy, importowane przez config bloku
// src/components/icons/names.ts — names only, imported by the block config
export const ICON_NAMES = ['phone', 'mail', 'mapPin', 'clock', 'check'] as const
export type IconName = (typeof ICON_NAMES)[number]
export const iconField = {
@@ -298,7 +298,7 @@ export const iconField = {
} as const
```
```tsx
// src/components/icons/Icon.tsx — mapa, importowana tylko przez komponenty
// src/components/icons/Icon.tsx — the map, imported only by components
import { Check, Clock, Mail, MapPin, Phone, type LucideIcon } from 'lucide-react'
import type { IconName } from './names'
@@ -310,18 +310,18 @@ export function Icon({ name, className }: { name?: IconName | null; className?:
return <Component className={className} aria-hidden />
}
```
Nazwy są osobno, żeby config bloku (`payload.config`) nie importował komponentów
React. **Nigdy** SVG wklejone w JSX sekcji.
The names are separate so the block config (`payload.config`) does not import React
components. **Never** SVG pasted into a section's JSX.
## Style
- **Tailwind w komponentach**, kolory i fonty jako **tokeny** w `styles.css`
(`@theme`) — źródłem jest `DESIGN.md` (Impeccable). W komponentach tylko nazwy
tokenów (`bg-primary`, `text-foreground`), **nigdy** `bg-[#ff6600]` ani hex.
- Tokeny pluginu mapuj na tokeny projektu — jeden kolor marki w jednym miejscu.
- Fonty przez `next/font` w layoucie, podpięte zmienną CSS do `@theme`.
- Bez CSS Modules i `style={{…}}` — wyjątek: wartość dynamiczna z danych.
- Warianty wizualne → `Record<Variant, string>` (§6.3), nie łańcuchy ternary.
- **Tailwind in components**, colors and fonts as **tokens** in `styles.css`
(`@theme`) — the source is `DESIGN.md` (Impeccable). Components use only token
names (`bg-primary`, `text-foreground`), **never** `bg-[#ff6600]` or hex.
- Map the plugin tokens to the project tokens — one brand color in one place.
- Fonts via `next/font` in the layout, wired to `@theme` with a CSS variable.
- No CSS Modules and no `style={{…}}` — exception: a dynamic value from data.
- Visual variants → `Record<Variant, string>` (§6.3), not ternary chains.
```css
/* src/app/(frontend)/styles.css */
@@ -337,7 +337,7 @@ React. **Nigdy** SVG wklejone w JSX sekcji.
}
:root {
--ipal-primary: var(--color-primary); /* baner cookies, Turnstile = kolor marki */
--ipal-primary: var(--color-primary); /* cookie banner, Turnstile = brand color */
--ipal-radius: 0.75rem;
}
```
+33 -33
View File
@@ -5,46 +5,46 @@ description: Decides whether something should be a Payload collection, a global,
# ipal-collection
Źródła: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §5,
Sources: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §5,
`docs/content.md`, `docs/hooks.md`, `docs/seo.md`.
## 1. Test (zawsze, przed jakimkolwiek kodem)
Odpowiedz użytkownikowi na 4 pytania — wszystkie muszą być TAK:
1. Lista wielu rekordów tego samego typu?
2. Każdy rekord ma **własny URL**?
3. Klient **jawnie** tego wymaga?
4. Payload nie ma tego wbudowanego?
## 1. Test (always, before any code)
Answer these 4 questions for the user — all must be YES:
1. Is it a list of many records of the same type?
2. Does each record have **its own URL**?
3. Does the client **explicitly** require it?
4. Does Payload not have it built in?
Którekolwiek NIE → to nie kolekcja:
- jeden zestaw danych (firma, menu, stopka, ustawienia) → **global**,
- część strony (FAQ, hero, opinie w sekcji) → **blok** (skill ipal-block),
- `users` → wstrzykuje plugin, gdy projekt go nie ma; własną kolekcję o tym slugu tworzysz
tylko, by dodać pola (wygrywa nad wstrzykniętą; role i 2FA dopinają się do niej).
Any NO → it is not a collection:
- one set of data (company, menu, footer, settings) → **global**,
- part of a page (FAQ, hero, testimonials in a section) → **block** (ipal-block skill),
- `users` → the plugin injects it when the project has none; create your own collection with that slug
only to add fields (it wins over the injected one; roles and 2FA attach to it).
Wyjątek: lista bez własnych URL-i zarządzana osobno (np. opinie używane w wielu
blokach) — kolekcja **bez** wpięcia w `content`. Uzasadnij to w planie.
Exception: a list without its own URLs managed separately (e.g. testimonials used in many
blocks) — a collection **without** wiring into `content`. Justify it in the plan.
## 2. Plan (zapisz, potem od razu kod — AGENT.md §0a)
slug (camelCase, l.mn.), pola, relacje, czy ma URL-e (archiwum), JSON-LD.
Decyzję „kolekcja vs global vs blok” zapisz w `AGENTS.md` → „Ustalenia projektu”.
Pytasz tylko, gdy brief nie rozstrzyga czegoś biznesowego (np. „czy wpisy mają autorów?”).
## 2. Plan (write it, then go straight to code — AGENT.md §0a)
slug (camelCase, plural), fields, relations, whether it has URLs (archive), JSON-LD.
Record the "collection vs global vs block" decision in `AGENTS.md` → "Project decisions".
Ask only when the brief leaves a business question open (e.g. "do posts have authors?").
## 3. Kod
1. `src/collections/<Nazwa>.ts`: `title` (localized), `buildSlugField({ from: 'title' })`,
tab SEO (plugin-seo), `buildNoindexField()`, `trackSlugHistoryHook`,
`buildRevalidateHook`, `setPublishedAtHook` (wpisy z datą), upload przez
`media`, linki przez `buildLinkField()`. Nazwy pól wg AGENT.md §6.5.
## 3. Code
1. `src/collections/<Name>.ts`: `title` (localized), `buildSlugField({ from: 'title' })`,
SEO tab (plugin-seo), `buildNoindexField()`, `trackSlugHistoryHook`,
`buildRevalidateHook`, `setPublishedAtHook` (dated entries), uploads via
`media`, links via `buildLinkField()`. Field names per AGENT.md §6.5.
Panel (AGENT.md §6.5a): `admin.useAsTitle`, `defaultColumns` (3–4), `admin.group: 'Content'`,
`labels` po angielsku, tablice z `labels` + `rowLabel()`, ustawienia w sidebarze.
2. Z URL-ami: dopisz do `content.config.ts` → `{ slug, perPage }`.
**Prefiks URL nie w kodzie** — redaktor przypisuje stronę-archiwum w
Site Settings (`<slug>Archive`). Plugin robi routing, sitemap,
`labels` in English, arrays with `labels` + `rowLabel()`, settings in the sidebar.
2. With URLs: add it to `content.config.ts` → `{ slug, perPage }`.
**No URL prefix in code** — the editor assigns the archive page in
Site Settings (`<slug>Archive`). The plugin handles routing, sitemap,
generateStaticParams, hreflang.
3. Lista wpisów = blok (EntriesList) z `getEntries`; strona wpisu z
`resolveRoute` (typ `entry`); JSON-LD wg seo.md (np. Article).
3. Entry list = a block (EntriesList) with `getEntries`; the entry page uses
`resolveRoute` (type `entry`); JSON-LD per seo.md (e.g. Article).
4. `pnpm generate:types`, `pnpm payload generate:importmap`.
5. Postgres z migracjami → `pnpm payload migrate:create`.
5. Postgres with migrations → `pnpm payload migrate:create`.
## 4. Weryfikacja
Skill **ipal-audit**. Ręcznie: wpis w panelu → widoczny pod `/<locale>/<archiwum>/<slug>`,
w sitemapie, zmiana sluga → 308 ze starego adresu.
## 4. Check
The **ipal-audit** skill. By hand: an entry in the panel → visible at `/<locale>/<archive>/<slug>`,
in the sitemap; changing the slug → 308 from the old address.
+43 -43
View File
@@ -5,74 +5,74 @@ description: Proves in a real browser (Playwright) that an ipal-kit site respect
# ipal-consent-check
RODO: tagi nie-Google ładują się **dopiero po zgodzie**; Google (GA4/GTM) może
się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ciasteczek.
GDPR: non-Google tags load **only after consent**; Google (GA4/GTM) may
load earlier only with the Consent Mode "denied" signal and without cookies.
## Kroki
1. Jednorazowo w projekcie:
## Steps
1. Once per project:
```bash
pnpm add -D playwright && pnpm exec playwright install chromium
```
2. Uruchom aplikację (`pnpm build && pnpm start`) i sprawdź **stronę z tagami**
(najlepiej stronę główną i stronę z formularzem/wideo):
2. Start the app (`pnpm build && pnpm start`) and check **a page with tags**
(ideally the homepage and a page with a form/video):
```bash
node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl
```
`--wait 6000` gdy tagi startują wolno (tryb `defer` w Analytics).
3. Wynik: trzy przebiegi w czystych profilach — brak decyzji, „Akceptuj”,
„Odrzuć” + przeładowanie. Każde `[ERROR]` to naruszenie — napraw:
`--wait 6000` when tags start slowly (`defer` mode in Analytics).
3. Output: three runs in clean profiles — no decision, "Accept",
"Reject" + reload. Every `[ERROR]` is a violation — fix it:
| Naruszenie | Przyczyna → poprawka |
| Violation | Cause → fix |
|---|---|
| piksel loaded without consent | skrypt wpięty ręcznie / skopiowany `Analytics` → ID w Site Integrations, `<Analytics>` z pluginu (analytics.md) |
| tracking cookie set without consent | to samo; albo GTM odpala tag bez warunku `ad_storage` (analytics.md → GTM) |
| GA hit with consent GRANTED | `setDefaultConsent` nie przed tagiem — `<Analytics>` musi być wewnątrz `<ConsentProvider>` (`SiteProviders` robi to sam) |
| YouTube / Maps before consent (warning) | `ConsentScript` (consent.md), `youtube-nocookie.com` albo „kliknij, aby załadować” |
| pixel loaded without consent | script wired by hand / copied `Analytics` → ID in Site Integrations, `<Analytics>` from the plugin (analytics.md) |
| tracking cookie set without consent | same; or GTM fires a tag without an `ad_storage` condition (analytics.md → GTM) |
| GA hit with consent GRANTED | `setDefaultConsent` not before the tag — `<Analytics>` must be inside `<ConsentProvider>` (`SiteProviders` does this itself) |
| YouTube / Maps before consent (warning) | `ConsentScript` (consent.md), `youtube-nocookie.com` or "click to load" |
4. Sekcja „after accept” mówi, co startuje po zgodzie — porównaj z ID w Site
Integrations (np. czy Meta Pixel jest, jeśli klient go ma). Nic nie startuje,
a ID są wpisane → zgłoś to jako problem do diagnozy (**ipal-debug**).
5. Banner nie znaleziony (`data-ipal="banner"`) → `<CookieBanner/>` nie jest
renderowany albo starsza wersja ipal-kit bez atrybutów `data-ipal` na przyciskach → **ipal-upgrade**.
4. The "after accept" section shows what starts after consent — compare it with the IDs in Site
Integrations (e.g. is Meta Pixel there, if the client has one). Nothing starts
but IDs are filled in → report it as a problem to diagnose (**ipal-debug**).
5. Banner not found (`data-ipal="banner"`) → `<CookieBanner/>` is not
rendered, or an older ipal-kit version without `data-ipal` attributes on the buttons → **ipal-upgrade**.
Skrypt wymaga przycisków z `data-ipal="accept"` / `"reject"` — ma je
`CookieBanner` z pluginu w każdym trybie `settings` (`inline`, `modal`, `detailed`). Własny baner w projekcie to naruszenie AGENT.md §7.
The script needs buttons with `data-ipal="accept"` / `"reject"` — the plugin's
`CookieBanner` has them in every `settings` mode (`inline`, `modal`, `detailed`). A custom banner in the project violates AGENT.md §7.
## Lista ciasteczek do polityki cookies (cookie-scan)
## Cookie list for the cookie policy (cookie-scan)
Po każdej zmianie narzędzi (nowy piksel, czat, mapa, wideo) i przed oddaniem strony:
After every change of tools (new pixel, chat, map, video) and before handing the site over:
1. Skan działającej strony (bez zgody i po „Akceptuj wszystko”, strona główna + do 10 stron z sitemapy):
1. Scan the running site (without consent and after "Accept all", homepage + up to 10 pages from the sitemap):
```bash
node .agents/skills/ipal-consent-check/scripts/cookie-scan.mjs http://localhost:3000 --lang pl
```
Wynik: `cookie-scan/cookies.json` i `cookie-scan/cookies.md` (tabela). `[ERROR]` = ciasteczko
**nie-niezbędne ustawione przed zgodą** — napraw jak w tabeli wyżej. `[WARNING] unknown` —
ustal dostawcę i cel, wpisz `category` (`necessary|functional|analytics|marketing`) i `purpose`
w `cookies.json`. Nie zgaduj — zapytaj, jeśli nie wiesz.
2. Import do panelu (Cookie Settings → Cookies), każdy język osobno (skan z `--lang en` dla angielskiego):
Output: `cookie-scan/cookies.json` and `cookie-scan/cookies.md` (table). `[ERROR]` = a
**non-necessary cookie set before consent** — fix it as in the table above. `[WARNING] unknown` —
find the provider and purpose, set `category` (`necessary|functional|analytics|marketing`) and `purpose`
in `cookies.json`. Do not guess — ask if you do not know.
2. Import into the panel (Cookie Settings → Cookies), each language separately (scan with `--lang en` for English):
```bash
LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
```
Łączy po nazwie, nie nadpisuje zmian redaktora (`OVERWRITE=1` wymusza). Nie usuwa ciasteczek,
których skan nie widział — to robi redaktor w panelu. Ta sama lista zasila okno
`<CookieBanner settings="detailed">` (rozwijana lista pod każdą kategorią) — po imporcie otwórz
„Ustawienia” w banerze i sprawdź, że każda kategoria pokazuje swoje ciasteczka, a podpisy
(Cookie Settings → Detail labels) są w danym języku.
3. Strona polityki cookies pokazuje tabelę z panelu — **nie wklejaj listy do treści polityki**:
It merges by name and does not overwrite editor changes (`OVERWRITE=1` forces it). It does not delete cookies
the scan did not see — the editor does that in the panel. The same list feeds the
`<CookieBanner settings="detailed">` window (an expandable list under each category) — after the import open
"Settings" in the banner and check that every category shows its cookies and that the labels
(Cookie Settings → Detail labels) are in that language.
3. The cookie policy page shows the table from the panel — **do not paste the list into the policy text**:
```tsx
import { getCookieTable } from '@intecion/ipal-kit'
import { CookieTable } from '@intecion/ipal-kit/rsc'
import { getCachedPayload, getSiteShell } from '@/lib/content'
const rows = await getCookieTable({ payload: await getCachedPayload(), locale })
const { consent } = await getSiteShell(locale) // nazwy kategorii z Cookie Settings
const { consent } = await getSiteShell(locale) // category names from Cookie Settings
<CookieTable rows={rows} categories={consent.categories} labels={labels} />
```
`labels` = `{ name, category, provider, purpose, duration }` (wszystkie wymagane). Panel pluginu
ma tylko `provider` / `purpose` / `duration` (Cookie Settings → Detail labels = `consent.details`);
nagłówki `name` i `category` daj z pól (localized) bloku projektu. Tabela bez stylów
(`classNames`: `table`, `caption`, `tr`, `th`, `td`; opcjonalny `caption`). Blok projektu „Cookie
table” na stronie polityki to dobre miejsce — wtedy redaktor decyduje, gdzie się pojawi.
`labels` = `{ name, category, provider, purpose, duration }` (all required). The plugin panel
has only `provider` / `purpose` / `duration` (Cookie Settings → Detail labels = `consent.details`);
take the `name` and `category` headers from (localized) fields of the project block. The table is unstyled
(`classNames`: `table`, `caption`, `tr`, `th`, `td`; optional `caption`). A project "Cookie
table" block on the policy page is a good place — then the editor decides where it appears.
Czas życia: Chrome skraca każde ciasteczko do maks. 400 dni (13 mies.) — skan pokazuje to, co
realnie zostaje w przeglądarce. Klucze localStorage (np. `ipal-theme` — wybrany motyw) są wymienione osobno.
Lifetime: Chrome caps every cookie at max. 400 days (13 months) — the scan shows what
really stays in the browser. localStorage keys (e.g. `ipal-theme` — the chosen theme) are listed separately.
+76 -76
View File
@@ -5,94 +5,94 @@ description: Systematic diagnosis for ipal-kit / Payload 3 / Next 16 projects
# ipal-debug
Nie zgaduj, nie przepisuj na ślepo, nie pytaj użytkownika, zanim nie przejdziesz
tej procedury. Pytasz tylko, gdy brakuje czegoś, czego nie możesz uzyskać sam
(sekret, dostęp do panelu produkcji, decyzja biznesowa).
Do not guess, do not rewrite blindly, and do not ask the user before you have gone
through this procedure. Ask only when you are missing something you cannot get yourself
(a secret, access to the production admin panel, a business decision).
## Procedura
1. **Odtwórz** — dokładna komenda / URL / klik, pełny komunikat (pierwszy błąd w
logu, nie ostatni). Dev i build zachowują się inaczej — sprawdź oba, jeśli dotyczy renderingu/SEO.
2. **Zawęź warstwę**:
| Pytanie | Jak sprawdzić |
## Procedure
1. **Reproduce** — the exact command / URL / click, the full message (the first error in
the log, not the last). Dev and build behave differently — check both if it concerns rendering/SEO.
2. **Narrow down the layer**:
| Question | How to check |
|---|---|
| kod projektu? | `git diff`/`git stash` → czy błąd znika |
| konfiguracja? | `payload.config.ts`, `next.config.ts`, `proxy.ts`, `.env` vs `docs/env.md` |
| dane w panelu? | ta sama strona w innym języku / inny dokument działa? `Save` kliknięty? |
| środowisko? | `rm -rf .next`, restart dev, `pnpm install`, wersje: `pnpm why @payloadcms/ui` |
| ipal-kit? | błąd w `node_modules/@intecion/ipal-kit/dist/…`, zachowanie niezgodne z `docs/<moduł>.md` |
3. **Tabela niżej** — większość błędów już się zdarzyła.
4. **Napraw przyczynę**, nie objaw (`as any`, `try/catch` połykający błąd,
`force-dynamic` „żeby działało”, kopia kodu pluginu do projektu = **nie**).
5. **Udowodnij**: ta sama komenda z kroku 1 przechodzi + `ipal-audit --quick` +
(rendering/SEO) `ipal-seo-check` na buildzie.
6. Błąd po stronie ipal-kit → obejście w projekcie **tylko jeśli jest czyste i
oznaczone** (`// WORKAROUND ipal-kit <wersja>: <opis>`) + raport **ipal-plugin-gap**.
Zapisz przypadek w `AGENTS.md` → „Ustalenia projektu”, jeśli wróci.
| project code? | `git diff`/`git stash` → does the error go away |
| configuration? | `payload.config.ts`, `next.config.ts`, `proxy.ts`, `.env` vs `docs/env.md` |
| panel data? | does the same page in another language / another document work? Was `Save` clicked? |
| environment? | `rm -rf .next`, restart dev, `pnpm install`, versions: `pnpm why @payloadcms/ui` |
| ipal-kit? | error in `node_modules/@intecion/ipal-kit/dist/…`, behaviour that contradicts `docs/<module>.md` |
3. **The table below** — most errors have happened before.
4. **Fix the cause**, not the symptom (`as any`, a `try/catch` that swallows the error,
`force-dynamic` "to make it work", copying plugin code into the project = **no**).
5. **Prove it**: the same command from step 1 passes + `ipal-audit --quick` +
(rendering/SEO) `ipal-seo-check` on the build.
6. Bug on the ipal-kit side → a workaround in the project **only if it is clean and
marked** (`// WORKAROUND ipal-kit <version>: <description>`) + an **ipal-plugin-gap** report.
Record the case in `AGENTS.md` → "Project decisions" if it may come back.
## Objaw → przyczyna → naprawa
## Symptom → cause → fix
### Build / TypeScript
| Objaw | Przyczyna | Naprawa |
| Symptom | Cause | Fix |
|---|---|---|
| `TS2307 next/navigation` w `dist` pluginu | import bez `.js` w kliencie pluginu (NodeNext) | **bug ipal-kit** → plugin-gap; plugin importuje `'next/navigation.js'` |
| `TS2307 @payloadcms/storage-s3` | brak pakietu przy `buildR2Storage` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| `does not provide an export named X` / `X is not a function` | symbol nie wyeksportowany z entry pointu albo zły subpath (`/client` vs root vs `/server` vs `/rsc`) | `docs/README.md` → właściwy import; brak w każdym entry → **bug ipal-kit** (eksport) |
| `Cannot find module '@clocklimited/payload-2fa'` | brak wstrzyknięcia | `twoFactor: { plugin: payloadTotp }` (`serverExternalPackages` nie pomaga — pada na `.css`) |
| `TS2322` przy `plugin: payloadTotp` (`string` vs `CollectionSlug`) | ipal-kit ≤ 1.8.13 typował `collection` jako `string` | zaktualizuj ipal-kit; usuń adapter/rzutowanie |
| `Page changed from static to dynamic at runtime` | `headers()`, `cookies()`, `searchParams` w drzewie strony (często `not-found.tsx`) | locale z `params`; `not-found` → `LocaleView` (pages.md); `headers()` tylko w server actions / route handlers |
| trasy `ƒ` mimo `generateStaticParams` | build nie widzi bazy | `DATABASE_URI` w buildzie (PROGRAMISTA §4.3) |
| build pada `ENOTFOUND` / Mongoose | trasa czyta bazę w buildzie bez bazy | trasy czytające bazę (sitemap.xml, manifest, llms.txt, llms-full.txt, api/health): `export const dynamic = 'force-dynamic'` (tylko one, nie strony) |
| `slug.join is not a function` | `[slug]` zamiast `[[...slug]]` | zmień nazwę folderu |
| `Missing <html> and <body>` | layout `[locale]` bez `<html>` po usunięciu root layoutu | `<html lang>` i `<body>` w `[locale]/layout.tsx` |
| `Export fileTypeFromFile doesn't exist in target module` (Turbopack, start dev) | `instrumentation.ts` importuje z roota pakietu → Payload w bundlu Edge | import z `@intecion/ipal-kit/env` + `NEXT_RUNTIME === 'nodejs'` (env.md) |
| `R2_PUBLIC_URL must be a valid URL (got "/media")` | stara wersja reguły / produkcja ze ścieżką względną | dev: `/media` dozwolone od nowej wersji; produkcja: pełny URL domeny bucketu |
| `server-only` w kliencie | import z `@intecion/ipal-kit/server` w `'use client'` | wywołuj przez server action |
| `TS2307 next/navigation` in the plugin's `dist` | import without `.js` in the plugin client (NodeNext) | **ipal-kit bug** → plugin gap; the plugin imports `'next/navigation.js'` |
| `TS2307 @payloadcms/storage-s3` | package missing when using `buildR2Storage` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| `does not provide an export named X` / `X is not a function` | symbol not exported from the entry point, or wrong subpath (`/client` vs root vs `/server` vs `/rsc`) | `docs/README.md` → the right import; missing from every entry → **ipal-kit bug** (export) |
| `Cannot find module '@clocklimited/payload-2fa'` | not injected | `twoFactor: { plugin: payloadTotp }` (`serverExternalPackages` does not help — it fails on `.css`) |
| `TS2322` on `plugin: payloadTotp` (`string` vs `CollectionSlug`) | ipal-kit ≤ 1.8.13 typed `collection` as `string` | update ipal-kit; remove the adapter/cast |
| `Page changed from static to dynamic at runtime` | `headers()`, `cookies()`, `searchParams` in the page tree (often `not-found.tsx`) | locale from `params`; `not-found` → `LocaleView` (pages.md); `headers()` only in server actions / route handlers |
| `ƒ` routes despite `generateStaticParams` | the build cannot see the database | `DATABASE_URI` in the build (PROGRAMISTA §4.3) |
| build fails with `ENOTFOUND` / Mongoose | a route reads the database during a build without a database | routes that read the database (sitemap.xml, manifest, llms.txt, llms-full.txt, api/health): `export const dynamic = 'force-dynamic'` (only these, not pages) |
| `slug.join is not a function` | `[slug]` instead of `[[...slug]]` | rename the folder |
| `Missing <html> and <body>` | `[locale]` layout without `<html>` after the root layout was removed | `<html lang>` and `<body>` in `[locale]/layout.tsx` |
| `Export fileTypeFromFile doesn't exist in target module` (Turbopack, dev start) | `instrumentation.ts` imports from the package root → Payload in the Edge bundle | import from `@intecion/ipal-kit/env` + `NEXT_RUNTIME === 'nodejs'` (env.md) |
| `R2_PUBLIC_URL must be a valid URL (got "/media")` | old version of the rule / production with a relative path | dev: `/media` allowed since the new version; production: full URL of the media domain, or leave it empty (media through the app) and make the rule optional (env.md) |
| `server-only` in the client | import from `@intecion/ipal-kit/server` in `'use client'` | call it through a server action |
### Panel (`/admin`)
| Objaw | Przyczyna | Naprawa |
### Admin panel (`/admin`)
| Symptom | Cause | Fix |
|---|---|---|
| `PayloadComponent not found in importMap` (np. `@intecion/ipal-kit/admin#RowLabel`) | importMap nieaktualny po aktualizacji pluginu / dodaniu `rowLabel` | `pnpm payload generate:importmap`, restart |
| `Cannot destructure property 'config'` / hooki UI bez kontekstu | dwie kopie `@payloadcms/ui` | `pnpm why @payloadcms/ui`; jedna wersja + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = pusto |
| pusty tab SEO, brak Forms | rozjazd wersji `@payloadcms/*` | wszystkie `@payloadcms/*` = wersja `payload` |
| upload odrzucony „Image is … Tick Optimize” | `buildOptimizeUploadHook` (zamierzone) | zaznacz checkbox albo przygotuj plik; limit w opcjach hooka |
| upload wideo odrzucony | limit `maxVideoBytes` | eksport wg komunikatu (H.264, 720–1080p, fast start) |
| zmiana w panelu niewidoczna | brak Save / ISR bez rewalidacji | kolekcja: `buildRevalidateHook`; global (Header, Footer…): własny `afterChange` z `revalidatePath('/', 'layout')` (ipal-nav) — globali pluginu (Site Settings, Cookie Settings, Notifications) plugin nie rewaliduje (raport ipal-plugin-gap): czeka do końca okna `revalidate`; doraźnie dopisz im `afterChange` własnym pluginem po `ipalKit` w `plugins` (modyfikuje `config.globals`) |
| `PayloadComponent not found in importMap` (e.g. `@intecion/ipal-kit/admin#RowLabel`) | importMap out of date after a plugin update / adding `rowLabel` | `pnpm payload generate:importmap`, restart |
| `Cannot destructure property 'config'` / UI hooks without context | two copies of `@payloadcms/ui` | `pnpm why @payloadcms/ui`; one version + `pnpm.overrides`; `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms` = empty |
| empty SEO tab, no Forms | mismatched `@payloadcms/*` versions | all `@payloadcms/*` = the `payload` version |
| upload rejected "Image is … Tick Optimize" | `buildOptimizeUploadHook` (intended) | tick the checkbox or prepare the file; limit in the hook options |
| video upload rejected | `maxVideoBytes` limit | export as the message says (H.264, 720–1080p, fast start) |
| change in the panel not visible | no Save / ISR without revalidation | collection: `buildRevalidateHook`; global (Header, Footer…): your own `afterChange` with `revalidatePath('/', 'layout')` (ipal-nav) — the plugin does not revalidate its own globals (Site Settings, Cookie Settings, Notifications) (ipal-plugin-gap report): the change waits until the `revalidate` window ends; as a stopgap add an `afterChange` to them with your own plugin placed after `ipalKit` in `plugins` (it modifies `config.globals`) |
### Front / routing / SEO
| Objaw | Przyczyna | Naprawa |
### Front end / routing / SEO
| Symptom | Cause | Fix |
|---|---|---|
| `/pl` → 404 | Homepage nieprzypisany w System Pages | ustaw w panelu |
| `/en/*` → 404, `/pl/*` działa | brak sluga/tytułu w EN | `ipal-locale-add` → `locale-coverage` |
| przełącznik języka → 404 | podmiana prefiksu zamiast `AlternateLinksUpdater` | i18n.md → AlternateLinks |
| metadata w `<body>` (seo-check) | streaming: brak `htmlLimitedBots`, jawny `<head>`, dynamiczna strona | AGENT §4; `generatePageMetadata` |
| canonical / sitemap z localhost | `NEXT_PUBLIC_SERVER_URL` nieustawione w buildzie | ustaw w env buildu (nie tylko runtime) |
| `/admin`, `/_next` → 500 lub pętla | matcher proxy nie jest literałem | matcher inline w `proxy.ts` |
| hydration mismatch przy banerze | odczyt cookie/`window` w renderze | consent tylko przez `CookieBanner`/`useConsentContext`; `Date`, `Math.random` poza renderem |
| obrazy nie ładują się (R2) | brak domeny w `images.remotePatterns` / zły `R2_PUBLIC_URL` | `next.config.ts` + env (storage.md) |
| 404 strona bez stylów/nav | `not-found.tsx` poza `[locale]` bez layoutu | pages.md — przykład `not-found` |
| `/pl` → 404 | Homepage not assigned in System Pages | set it in the panel |
| `/en/*` → 404, `/pl/*` works | slug/title missing in EN | `ipal-locale-add` → `locale-coverage` |
| language switcher → 404 | prefix swap instead of `AlternateLinksUpdater` | i18n.md → AlternateLinks |
| metadata in `<body>` (seo-check) | streaming: no `htmlLimitedBots`, explicit `<head>`, dynamic page | AGENT §4; `generatePageMetadata` |
| canonical / sitemap with localhost | `NEXT_PUBLIC_SERVER_URL` not set in the build | set it in the build env (not only at runtime) |
| `/admin`, `/_next` → 500 or a loop | the proxy matcher is not a literal | inline matcher in `proxy.ts` |
| hydration mismatch on the banner | reading cookie/`window` during render | consent only through `CookieBanner`/`useConsentContext`; `Date`, `Math.random` outside render |
| images do not load (R2) | media domain missing in `images.remotePatterns` / wrong `R2_PUBLIC_URL`; without `R2_PUBLIC_URL`: Media has no `access.read: () => true` → 403 on `/api/media/file/…` | `next.config.ts` + env, or Media access (storage.md) |
| 404 page without styles/nav | `not-found.tsx` outside `[locale]` without a layout | pages.md — `not-found` example |
### Zgoda / analityka / formularze / mail
| Objaw | Przyczyna | Naprawa |
### Consent / analytics / forms / email
| Symptom | Cause | Fix |
|---|---|---|
| piksel przed zgodą (consent-check) | skrypt wpięty ręcznie (`<Script>`) | wyłącznie przez panel → `<Analytics>` (GA/GTM/piksele) albo `<ConsentScript>` (analytics.md, consent.md) |
| baner bez stylów | Tailwind nie skanuje pluginu | `@source` na `node_modules/@intecion/ipal-kit/dist/**/*.js` (ścieżka względem pliku CSS, PROGRAMISTA §2.5) |
| maile nie wychodzą | brak `email: mailAdapter()` / pusty transport / pusta zakładka Emails | email.md; Send test w panelu |
| nadawca maila stary | cache klienta poczty | sprawdź surowe nagłówki |
| formularz: `unknown_fields` | pole spoza definicji (honeypot nieusunięty) | `ipal-form` → actions.ts |
| Turnstile zawsze odrzuca | log `[ipal] Turnstile …` mówi dlaczego: brak sekretu, `invalid-input-secret`, `timeout-or-duplicate` | turnstile.md → tabela; sekret w panelu albo `TURNSTILE_SECRET_KEY`; **nie** zapisuj sekretu kodem |
| pixel before consent (consent-check) | script wired by hand (`<Script>`) | only through the panel → `<Analytics>` (GA/GTM/pixels) or `<ConsentScript>` (analytics.md, consent.md) |
| banner without styles | Tailwind does not scan the plugin | `@source` on `node_modules/@intecion/ipal-kit/dist/**/*.js` (path relative to the CSS file, PROGRAMISTA §2.5) |
| emails are not sent | no `email: mailAdapter()` / empty transport / empty Emails tab | email.md; Send test in the panel |
| old email sender | mail client cache | check the raw headers |
| form: `unknown_fields` | field outside the definition (honeypot not removed) | `ipal-form` → actions.ts |
| Turnstile always rejects | the `[ipal] Turnstile …` log says why: no secret, `invalid-input-secret`, `timeout-or-duplicate` | turnstile.md → table; secret in the panel or `TURNSTILE_SECRET_KEY`; **do not** write the secret in code |
### Środowisko
| Objaw | Przyczyna | Naprawa |
### Environment
| Symptom | Cause | Fix |
|---|---|---|
| zmiana w pluginie niewidoczna | stara wersja w `node_modules` / `.next` | `pnpm add @intecion/ipal-kit@<wersja>`, `grep -c <symbol> node_modules/@intecion/ipal-kit/dist/...`, `rm -rf .next`, restart |
| skille nieaktualne po aktualizacji | nie odświeżone | `pnpm exec ipal-skills` |
| `ipal-skills: command not found` | ipal-kit ≤ 1.8.13 nie publikował `bin` | zaktualizuj ipal-kit |
| „Kod dobry, zachowanie złe” | — | po kolei: restart dev → Save w panelu → dublet zależności → importmap → cache |
| change in the plugin not visible | old version in `node_modules` / `.next` | `pnpm add @intecion/ipal-kit@<version>`, `grep -c <symbol> node_modules/@intecion/ipal-kit/dist/...`, `rm -rf .next`, restart |
| skills out of date after an update | not refreshed | `pnpm exec ipal-skills` |
| `ipal-skills: command not found` | ipal-kit ≤ 1.8.13 did not publish `bin` | update ipal-kit |
| "Code is right, behaviour is wrong" | — | in order: restart dev → Save in the panel → duplicate dependency → importmap → cache |
## Kiedy to bug ipal-kit (raport, nie łatka w node_modules)
- błąd wskazuje plik w `dist` pluginu i nie wynika z błędnego użycia API z dokumentacji;
- zachowanie niezgodne z `docs/<moduł>.md`;
- dokumentacja każe importować coś, czego entry point nie eksportuje;
- ten sam boilerplate piszesz w drugim projekcie z rzędu (kandydat na moduł).
Wtedy **ipal-plugin-gap**: objaw, minimalne odtworzenie, wersja, proponowana
zmiana w pluginie, obejście użyte w projekcie. **Nigdy** nie edytuj `node_modules`.
## When it is an ipal-kit bug (report, not a patch in node_modules)
- the error points to a file in the plugin's `dist` and does not come from misusing the documented API;
- behaviour contradicts `docs/<module>.md`;
- the docs tell you to import something that the entry point does not export;
- you are writing the same boilerplate in a second project in a row (a module candidate).
Then **ipal-plugin-gap**: symptom, minimal reproduction, version, proposed
change in the plugin, workaround used in the project. **Never** edit `node_modules`.
+103 -101
View File
@@ -5,16 +5,16 @@ description: Wires forms the ipal-kit way — forms built by the editor in the p
# ipal-form
**Formularz buduje redaktor w panelu. Projekt ma akcję, blok z `<RenderForm>` i klasy.** Każdy
kolejny formularz — także krokowy, z listami wyboru — to tylko panel. Ręcznie wpisane pola/etykiety w JSX = błąd
(ipal-audit to złapie). Szczegóły API: `docs/forms.md`, `turnstile.md`, `notifications.md`, `email.md`.
**The editor builds the form in the panel. The project has the action, a block with `<RenderForm>` and the classes.** Every
further form — including multi-step ones and ones with choice lists — is panel work only. Fields/labels typed by hand in JSX = an error
(ipal-audit catches it). API details: `docs/forms.md`, `turnstile.md`, `notifications.md`, `email.md`.
## 1. Config (raz na projekt)
## 1. Config (once per project)
```ts
// payload.config.ts
import { ipalKit, mailAdapter, buildFormAnalyticsFields } from '@intecion/ipal-kit'
export default buildConfig({
email: mailAdapter(), // bez tego maile z Forms → Emails nie wyjdą
email: mailAdapter(), // without this, emails from Forms → Emails are not sent
plugins: [ipalKit({
i18n: i18nConfig,
forms: {
@@ -24,127 +24,129 @@ export default buildConfig({
})],
})
```
`@payloadcms/plugin-form-builder` w `dependencies` projektu **w tej samej wersji co
`payload`** (rozjazd = brak kolekcji Forms). Po zmianie: `generate:types`,
`@payloadcms/plugin-form-builder` in the project's `dependencies` **at the same version as
`payload`** (a mismatch = no Forms collection). After a change: `generate:types`,
`generate:importmap`, restart.
## 2. Layout — Turnstile raz
`<SiteProviders shell={await getSiteShell(locale)}>` w `[locale]/layout.tsx` (PROGRAMISTA §2.8)
wpina `TurnstileProvider` z kluczem z panelu — **zawsze**, nie warunkuj providera ani widgetu.
Własny layout bez SiteProviders: `<TurnstileProvider siteKey={shell.turnstileSiteKey}>` (turnstile.md).
Zachowanie z pluginu: **oba klucze** (panel lub env) → widget widoczny, a `submitForm`
**wymaga** tokenu (bot nie ominie, nie wysyłając go); brak kluczy → widgetu nie ma,
weryfikacji nie ma, formularz działa; jeden klucz → wyłączony + alert na dashboardzie.
## 2. Layout — Turnstile once
`<SiteProviders shell={await getSiteShell(locale)}>` in `[locale]/layout.tsx` (PROGRAMISTA §2.8)
wires `TurnstileProvider` with the key from the panel — **always**; never make the provider or the widget conditional.
Custom layout without SiteProviders: `<TurnstileProvider siteKey={shell.turnstileSiteKey}>` (turnstile.md).
Plugin behavior: **both keys** (panel or env) → the widget is visible and `submitForm`
**requires** a token (a bot cannot get around it by not sending one); no keys → no widget,
no verification, the form works; one key → off + an alert on the dashboard.
## 3. Kod — import, nie kopia
Renderer, kroki, walidacja, Turnstile, honeypot, przekierowanie i zdarzenie GTM są w
pluginie. W projekcie zostają **trzy krótkie pliki**:
## 3. Code — import, not copy
The renderer, steps, validation, Turnstile, honeypot, redirect and GTM event live in the
plugin. The project keeps **three short files**:
| Plik | Do projektu | Rola |
| File | Into the project | Role |
|---|---|---|
| `resources/actions.ts` | `src/app/(frontend)/[locale]/actions.ts` | `export const sendForm = createSubmitAction({ getCachedPayload, headers })` |
| `resources/FormBlock.tsx` | `src/blocks/FormBlock/Component.tsx` | `<RenderForm>` z `/rsc` + klasy projektu, w `<Section>`/`<SectionHeader>` |
| `resources/formClasses.ts` | `src/components/forms/formClasses.ts` | **jedyne** miejsce wyglądu formularzy (klasy z DESIGN.md) |
| `resources/seed-form.template.ts` | `scripts/seed-form-<nazwa>.ts` | formularz w bazie: pola, potwierdzenie, mail do firmy + do klienta, każdy język |
| `resources/FormBlock.tsx` | `src/blocks/FormBlock/Component.tsx` | `<RenderForm>` from `/rsc` + project classes, inside `<Section>`/`<SectionHeader>` |
| `resources/formClasses.ts` | `src/components/forms/formClasses.ts` | the **only** place for form styling (classes from DESIGN.md) |
| `resources/seed-form.template.ts` | `scripts/seed-form-<name>.ts` | the form in the database: fields, confirmation, email to the company + to the customer, every language |
`RenderForm` (serwer) renderuje bloki „message” i potwierdzenie przez `RenderRichText`,
wiąże akcję z formularzem i językiem, rozwiązuje redirect i **wysyła do przeglądarki tylko
publiczną część formularza** (zakładka Emails z adresami firmy nigdy nie trafia do HTML).
Pod spodem `BuilderForm` (klient) — czysty, dostępny HTML **bez stylów**: wygląd = `classNames`
(+ atrybuty `data-ipal`, `data-type`, `data-width`, `data-step`).
`RenderForm` (server) renders the "message" blocks and the confirmation via `RenderRichText`,
binds the action to the form and the language, resolves the redirect and **sends only the
public part of the form to the browser** (the Emails tab with the company addresses never reaches the HTML).
Underneath is `BuilderForm` (client) — clean, accessible HTML **without styles**: the look = `classNames`
(+ the `data-ipal`, `data-type`, `data-width`, `data-step` attributes).
**Typy pól w panelu:** text, email, textarea, number, **date**, **time**, select, **radio** (jeden wybór),
checkbox, **Checkbox group** (wiele wyborów, min/max), message, **Step** (podział na kroki),
country, state (domyślnie włączone przez form-buildera, renderowane jako pole tekstowe).
Wyłączenie typu: `forms.fields: { country: false, state: false }`.
- **Formularz krokowy:** redaktor wstawia blok **Step** (tytuł, opis) — pola pod nim to jeden
ekran. Przyciski Dalej/Wstecz i „Krok 1 z 3” z **Notifications → Form messages** (next, back,
stepOf). Dalej waliduje tylko bieżący krok; błąd z serwera wraca na krok z polem; fokus
przechodzi na nowy krok. Bez Step = jeden ekran.
- `width` ≤ 50 → klasa `fieldHalf`, inaczej `fieldFull`.
**Field types in the panel:** text, email, textarea, number, **date**, **time**, select, **radio** (single choice),
checkbox, **Checkbox group** (multiple choice, min/max), message, **Step** (splits into steps),
country, state (on by default in form-builder, rendered as a text field).
Turning a type off: `forms.fields: { country: false, state: false }`.
- **Multi-step form:** the editor inserts a **Step** block (title, description) — the fields below it form one
screen. The Next/Back buttons and "Step 1 of 3" come from **Notifications → Form messages** (next, back,
stepOf). Next validates only the current step; a server error returns to the step with the field; focus
moves to the new step. No Step = one screen.
- `width` ≤ 50 → class `fieldHalf`, otherwise `fieldFull`.
**Formularz nietypowy** (karty do wyboru zamiast radio, podsumowanie przed wysłaniem,
własny typ pola, suwak): nie kopiuj silnika — w kolejności:
1. `renderField` w `BuilderForm` (plik `'use client'`): podmieniasz wybrane pola, reszta domyślna
(`defaultRender()` daje oryginał do owinięcia);
2. własny komponent na `useBuilderForm` — pełna kontrola nad markupem, ta sama logika
**Unusual form** (option cards instead of radios, a summary before sending,
a custom field type, a slider): do not copy the engine — in this order:
1. `renderField` in `BuilderForm` (a `'use client'` file): replace chosen fields, the rest stay default
(`defaultRender()` gives the original to wrap);
2. your own component on `useBuilderForm` — full control over markup, same logic
(`resources/CustomForm.example.tsx`): `steps`, `step`, `next/back/goTo`, `submit`,
`getInputProps / getTextareaProps / getSelectProps / getOptionProps`, `errors`, `TurnstileWidget`.
**Pole wypełniane przez stronę** (wybrany wariant produktu, kategoria, oferta): w panelu zwykłe pole tekstowe
(np. `subject`), w kodzie `RenderForm values={{ subject }}`; wartość zmieniana w przeglądarce →
`prepareBuilderForm` (serwer) + `<BuilderForm values>` (klient). Nigdy kopia `publicForm` w projekcie (forms.md).
Własny typ pola w panelu: typ `FormsOption['fields']` przyjmuje tylko `boolean` dla znanych typów
(runtime przepuszcza obiekt bloku do form-buildera, ale TS go odrzuci), a serwer i tak potraktuje
nieznany typ jak tekst — potrzebujesz własnego typu lub walidacji → **ipal-plugin-gap**.
**Field filled in by the page** (selected product variant, category, offer): in the panel a plain text field
(e.g. `subject`), in code `RenderForm values={{ subject }}`; a value changed in the browser →
`prepareBuilderForm` (server) + `<BuilderForm values>` (client). Never a copy of `publicForm` in the project (forms.md).
Custom field type in the panel: the `FormsOption['fields']` type only accepts `boolean` for known types
(at runtime the block object passes through to form-builder, but TS rejects it), and the server treats
an unknown type as text anyway — if you need a custom type or validation → **plugin gap** (`ipal-plugin-gap`).
## 4. Strona — dane do bloku raz (bloki nie importują `lib/*`)
Z `createPageRoute` (PROGRAMISTA §2.8):
## 4. Page — block data once (blocks do not import `lib/*`)
From `createPageRoute` (PROGRAMISTA §2.8):
```tsx
const route = createPageRoute(content, {
blocks: blockRegistry, notFound, permanentRedirect,
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
})
```
Własna strona: to samo w `enhanceProps` (`formTexts` z `getFormTexts(locale)`, `sendForm` z `actions.ts`).
Zapytanie strony: `depth` ≥ 1 (relacja `form` jako obiekt). Rejestr bloków:
`formBlock: FormBlock`. Formularz poza blokiem (stopka, modal) = ten sam `<RenderForm>`
z formularzem z relacji w globalu, nigdy kopia.
Custom page: the same in `enhanceProps` (`formTexts` from `getFormTexts(locale)`, `sendForm` from `actions.ts`).
Page query: `depth` ≥ 1 (the `form` relationship as an object). Block registry:
`formBlock: FormBlock`. A form outside a block (footer, modal) = the same `<RenderForm>`
with the form from a relationship in a global, never a copy.
## 5. Formularz w bazie — ZAWSZE seedem (`resources/seed-form.template.ts`)
Każdy formularz z briefu powstaje skryptem, nie ręcznie: wtedy jest powtarzalny (dev → produkcja),
ma wszystkie języki i **oba maile**, o których łatwo zapomnieć:
- **powiadomienie do firmy**: `emailTo` = adres z panelu (global firmy), `replyTo: {{email}}`, treść `{{*:table}}`;
- **potwierdzenie do klienta**: `emailTo: {{email}}`, `replyTo` = adres firmy, temat i treść per język.
## 5. Form in the database — ALWAYS via a seed (`resources/seed-form.template.ts`)
Every form from the brief is created by a script, not by hand: that makes it repeatable (dev → production),
it has every language and **both emails**, which are easy to forget:
- **notification to the company**: `emailTo` = address from the panel (company global), `replyTo: {{email}}`, body `{{*:table}}`;
- **confirmation to the customer**: `emailTo: {{email}}`, `replyTo` = company address, subject and body per language.
```bash
cp .agents/skills/ipal-form/resources/seed-form.template.ts scripts/seed-form-contact.ts
# uzupełnij FORM z briefu (pola, etykiety, komunikaty, tematy maili — każdy język), NOTIFY = global/pole z adresem firmy
# fill FORM from the brief (fields, labels, messages, email subjects — every language), NOTIFY = global/field with the company address
pnpm payload run scripts/seed-form-contact.ts
```
Bez adresu powiadomień skrypt **zatrzymuje się** — zapytaj klienta, na jaką skrzynkę mają przychodzić
zgłoszenia (pytanie z listy w ipal-site), wpisz go w panelu i uruchom ponownie. Nie wpisuj adresu w kod.
Skrypt commitujesz — na produkcji uruchamiasz go po migracji. Zmiana formularza: popraw FORM,
`SEED_UPDATE=1 pnpm payload run …` (nadpisuje zmiany redaktora — tylko przed oddaniem).
Without a notification address the script **stops** — ask the client which inbox should receive
submissions (a question from the list in ipal-site), enter it in the panel and run again. Never put the address in code.
Commit the script — in production run it after the migration: `SEED_DRY_RUN=1` first, back up the database, then
the real run (rules: `node_modules/@intecion/ipal-kit/docs/seeding.md`). Changing the form: fix FORM,
`SEED_UPDATE=1 pnpm payload run …` — it updates the form only if nobody edited it since seeding (otherwise
`skip (edited)`); on production / a non-local database it also needs `IPAL_SEED_ALLOW_PROD_UPDATE=1`.
Szczegóły, które seed już spełnia, a które sprawdzasz po każdej ręcznej zmianie w panelu:
1. **Forms → formularz**: pola z briefu, `name` po angielsku, małe litery
(`name`, `email`, `phone`, `message`, `consent`); etykiety per język.
2. **Zgoda RODO**: checkbox `consent`, etykieta z linkiem do polityki, **nie**
zaznaczony domyślnie (plugin i tak wymusza server-side → `reason: 'consent'`).
3. **Confirmation**: komunikat (per język) albo redirect na stronę „Dziękujemy”
(wtedy ta strona `noindex`).
4. **Emails**: powiadomienie do firmy (`emailTo` z globalu firmy/panelu, `replyTo: {{email}}`,
treść `{{*:table}}`) **i** potwierdzenie do wysyłającego (`emailTo: {{email}}`) — oba obowiązkowe.
Pole e-mail musi mieć `name: 'email'` (plugin przyjmuje w nim dokładnie jeden adres).
5. **Analytics (GTM / dataLayer)**: Event name `generate_lead` / `form_submit`, parametry `form_name`.
6. **Site Integrations**: transport maila (SMTP/Graph) + **Send test**; klucze Turnstile.
7. **Notifications → form.\***: teksty w każdym języku.
Details the seed already covers, which you check after every manual change in the panel:
1. **Forms → the form**: fields from the brief, `name` in English, lowercase
(`name`, `email`, `phone`, `message`, `consent`); labels per language.
2. **GDPR consent**: a `consent` checkbox, a label with a link to the policy, **not**
ticked by default (the plugin enforces it server-side anyway → `reason: 'consent'`).
3. **Confirmation**: a message (per language) or a redirect to a "Thank you" page
(then that page gets `noindex`).
4. **Emails**: notification to the company (`emailTo` from the company global/panel, `replyTo: {{email}}`,
body `{{*:table}}`) **and** confirmation to the sender (`emailTo: {{email}}`) — both mandatory.
The email field must have `name: 'email'` (the plugin accepts exactly one address in it).
5. **Analytics (GTM / dataLayer)**: Event name `generate_lead` / `form_submit`, parameters `form_name`.
6. **Site Integrations**: mail transport (SMTP/Graph) + **Send test**; Turnstile keys.
7. **Notifications → form.\***: texts in every language.
## 6. Sprawdź sam, zanim powiesz „gotowe”
- [ ] wysyłka z pustymi wymaganymi polami → błędy przy polach, bez requestu;
- [ ] poprawna wysyłka → potwierdzenie, rekord w **Form Submissions**, mail do firmy doszedł
**i** potwierdzenie doszło na adres wpisany w formularzu
(Send test w panelu działa = transport OK; brak maila mimo to → zakładka Emails formularza);
- [ ] niezaznaczona zgoda → komunikat z Notifications (nie angielski fallback);
- [ ] 6 szybkich wysyłek → `rate_limited`;
- [ ] Turnstile z kluczami → widget widoczny; wysłanie bez rozwiązanego widgetu → `turnstile`;
zły sekret → formularz przechodzi, a w panelu (dashboard + Site Integrations → Turnstile) jest czerwony alert;
- [ ] Turnstile bez kluczy → brak widgetu, formularz przechodzi;
- [ ] drugi język → etykiety i komunikaty w tym języku;
- [ ] GTM Preview → zdarzenie z nazwą z panelu po sukcesie;
- [ ] formularz krokowy: Dalej z pustym krokiem → błędy, krok zostaje; Wstecz zachowuje wpisane wartości;
- [ ] `ipal-audit --quick` → zero hardkodów w FormBlock, brak kopii silnika formularza;
- [ ] `ipal-consent-check` → nadal 0 naruszeń (Turnstile to niezbędny, nie śledzący).
## 6. Check it yourself before you say "done"
- [ ] submitting with empty required fields → errors at the fields, no request;
- [ ] a valid submission → confirmation, a record in **Form Submissions**, the email to the company arrived
**and** the confirmation arrived at the address entered in the form
(Send test in the panel works = transport OK; still no email → the form's Emails tab);
- [ ] unticked consent → a message from Notifications (not the English fallback);
- [ ] 6 quick submissions → `rate_limited`;
- [ ] Turnstile with keys → widget visible; submitting without solving the widget → `turnstile`;
wrong secret → the form goes through, and the panel (dashboard + Site Integrations → Turnstile) shows a red alert;
- [ ] Turnstile without keys → no widget, the form goes through;
- [ ] second language → labels and messages in that language;
- [ ] GTM Preview → an event with the name from the panel after success;
- [ ] multi-step form: Next with an empty step → errors, the step stays; Back keeps the entered values;
- [ ] `ipal-audit --quick` → zero hardcoding in FormBlock, no copy of the form engine;
- [ ] `ipal-consent-check` → still 0 violations (Turnstile is necessary, not tracking).
## Diagnostyka
| Objaw | Przyczyna → naprawa |
## Diagnostics
| Symptom | Cause → fix |
|---|---|
| brak kolekcji Forms w panelu | rozjazd wersji form-buildera vs payload → ta sama wersja, `pnpm.overrides` |
| blok renderuje nic | `form` to ID (za małe `depth`) albo brak `formTexts`/`sendForm` w enhanceProps |
| `reason: 'validation'`, `kind: 'unknown_fields'` | front wysyła pole, którego formularz nie ma (własny renderer z dodatkowym polem, literówka w `name`) |
| przyciski „Next/Back” po angielsku | puste Notifications → Form messages → next / back / stepOf w tym języku |
| `reason: 'not_found'` | `formId` z innej bazy (seed na dev, prod inny ID) — relacja z panelu, nie stałe ID w kodzie |
| zgłoszenie jest, maila brak | brak `email: mailAdapter()`, pusta zakładka Emails, transport w panelu; logi serwera |
| zawsze `turnstile` | zła para kluczy / domena w Cloudflare (reset tokenu po błędzie robi BuilderForm) |
| strona stała się dynamiczna (`ƒ`) | `headers()` w komponencie zamiast w akcji |
| komunikaty po angielsku | puste Notifications w tym języku |
| no Forms collection in the panel | form-builder vs payload version mismatch → same version, `pnpm.overrides` |
| the block renders nothing | `form` is an ID (`depth` too low) or `formTexts`/`sendForm` missing in enhanceProps |
| `reason: 'validation'`, `kind: 'unknown_fields'` | the frontend sends a field the form does not have (custom renderer with an extra field, typo in `name`) |
| "Next/Back" buttons in English | empty Notifications → Form messages → next / back / stepOf in that language |
| `reason: 'not_found'` | `formId` from another database (seeded on dev, another ID on prod) — use a relationship from the panel, not a fixed ID in code |
| submission exists, no email | missing `email: mailAdapter()`, empty Emails tab, transport in the panel; server logs |
| always `turnstile` | wrong key pair / domain in Cloudflare (BuilderForm resets the token after an error) |
| the page became dynamic (`ƒ`) | `headers()` in a component instead of in the action |
| messages in English | empty Notifications in that language |
@@ -5,7 +5,7 @@ import type { BuilderFormClassNames } from '@intecion/ipal-kit/client'
export const formClasses: BuilderFormClassNames = {
form: 'grid gap-6',
progress: 'text-sm text-muted', // "Krok 1 z 3"
progress: 'text-sm text-muted', // "Step 1 of 3"
step: 'grid gap-4',
stepTitle: 'text-h3 font-semibold',
stepDescription: 'text-muted',
@@ -2,10 +2,17 @@
* Seed of ONE form in the database — fields, confirmation, and the two e-mails
* every site needs: a notification to the company and a confirmation to the
* person who sent it. Copy to scripts/seed-form-<name>.ts, fill FORM from the
* brief (every language), run:
* brief (every language), run (rules: docs/seeding.md):
*
* pnpm payload run scripts/seed-form-contact.ts # creates the form if missing
* SEED_UPDATE=1 pnpm payload run scripts/seed-form-contact.ts # also overwrites an existing one
* SEED_DRY_RUN=1 pnpm payload run scripts/seed-form-contact.ts # no writes: prints create / skip / update
* pnpm payload run scripts/seed-form-contact.ts # creates the form if missing, never overwrites
* SEED_UPDATE=1 pnpm payload run scripts/seed-form-contact.ts # also updates it if nobody edited it since seeding
* (`--dry-run` after the script path works too.)
*
* Safety: the form is matched by its title; nothing is ever deleted. SEED_UPDATE=1 is
* refused when NODE_ENV=production or the database is not local, unless
* IPAL_SEED_ALLOW_PROD_UPDATE=1 is also set — back up the database first. A form an
* editor changed is skipped and reported ("skip (edited)"); see SAFETY below.
*
* Nothing about the company lives in this file. The notification address comes
* from the panel — NOTIFY.global / NOTIFY.field below (the project's company
@@ -14,7 +21,12 @@
*
* Safe to send to {{email}}: submitForm accepts exactly one address in an
* `email` field (no extra recipients, no header injection).
*
* GOTCHA (Payload, localization.fallback: true): a read or update in locale X without
* `fallbackLocale: false` merges the FALLBACK values into X — the default-locale
* text gets saved as the X translation. Every non-default read and write below sets it.
*/
import { createHash } from 'node:crypto'
import config from '@payload-config'
import { getPayload } from 'payload'
@@ -70,6 +82,63 @@ const FORM = {
const NOTIFY = { global: 'company', field: 'email' }
// ────────────────────────────────────────────────────────────────────────────
// ─── SAFETY — defaults the project may change here or through env (docs/seeding.md) ───
/** Env var that holds the database URL (ipal-kit projects: DATABASE_URI). */
const DB_URL_ENV = process.env.SEED_DB_URL_ENV || 'DATABASE_URI'
/** Hosts that count as a local database. Add more with SEED_LOCAL_HOSTS=db,postgres. */
const LOCAL_HOSTS = ['localhost', '127.0.0.1', '::1', ...(process.env.SEED_LOCAL_HOSTS ?? '').split(',').map((h) => h.trim()).filter(Boolean)]
/**
* "Untouched since seeding", primary method: updatedAt is at most this many seconds
* after createdAt. After one seeded update the form counts as edited — add a hidden
* SEED_HASH_FIELD (formOverrides) for repeated updates.
*/
const UNTOUCHED_SECONDS = Number(process.env.SEED_UNTOUCHED_SECONDS ?? 120)
/** Optional: hidden text field with a hash of the seeded values; used only if the forms collection has it. */
const HASH_FIELD = process.env.SEED_HASH_FIELD ?? 'seedHash'
/** SEED_FORCE=1 also overwrites an edited form — refused outside a local database. */
const FORCE_ONLY_LOCAL = true
// ────────────────────────────────────────────────────────────────────────────
const DRY = process.argv.includes('--dry-run') || process.env.SEED_DRY_RUN === '1'
const UPDATE = process.env.SEED_UPDATE === '1'
const FORCE = UPDATE && process.env.SEED_FORCE === '1'
function dbIsLocal(): boolean {
const url = (process.env[DB_URL_ENV] ?? '').trim()
if (!url) return false
if (/^file:/i.test(url) || /\.(db|sqlite3?)$/i.test(url)) return true // SQLite file
try {
const u = new URL(url)
if (u.protocol === 'mongodb+srv:') return false
if (u.searchParams.get('host')?.startsWith('/')) return true // ?host=/var/run/postgresql
const host = decodeURIComponent(u.hostname).replace(/^\[|\]$/g, '')
if (!host || host.startsWith('/')) return true // postgres:///db = unix socket
return LOCAL_HOSTS.includes(host)
} catch {
return false // unparsable (e.g. several Mongo hosts) = not local
}
}
const local = dbIsLocal()
const prodLike = process.env.NODE_ENV === 'production' || !local
if (UPDATE && prodLike && process.env.IPAL_SEED_ALLOW_PROD_UPDATE !== '1') {
console.error(
`[seed-form] SEED_UPDATE=1 refused: ${process.env.NODE_ENV === 'production' ? 'NODE_ENV=production' : `${DB_URL_ENV} is not a local database`}.\n` +
' 1. Back up the database (Coolify → database → Backups → Backup now, or pg_dump -Fc "$DATABASE_URI" > before-seed.dump).\n' +
' 2. Run with SEED_DRY_RUN=1 and read the plan.\n' +
' 3. Run again with IPAL_SEED_ALLOW_PROD_UPDATE=1. An edited form is still skipped.',
)
process.exit(1)
}
if (FORCE && FORCE_ONLY_LOCAL && prodLike) {
console.error('[seed-form] SEED_FORCE=1 refused: it overwrites editors\' changes and works only on a local database.')
process.exit(1)
}
if (UPDATE && prodLike) console.warn('[seed-form] Updating a production-like database (IPAL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?')
// disableRevalidate + ipalSkipIndexNow: the plugin's hooks skip revalidation and IndexNow. ipalSeed: for project hooks.
const CTX = { ipalSeed: true, disableRevalidate: true, ipalSkipIndexNow: true }
type Localized = Readonly<Record<string, string>>
/** Plain text (with blank-line paragraphs) → Lexical rich text, as form-builder messages expect. */
@@ -158,46 +227,118 @@ function dataFor(locale: string) {
}
}
const existing = await payload.find({ collection: 'forms' as never, limit: 1, where: { title: { equals: FORM.title } } })
let id = existing.docs[0]?.id as number | string | undefined
if (id && process.env.SEED_UPDATE !== '1') {
console.log(`[seed-form] "${FORM.title}" exists (id ${id}) — unchanged. SEED_UPDATE=1 overwrites it.`)
process.exit(0)
}
if (!id) {
const created = await payload.create({ collection: 'forms' as never, data: dataFor(defaultLocale) as never, locale: defaultLocale as never })
id = created.id
} else {
await payload.update({ collection: 'forms' as never, data: dataFor(defaultLocale) as never, id, locale: defaultLocale as never })
}
// Other languages: same rows (ids kept), localized texts per locale.
for (const locale of locales.filter((l) => l !== defaultLocale)) {
const doc = (await payload.findByID({ collection: 'forms' as never, depth: 0, id, locale: locale as never })) as {
emails?: { id?: string }[]
fields?: { id?: string; options?: { id?: string }[] }[]
/** JSON with sorted keys, no row ids, null = missing — so equal content gives an equal hash. */
const stable = (v: unknown): string =>
Array.isArray(v) ? `[${v.map(stable).join(',')}]`
: v && typeof v === 'object'
? `{${Object.keys(v).filter((k) => k !== 'id' && (v as Record<string, unknown>)[k] != null).sort()
.map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`
: JSON.stringify(v ?? null)
const hashOf = (v: unknown) => createHash('sha256').update(stable(v)).digest('hex').slice(0, 32)
/** The current values at the keys the seed writes (everything else in the form is ignored). */
function project(seed: unknown, cur: unknown): unknown {
if (Array.isArray(seed)) return Array.isArray(cur) && cur.length === seed.length ? seed.map((x, i) => project(x, cur[i])) : cur
if (seed && typeof seed === 'object') {
if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return cur
return Object.fromEntries(Object.keys(seed).map((k) => [k, project((seed as Record<string, unknown>)[k], (cur as Record<string, unknown>)[k])]))
}
const d = dataFor(locale)
await payload.update({
collection: 'forms' as never,
data: {
...d,
emails: d.emails.map((e, i) => ({ ...e, id: doc.emails?.[i]?.id })),
// Keep row ids (fields and their options) — new ids would wipe the other languages' texts.
fields: d.fields.map((f, i) => ({
...f,
id: doc.fields?.[i]?.id,
...(Array.isArray(f.options)
? { options: (f.options as Record<string, unknown>[]).map((o, j) => ({ ...o, id: doc.fields?.[i]?.options?.[j]?.id })) }
: {}),
})),
} as never,
id,
locale: locale as never,
return cur
}
const seedHash = () => hashOf(Object.fromEntries(locales.map((l) => [l, dataFor(l)])))
const hasHashField = !!HASH_FIELD && !!(payload.collections['forms' as never]?.config.fields as { name?: string }[] | undefined)?.some((f) => f.name === HASH_FIELD)
type FormDoc = Record<string, unknown> & { emails?: { id?: string }[]; fields?: { id?: string; options?: { id?: string }[] }[] }
const readForm = async (formId: number | string, locale: string) =>
(await payload.findByID({ collection: 'forms' as never, depth: 0, id: formId, locale: locale as never, fallbackLocale: false as never })) as FormDoc
/** null = untouched since seeding; a string = why it counts as edited. */
async function editedReason(formId: number | string): Promise<string | null> {
const doc = await readForm(formId, defaultLocale)
const stored = hasHashField ? doc[HASH_FIELD] : undefined
if (typeof stored === 'string' && stored) {
const current: Record<string, unknown> = {}
for (const l of locales) current[l] = project(dataFor(l), l === defaultLocale ? doc : await readForm(formId, l))
return hashOf(current) === stored ? null : `${HASH_FIELD} differs`
}
const c = Date.parse(String(doc.createdAt)), u = Date.parse(String(doc.updatedAt))
if (!Number.isFinite(c) || !Number.isFinite(u)) return 'no createdAt/updatedAt'
const sec = Math.round((u - c) / 1000)
return sec <= UNTOUCHED_SECONDS ? null : `updated ${sec}s after creation`
}
/** Locale data onto the existing row ids (fields, their options, e-mails) — new ids would wipe the other languages' texts. */
function withRowIds(d: ReturnType<typeof dataFor>, doc: FormDoc | undefined) {
if (!doc) return d
return {
...d,
emails: d.emails.map((e, i) => ({ ...e, id: doc.emails?.[i]?.id })),
fields: d.fields.map((f, i) => ({
...f,
id: doc.fields?.[i]?.id,
...(Array.isArray(f.options)
? { options: (f.options as Record<string, unknown>[]).map((o, j) => ({ ...o, id: doc.fields?.[i]?.options?.[j]?.id })) }
: {}),
})),
}
}
const summary = (status: string, errors = 0) => {
console.log(`\n[seed-form] summary${DRY ? ' (dry run — nothing written)' : ''}`)
console.table({
created: status === 'create' ? 1 : 0,
skipped: status === 'skip (exists)' ? 1 : 0,
updated: status === 'update' ? 1 : 0,
'skipped-edited': status === 'skip (edited)' ? 1 : 0,
errors,
})
}
console.log(`[seed-form] "${FORM.title}" ready (id ${id}) in ${locales.join(', ')} — notifications to ${notifyTo}, confirmation to the sender.`)
console.log(`[seed-form] ${DRY ? 'DRY RUN — nothing is written' : 'writing'} · ${UPDATE ? `updates on${FORCE ? ' (FORCE)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'}`)
const existing = await payload.find({ collection: 'forms' as never, limit: 1, where: { title: { equals: FORM.title } } })
let id = existing.docs[0]?.id as number | string | undefined
let status: 'create' | 'skip (exists)' | 'update' | 'skip (edited)' = id ? 'update' : 'create'
let note = ''
if (id && !UPDATE) { status = 'skip (exists)'; note = 'SEED_UPDATE=1 updates it if nobody edited it' }
if (id && UPDATE) {
const why = await editedReason(id)
if (why && !FORCE) { status = 'skip (edited)'; note = why }
}
if (DRY || status === 'skip (exists)' || status === 'skip (edited)') {
console.log(`${status.padEnd(14)} form "${FORM.title}"${id ? ` (id ${id})` : ''}${note ? ` — ${note}` : ''}`)
summary(status)
process.exit(0)
}
try {
const hash = hasHashField ? { [HASH_FIELD]: seedHash() } : {}
if (!id) {
const created = await payload.create({ collection: 'forms' as never, data: { ...dataFor(defaultLocale), ...hash } as never, locale: defaultLocale as never, context: CTX })
id = created.id
} else {
const doc = await readForm(id, defaultLocale)
await payload.update({ collection: 'forms' as never, data: { ...withRowIds(dataFor(defaultLocale), doc), ...hash } as never, id, locale: defaultLocale as never, context: CTX })
}
const formId = id
// Other languages: same rows (ids kept), localized texts per locale.
for (const locale of locales.filter((l) => l !== defaultLocale)) {
const doc = await readForm(formId, locale)
await payload.update({
collection: 'forms' as never,
data: withRowIds(dataFor(locale), doc) as never,
id: formId,
locale: locale as never,
fallbackLocale: false as never,
context: CTX,
})
}
} catch (e) {
console.error(`error form "${FORM.title}" — ${(e as Error).message}`)
summary('', 1)
process.exit(1)
}
console.log(`${status.padEnd(14)} form "${FORM.title}" (id ${id}) in ${locales.join(', ')} — notifications to ${notifyTo}, confirmation to the sender.`)
summary(status)
console.log('Next: place the form in a Form block on the contact page, then Site Integrations → Send test.')
process.exit(0)
+62 -62
View File
@@ -5,79 +5,79 @@ description: Adds a new language to an ipal-kit site (or turns a single-language
# ipal-locale-add
Nowy język to **konfiguracja + treść**. Kod frontu prawie się nie zmienia —
routing, hreflang, sitemap, przełącznik i consent czytają locale z jednego źródła.
Typowa porażka to nie kod, tylko **brak sluga/tytułu w nowym języku → 404** i
puste teksty globali (baner cookies po angielsku z fallbacku).
A new language is **configuration + content**. Front-end code barely changes —
routing, hreflang, sitemap, the switcher and consent read locales from one source.
The typical failure is not code but **a missing slug/title in the new language → 404** and
empty global texts (cookie banner in English from the fallback).
## 0. Ustal (zbierz w jedną listę pytań, jeśli brief nie mówi)
- kod języka (`de`, `en`, `uk`…) i etykieta w przełączniku (`Deutsch`);
- **kto tłumaczy treść**: klient w panelu / Ty robisz wersję roboczą do akceptacji /
zostają placeholdery. Bez odpowiedzi → wersja robocza oznaczona w raporcie
„do weryfikacji przez klienta”, nigdy publikacja jako finalna;
- czy wszystkie strony mają istnieć w nowym języku (domyślnie: tak).
- RTL (arabski, hebrajski) → `rtl: true` w locale + sprawdzenie stylów (`dir`, `ms-/me-` zamiast `ml-/mr-`).
## 0. Settle (collect into one list of questions if the brief does not say)
- language code (`de`, `en`, `uk`…) and the switcher label (`Deutsch`);
- **who translates the content**: the client in the admin panel / you write a draft for approval /
placeholders stay. No answer → a draft marked in the report as
"to be verified by the client", never published as final;
- whether every page should exist in the new language (default: yes).
- RTL (Arabic, Hebrew) → `rtl: true` on the locale + check the styles (`dir`, `ms-/me-` instead of `ml-/mr-`).
## 1. Projekt jednojęzyczny → wielojęzyczny (tylko jeśli był 1 locale)
To przebudowa struktury (i18n.md → „Przejście jedno- → wielojęzyczny”):
- `app/(frontend)/[[...slug]]` → `app/(frontend)/[locale]/[[...slug]]`, layout czyta `locale` z `params`;
- `generateStaticParams` zwraca pary `{ locale, slug }` dla `getConfiguredLocales()`;
- `proxy.ts` z `createProxy(i18nConfig, { NextResponse })` (redirect `/` → `/pl`);
- stare adresy bez prefiksu → przekierowania 301 na `/pl/...` (redirects w panelu albo `next.config`);
- `LanguageSwitcher` w Header + `AlternateLinksProvider` w layoucie + `AlternateLinksUpdater` na stronach.
## 1. Single-language project → multilingual (only if it had 1 locale)
This is a structural rebuild (i18n.md → "Moving from single- to multi-language"):
- `app/(frontend)/[[...slug]]` → `app/(frontend)/[locale]/[[...slug]]`, the layout reads `locale` from `params`;
- `generateStaticParams` returns `{ locale, slug }` pairs for `getConfiguredLocales()`;
- `proxy.ts` with `createProxy(i18nConfig, { NextResponse })` (redirect `/` → `/pl`);
- old addresses without a prefix → 301 redirects to `/pl/...` (redirects in the panel or `next.config`);
- `LanguageSwitcher` in the Header + `AlternateLinksProvider` in the layout + `AlternateLinksUpdater` on pages.
## 2. Konfiguracja (projekt wielojęzyczny)
1. `src/i18n.config.ts` — dopisz `{ code: 'de', label: 'Deutsch' }`. To jedyne
miejsce; `ipalKit({ i18n: i18nConfig })`, proxy, switcher i sitemap biorą stąd.
**Nie** zmieniaj `defaultLocale` przy okazji (zmienia wszystkie kanoniczne URL-e).
2. Postgres: `pnpm payload migrate:create add-locale-de` → przejrzyj (enum `_locales`,
tabele `_locales`) → `pnpm payload migrate`. Mongo: nic.
3. `pnpm payload generate:types` · restart dev (Payload buduje localization przy starcie).
4. `grep -rn "'pl'\|'en'\|\[\"pl\"" src/ --include=*.ts*` — każdy hardkod listy języków
w kodzie projektu (mapy etykiet, `if (locale === 'en')`) to błąd: przenieś do panelu
albo do `i18n.config`.
## 2. Configuration (multilingual project)
1. `src/i18n.config.ts` — add `{ code: 'de', label: 'Deutsch' }`. This is the only
place; `ipalKit({ i18n: i18nConfig })`, the proxy, the switcher and the sitemap take it from here.
**Do not** change `defaultLocale` along the way (it changes every canonical URL).
2. Postgres: `pnpm payload migrate:create add-locale-de` → review it (`_locales` enum,
`_locales` tables) → `pnpm payload migrate`. Mongo: nothing.
3. `pnpm payload generate:types` · restart dev (Payload builds localization at startup).
4. `grep -rn "'pl'\|'en'\|\[\"pl\"" src/ --include=*.ts*` — every hardcoded language list
in project code (label maps, `if (locale === 'en')`) is a bug: move it to the panel
or to `i18n.config`.
## 3. Treść — co MUSI mieć wartość w nowym języku
Uruchom raport braków (tylko odczyt):
## 3. Content — what MUST have a value in the new language
Run the gap report (read-only):
```bash
pnpm payload run .agents/skills/ipal-locale-add/scripts/locale-coverage.ts
LOCALE=de pnpm payload run .agents/skills/ipal-locale-add/scripts/locale-coverage.ts
```
Wypisuje: dokumenty bez `slug`/tytułu w danym języku (= 404, brak w sitemapie i
hreflang) oraz puste pola lokalizowane globali, które są wypełnione w defaultLocale.
It prints: documents without a `slug`/title in a given language (= 404, missing from the sitemap and
hreflang) and empty localized global fields that are filled in the defaultLocale.
Uzupełnij w tej kolejności (panel albo skrypt Local API z `locale: 'de'`):
| Co | Gdzie | Skutek braku |
Fill them in this order (panel or a Local API script with `locale: 'de'`):
| What | Where | Effect if missing |
|---|---|---|
| slug + tytuł każdej strony | Pages (i inne kolekcje z URL) | 404 w nowym języku |
| Homepage/404/polityka | System Pages (relacje wspólne) + ich slug w `de` | `/de` → 404, link polityki pusty |
| Header / Footer — etykiety linków | globale nawigacji | puste pozycje menu |
| Site Settings — nazwa, opis, OG | Site Settings | tytuł/OG z fallbacku |
| Cookie Settings — wszystkie teksty + `privacyLinkLabel`, Detail labels, Cookies (`purpose`, `duration`) | Cookie Settings | baner / okno `detailed` w innym języku (RODO: zgoda musi być zrozumiała); skan + import z `--lang <kod>` (ipal-consent-check) |
| Notifications — `form.*` | Notifications | komunikaty formularza z angielskiego fallbacku |
| Forms — etykiety pól, potwierdzenie, Emails | Forms (każdy formularz) | formularz w złym języku |
| SEO tab — meta title/description | każda strona | duplikaty/braki w seo-check |
| Media — `alt` (jeśli localized) | Media | a11y |
| slug + title of every page | Pages (and other collections with a URL) | 404 in the new language |
| Homepage/404/policy | System Pages (shared relations) + their slug in `de` | `/de` → 404, empty policy link |
| Header / Footer — link labels | navigation globals | empty menu items |
| Site Settings — name, description, OG | Site Settings | title/OG from the fallback |
| Cookie Settings — all texts + `privacyLinkLabel`, Detail labels, Cookies (`purpose`, `duration`) | Cookie Settings | banner / `detailed` window in another language (GDPR: consent must be understandable); scan + import with `--lang <code>` (ipal-consent-check) |
| Notifications — `form.*` | Notifications | form messages from the English fallback |
| Forms — field labels, confirmation, Emails | Forms (every form) | form in the wrong language |
| SEO tab — meta title/description | every page | duplicates/gaps in seo-check |
| Media — `alt` (if localized) | Media | a11y |
Slugi w nowym języku: słowa w tym języku, małe litery, bez znaków diakrytycznych
(`ueber-uns`, nie `über-uns`). Strona główna to strona przypisana w System Pages → Homepage —
uzupełnij jej slug w `de` jak każdej strony (coverage go sprawdza), ale jej adres to zawsze `/de`.
Pisząc przez Local API: `payload.update({ collection, id, locale: 'de', fallbackLocale: false, data })`:
- **`fallbackLocale: false` obowiązkowo** — bez tego (przy `fallback: true`) Payload
zapisze polski tekst jako tłumaczenie niemieckie we wszystkich polach, których nie podałeś;
- **bloki/tablice: zachowaj `id` wierszy z odczytu w defaultLocale**, inaczej powstaną
nowe wiersze. Gotowy mechanizm: `ipal-site/resources/seed-content.template.ts`
(wartości `{ pl, en, de }` obok siebie, `SEED_UPDATE=1` dla istniejących stron).
Slugs in the new language: words in that language, lowercase, no diacritics
(`ueber-uns`, not `über-uns`). The home page is the page assigned in System Pages → Homepage —
fill in its slug in `de` like any page (coverage checks it), but its address is always `/de`.
When writing through the Local API: `payload.update({ collection, id, locale: 'de', fallbackLocale: false, data })`:
- **`fallbackLocale: false` is mandatory** — without it (with `fallback: true`) Payload
saves the Polish text as the German translation in every field you did not provide;
- **blocks/arrays: keep the row `id`s from the defaultLocale read**, otherwise new
rows are created. Ready-made mechanism: `ipal-site/resources/seed-content.template.ts`
(`{ pl, en, de }` values side by side, `SEED_UPDATE=1` for existing pages).
## 4. Sprawdzenie
1. `locale-coverage` → `0 gap(s)` (albo lista świadomie pustych pól w raporcie).
## 4. Check
1. `locale-coverage` → `0 gap(s)` (or a list of deliberately empty fields in the report).
2. `pnpm build && pnpm start` → `ipal-seo-check http://localhost:3000`:
hreflang `de` na stronach PL/EN, x-default, `/de/...` w sitemapie, brak 404.
3. `ipal-consent-check http://localhost:3000/de` — baner po niemiecku, zgoda działa.
4. Ręcznie: przełącznik języka z podstrony (nie z home) trafia na odpowiednik, nie na `/de`.
5. `ipal-audit --quick` — zero nowych hardkodów.
hreflang `de` on PL/EN pages, x-default, `/de/...` in the sitemap, no 404.
3. `ipal-consent-check http://localhost:3000/de` — banner in German, consent works.
4. By hand: the language switcher on a subpage (not home) lands on the counterpart, not on `/de`.
5. `ipal-audit --quick` — zero new hardcoded values.
## Raport
Nowy język: kod, liczba stron przetłumaczonych / pustych, kto tłumaczył (wersja
robocza = „do akceptacji klienta”), wynik coverage + seo-check, lista pól do
uzupełnienia przez klienta.
## Report
New language: code, number of pages translated / empty, who translated (a draft
= "awaiting client approval"), coverage + seo-check result, list of fields for the
client to fill in.
+78 -78
View File
@@ -5,102 +5,102 @@ description: Safely changes the shape of fields that already hold content in an
# ipal-migrate-fields
Payload **nie migruje danych za Ciebie**. Zmiana nazwy pola albo jego typu w kodzie
= stare dane zostają w bazie pod starym kluczem, panel pokazuje puste pole, front
renderuje pustkę. Na Postgresie dochodzi migracja schematu, która może **usunąć
kolumnę z danymi**. Dlatego zawsze trzy fazy, nigdy „zmień i zobacz”.
Payload **does not migrate data for you**. Renaming a field or changing its type in code
= the old data stays in the database under the old key, the admin panel shows an empty field, the front end
renders nothing. On Postgres there is also a schema migration that can **drop the column
with the data**. So always three phases, never "change it and see".
## Kiedy NIE potrzebujesz tego skilla
- Projekt bez treści (świeży, seed od zera) → zmień schemat, przeseeduj.
- Dodajesz **nowe** pole (bez zastępowania starego) → zwykła zmiana.
- Zmieniasz tylko `label`, `admin.*`, `validate`, `defaultValue` → bez wpływu na dane.
## When you do NOT need this skill
- Project without content (fresh, seeded from scratch) → change the schema, re-seed.
- You are adding a **new** field (not replacing an old one) → a normal change.
- You only change `label`, `admin.*`, `validate`, `defaultValue` → no effect on data.
Wszystko inne (rename, typ, przeniesienie do grupy/tablicy, `localized: true/false`,
zamiana pól CTA na `buildLinkField`, podział bloku) → ten skill.
Everything else (rename, type, moving into a group/array, `localized: true/false`,
replacing CTA fields with `buildLinkField`, splitting a block) → this skill.
## Przed startem (sam, bez pytania)
1. **Kopia bazy** — Mongo: `mongodump --uri "$DATABASE_URI" --out backup/$(date +%F)`;
Postgres: `pg_dump "$DATABASE_URI" > backup/$(date +%F).sql`. Bez kopii nie zaczynaj.
2. Ustal adapter bazy (`payload.config.ts` → `mongooseAdapter` / `postgresAdapter`).
3. Spisz: kolekcja/global, typ bloku, STARE pola → NOWE pola, które są `localized`.
4. Znajdź wszystkie miejsca czytające stare pola: `grep -rn "<staraNazwa>" src/`.
## Before you start (on your own, without asking)
1. **Database backup** — Mongo: `mongodump --uri "$DATABASE_URI" --out backup/$(date +%F)`;
Postgres: `pg_dump "$DATABASE_URI" > backup/$(date +%F).sql`. Do not start without a backup.
2. Identify the database adapter (`payload.config.ts` → `mongooseAdapter` / `postgresAdapter`).
3. Write down: collection/global, block type, OLD fields → NEW fields, which ones are `localized`.
4. Find every place that reads the old fields: `grep -rn "<oldName>" src/`.
## Faza 1 — dodaj NOWE pola obok STARYCH
- Dodaj nowe pola do schematu; stare **zostają**, oznacz je w panelu:
`admin: { description: 'DEPRECATED — migrowane do <nowe>', readOnly: true }`.
- Front: czytaj NOWE z fallbackiem na STARE (na czas przejścia):
## Phase 1 — add the NEW fields next to the OLD ones
- Add the new fields to the schema; the old ones **stay**, mark them in the panel:
`admin: { description: 'DEPRECATED — migrated to <new>', readOnly: true }`.
- Front end: read the NEW fields with a fallback to the OLD ones (during the transition):
`const links = block.links?.length ? block.links : legacyToLinks(block)`.
- `pnpm payload generate:types` · Postgres: `pnpm payload migrate:create add-<nazwa>` +
`pnpm payload migrate` (migracja tylko DODAJE kolumny — przejrzyj plik, zanim uruchomisz).
- `tsc --noEmit` czysto.
- `pnpm payload generate:types` · Postgres: `pnpm payload migrate:create add-<name>` +
`pnpm payload migrate` (the migration only ADDS columns — review the file before you run it).
- `tsc --noEmit` clean.
## Faza 2 — przenieś dane skryptem
1. Skopiuj szablon: `resources/migrate-block-fields.template.ts` →
`scripts/migrate-<nazwa>.ts`. Zmieniasz tylko sekcję `CONFIG` i `migrateBlock()`.
Szablon: wszystkie dokumenty × wszystkie locale, idempotentny,
## Phase 2 — move the data with a script
1. Copy the template: `resources/migrate-block-fields.template.ts` →
`scripts/migrate-<name>.ts`. Change only the `CONFIG` section and `migrateBlock()`.
The template: all documents × all locales, idempotent,
`context: { ipalMigration: true, ipalSkipIndexNow: true, disableRevalidate: true }`.
2. Zasady w `migrateBlock()`:
- **Pierwszy przebieg (defaultLocale) tworzy strukturę** (wiersze tablic, bloki).
- **Kolejne locale tylko wypełniają pola `localized`** w istniejących wierszach —
używaj `id` wierszy z odczytu (nowe `id` = Payload tworzy nowe wiersze, w innych
językach znika treść).
- Relacje przy `depth: 0` to ID — przepisuj ID, nie obiekty.
- Pola nielokalizowane zapisuj tylko w defaultLocale.
- Zapis w innym języku zawsze z `fallbackLocale: false` (jest w szablonie) — inaczej
Payload zapisze tekst z defaultLocale jako tłumaczenie.
3. Dry run: `pnpm payload run scripts/migrate-<nazwa>.ts` → przeczytaj listę zmian,
sprawdź 2–3 dokumenty ręcznie (zwłaszcza drugi język). Gdy migracja tworzy nowe
wiersze, dry run pokazuje tylko przebieg defaultLocale (wierszy jeszcze nie ma) —
pozostałe języki zobaczysz w wyniku APPLY.
4. Zapis: `APPLY=1 pnpm payload run scripts/migrate-<nazwa>.ts`.
5. Weryfikacja: ponowny dry run → `0 block change(s)`; w panelu otwórz dokument w
każdym języku; na froncie `pnpm build && pnpm start` + `ipal-seo-check`.
2. Rules in `migrateBlock()`:
- **The first pass (defaultLocale) creates the structure** (array rows, blocks).
- **Other locales only fill `localized` fields** in existing rows —
use the row `id`s from the read (new `id` = Payload creates new rows, and content
disappears in other languages).
- Relations at `depth: 0` are IDs — copy IDs, not objects.
- Write non-localized fields only in the defaultLocale.
- Always write another language with `fallbackLocale: false` (it is in the template) — otherwise
Payload saves the defaultLocale text as the translation.
3. Dry run: `pnpm payload run scripts/migrate-<name>.ts` → read the list of changes,
check 2–3 documents by hand (especially the second language). When the migration creates new
rows, the dry run shows only the defaultLocale pass (the rows do not exist yet) —
you will see the other languages in the APPLY output.
4. Write: `APPLY=1 pnpm payload run scripts/migrate-<name>.ts`.
5. Verify: another dry run → `0 block change(s)`; in the panel open the document in
every language; on the front end `pnpm build && pnpm start` + `ipal-seo-check`.
Globale (Header, Footer): zamiast `find` → `findGlobal`/`updateGlobal({ slug, data, locale })`
— ta sama pętla po locale. Kolekcja z `versions.drafts`: skrypt aktualizuje
wersję główną; jeśli dokument ma nowszy szkic, dodaj `draft: true` w odczycie i
zapisie albo opublikuj szkice przed migracją (zapytaj, tylko jeśli są szkice klienta).
Globals (Header, Footer): instead of `find` → `findGlobal`/`updateGlobal({ slug, data, locale })`
— the same loop over locales. Collection with `versions.drafts`: the script updates
the main version; if a document has a newer draft, add `draft: true` to the read and
the write, or publish the drafts before the migration (ask only if they are the client's drafts).
Hooki projektu, które wysyłają maile/rewalidują/wołają webhooki: przy `context.ipalMigration`
mają nic nie robić (`if (context?.ipalMigration) return`). Sprawdź przed APPLY. Hooki pluginu
mają własne flagi (są w szablonie): `ipalSkipIndexNow` (IndexNow przy `indexNow: true` na
produkcji pingowałby Binga dla każdej strony), `disableRevalidate` (`buildRevalidateHook`).
Project hooks that send emails/revalidate/call webhooks: with `context.ipalMigration`
they must do nothing (`if (context?.ipalMigration) return`). Check before APPLY. Plugin hooks
have their own flags (they are in the template): `ipalSkipIndexNow` (IndexNow with `indexNow: true` in
production would ping Bing for every page), `disableRevalidate` (`buildRevalidateHook`).
## Faza 3 — usuń STARE pola
- **Produkcja z treścią klienta → zapytaj użytkownika przed fazą 3** (jedyne pytanie
w tym skillu). Lokalnie / staging → rób sam.
- Usuń stare pola ze schematu, fallback z frontu, `grep` → zero trafień.
- `generate:types`; Postgres: `migrate:create remove-<nazwa>` — ta migracja
**USUWA kolumny**; uruchom dopiero po fazie 2 na tej samej bazie.
- Mongo: stare klucze zostają w dokumentach (nieszkodliwe). Sprzątanie opcjonalne:
`$unset` w osobnym skrypcie.
- `ipal-audit --quick` → 0 błędów.
## Phase 3 — remove the OLD fields
- **Production with client content → ask the user before phase 3** (the only question
in this skill). Locally / on staging → do it yourself.
- Remove the old fields from the schema, the fallback from the front end, `grep` → zero hits.
- `generate:types`; Postgres: `migrate:create remove-<name>` — this migration
**DROPS columns**; run it only after phase 2 on the same database.
- Mongo: the old keys stay in the documents (harmless). Cleanup is optional:
`$unset` in a separate script.
- `ipal-audit --quick` → 0 errors.
## Typowe przypadki → co w migrateBlock
## Common cases → what goes in migrateBlock
| Zmiana | Pierwszy przebieg | Kolejne locale |
| Change | First pass | Other locales |
|---|---|---|
| rename `title` → `heading` | `{ heading: block.title }` | to samo, jeśli localized |
| CTA (`ctaLabel`, `ctaUrl`) → `buildLinkField` | `{ link: { type: 'external', url, label, appearance } }` (strona z panelu: `type: 'internal', page: id`) | tylko `link.label` |
| CTA z relacją → `buildLinksField` | wiersz `{ link: { type: 'internal', page: id, … } }` (szablon) | `links[i].link.label` z zachowaniem `id` |
| pola → `group` | `{ grupa: { a: block.a, b: block.b } }` | pola localized w grupie |
| `text` → `richText` | `{ body: textToLexical(block.text) }` (akapity → `paragraph` nodes) | to samo |
| nielokalizowane → `localized` | skopiuj wartość do defaultLocale | (opcjonalnie) ta sama wartość jako start tłumaczenia — zapytaj |
| podział bloku A → A + B | dodaj nowy blok za A (`blockType: 'b'`, bez `id`) | uzupełnij pola localized po `id` nowego bloku |
| rename `title` → `heading` | `{ heading: block.title }` | the same, if localized |
| CTA (`ctaLabel`, `ctaUrl`) → `buildLinkField` | `{ link: { type: 'external', url, label, appearance } }` (page from the panel: `type: 'internal', page: id`) | only `link.label` |
| CTA with a relation → `buildLinksField` | row `{ link: { type: 'internal', page: id, … } }` (template) | `links[i].link.label`, keeping the `id` |
| fields → `group` | `{ group: { a: block.a, b: block.b } }` | localized fields in the group |
| `text` → `richText` | `{ body: textToLexical(block.text) }` (paragraphs → `paragraph` nodes) | the same |
| non-localized → `localized` | copy the value to the defaultLocale | (optional) the same value as a starting translation — ask |
| split block A → A + B | add a new block after A (`blockType: 'b'`, no `id`) | fill the localized fields by the new block's `id` |
Lexical z tekstu:
Lexical from text:
```ts
const textToLexical = (t: string) => ({ root: { type: 'root', format: '', indent: 0, version: 1, direction: 'ltr',
children: t.split(/\n{2,}/).map((p) => ({ type: 'paragraph', format: '', indent: 0, version: 1, direction: 'ltr', textFormat: 0,
children: [{ type: 'text', text: p, format: 0, style: '', mode: 'normal', detail: 0, version: 1 }] })) } })
```
## Gdy coś pójdzie źle
- Wiersze zdublowane w drugim języku → nie użyto `id` wierszy; przywróć kopię, popraw, powtórz.
- `ValidationError` przy APPLY → nowe pole `required` bez wartości w starych danych;
uzupełnij wartość domyślną w `migrateBlock` albo tymczasowo zdejmij `required`.
- Skrypt nie startuje (`Cannot find module '@payload-config'`) → alias w `tsconfig.json`
(`"@payload-config": ["./src/payload.config.ts"]`) — standard w szablonie Payload.
## When something goes wrong
- Duplicated rows in the second language → row `id`s were not used; restore the backup, fix, repeat.
- `ValidationError` on APPLY → a new `required` field has no value in the old data;
add a default value in `migrateBlock` or temporarily drop `required`.
- The script does not start (`Cannot find module '@payload-config'`) → alias in `tsconfig.json`
(`"@payload-config": ["./src/payload.config.ts"]`) — standard in the Payload template.
Raport końcowy: ile dokumentów / bloków / locale zmieniono, gdzie jest kopia bazy,
czy faza 3 wykonana (albo czeka na zgodę).
Final report: how many documents / blocks / locales were changed, where the database backup is,
whether phase 3 was done (or is waiting for approval).
+28 -28
View File
@@ -5,34 +5,34 @@ description: Builds the site header, footer, mobile menu and company data in an
# ipal-nav
Gotowy kod: `resources/kod-nawigacji.md` (ten skill). Reguły: AGENT.md §6.8.
Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (jak skill ipal-block, krok 0).
Ready code: `resources/nav-code.md` (this skill). Rules: AGENT.md §6.8.
Requires the UI primitives from `../ipal-block/resources/section-code.md` (like the ipal-block skill, step 0).
## Plan (zapisz, potem od razu kod — AGENT.md §0a)
- pozycje menu (jeden poziom podmenu, nie głębiej), CTA w nagłówku (`links`),
- kolumny stopki, notka,
- model `Company` dla rynku z AGENTS.md (PL: NIP/REGON, AU: ABN, US: EIN…),
- etykiety a11y (przycisk menu itp.) — pola w panelu.
## Plan (write it down, then go straight to code — AGENT.md §0a)
- menu items (one submenu level, no deeper), CTA in the header (`links`),
- footer columns, note,
- `Company` model for the market in AGENTS.md (PL: NIP/REGON, AU: ABN, US: EIN…),
- a11y labels (menu button etc.) — fields in the admin panel.
## Kod
1. `src/globals/Header.ts`, `Footer.ts` — z §6.8; `Company.ts` — dane firmy
(teksty localized), `access.read: () => true`.
2. Hook `afterChange` na każdym globalu: `revalidatePath('/', 'layout')`
(import z `next/cache`, hooks.md). `buildRevalidateHook` z pluginu jest tylko dla
kolekcji ze slugiem — globali nie odświeża. Pomiń wywołanie poza serwerem Next
(`!process.env.NEXT_RUNTIME` — seed, migracja) i przy `context.disableRevalidate`,
inaczej `next/cache` rzuca „static generation store missing”.
3. Menu: `await resolveNav(header.navItems, locale)` z `lib/content` (plugin) — linki
rozwiązane na serwerze do `{ href, label, internal, newTab, targetProps, children }`.
Nie twórz `lib/navigation.ts`.
4. `src/components/layout/Header.tsx`, `Footer.tsx` (serwer), `MobileNav.tsx`
(`'use client'`, tylko stan otwarcia, dane przez props, `import type { NavItem } from '@intecion/ipal-kit'`).
5. **Linki prawne w stopce** z ról System Pages: `getSystemLinks(locale)` (href + tytuł
strony) — nie jako ręczne pozycje. Rok w copyright z kodu, nazwa z `Company`.
6. Logo z Site Settings przez `<Media>` — nie duplikuj pola w Header.
7. Podepnij w `src/app/(frontend)/[locale]/layout.tsx` (pobranie globali przez
cached gettery w `lib/`, przekazanie jako props).
## Code
1. `src/globals/Header.ts`, `Footer.ts` — from §6.8; `Company.ts` — company data
(localized texts), `access.read: () => true`.
2. An `afterChange` hook on every global: `revalidatePath('/', 'layout')`
(import from `next/cache`, hooks.md). The plugin's `buildRevalidateHook` is only for
collections with a slug — it does not refresh globals. Skip the call outside the Next server
(`!process.env.NEXT_RUNTIME` — seed, migration) and when `context.disableRevalidate` is set,
otherwise `next/cache` throws "static generation store missing".
3. Menu: `await resolveNav(header.navItems, locale)` from `lib/content` (plugin) — links
resolved on the server to `{ href, label, internal, newTab, targetProps, children }`.
Do not create `lib/navigation.ts`.
4. `src/components/layout/Header.tsx`, `Footer.tsx` (server), `MobileNav.tsx`
(`'use client'`, open state only, data via props, `import type { NavItem } from '@intecion/ipal-kit'`).
5. **Legal links in the footer** from the System Pages roles: `getSystemLinks(locale)` (href + page
title) — not as manual items. Copyright year from code, name from `Company`.
6. Logo from Site Settings via `<Media>` — do not duplicate the field in Header.
7. Wire it in `src/app/(frontend)/[locale]/layout.tsx` (fetch the globals through
cached getters in `lib/`, pass them as props).
## Weryfikacja
Skill **ipal-audit**. Ręcznie: dodanie pozycji menu w panelu widać od razu po
zapisie; menu mobilne działa z klawiatury (Tab, Enter, Esc).
## Verification
The **ipal-audit** skill. By hand: a menu item added in the panel is visible right after
saving; the mobile menu works with the keyboard (Tab, Enter, Esc).
@@ -1,13 +1,13 @@
# Kod nawigacji — Header, Footer, menu mobilne
# Navigation code — Header, Footer, mobile menu
> Zasoby skilla **ipal-nav**. Reguły: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.8.
> Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (CMSLink, Media).
> Resources of the **ipal-nav** skill. Rules: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.8.
> Requires the UI primitives from `../ipal-block/resources/section-code.md` (CMSLink, Media).
## Header i Footer (globale nawigacji)
## Header and Footer (navigation globals)
Nawigacja, stopka i dane firmy to **globale projektu** (model zależy od klienta
i kraju), budowane z tych samych wspólnych pól co sekcje. Logo i nazwa są w
Site Settings — nie duplikuj ich w Header.
Navigation, footer and company data are **project globals** (the model depends on the client
and the country), built from the same shared fields as sections. Logo and name live in
Site Settings — do not duplicate them in Header.
```ts
// src/globals/Header.ts
@@ -27,7 +27,7 @@ export const Header: GlobalConfig = {
fields: [
buildLinkField({ appearances: false }),
{
name: 'subItems', // jeden poziom podmenu — głębiej nie budujemy
name: 'subItems', // one submenu level — we do not build deeper
type: 'array',
labels: { singular: 'Submenu item', plural: 'Submenu' },
maxRows: 10,
@@ -36,7 +36,7 @@ export const Header: GlobalConfig = {
},
],
},
buildLinksField({ maxRows: 1 }), // przycisk CTA w nagłówku
buildLinksField({ maxRows: 1 }), // CTA button in the header
{
name: 'menuLabel',
type: 'text',
@@ -73,40 +73,40 @@ export const Footer: GlobalConfig = {
},
],
},
{ name: 'note', type: 'textarea', localized: true }, // np. „Wszelkie prawa zastrzeżone”
{ name: 'note', type: 'textarea', localized: true }, // e.g. "All rights reserved"
],
}
```
- **Linki prawne w stopce** (polityka, cookies, regulamin): `await getSystemLinks(locale)` z `lib/content`
— href i etykieta (tytuł strony) z System Pages; nie dodawaj ich ręcznie do `columns`, nie wpisuj etykiet w kod.
- Wyróżniona pozycja menu / przycisk w innym kolorze = styl w panelu:
`buildLinkField({ appearances: ['default', { label: 'Highlighted', value: 'highlight' }] })` → klasa w projekcie.
- **Dane firmy** (nazwa, adres, NIP/ABN, telefon) — global `company` projektu;
stopka i JSON-LD czytają z niego. Rok w copyright licz w kodzie
(`new Date().getFullYear()`), nazwę bierz z globala.
- **Odświeżanie:** global zmienia się na każdej stronie → hook `afterChange`
z `revalidatePath('/', 'layout')` (hooks.md; `buildRevalidateHook` nie obsługuje globali):
- **Legal links in the footer** (privacy policy, cookies, terms): `await getSystemLinks(locale)` from `lib/content`
— href and label (page title) from System Pages; do not add them by hand to `columns`, do not write labels in code.
- Highlighted menu item / button in a different colour = a style in the admin panel:
`buildLinkField({ appearances: ['default', { label: 'Highlighted', value: 'highlight' }] })` → a class in the project.
- **Company data** (name, address, NIP/ABN, phone) — the project's `company` global;
the footer and JSON-LD read from it. Compute the copyright year in code
(`new Date().getFullYear()`), take the name from the global.
- **Refreshing:** a global changes on every page → an `afterChange` hook
with `revalidatePath('/', 'layout')` (hooks.md; `buildRevalidateHook` does not handle globals):
```ts
// src/globals/Header.ts (i Footer, Company)
// src/globals/Header.ts (and Footer, Company)
import { revalidatePath } from 'next/cache'
hooks: {
afterChange: [({ context }) => {
// poza serwerem Next (seed, migracja) next/cache rzuca błąd
// outside the Next server (seed, migration) next/cache throws
if (process.env.NEXT_RUNTIME && !context.disableRevalidate) revalidatePath('/', 'layout')
}],
},
```
Menu z globala rozwiązuje plugin: `await resolveNav(header.navItems, locale)` z `lib/content`
→ `{ href, label, internal, newTab, targetProps, children }[]` (martwe linki pominięte, dowolna
głębokość). To zwykłe dane — idą wprost do klienckiego `MobileNav`. Nie twórz `lib/navigation.ts`.
The plugin resolves the menu from the global: `await resolveNav(header.navItems, locale)` from `lib/content`
→ `{ href, label, internal, newTab, targetProps, children }[]` (dead links skipped, any
depth). This is plain data — it goes straight to the client `MobileNav`. Do not create `lib/navigation.ts`.
```tsx
// src/components/layout/Header.tsx — serwer
// src/components/layout/Header.tsx — server
import Link from 'next/link'
import type { Header as HeaderData } from '@/payload-types'
import { resolveNav } from '@/lib/content'
@@ -135,11 +135,11 @@ export async function Header({ header, locale }: { header: HeaderData; locale: s
```
```tsx
// src/components/layout/MobileNav.tsx — klient, tylko stan otwarcia
// src/components/layout/MobileNav.tsx — client, open state only
'use client'
import { useState } from 'react'
import Link from 'next/link'
import type { NavItem } from '@intecion/ipal-kit' // import TYPU — nie ciągnie kodu serwera
import type { NavItem } from '@intecion/ipal-kit' // TYPE import — does not pull in server code
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
const [open, setOpen] = useState(false)
@@ -162,17 +162,17 @@ export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: s
}
```
Header/Footer pobierasz w `[locale]/layout.tsx` (przez cached getter w
`lib/`) i podajesz jako props — layout to jedyne miejsce, które je składa.
Fetch Header/Footer in `[locale]/layout.tsx` (through a cached getter in
`lib/`) and pass them as props — the layout is the only place that assembles them.
Komponent `Footer` — treść w `NoSnippet` (inaczej Google pokazuje adres ze stopki jako
opis każdej podstrony; seo.md → „Opisy w Google”):
`Footer` component — content inside `NoSnippet` (otherwise Google shows the footer address as
the description of every subpage; seo.md → "Descriptions in Google"):
```tsx
import { NoSnippet } from '@intecion/ipal-kit/rsc'
<footer className="…">
<NoSnippet className="…">{/* dane firmy, linki, linki prawne */}</NoSnippet>
<NoSnippet className="…">{/* company data, links, legal links */}</NoSnippet>
</footer>
```
+36 -36
View File
@@ -5,48 +5,48 @@ description: Handles the moment when @intecion/ipal-kit seems to lack a feature
# ipal-plugin-gap
Reguła: AGENT.md §1.3 — **nie łataj po cichu**. Raport + minimalne, oznaczone
obejście (jeśli praca tego wymaga) — i pracujesz dalej, nie czekasz na odpowiedź.
Typ raportu: **błąd** (plugin działa niezgodnie z docs) albo **usprawnienie**
(ten sam kod pisany w kolejnym projekcie; brak opcji, która by go usunęła).
Rule: AGENT.md §1.3 — **do not patch silently**. A report + a minimal, marked
workaround (if the work needs it) — and you keep working, you do not wait for a reply.
Report type: **bug** (the plugin behaves differently from the docs) or **improvement**
(the same code written in yet another project; no option exists that would remove it).
**Zasada pluginu:** ipal-kit pomaga projektowi, nigdy go nie ogranicza. Każdy moduł da się
wyłączyć osobno; każdy domyślny element (dostęp, pola, hooki, etykiety, trasy, kolekcje,
globale) da się nadpisać i wygrywa config projektu; bezpieczne domyślne mają opcję
poluzowania; plugin eksportuje klocki, nie tylko gotowe funkcje. Brak takiej opcji lub
klocka to **luka do zgłoszenia** (typ: usprawnienie) — nie powód do łatania `node_modules`.
**Plugin rule:** ipal-kit helps the project, never limits it. Every module can be
turned off separately; every default (access, fields, hooks, labels, routes, collections,
globals) can be overridden and the project config wins; safe defaults have an option to
relax them; the plugin exports building blocks, not only ready-made functions. A missing option or
building block is a **plugin gap to report** (type: improvement) — not a reason to patch `node_modules`.
## 1. Sprawdź, czy plugin tego nie ma
- `ls node_modules/@intecion/ipal-kit/docs/` — przeczytaj plik modułu,
- `grep -rn "<słowo kluczowe>" node_modules/@intecion/ipal-kit/dist --include=*.d.ts`,
- opcje `ipalKit` (`IpalOptions` w `dist/types.d.ts`: `*Fields`, `formOverrides`, `access`, `enabled`…)
i eksportowane klocki (`build*`, `create*`) — często wystarczy nadpisanie, nie nowa funkcja,
- sprawdź wersję: `grep '"version"' node_modules/@intecion/ipal-kit/package.json`
(może problem jest naprawiony w nowszej — skill **ipal-upgrade**).
## 1. Check that the plugin does not already have it
- `ls node_modules/@intecion/ipal-kit/docs/` — read the module file,
- `grep -rn "<keyword>" node_modules/@intecion/ipal-kit/dist --include=*.d.ts`,
- `ipalKit` options (`IpalOptions` in `dist/types.d.ts`: `*Fields`, `formOverrides`, `access`, `enabled`…)
and the exported building blocks (`build*`, `create*`) — often an override is enough, not a new function,
- check the version: `grep '"version"' node_modules/@intecion/ipal-kit/package.json`
(the problem may be fixed in a newer one — the **ipal-upgrade** skill).
Plugin to ma → użyj go i powiedz użytkownikowi, gdzie to było.
The plugin has it → use it and tell the user where it was.
## 2. Raport (gdy naprawdę brakuje albo nie działa)
Zapisz w `docs/plugin-requests/<data>-<temat>.md` projektu. Użytkownikowi pokazujesz
od razu tylko **blokujący błąd** (bez obejścia nie da się iść dalej); resztę zbiera
raport końcowy (ipal-site, sekcja „Dla ipal-kit”).
## 2. Report (when it really is missing or broken)
Save it in the project's `docs/plugin-requests/<date>-<topic>.md`. Show the user
right away only a **blocking bug** (you cannot go on without a workaround); everything else goes into
the final report (ipal-site, "For ipal-kit" section).
```markdown
# <temat>
**Typ:** błąd / usprawnienie · **Projekt:** <nazwa> · **ipal-kit:** <wersja>
# <topic>
**Type:** bug / improvement · **Project:** <name> · **ipal-kit:** <version>
## Problem
<co nie działa / czego brakuje; komunikat błędu; kroki odtworzenia>
## Dlaczego to do pluginu
<czy przyda się w innych projektach — konkretnie>
## Proponowane API
<sygnatura funkcji / opcja ipalKit / pole w panelu; przykład użycia w projekcie>
## Obejście tymczasowe (jeśli konieczne)
<minimalne, w jednym pliku, z komentarzem `// WORKAROUND ipal-kit <wersja>: docs/plugin-requests/<plik>`>
<what does not work / what is missing; error message; steps to reproduce>
## Why it belongs in the plugin
<whether other projects will need it — be specific>
## Proposed API
<function signature / ipalKit option / admin panel field; usage example in the project>
## Temporary workaround (if needed)
<minimal, in one file, with the comment `// WORKAROUND ipal-kit <version>: docs/plugin-requests/<file>`>
```
## 3. Czego nie robić
- hooka z zaszytą domeną/nazwą/kolorem klienta,
- kopii komponentu pluginu do projektu (np. `Analytics`, `CookieBanner`),
- edycji / `patch-package` w `node_modules/@intecion/ipal-kit`,
- `as any` / `@ts-ignore` żeby „przeszło”,
- dynamicznego `import()` przez zmienną (nie wbundluje się).
## 3. What not to do
- a hook with the client's domain/name/colour hardcoded,
- a copy of a plugin component in the project (e.g. `Analytics`, `CookieBanner`),
- edits / `patch-package` in `node_modules/@intecion/ipal-kit`,
- `as any` / `@ts-ignore` "to make it pass",
- dynamic `import()` through a variable (it will not be bundled).
+154 -152
View File
@@ -5,190 +5,192 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
# ipal-reference
## Jak używać
- **Najpierw tutaj**, potem kod. Szukasz funkcji → `grep -n "<słowo>" resources/api.md`
(`resources/api.md` — każdy eksport: import, do czego). Opis modułu:
`node_modules/@intecion/ipal-kit/docs/<strona>.md` (kolumna „szczegóły”).
- **Plugin pomaga, nie ogranicza:** każdy moduł da się wyłączyć, każdy domyślny element nadpisać,
config projektu wygrywa, klocki (`build*`, `create*`) są eksportowane — złożysz z nich własną wersję.
- Brak opcji / zachowanie niezgodne z docs → skill **ipal-plugin-gap** (raport). Nigdy nie łataj `node_modules`.
- Stan opisany wg kodu 1.12.x. „obecnie zawsze” = nie ma dziś opcji wyłączenia (luka → ipal-plugin-gap).
## How to use
- **Look here first**, then at the code. Looking for a function → `grep -n "<word>" resources/api.md`
(`resources/api.md` — every export: import, what it does). Module description:
`node_modules/@intecion/ipal-kit/docs/<page>.md` (the "details" column).
- **The plugin helps, never limits:** every module can be turned off, every default can be overridden,
the project config wins, the building blocks (`build*`, `create*`) are exported — compose your own version from them.
- Missing option / behaviour that does not match the docs → skill **ipal-plugin-gap** (report). Never patch `node_modules`.
- Described per the 1.12.x code. "currently always" = no option to turn it off today (gap → ipal-plugin-gap).
## 1. Opcje `ipalKit({...})` (`IpalOptions`, `dist/types.d.ts`)
## 1. `ipalKit({...})` options (`IpalOptions`, `dist/types.d.ts`)
| opcja | domyślnie | co dodaje / zmienia | jak wyłączyć / nadpisać |
| option | default | what it adds / changes | how to turn off / override |
|---|---|---|---|
| `i18n` **(wymagane)** | — | `config.localization` (zawsze nadpisywane); walidacja od razu przy `ipalKit()` (rzuca przy złym configu) | jedno źródło: `src/i18n.config.ts`; własne `localization` w configu i tak zostanie nadpisane |
| `i18n.defaultLocale` | — | `localization.defaultLocale`, przekierowanie `/` w proxy | musi być w `locales` |
| `i18n` **(required)** | — | `config.localization` (always overwritten); validated right away in `ipalKit()` (throws on a bad config) | one source: `src/i18n.config.ts`; your own `localization` in the config gets overwritten anyway |
| `i18n.defaultLocale` | — | `localization.defaultLocale`, `/` redirect in the proxy | must be in `locales` |
| `i18n.fallback` | `true` | `localization.fallback` | `false` |
| `i18n.locales[]` `{ code, label, rtl? }` | — | lista języków (min. 1); `rtl: true` → `rtl` w Payload | dodanie języka: skill **ipal-locale-add** |
| `access` | brak | pole `roles` (`user` < `editor` < `admin`, `saveToJWT`) w kolekcji auth | pomiń → **brak ról**: nikt nie jest adminem dla Site Integrations, test e-maila, statystyk, consent-records; `form-submissions` czyta tylko editor+ |
| `access.authCollection` | — (wymagane w `access`) | kolekcja, do której trafia `roles`; też slug wstrzykiwanej kolekcji auth | własna kolekcja o tym slugu wygrywa |
| `access.defaultRole` | `'user'` | `defaultValue` pola `roles` | `'editor'` / `'admin'` |
| `adminRoute` | `'/admin'` | `config.routes.admin`; link i widoki statystyk, `IntegrationAlerts` | projekt sam przenosi `app/(payload)/<route>/` i wpisuje route w matcher proxy (security.md) |
| `twoFactor` | **brak = błąd** | `@clocklimited/payload-2fa` z `forceSetup: true` (TOTP wymuszone, sprawdzane też w API) | `twoFactor: false` (odradzane); pominięcie opcji rzuca `[ipal] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (wymagane) | nazwa w aplikacji uwierzytelniającej | — |
| `twoFactor.plugin` | — (wymagane) | wstrzyknięty `payloadTotp` (plugin nie importuje peera) | brak funkcji → rzuca |
| `twoFactor.collectionSlug` | `'users'` | kolekcja z 2FA | **nie** bierze `access.authCollection` — przy innym slugu podaj oba |
| `whiteLabel` | brak | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) z Site Settings + kredyt dostawcy | pomiń / `false`; `true` = domyślne |
| `whiteLabel.settingsSlug` | `'site-settings'` | global, z którego czyta logo/nazwę | — |
| `whiteLabel.logoField` / `iconField` / `nameField` | `'logo'` / `'favicon'` / `'siteName'` | pola w Site Settings | dowolne pole upload/tekst |
| `whiteLabel.titleSuffix` | brak | `admin.meta.titleSuffix` (tytuł karty) | — |
| `whiteLabel.credit` | wł. | `IntecionCredit` w `afterLogin` i `afterNavLinks` | `false`; `{ text, url }` nadpisuje |
| `pages` | brak | Site Settings → zakładki **System Pages** (role stron) i **Under construction** | pomiń → brak obu zakładek |
| `pages.slug` | — (wymagane w `pages`) | kolekcja stron projektu (relacje System Pages, construction, IndexNow) | — |
| `pages.roles` | wszystkie: `homepage`, `notFound`, `privacyPolicy`, `cookiePolicy`, `termsOfService` | które przypisania pokazać | podzbiór tablicy |
| `content` | brak | pole `<slug>Archive` w System Pages per kolekcja (URL wpisów = slug strony archiwum) | **bez `pages` ignorowane** (brak pól archiwum; IndexNow nadal działa) |
| `content.collections[]` `{ slug, label?, perPage? }` | `label` = slug, `perPage` 10 | wpis do archiwum; ta sama wartość idzie do `createContentHelpers({ content })` | kolekcję tworzy projekt (skill **ipal-collection**) |
| `seo` | brak | `@payloadcms/plugin-seo` (grupa `meta` + `titleOverride`), zakładki Content/SEO, hook auto-fill | pomiń |
| `seo.collections` | — (wymagane) | kolekcje z `meta` | — |
| `seo.autoFill` | `{ title: 'title', content: 'layout', descriptionLength: 155 }` | `beforeChange`: pusty `meta.title/description` z pól dokumentu | `false`; obiekt `{ title, description, content, descriptionLength }` |
| `seo.descriptionCheck` | wł. (`settingsSlug: 'site-settings'`, `siteDescriptionField: 'siteDescription'`) | pole UI `MetaDescriptionCheck` pod opisem (pusty / powtórzony) | `false`; obiekt nadpisuje slug/pole |
| `seo.fields` | `[]` | dodatkowe pola w grupie SEO | — |
| `seo.generateTitle` / `generateDescription` | plugin-seo | podgląd / generowanie w panelu | własna funkcja `({ doc }) => string` |
| — (brak opcji) | `uploadsCollection: 'media'` | obraz meta z kolekcji `media` | obecnie zawsze `media` (luka) |
| `forms` | brak | `@payloadcms/plugin-form-builder`: kolekcje `forms`, `form-submissions` | pomiń |
| `forms.adminGroup` | `'Forms'` | grupa w sidebarze | `false` = domyślna Payloada; `admin.group` w overrides wygrywa |
| `forms.fields.*` | wł.: `checkbox`, `checkboxGroup`, `country`, `date`, `email`, `message`, `number`, `radio`, `select`, `state`, `step`, `text`, `textarea`, `time`; wył.: `payment` | typy bloków w kreatorze (wszystkie z „Show only when”) | `<typ>: false`; obiekt bloku podmienia; `payment: true` **nic nie robi** (przefiltrowane) — podaj obiekt bloku |
| `forms.formOverrides` | etykiety Form/Forms, `emails` czytelne tylko dla zalogowanych | nadpisanie kolekcji `forms` (`fields: ({ defaultFields }) => …`, `slug`, `admin`, `access`…) | dowolny `CollectionConfig` |
| `forms.formSubmissionOverrides` | create: zalogowani, read: editor+, delete: admin | nadpisanie `form-submissions` | `access.create` itd. wygrywa |
| `forms.redirectRelationships` | brak | kolekcje, do których formularz przekierowuje | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` z layoutem (logo, kolor, stopka) + zakładka Site Settings → **Emails**; `{{*:table}}` czytelne | `true` |
| `forms.beforeEmail` | brak | własna modyfikacja maili (po layoucie) | funkcja form-buildera |
| `forms.consentFieldName` | (`'consent'`) | **obecnie nieużywane przez plugin** — nazwę pola zgody podajesz w `createSubmitAction({ consentFieldName })` / `submitForm` | — |
| `consentLog` | wył. | kolekcja `consent-records` + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (domyślnie 1095) |
| `stats` | wył. | kolekcja `stats-visits`, `POST /api/ipal/hit`, widok `/<admin>/stats`, link w nav, wykres na dashboardzie | `true` / obiekt |
| `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | czas przechowania, granica dnia, `StatsWidget` | `dashboard: false` chowa wykres |
| `indexNow` | `false` | hook `afterChange` (publikacja → IndexNow, tylko produkcja + https) w kolekcji `pages.slug ?? 'pages'` i każdej z `content` | `true` + trasa `indexnow-key.txt` |
| `siteSettingsFields` | brak | zakładka **Custom** w Site Settings | `Field[]` |
| `integrationsFields` | brak | zakładka **Custom** w Site Integrations | `Field[]` |
| `enabled` | `true` | `false` → plugin **zwraca config bez zmian**: znikają wstrzyknięte kolekcje, globale, endpointy, 2FA, role (dane w bazie zostają, panel ich nie widzi); `i18n` i tak walidowane | `false` |
| `i18n.locales[]` `{ code, label, rtl? }` | — | list of languages (min. 1); `rtl: true` → `rtl` in Payload | adding a language: skill **ipal-locale-add** |
| `access` | none | `roles` field (`user` < `editor` < `admin`, `saveToJWT`) in the auth collection | omit → **no roles**: nobody is admin for Site Integrations, the e-mail test, stats, consent-records; `form-submissions` readable by editor+ only |
| `access.authCollection` | — (required in `access`) | collection that gets `roles`; also the slug of the injected auth collection | your own collection with that slug wins |
| `access.defaultRole` | `'user'` | `defaultValue` of the `roles` field | `'editor'` / `'admin'` |
| `adminRoute` | `'/admin'` | `config.routes.admin`; stats link and views, `IntegrationAlerts` | the project moves `app/(payload)/<route>/` itself and adds the route to the proxy matcher (security.md) |
| `twoFactor` | **none = error** | `@clocklimited/payload-2fa` with `forceSetup: true` (TOTP enforced, also checked in the API) | `twoFactor: false` (discouraged); omitting the option throws `[ipal] twoFactor.issuer is required` |
| `twoFactor.issuer` | — (required) | name in the authenticator app | — |
| `twoFactor.plugin` | — (required) | injected `payloadTotp` (the plugin does not import the peer) | missing function → throws |
| `twoFactor.collectionSlug` | `'users'` | collection with 2FA | does **not** take `access.authCollection` — with a different slug, set both |
| `whiteLabel` | none | `admin.components.graphics.Logo/Icon` (`AdminLogo`/`AdminIcon`) from Site Settings + vendor credit | omit / `false`; `true` = defaults |
| `whiteLabel.settingsSlug` | `'site-settings'` | global it reads the logo/name from | — |
| `whiteLabel.logoField` / `iconField` / `nameField` | `'logo'` / `'favicon'` / `'siteName'` | fields in Site Settings | any upload/text field |
| `whiteLabel.titleSuffix` | none | `admin.meta.titleSuffix` (tab title) | — |
| `whiteLabel.credit` | on | `IntecionCredit` in `afterLogin` and `afterNavLinks` | `false`; `{ text, url }` overrides |
| `pages` | none | Site Settings → **System Pages** (page roles) and **Under construction** tabs | omit → neither tab |
| `pages.slug` | — (required in `pages`) | the project's pages collection (System Pages relations, construction, IndexNow) | — |
| `pages.roles` | all: `homepage`, `notFound`, `privacyPolicy`, `cookiePolicy`, `termsOfService` | which assignments to show | subset of the array |
| `content` | none | `<slug>Archive` field in System Pages per collection (entry URL = archive page slug) | **ignored without `pages`** (no archive fields; IndexNow still works) |
| `content.collections[]` `{ slug, label?, perPage? }` | `label` = slug, `perPage` 10 | archive entry; the same value goes to `createContentHelpers({ content })` | the project creates the collection (skill **ipal-collection**) |
| `seo` | none | `@payloadcms/plugin-seo` (`meta` group + `titleOverride`), Content/SEO tabs, auto-fill hook | omit |
| `seo.collections` | — (required) | collections with `meta` | — |
| `seo.autoFill` | `{ title: 'title', content: 'layout', descriptionLength: 155 }` | `beforeChange`: empty `meta.title/description` filled from document fields | `false`; object `{ title, description, content, descriptionLength }` |
| `seo.descriptionCheck` | on (`settingsSlug: 'site-settings'`, `siteDescriptionField: 'siteDescription'`) | UI field `MetaDescriptionCheck` below the description (empty / duplicated) | `false`; object overrides slug/field |
| `seo.fields` | `[]` | extra fields in the SEO group | — |
| `seo.generateTitle` / `generateDescription` | plugin-seo | preview / generation in the panel | your own function `({ doc }) => string` |
| — (no option) | `uploadsCollection: 'media'` | meta image from the `media` collection | currently always `media` (gap) |
| `forms` | none | `@payloadcms/plugin-form-builder`: `forms`, `form-submissions` collections | omit |
| `forms.adminGroup` | `'Forms'` | sidebar group | `false` = Payload default; `admin.group` in overrides wins |
| `forms.fields.*` | on: `checkbox`, `checkboxGroup`, `country`, `date`, `email`, `message`, `number`, `radio`, `select`, `state`, `step`, `text`, `textarea`, `time`; off: `payment` | block types in the builder (all with "Show only when") | `<type>: false`; a block object replaces it; `payment: true` **does nothing** (filtered out) — pass a block object |
| `forms.formOverrides` | Form/Forms labels, `emails` readable by logged-in users only | overrides the `forms` collection (`fields: ({ defaultFields }) => …`, `slug`, `admin`, `access`…) | any `CollectionConfig` |
| `forms.formSubmissionOverrides` | create: logged-in, read: editor+, delete: admin | overrides `form-submissions` | `access.create` etc. wins |
| `forms.redirectRelationships` | none | collections a form can redirect to | `['pages']` |
| `forms.emailLayout` | `false` | `beforeEmail` with a layout (logo, colour, footer) + Site Settings → **Emails** tab; `{{*:table}}` readable | `true` |
| `forms.beforeEmail` | none | your own e-mail changes (after the layout) | form-builder function |
| `forms.consentFieldName` | (`'consent'`) | **currently unused by the plugin** — pass the consent field name in `createSubmitAction({ consentFieldName })` / `submitForm` | — |
| `consentLog` | off | `consent-records` collection + `POST /api/ipal/consent` (rate limit 20/min) | `true` / `{ retentionDays }` (default 1095) |
| `stats` | off | `stats-visits` collection, `POST /api/ipal/hit`, `/<admin>/stats` view, nav link, dashboard chart | `true` / object |
| `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | retention, day boundary, `StatsWidget` | `dashboard: false` hides the chart |
| `indexNow` | `false` | `afterChange` hook (publish → IndexNow, production + https only) in the `pages.slug ?? 'pages'` collection and each one from `content` | `true` + `indexnow-key.txt` route |
| `siteSettingsFields` | none | **Custom** tab in Site Settings | `Field[]` |
| `integrationsFields` | none | **Custom** tab in Site Integrations | `Field[]` |
| `enabled` | `true` | `false` → the plugin **returns the config unchanged**: injected collections, globals, endpoints, 2FA and roles disappear (data stays in the database, the panel does not see it); `i18n` is validated anyway | `false` |
## 2. Co plugin wstrzykuje sam
## 2. What the plugin adds by itself
| element | co | kontroluje | wyłączenie dziś |
| element | what | controlled by | turning off today |
|---|---|---|---|
| kolekcja auth (`users`) | `{ slug, auth: true, useAsTitle: 'email' }`, gdy projekt jej nie ma (slug: `access.authCollection` → `twoFactor.collectionSlug` → `admin.user` → `'users'`) | własna kolekcja o tym slugu | własna wygrywa |
| `forms`, `form-submissions` | form-builder + ipal bloki `step`, `checkboxGroup`, `time` | `forms` | pomiń `forms` |
| `consent-records` | dowód zgody (id, wybory, wersja polityki) | `consentLog` | domyślnie wył. |
| `stats-visits` | wizyty bez IP (admin czyta/usuwa) | `stats` | domyślnie wył. |
| global `site-settings` | General, Theme, [System Pages], [Emails], [Under construction], [Custom]; publiczny odczyt | `pages`, `content`, `forms.emailLayout`, `siteSettingsFields` | **obecnie zawsze** |
| global `site-integrations` | Analytics, Turnstile, SMTP, IndexNow, [Custom]; tylko admin | `integrationsFields` | **obecnie zawsze** |
| global `cookie-settings` | teksty banera, kategorie, lista cookies | — | **obecnie zawsze** |
| global `notifications` | komunikaty formularzy per język | — | **obecnie zawsze** |
| `POST /api/ipal/test-email` | test SMTP/Graph (tylko admin) | — | **obecnie zawsze** |
| `POST /api/ipal/consent` | zapis zgody | `consentLog` | wył. domyślnie |
| `POST /api/ipal/hit` | odsłona do statystyk | `stats` | wył. domyślnie |
| `localization` | z `i18n` | `i18n` | **obecnie zawsze** |
| `routes.admin` | z `adminRoute` | `adminRoute` | — |
| hook `beforeChange` auto-fill meta | w `seo.collections` | `seo.autoFill` | `autoFill: false` |
| hook `afterChange` IndexNow | pages + content | `indexNow` | wył. domyślnie |
| `onInit` | migracja przycisku Cookie Settings + log `[ipal] Plugin initialized.` (Twój `onInit` leci pierwszy) | — | **obecnie zawsze** |
| auth collection (`users`) | `{ slug, auth: true, useAsTitle: 'email' }`, when the project has none (slug: `access.authCollection` → `twoFactor.collectionSlug` → `admin.user` → `'users'`) | your own collection with that slug | yours wins |
| `forms`, `form-submissions` | form-builder + ipal blocks `step`, `checkboxGroup`, `time` | `forms` | omit `forms` |
| `consent-records` | proof of consent (id, choices, policy version) | `consentLog` | off by default |
| `stats-visits` | visits without IP (admin reads/deletes) | `stats` | off by default |
| global `site-settings` | General, Theme, [System Pages], [Emails], [Under construction], [Custom]; public read | `pages`, `content`, `forms.emailLayout`, `siteSettingsFields` | **currently always** |
| global `site-integrations` | Analytics, Turnstile, SMTP, IndexNow, [Custom]; admin only | `integrationsFields` | **currently always** |
| global `cookie-settings` | banner texts, categories, cookie list | — | **currently always** |
| global `notifications` | form messages per language | — | **currently always** |
| `POST /api/ipal/test-email` | SMTP/Graph test (admin only) | — | **currently always** |
| `POST /api/ipal/consent` | saves consent | `consentLog` | off by default |
| `POST /api/ipal/hit` | page view for stats | `stats` | off by default |
| `localization` | from `i18n` | `i18n` | **currently always** |
| `routes.admin` | from `adminRoute` | `adminRoute` | — |
| `beforeChange` meta auto-fill hook | in `seo.collections` | `seo.autoFill` | `autoFill: false` |
| `afterChange` IndexNow hook | pages + content | `indexNow` | off by default |
| `onInit` | Cookie Settings button migration + log `[ipal] Plugin initialized.` (your `onInit` runs first) | — | **currently always** |
**Import map** (`@intecion/ipal-kit/admin#…`) — po każdej zmianie opcji: `pnpm generate:importmap`
(`pnpm payload generate:importmap`), inaczej panel jest pusty / brak komponentu.
**Import map** (`@intecion/ipal-kit/admin#…`) — after every option change: `pnpm generate:importmap`
(`pnpm payload generate:importmap`), otherwise the panel is blank / a component is missing.
| komponent | gdzie | warunek |
| component | where | condition |
|---|---|---|
| `AdminLogo`, `AdminIcon` | `graphics.Logo/Icon` | `whiteLabel` |
| `IntecionCredit` | `afterLogin`, `afterNavLinks` | `whiteLabel` i `credit !== false` |
| `StatsNavLink`, `StatsView` (`views.ipalStats`, `/stats`), `StatsWidget` (`beforeDashboard`) | nav, widok, dashboard | `stats` (`dashboard: false` bez widgetu) |
| `IntegrationAlerts` | `beforeDashboard` | **obecnie zawsze** (nic nie renderuje, gdy wszystko działa) |
| `IntegrationStatusBanner` | pole UI w zakładkach Site Integrations | zawsze (z globalem) |
| `MaskedField` | sekrety SMTP / Turnstile | zawsze |
| `TestEmailButton` | Site Integrations → SMTP | zawsze |
| `MetaDescriptionCheck` | pod `meta.description` | `seo` i `descriptionCheck !== false` |
| `RowLabel` | etykiety wierszy array | tylko gdy projekt użyje `rowLabel(...)` (admin-ui) |
| `IntecionCredit` | `afterLogin`, `afterNavLinks` | `whiteLabel` and `credit !== false` |
| `StatsNavLink`, `StatsView` (`views.ipalStats`, `/stats`), `StatsWidget` (`beforeDashboard`) | nav, view, dashboard | `stats` (`dashboard: false` without the widget) |
| `IntegrationAlerts` | `beforeDashboard` | **currently always** (renders nothing when everything works) |
| `IntegrationStatusBanner` | UI field in the Site Integrations tabs | always (with the global) |
| `MaskedField` | SMTP / Turnstile secrets | always |
| `TestEmailButton` | Site Integrations → SMTP | always |
| `MetaDescriptionCheck` | below `meta.description` | `seo` and `descriptionCheck !== false` |
| `RowLabel` | array row labels | only when the project uses `rowLabel(...)` (admin-ui) |
## 3. Co projekt podpina sam
## 3. What the project wires itself
Komplet obowiązkowy: AGENT.md §0b, skill **ipal-setup**; kontrola: **ipal-audit**, **ipal-seo-check**.
`$U` = `NEXT_PUBLIC_SERVER_URL` (np. `http://localhost:3000`).
Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ipal-seo-check**.
`$U` = `NEXT_PUBLIC_SERVER_URL` (e.g. `http://localhost:3000`).
| element | plik | minimalny przykład | jak sprawdzić | szczegóły |
| element | file | minimal example | how to check | details |
|---|---|---|---|---|
| plugin | `src/payload.config.ts` | `plugins: [ipalKit({ i18n: i18nConfig, access: { authCollection: 'users' }, twoFactor: { issuer, plugin: payloadTotp }, … })]` | `pnpm dev` → log `[ipal] Plugin initialized.` | PROGRAMISTA §2.3 |
| języki | `src/i18n.config.ts` | `export const i18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const satisfies I18nConfig` | `curl -sI $U/` → 3xx na `/pl` | i18n.md |
| proxy | `src/proxy.ts` | `export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })` + `export const config = { matcher: ['/((?!api\|admin\|_next\|.*\\..*).*)'] }` (literał!) | `curl -sI $U/` → `/pl`; `curl -s -H 'Accept: text/markdown' $U/pl` → Markdown | i18n.md, PROGRAMISTA §2.6 |
| proxy (Next 15 / własny) | `middleware`/`proxy.ts` | `createLocaleMiddleware({ config, … })` (`/next/middleware` lub główny entry) | jw. | i18n.md |
| walidacja env | `src/instrumentation.ts` | `if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` z `@intecion/ipal-kit/env` | usuń zmienną → start pada z listą braków | env.md |
| languages | `src/i18n.config.ts` | `export const i18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const satisfies I18nConfig` | `curl -sI $U/` → 3xx to `/pl` | i18n.md |
| proxy | `src/proxy.ts` | `export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })` + `export const config = { matcher: ['/((?!api\|admin\|_next\|.*\\..*).*)'] }` (a literal!) | `curl -sI $U/` → `/pl`; `curl -s -H 'Accept: text/markdown' $U/pl` → Markdown | i18n.md, PROGRAMISTA §2.6 |
| proxy (Next 15 / custom) | `middleware`/`proxy.ts` | `createLocaleMiddleware({ config, … })` (`/next/middleware` or the main entry) | as above | i18n.md |
| env validation | `src/instrumentation.ts` | `if (process.env.NEXT_RUNTIME === 'nodejs') assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` from `@intecion/ipal-kit/env` | remove a variable → startup fails with the list of missing ones | env.md |
| Next config | `next.config.ts` | `withPayload({ images: buildImagesConfig(), htmlLimitedBots: /Googlebot\|Bingbot…/i, headers: async () => [{ source: '/:path*', headers: buildSecurityHeaders({ hsts }) }, ...buildUploadSecurityHeaders()] })` | `curl -sI $U/pl \| grep -i 'x-content-type\|strict-transport'` | security.md, storage.md, PROGRAMISTA §2.9 |
| CSP | `next.config.ts` | `buildCsp({ mode: 'report-only', … })` → potem `enforce` | konsola przeglądarki bez naruszeń | security.md |
| dane / trasy | `src/lib/content.ts` | `export const { … } = createContentHelpers({ config, content, i18n: i18nConfig, baseUrl, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName } })` | `pnpm tsc --noEmit` | frontend.md, PROGRAMISTA §2.7 |
| layout | `app/(frontend)/[locale]/layout.tsx` | `const shell = await getSiteShell(locale)`; `<SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />} theme stats>` | HTML: `<script type="application/ld+json">` (WebSite+Organization), baner cookies | frontend.md, consent.md |
| motyw | layout | `<SiteProviders theme>` (lub `<ThemeScript {...shell.theme} />` z `/rsc`), `<html suppressHydrationWarning>`; przełącznik `<ThemeSwitcher>` (`/client`) | `data-theme` na `<html>` przed hydracją | theme.md |
| catch-all | `app/(frontend)/[locale]/[[...slug]]/page.tsx` | `export const revalidate = 3600`; `const route = createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })`; `export default route.Page`; `generateMetadata`, `generateStaticParams` | `curl -s $U/pl/<slug>` 200; zmień slug → stary daje 308 | frontend.md, pages.md |
| 404 | `[locale]/not-found.tsx` + `notFoundView.ts` | `export default createNotFoundPage(content, { load: loadNotFoundView })`; `'use server'` `renderNotFoundView(content, { blocks }, locale)` | `curl -sI $U/pl/xyz` → 404 z treścią z System Pages | pages.md |
| sitemap | `app/sitemap.xml/route.ts` | `export { sitemapRoute as GET } from '@/lib/content'` + `dynamic = 'force-dynamic'` (albo `sitemap.ts` z `sitemap` — nigdy oba) | `curl -s $U/sitemap.xml` (hreflang, styl XSL) | seo.md |
| robots | `app/robots.ts` | `export { robots as default } from '@/lib/content'` | `curl -s $U/robots.txt` (Sitemap:, boty AI) | seo.md |
| CSP | `next.config.ts` | `buildCsp({ mode: 'report-only', … })` → later `enforce` | browser console without violations | security.md |
| data / routes | `src/lib/content.ts` | `export const { … } = createContentHelpers({ config, content, i18n: i18nConfig, baseUrl, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName } })` | `pnpm tsc --noEmit` | frontend.md, PROGRAMISTA §2.7 |
| layout | `app/(frontend)/[locale]/layout.tsx` | `const shell = await getSiteShell(locale)`; `<SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />} theme stats>` | HTML: `<script type="application/ld+json">` (WebSite+Organization), cookie banner | frontend.md, consent.md |
| theme | layout | `<SiteProviders theme>` (or `<ThemeScript {...shell.theme} />` from `/rsc`), `<html suppressHydrationWarning>`; switcher `<ThemeSwitcher>` (`/client`) | `data-theme` on `<html>` before hydration | theme.md |
| catch-all | `app/(frontend)/[locale]/[[...slug]]/page.tsx` | `export const revalidate = 3600`; `const route = createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })`; `export default route.Page`; `generateMetadata`, `generateStaticParams` | `curl -s $U/pl/<slug>` 200; change the slug → the old one gives 308 | frontend.md, pages.md |
| 404 | `[locale]/not-found.tsx` + `notFoundView.ts` | `export default createNotFoundPage(content, { load: loadNotFoundView })`; `'use server'` `renderNotFoundView(content, { blocks }, locale)` | `curl -sI $U/pl/xyz` → 404 with content from System Pages | pages.md |
| sitemap | `app/sitemap.xml/route.ts` | `export { sitemapRoute as GET } from '@/lib/content'` + `dynamic = 'force-dynamic'` (or `sitemap.ts` with `sitemap` — never both) | `curl -s $U/sitemap.xml` (hreflang, XSL style) | seo.md |
| robots | `app/robots.ts` | `export { robots as default } from '@/lib/content'` | `curl -s $U/robots.txt` (Sitemap:, AI bots) | seo.md |
| manifest | `app/manifest.ts` | `export { manifest as default }` + `force-dynamic` | `curl -s $U/manifest.webmanifest` | seo.md |
| llms | `app/llms.txt/route.ts`, `app/llms-full.txt/route.ts` | `export { llmsRoute as GET }` / `llmsFullRoute` + `force-dynamic` | `curl -s $U/llms.txt` | seo.md |
| Markdown | `app/md/[locale]/[[...slug]]/route.ts` | `export { markdownRoute as GET }` + `force-dynamic` | `curl -s $U/md/pl` | content.md |
| MCP | `app/api/mcp/route.ts` | `export { mcpGET as GET, mcpPOST as POST }` + `force-dynamic` | `curl -s -X POST $U/api/mcp -H 'content-type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'` | mcp.md |
| health | `app/api/health/route.ts` | `export { healthRoute as GET }` + `force-dynamic` | `curl -s $U/api/health` → `"status":"ok"` (503 przy błędzie bazy) | deployment.md |
| IndexNow klucz | `app/indexnow-key.txt/route.ts` | `export { indexNowKeyRoute as GET }` + `force-dynamic` | `curl -s $U/indexnow-key.txt` = klucz | seo.md |
| wyszukiwarka (opcja) | `app/api/search/route.ts` | `export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig, baseUrl })` | `curl -s "$U/api/search?q=test&locale=pl"` | content.md |
| Pages | `src/collections/Pages.ts` | `buildSlugField({ from: 'title' })`, `buildNoindexField()`, `buildSummaryField()`, pole `slugHistory` + `trackSlugHistoryHook`, `buildRevalidateHook({ revalidatePath, config })` → `afterChange`/`afterDelete` | edycja w panelu → strona odświeża się bez deployu | slug.md, hooks.md, seo.md |
| Pages — ochrona | jw. | `beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })]`; `setPublishedAtHook`, `buildCrossLocaleFieldSync(...)` wg potrzeby | usuń stronę główną → błąd | hooks.md |
| Media | `src/collections/Media.ts` | `upload: { focalPoint: true }`, `hooks.beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()]`, pola `buildOptimizeUploadField()`, `buildMediaPlaceholderField()`, `alt` | upload `Zdjęcie Ś.JPG` → `zdjecie-s.jpg`, placeholder w dokumencie | media.md |
| obraz na froncie | prymityw `Media` | `<Image {...mediaImageProps(media, { sizes })} />`, wideo `videoProps` | blur przed załadowaniem | media.md |
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — zawsze (bez `R2_*` = dysk lokalny) | upload → URL z `R2_PUBLIC_URL` | storage.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP z panelu / Graph z env; też `panelSmtpAdapter`, `graphAdapter`, `sendEmail` z `/server`) | Site Integrations → SMTP → **Send test** | email.md |
| formularze — akcja | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | wysyłka → dokument w Form Submissions + maile | forms.md, skill **ipal-form** |
| formularze — render | blok formularza | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | formularz z panelu, Turnstile, komunikat z Notifications | forms.md |
| Turnstile | panel / env | `TurnstileProvider` wpina `SiteProviders`; klucze w Site Integrations → Turnstile albo env; serwer: `verifyTurnstile` (`/server`) | widżet w formularzu; alert na dashboardzie przy złym kluczu | turnstile.md |
| zgoda | layout + strona polityki | baner przez `SiteProviders`; tabela `<CookieTable rows={…} labels={…} />` (`/rsc`) z `getCookieTable` | `ipal-consent-check`; usuń cookie zgody → baner wraca | consent.md |
| dowód zgody | config + layout | `consentLog: true` + `logEndpoint="/api/ipal/consent"` | po kliknięciu dokument w Consent Records | consent.md |
| statystyki | config + layout | `stats: true` + `<SiteProviders stats={{ locale }}>` (lub `<PageStats locale />` w `ConsentProvider`) | `/<admin>/stats`; request `POST /api/ipal/hit` w Network | stats.md |
| analityka | layout | `Analytics` wpina `SiteProviders` (ID z Site Integrations → Analytics) | GTM/GA ładuje się dopiero po zgodzie | analytics.md, gtm-meta-pixel.md |
| JSON-LD dodatkowe | layout / `lib/content` | `jsonLd={[buildNavigationJsonLd(…)]}`; `siteJsonLd` → `buildLocalBusinessJsonLd` | Rich Results Test | seo.md |
| linki i nawigacja | komponenty | `buildLinkField`/`buildLinksField` w polach; `resolveNav`, `resolveLink`, `getSystemLinks` | link w menu po zmianie sluga działa | links.md, skill **ipal-nav** |
| bloki | `src/blocks/registry.ts` | `blocks` dla `createPageRoute`; pola `buildSectionHeaderField`, `buildSectionSettingsField` | blok widoczny na stronie | blocks.md, skill **ipal-block** |
| języki w nagłówku | header | `<LanguageSwitcher>` (`/client`), `<AlternateLinksUpdater>` | przełączenie na `/en/<slug-en>` | i18n.md |
| Tailwind | `styles.css` | `@import "@intecion/ipal-kit/fluid.css";` + `@source "…/node_modules/@intecion/ipal-kit/dist/**/*.js";` | baner cookies ma style | PROGRAMISTA §2.5 |
| panel `/its` | `app/(payload)/its/…` | `adminRoute: '/its'` + `its` w matcherze proxy | `/its` logowanie, `/admin` 404 | security.md |
| skille | `package.json` | `"ipal:skills": "ipal-skills"` | `.agents/skills/` aktualne | PROGRAMISTA §2.1a |
| health | `app/api/health/route.ts` | `export { healthRoute as GET }` + `force-dynamic` | `curl -s $U/api/health` → `"status":"ok"` (503 on a database error) | deployment.md |
| IndexNow key | `app/indexnow-key.txt/route.ts` | `export { indexNowKeyRoute as GET }` + `force-dynamic` | `curl -s $U/indexnow-key.txt` = the key | seo.md |
| search (optional) | `app/api/search/route.ts` | `export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig, baseUrl })` | `curl -s "$U/api/search?q=test&locale=pl"` | content.md |
| Pages | `src/collections/Pages.ts` | `buildSlugField({ from: 'title' })`, `buildNoindexField()`, `buildSummaryField()`, `slugHistory` field + `trackSlugHistoryHook`, `buildRevalidateHook({ revalidatePath, config })` → `afterChange`/`afterDelete` | edit in the panel → the page refreshes without a deploy | slug.md, hooks.md, seo.md |
| Pages — protection | as above | `beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })]`; `setPublishedAtHook`, `buildCrossLocaleFieldSync(...)` as needed | delete the homepage → error | hooks.md |
| Media | `src/collections/Media.ts` | `upload: { focalPoint: true }`, `hooks.beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()]`, fields `buildOptimizeUploadField()`, `buildMediaPlaceholderField()`, `alt` | upload `Zdjęcie Ś.JPG` → `zdjecie-s.jpg`, placeholder in the document | media.md |
| image on the frontend | `Media` primitive | `<Image {...mediaImageProps(media, { sizes })} />`, video `videoProps` | blur before load | media.md |
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site Integrations → SMTP → **Send test** | email.md |
| forms — action | `app/(frontend)/[locale]/actions.ts` | `'use server'`; `export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`/server`) | submit → document in Form Submissions + e-mails | forms.md, skill **ipal-form** |
| forms — render | form block | `<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />` (`/rsc`) | form from the panel, Turnstile, message from Notifications | forms.md |
| Turnstile | panel / env | `SiteProviders` wires `TurnstileProvider`; keys in Site Integrations → Turnstile or env; server: `verifyTurnstile` (`/server`) | widget in the form; dashboard alert on a bad key | turnstile.md |
| consent | layout + policy page | banner via `SiteProviders`; table `<CookieTable rows={…} labels={…} />` (`/rsc`) from `getCookieTable` | `ipal-consent-check`; delete the consent cookie → the banner comes back | consent.md |
| proof of consent | config + layout | `consentLog: true` + `logEndpoint="/api/ipal/consent"` | after a click, a document in Consent Records | consent.md |
| stats | config + layout | `stats: true` + `<SiteProviders stats={{ locale }}>` (or `<PageStats locale />` inside `ConsentProvider`) | `/<admin>/stats`; `POST /api/ipal/hit` request in Network | stats.md |
| analytics | layout | `SiteProviders` wires `Analytics` (ID from Site Integrations → Analytics) | GTM/GA loads only after consent | analytics.md, gtm-meta-pixel.md |
| extra JSON-LD | layout / `lib/content` | `jsonLd={[buildNavigationJsonLd(…)]}`; `siteJsonLd` → `buildLocalBusinessJsonLd` | Rich Results Test | seo.md |
| links and navigation | components | `buildLinkField`/`buildLinksField` in fields; `resolveNav`, `resolveLink`, `getSystemLinks` | a menu link still works after a slug change | links.md, skill **ipal-nav** |
| blocks | `src/blocks/registry.ts` | `blocks` for `createPageRoute`; fields `buildSectionHeaderField`, `buildSectionSettingsField` | block visible on the page | blocks.md, skill **ipal-block** |
| languages in the header | header | `<LanguageSwitcher>` (`/client`), `<AlternateLinksUpdater>` | switches to `/en/<slug-en>` | i18n.md |
| Tailwind | `styles.css` | `@import "@intecion/ipal-kit/fluid.css";` + `@source "…/node_modules/@intecion/ipal-kit/dist/**/*.js";` | the cookie banner is styled | PROGRAMISTA §2.5 |
| `/its` panel | `app/(payload)/its/…` | `adminRoute: '/its'` + `its` in the proxy matcher | `/its` login, `/admin` 404 | security.md |
| skills | `package.json` | `"ipal:skills": "ipal-skills"` | `.agents/skills/` up to date | PROGRAMISTA §2.1a |
**Klucze `createContentHelpers` (eksporty `@/lib/content`)** — wszystkie leniwe i w cache na request:
**`createContentHelpers` keys (exports of `@/lib/content`)** — all lazy and cached per request:
| klucz | użycie |
| key | use |
|---|---|
| `getCachedPayload` | `await getCachedPayload()` — Local API (akcje, trasy) |
| `getCachedPayload` | `await getCachedPayload()` — Local API (actions, routes) |
| `getSettings(locale)` | Site Settings (`depth: 2`) |
| `getConfiguredLocales()` | layout: `notFound()` dla obcego języka |
| `resolveRoute`, `getEntries`, `getNotFoundPage`, `resolvePageRedirect` | własna strona / archiwum zamiast `createPageRoute` |
| `generatePageMetadata`, `generateStaticParams`, `getPageJsonLd` | używa `createPageRoute`; ręcznie w własnych stronach |
| `getConfiguredLocales()` | layout: `notFound()` for an unknown language |
| `resolveRoute`, `getEntries`, `getNotFoundPage`, `resolvePageRedirect` | your own page / archive instead of `createPageRoute` |
| `generatePageMetadata`, `generateStaticParams`, `getPageJsonLd` | used by `createPageRoute`; call by hand in your own pages |
| `getSiteShell(locale)` | layout → `SiteProviders shell` |
| `getFormTexts(locale)` | `blockProps` dla formularzy |
| `getFormTexts(locale)` | `blockProps` for forms |
| `getLinkOptions`, `getHomeSlug`, `resolveLink`, `resolveNav`, `getSystemLinks` | header, footer, CMSLink |
| `getConstructionMode` | „strona w budowie” (construction.md) |
| `sitemap`, `sitemapRoute`, `robots`, `manifest`, `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`, `mcpPOST`, `healthRoute`, `indexNowKeyRoute` | re-eksporty w `app/` (tabela wyżej) |
| `i18n` | przekazany `I18nConfig` |
| `getConstructionMode` | under-construction mode (construction.md) |
| `sitemap`, `sitemapRoute`, `robots`, `manifest`, `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`, `mcpPOST`, `healthRoute`, `indexNowKeyRoute` | re-exports in `app/` (table above) |
| `i18n` | the `I18nConfig` passed in |
Opcje `createContentHelpers` (`baseUrl`, `pagesSlug`, `settingsSlug`, `redirectCollections`, `markdown`,
`createContentHelpers` options (`baseUrl`, `pagesSlug`, `settingsSlug`, `redirectCollections`, `markdown`,
`markdownAlternate`, `mcp`, `pageJsonLd`, `robots`, `siteJsonLd`, `sitemapImages`, `sitemapStyle`, `summaryField`)
i co rzuca bez `i18n`: frontend.md. `SiteProviders` propsy: `shell`, `banner`, `cookieButton`, `analytics`,
`cookieMap`, `jsonLd`, `logEndpoint`, `preconnect`, `stats`, `theme` — każdą część podmienisz albo `false`.
and what throws without `i18n`: frontend.md. `SiteProviders` props: `shell`, `banner`, `cookieButton`, `analytics`,
`cookieMap`, `jsonLd`, `logEndpoint`, `preconnect`, `stats`, `theme` — replace any part or set it to `false`.
## 4. Zmienne środowiskowe
## 4. Environment variables
`.env` w dev, runtime hostingu (Coolify) na produkcji, `.env.example` bez wartości w repo. Walidacja: `ipalEnvRules(features)`.
`.env` in dev, the hosting runtime (Coolify) in production, `.env.example` without values in the repo. Validation: `ipalEnvRules(features)`.
| zmienna | wymagana kiedy | skutek braku | gdzie ustawić |
| variable | required when | effect when missing | where to set |
|---|---|---|---|
| `DATABASE_URI` | zawsze (Payload; `ipalEnvRules` zawsze) | brak bazy, start pada | env (nazwa: `databaseVar`) |
| `PAYLOAD_SECRET` | zawsze | Payload nie startuje; `assertEnv` rzuca | env, ≥32 znaki, inny na prod (`secretVar`) |
| `NEXT_PUBLIC_SERVER_URL` | zawsze (`kind: 'url'`) | sitemap/robots/canonical/JSON-LD/llms z origin `''` (względne), IndexNow nie wysyła, R2 względny URL bez prefiksu | env (`serverUrlVar`) |
| `NODE_ENV` | nie (`development`/`production`/`test`) | `production` zaostrza: R2 i `IPAL_IP_HEADER` wymagane, IndexNow działa, ostrzeżenie o IP, `buildImagesConfig` prod | ustawia Next / hosting |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | `storage: true` + produkcja, albo gdy ustawiona choć jedna (wszystkie albo żadna) | dysk lokalny (na prod pliki znikają przy redeployu); niepełny komplet → ostrzeżenie | env |
| `R2_PUBLIC_URL` | jak wyżej; na prod absolutny URL | uploady działają, obrazy się nie wyświetlają; samo `R2_PUBLIC_URL` w dev = media tylko do odczytu; `/media` dozwolone poza prod; używane też przez `buildImagesConfig`, `MediaPreconnect`, CSP | env |
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | `emailGraph: true` / transport Graph w panelu | `mailAdapter` przechodzi na SMTP z panelu (log) | env (Exchange agencji) |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | `turnstile: true` (nazwy: `siteKeyVar`/`secretVar`) | fallback dla kluczy z Site Integrations → Turnstile; brak obu → Turnstile wyłączony | panel (pierwszeństwo) albo env |
| `INDEXNOW_KEY` | nie | klucz z Site Integrations → IndexNow (generowany) | env albo panel |
| `IPAL_IP_HEADER` | `ipHeader: true` + produkcja | rate limit ufa dowolnemu nagłówkowi IP (spoofing) + ostrzeżenie na prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) |
| `IPAL_NOINDEX` | nie; `1`/`true`/`yes` **tylko staging/preview** | — (ustawione: robots Disallow, meta noindex, `X-Robots-Tag`) | env stagingu |
| `NEXT_RUNTIME` | ustawia Next | `instrumentation.ts` sprawdza `nodejs`; brak (skrypty, seed) → `buildRevalidateHook` nie rewaliduje | nie ustawiaj ręcznie |
| `DATABASE_URI` | always (Payload; `ipalEnvRules` always) | no database, startup fails | env (name: `databaseVar`) |
| `PAYLOAD_SECRET` | always | Payload does not start; `assertEnv` throws | env, ≥32 characters, different in prod (`secretVar`) |
| `NEXT_PUBLIC_SERVER_URL` | always (`kind: 'url'`) | sitemap/robots/canonical/JSON-LD/llms with origin `''` (relative), IndexNow does not send, R2 relative URL without a prefix | env (`serverUrlVar`) |
| `NODE_ENV` | no (`development`/`production`/`test`) | `production` is stricter: R2 and `IPAL_IP_HEADER` required, IndexNow works, IP warning, `buildImagesConfig` prod | set by Next / hosting |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY` | `storage: true` + production, or when at least one is set (all or none) | local disk (in prod files disappear on redeploy); incomplete set → warning | env |
| `R2_PUBLIC_URL` | as above; absolute URL in prod | empty (default) → media served by the app at `/api/media/file/…` (Media needs `access.read: () => true`; with `ipalEnvRules({ storage: true })` make the rule optional, env.md); set it only for a media domain on Cloudflare (storage.md); `R2_PUBLIC_URL` alone in dev = media read-only; `/media` allowed outside prod; also used by `buildImagesConfig`, `MediaPreconnect`, CSP | env |
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | `emailGraph: true` / Graph transport in the panel | `mailAdapter` falls back to SMTP from the panel (logged) | env (agency Exchange) |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | `turnstile: true` (names: `siteKeyVar`/`secretVar`) | fallback for keys from Site Integrations → Turnstile; neither set → Turnstile off | panel (takes precedence) or env |
| `INDEXNOW_KEY` | no | key from Site Integrations → IndexNow (generated) | env or panel |
| `IPAL_IP_HEADER` | `ipHeader: true` + production | rate limit trusts any IP header (spoofing) + warning in prod | env: `cf-connecting-ip` (Cloudflare) / `x-forwarded-for` (Traefik/nginx) |
| `IPAL_NOINDEX` | no; `1`/`true`/`yes` **staging/preview only** | — (when set: robots Disallow, meta noindex, `X-Robots-Tag`) | staging env |
| `NEXT_RUNTIME` | set by Next | `instrumentation.ts` checks for `nodejs`; missing (scripts, seed) → `buildRevalidateHook` does not revalidate | do not set by hand |
Szczegóły: env.md, deployment.md, PROGRAMISTA §3.
Details: env.md, deployment.md, PROGRAMISTA §3.
**DNS** (A/AAAA, www, CAA, TXT Search Console, Bing, SPF/DKIM/DMARC domeny From, domena R2): plugin nic nie ustawia — lista rekordów z `dig` do sprawdzenia: `deployment.md` §6, skrót w **ipal-setup** etap 11.
**DNS** (A/AAAA, www, CAA, Search Console TXT, Bing, SPF/DKIM/DMARC for the From domain, R2 domain): the plugin sets nothing — list of records to check with `dig`: `deployment.md` §6, summary in **ipal-setup** stage 11.
**Seeding** (content in pages, forms, globals): create-only, matched by a natural key, never delete, never seed users or secrets, dry run → backup → real run; updates on production only for untouched records and only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`. Templates: `ipal-site/resources/seed-content.template.ts`, `ipal-form/resources/seed-form.template.ts`. Rules and Coolify steps: `node_modules/@intecion/ipal-kit/docs/seeding.md`.
+405 -405
View File
@@ -1,576 +1,576 @@
# ipal-kit — indeks eksportów
# ipal-kit — export index
Każdy publiczny eksport `@intecion/ipal-kit` (wszystkie wejścia: root, `/client`, `/rsc`,
`/server`, `/next/middleware`, `/admin`, `/env`), pogrupowany wg modułu. Szukaj grepem
(`grep -n "nazwa" .agents/skills/ipal-reference/resources/api.md`), zanim napiszesz coś sam.
Kolumna „Import z” — pierwsze wejście jest preferowane. Opcje pluginu, env, trasy i to, co
projekt podpina: `../SKILL.md`. Szczegóły modułu: `node_modules/@intecion/ipal-kit/docs/<strona>.md`.
Every public export of `@intecion/ipal-kit` (all entries: root, `/client`, `/rsc`,
`/server`, `/next/middleware`, `/admin`, `/env`), grouped by module. Search with grep
(`grep -n "name" .agents/skills/ipal-reference/resources/api.md`) before you write anything yourself.
"Import from" column — the first entry is preferred. Plugin options, env, routes and what the
project wires: `../SKILL.md`. Module details: `node_modules/@intecion/ipal-kit/docs/<page>.md`.
## Plugin (`plugin`, `types`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md`
## Plugin (`plugin`, `types`) — details: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `ipalKit(options)` | `@intecion/ipal-kit` | Plugin Payload 3 (`plugins: [ipalKit({...})]`) — jedyny punkt wpięcia: dodaje globale (SiteSettings, SiteIntegrations, CookieSettings, Notifications), role, wymuszone 2FA, SEO, formularze, i18n (lokalizacja), white-label, statystyki, log zgód, endpointy `/api/ipal/*`; brak kolekcji auth → wstrzykuje prostą `users`. Waliduje `i18n` od razu (fail fast). `enabled: false` = schemat zostaje, zachowanie wyłączone. |
| `ipalKit(options)` | `@intecion/ipal-kit` | Payload 3 plugin (`plugins: [ipalKit({...})]`) — the only wiring point: adds globals (SiteSettings, SiteIntegrations, CookieSettings, Notifications), roles, enforced 2FA, SEO, forms, i18n (localization), white-label, stats, consent log, `/api/ipal/*` endpoints; no auth collection → injects a simple `users`. Validates `i18n` right away (fail fast). `enabled: false` = schema stays, behaviour off. |
**Typy:** `IpalOptions` — opcje `ipalKit()`: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` lub `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `forms`, `pages`, `seo`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `enabled`.
**Types:** `IpalOptions` — `ipalKit()` options: `i18n`, `access`, `twoFactor` (`{ issuer, plugin: payloadTotp }` or `false`), `whiteLabel`, `adminRoute`, `consentLog`, `content`, `forms`, `pages`, `seo`, `stats`, `indexNow`, `siteSettingsFields`, `integrationsFields`, `enabled`.
## Admin (import map) (`admin`, `branding`, `admin-ui`, `globals/SiteIntegrations`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/white-label.md`, `…/docs/integrations.md`, `…/docs/email.md`, `…/docs/links.md`
## Admin (import map) (`admin`, `branding`, `admin-ui`, `globals/SiteIntegrations`) — details: `node_modules/@intecion/ipal-kit/docs/white-label.md`, `…/docs/integrations.md`, `…/docs/email.md`, `…/docs/links.md`
Komponenty panelu z `@intecion/ipal-kit/admin` — projekt ich NIE importuje; plugin (lub helper) wpisuje ścieżkę `@intecion/ipal-kit/admin#Nazwa` do configu, Payload rozwiązuje ją przez import map.
Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT import them; the plugin (or a helper) writes the path `@intecion/ipal-kit/admin#Name` into the config, and Payload resolves it through the import map.
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `MaskedField` | `@intecion/ipal-kit/admin` | Pole tekstowe maskowane (••••, przycisk Reveal) dla sekretów w SiteIntegrations (hasło SMTP, klucz R2, sekret Turnstile) — maskowanie tylko w UI, nie szyfrowanie. Wstrzykiwany przez plugin; można też podpiąć do własnego pola `text` przez `admin.components.Field`, potem `pnpm generate:importmap`. |
| `TestEmailButton` | `@intecion/ipal-kit/admin` | Przycisk „wyślij testowy e-mail” w zakładce e-mail SiteIntegrations — POST `/api/ipal/test-email` przez wybrany transport (SMTP/Graph), pokazuje wynik/błąd. Wstrzykiwany przez plugin — nie wołaj. |
| `RowLabel` | `@intecion/ipal-kit/admin` | Tytuł wiersza tablicy w panelu z treści wiersza (np. „Szybka dostawa” zamiast „Item 01”). Nie podpinaj ręcznie — użyj `rowLabel()`; po dodaniu `pnpm generate:importmap`. |
| `AdminLogo` | `@intecion/ipal-kit/admin` | Server Component: duże logo panelu (ekran logowania) z SiteSettings `logo`, fallback `siteName`. Wstrzykiwany przez plugin przy `whiteLabel`; po włączeniu opcji `pnpm generate:importmap`. |
| `AdminIcon` | `@intecion/ipal-kit/admin` | Server Component: mała ikona nawigacji panelu z SiteSettings `favicon`, fallback inicjały. Wstrzykiwany przez plugin przy `whiteLabel`; po włączeniu opcji `pnpm generate:importmap`. |
| `IntecionCredit` | `@intecion/ipal-kit/admin` | Linijka „Technology supported by Intecion.com” pod nawigacją i pod formularzem logowania (`variant: 'nav' \| 'login'`). Wstrzykiwany przez plugin przy `whiteLabel`; wyłączenie: `whiteLabel: { credit: false }`. |
| `MaskedField` | `@intecion/ipal-kit/admin` | Masked text field (••••, Reveal button) for secrets in SiteIntegrations (SMTP password, R2 key, Turnstile secret) — masking in the UI only, not encryption. Injected by the plugin; you can also wire it to your own `text` field via `admin.components.Field`, then `pnpm generate:importmap`. |
| `TestEmailButton` | `@intecion/ipal-kit/admin` | "Send test e-mail" button in the SiteIntegrations e-mail tab — POST `/api/ipal/test-email` through the selected transport (SMTP/Graph), shows the result/error. Injected by the plugin — do not call. |
| `RowLabel` | `@intecion/ipal-kit/admin` | Array row title in the panel taken from the row content (e.g. "Fast delivery" instead of "Item 01"). Do not wire by hand — use `rowLabel()`; after adding, `pnpm generate:importmap`. |
| `AdminLogo` | `@intecion/ipal-kit/admin` | Server Component: large panel logo (login screen) from SiteSettings `logo`, fallback `siteName`. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
| `AdminIcon` | `@intecion/ipal-kit/admin` | Server Component: small panel nav icon from SiteSettings `favicon`, fallback initials. Injected by the plugin with `whiteLabel`; after turning the option on, `pnpm generate:importmap`. |
| `IntecionCredit` | `@intecion/ipal-kit/admin` | The line "Technology supported by Intecion.com" below the nav and below the login form (`variant: 'nav' \| 'login'`). Injected by the plugin with `whiteLabel`; turn off: `whiteLabel: { credit: false }`. |
## Czytelne wiersze tablic w panelu (`admin-ui`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/links.md`
## Readable array rows in the panel (`admin-ui`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `rowLabel(fields, fallback = 'Item')` | `@intecion/ipal-kit` | Zwraca `{ RowLabel: { path, clientProps } }` do wstawienia w `admin.components` pola `array` — wiersz pokazuje pierwszą niepustą ścieżkę z `fields` (np. `'heading'`, `['name','link.label']`), inaczej „{fallback} 02”. Używaj w każdej tablicy projektu; `buildLinksField` ma go wbudowanego. Potem `pnpm generate:importmap`. |
| `rowLabel(fields, fallback = 'Item')` | `@intecion/ipal-kit` | Returns `{ RowLabel: { path, clientProps } }` to put in `admin.components` of an `array` field — the row shows the first non-empty path from `fields` (e.g. `'heading'`, `['name','link.label']`), otherwise "{fallback} 02". Use it in every array in the project; `buildLinksField` has it built in. Then `pnpm generate:importmap`. |
**Typy:** `RowLabelProps` — props komponentu `RowLabel` (`fields`, `fallback`).
**Types:** `RowLabelProps` — props of the `RowLabel` component (`fields`, `fallback`).
## Role i dostęp (`access`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/access.md`
## Roles and access (`access`) — details: `node_modules/@intecion/ipal-kit/docs/access.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `adminOnly` | `@intecion/ipal-kit` | `Access` kolekcji: tylko rola `admin`. W `access.read/create/update/delete`. |
| `adminOrEditor` | `@intecion/ipal-kit` | `Access` kolekcji: `editor` lub `admin`. Typowe dla treści edytowanych w panelu. |
| `adminOrSelf` | `@intecion/ipal-kit` | `Access` kolekcji: admin widzi wszystko, zalogowany tylko własny dokument (`Where` `id = user.id`), anonim nic. Np. `users.read`. |
| `authenticated` | `@intecion/ipal-kit` | `Access` kolekcji: dowolny zalogowany użytkownik. |
| `requireRole(minimum)` | `@intecion/ipal-kit` | Fabryka `Access` kolekcji: co najmniej podana rola (`'user' \| 'editor' \| 'admin'`). |
| `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (tylko boolean): pole tylko dla admina. W `field.access.read/update`. |
| `adminOrEditorField` | `@intecion/ipal-kit` | `FieldAccess`: pole dla editora lub admina. |
| `requireRoleField(minimum)` | `@intecion/ipal-kit` | Fabryka `FieldAccess`: co najmniej podana rola. |
| `hasMinimumRole(user, minimum)` | `@intecion/ipal-kit` | Predykat → `boolean`: czy user ma rolę ≥ `minimum` (bezpiecznie czyta `user.roles`). Do własnej logiki dostępu/hooków. |
| `isAdmin(user)` | `@intecion/ipal-kit` | Predykat → `boolean`: rola `admin`. |
| `isEditor(user)` | `@intecion/ipal-kit` | Predykat → `boolean`: `editor` lub wyżej. |
| `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Stała `['user', 'editor', 'admin']` (od najniższej) — wyższa rola spełnia wymagania niższej. Pole `roles` wstrzykuje plugin do kolekcji auth (`access.authCollection`). |
| `adminOnly` | `@intecion/ipal-kit` | Collection `Access`: `admin` role only. In `access.read/create/update/delete`. |
| `adminOrEditor` | `@intecion/ipal-kit` | Collection `Access`: `editor` or `admin`. Typical for content edited in the panel. |
| `adminOrSelf` | `@intecion/ipal-kit` | Collection `Access`: admin sees everything, a logged-in user only their own document (`Where` `id = user.id`), anonymous nothing. E.g. `users.read`. |
| `authenticated` | `@intecion/ipal-kit` | Collection `Access`: any logged-in user. |
| `requireRole(minimum)` | `@intecion/ipal-kit` | Collection `Access` factory: at least the given role (`'user' \| 'editor' \| 'admin'`). |
| `adminOnlyField` | `@intecion/ipal-kit` | `FieldAccess` (boolean only): field for admin only. In `field.access.read/update`. |
| `adminOrEditorField` | `@intecion/ipal-kit` | `FieldAccess`: field for editor or admin. |
| `requireRoleField(minimum)` | `@intecion/ipal-kit` | `FieldAccess` factory: at least the given role. |
| `hasMinimumRole(user, minimum)` | `@intecion/ipal-kit` | Predicate → `boolean`: whether the user has a role ≥ `minimum` (reads `user.roles` safely). For your own access logic/hooks. |
| `isAdmin(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `admin` role. |
| `isEditor(user)` | `@intecion/ipal-kit` | Predicate → `boolean`: `editor` or higher. |
| `ROLE_HIERARCHY` | `@intecion/ipal-kit` | Constant `['user', 'editor', 'admin']` (lowest first) — a higher role meets the requirements of a lower one. The plugin injects the `roles` field into the auth collection (`access.authCollection`). |
**Typy:** `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (opcja `access` pluginu: `authCollection`, `defaultRole`).
**Types:** `Role` (`'user' \| 'editor' \| 'admin'`), `AccessOption` (the plugin's `access` option: `authCollection`, `defaultRole`).
## Dostępność — widget (`accessibility`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
## Accessibility — widget (`accessibility`) — details: `node_modules/@intecion/ipal-kit/docs/accessibility.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `AccessibilityProvider` | `@intecion/ipal-kit/client` | Provider preferencji dostępności: trzyma stan, zapisuje cookie `a11y-prefs`, ustawia atrybuty `data-a11y-*` na `<html>`. Owiń layout raz. Plugin nie dostarcza CSS — projekt stylizuje atrybuty. |
| `AccessibilityWidget` | `@intecion/ipal-kit/client` | Pływający przycisk + panel opcji (rozmiar tekstu, interlinia, kontrast, skala szarości, podkreślanie linków, czytelna czcionka, redukcja ruchu, duży kursor). Props `classNames`, `texts` (domyślnie angielskie — tłumacz per locale). Wewnątrz `AccessibilityProvider`. |
| `useAccessibility()` | `@intecion/ipal-kit/client` | Hook → `{ state, set(key, value), reset() }` — do własnego UI dostępności. Wewnątrz `AccessibilityProvider`. |
| `A11Y_COOKIE` | `@intecion/ipal-kit` | Nazwa cookie preferencji: `'a11y-prefs'` — czytaj w SSR, by ustawić atrybuty bez mignięcia. |
| `A11Y_DEFAULT` | `@intecion/ipal-kit` | Domyślny `A11yState` (wszystko wyłączone, `contrast: 'default'`, `textSize: 0`, `lineHeight: 0`). |
| `parseA11y(raw)` | `@intecion/ipal-kit` | Wartość cookie → `A11yState` (przy błędzie `A11Y_DEFAULT`). Do SSR w layoucie. |
| `serializeA11y(state)` | `@intecion/ipal-kit` | `A11yState` → string JSON do cookie. |
| `a11yAttributes(state)` | `@intecion/ipal-kit` | `A11yState` → `{ 'data-a11y-*': string \| null }` (null = usuń atrybut). Do ustawienia atrybutów na `<html>` w SSR. |
| `AccessibilityProvider` | `@intecion/ipal-kit/client` | Accessibility preferences provider: holds state, saves the `a11y-prefs` cookie, sets `data-a11y-*` attributes on `<html>`. Wrap the layout once. The plugin ships no CSS — the project styles the attributes. |
| `AccessibilityWidget` | `@intecion/ipal-kit/client` | Floating button + options panel (text size, line height, contrast, grayscale, link underline, readable font, reduced motion, large cursor). Props `classNames`, `texts` (English by default — translate per locale). Inside `AccessibilityProvider`. |
| `useAccessibility()` | `@intecion/ipal-kit/client` | Hook → `{ state, set(key, value), reset() }` — for your own accessibility UI. Inside `AccessibilityProvider`. |
| `A11Y_COOKIE` | `@intecion/ipal-kit` | Preferences cookie name: `'a11y-prefs'` — read it in SSR to set attributes without a flash. |
| `A11Y_DEFAULT` | `@intecion/ipal-kit` | Default `A11yState` (everything off, `contrast: 'default'`, `textSize: 0`, `lineHeight: 0`). |
| `parseA11y(raw)` | `@intecion/ipal-kit` | Cookie value → `A11yState` (`A11Y_DEFAULT` on error). For SSR in the layout. |
| `serializeA11y(state)` | `@intecion/ipal-kit` | `A11yState` → JSON string for the cookie. |
| `a11yAttributes(state)` | `@intecion/ipal-kit` | `A11yState` → `{ 'data-a11y-*': string \| null }` (null = remove the attribute). To set attributes on `<html>` in SSR. |
**Typy:** `A11yState` (root i `/client`) — stan preferencji; `A11yTexts`, `A11yClassNames` (`/client`) — teksty i klasy `AccessibilityWidget`.
**Types:** `A11yState` (root and `/client`) — preferences state; `A11yTexts`, `A11yClassNames` (`/client`) — `AccessibilityWidget` texts and classes.
## Analityka i piksele (`analytics`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/analytics.md`
## Analytics and pixels (`analytics`) — details: `node_modules/@intecion/ipal-kit/docs/analytics.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `getAnalyticsConfig(payload)` | `@intecion/ipal-kit` | Serwer: czyta publiczne ID tagów (GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok) z SiteIntegrations, waliduje format → `Promise<AnalyticsConfig>`; wynik przekaż do `<Analytics>`. |
| `Analytics` | `@intecion/ipal-kit/client` | Ładuje wszystkie skonfigurowane tagi z poszanowaniem zgody: Google przez Consent Mode, pozostałe dopiero po zgodzie kategorii (marketing / analytics). Props = `AnalyticsConfig` + `defer`, `deferTimeoutMs`. Renderuje nic; montuj raz wewnątrz `ConsentProvider`. Nie wstawiaj tagów ręcznie. |
| `pushDataLayer(event, params?)` | `@intecion/ipal-kit/client` | Wrzuca zdarzenie do `window.dataLayer` GTM (SSR-safe, buforuje przed załadowaniem GTM). Np. `form_submit` po wysłaniu formularza (`docs/gtm-meta-pixel.md`). |
| `loadMetaPixel(id)` | `@intecion/ipal-kit/client` | Niskopoziomowy loader Meta Pixel (idempotentny, PageView). `Analytics` woła go sam po zgodzie marketing — ręcznie tylko w nietypowych przypadkach, i tylko po zgodzie. |
| `loadClarity(id)` | `@intecion/ipal-kit/client` | Loader Microsoft Clarity (kategoria analytics). `Analytics` woła sam — nie wołaj zwykle. |
| `loadLinkedIn(partnerId)` | `@intecion/ipal-kit/client` | Loader LinkedIn Insight Tag (marketing). `Analytics` woła sam — nie wołaj zwykle. |
| `loadTikTok(id)` | `@intecion/ipal-kit/client` | Loader TikTok Pixel (marketing). `Analytics` woła sam — nie wołaj zwykle. |
| `getAnalyticsConfig(payload)` | `@intecion/ipal-kit` | Server: reads public tag IDs (GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok) from SiteIntegrations, validates the format → `Promise<AnalyticsConfig>`; pass the result to `<Analytics>`. |
| `Analytics` | `@intecion/ipal-kit/client` | Loads all configured tags respecting consent: Google through Consent Mode, the rest only after consent for the category (marketing / analytics). Props = `AnalyticsConfig` + `defer`, `deferTimeoutMs`. Renders nothing; mount once inside `ConsentProvider`. Do not add tags by hand. |
| `pushDataLayer(event, params?)` | `@intecion/ipal-kit/client` | Pushes an event to the GTM `window.dataLayer` (SSR-safe, buffers before GTM loads). E.g. `form_submit` after a form is sent (`docs/gtm-meta-pixel.md`). |
| `loadMetaPixel(id)` | `@intecion/ipal-kit/client` | Low-level Meta Pixel loader (idempotent, PageView). `Analytics` calls it itself after marketing consent — call by hand only in unusual cases, and only after consent. |
| `loadClarity(id)` | `@intecion/ipal-kit/client` | Microsoft Clarity loader (analytics category). `Analytics` calls it itself — usually do not call. |
| `loadLinkedIn(partnerId)` | `@intecion/ipal-kit/client` | LinkedIn Insight Tag loader (marketing). `Analytics` calls it itself — usually do not call. |
| `loadTikTok(id)` | `@intecion/ipal-kit/client` | TikTok Pixel loader (marketing). `Analytics` calls it itself — usually do not call. |
**Typy:** `AnalyticsConfig` (root) — ID tagów z SiteIntegrations; `AnalyticsProps` (`/client`) — props `Analytics`.
**Types:** `AnalyticsConfig` (root) — tag IDs from SiteIntegrations; `AnalyticsProps` (`/client`) — `Analytics` props.
## Bloki i sekcje (`blocks`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/blocks.md`
## Blocks and sections (`blocks`) — details: `node_modules/@intecion/ipal-kit/docs/blocks.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `RenderBlocks` | `@intecion/ipal-kit/rsc` | Serwerowy renderer bloków: `{ blocks, components, enhanceProps? }` — każdy blok przez mapę `blockType → komponent`, nieznane pomija, bez dodatkowego markupu. Nie pisz własnej pętli po blokach. Bloki zagnieżdżone renderują własny `RenderBlocks` (mapy nie przekazuj propsem). |
| `buildSectionHeaderField(opts?)` | `@intecion/ipal-kit` | Grupa pól `header` (eyebrow, heading, intro — lokalizowane) do każdego bloku sekcji; `interfaceName` `SectionHeaderData`. Opcje: `name`, `fields`, `interfaceName`. |
| `buildSectionSettingsField(opts?)` | `@intecion/ipal-kit` | Grupa `settings` w sidebarze bloku: `anchor` (#id) + `background` (select, domyślnie Default/Muted/Inverted) + własne pola; zamiast `bgColor`/`sectionId` per blok. |
| `RenderBlocks` | `@intecion/ipal-kit/rsc` | Server block renderer: `{ blocks, components, enhanceProps? }` — each block through a `blockType → component` map, skips unknown ones, no extra markup. Do not write your own loop over blocks. Nested blocks render their own `RenderBlocks` (do not pass the map as a prop). |
| `buildSectionHeaderField(opts?)` | `@intecion/ipal-kit` | `header` field group (eyebrow, heading, intro — localized) for every section block; `interfaceName` `SectionHeaderData`. Options: `name`, `fields`, `interfaceName`. |
| `buildSectionSettingsField(opts?)` | `@intecion/ipal-kit` | `settings` group in the block sidebar: `anchor` (#id) + `background` (select, default Default/Muted/Inverted) + your own fields; instead of a per-block `bgColor`/`sectionId`. |
**Typy:** `BlockData`, `BlockComponentMap`, `EnhanceProps`, `RenderBlocksProps` (`/rsc`) — dane bloku, mapa komponentów, enhancer propsów, props renderera; `SectionHeaderFieldOptions`, `SectionSettingsFieldOptions` (root) — opcje builderów pól sekcji.
**Types:** `BlockData`, `BlockComponentMap`, `EnhanceProps`, `RenderBlocksProps` (`/rsc`) — block data, component map, props enhancer, renderer props; `SectionHeaderFieldOptions`, `SectionSettingsFieldOptions` (root) — options of the section field builders.
## Zgoda na cookies (`consent`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/consent.md`
## Cookie consent (`consent`) — details: `node_modules/@intecion/ipal-kit/docs/consent.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `ConsentProvider` | `@intecion/ipal-kit/client` | Provider zgody: `{ texts, cookieMap?, logEndpoint? }` — stan zgody, cookie, Consent Mode, usuwanie cookies po wycofaniu zgody, opcjonalny POST decyzji do logu (`'/api/ipal/consent'`). Owiń layout raz; wymagany przez baner, `Analytics`, `ConsentScript`. |
| `CookieBanner` | `@intecion/ipal-kit/client` | Baner zgody + ustawienia kategorii: `settings: 'inline' \| 'modal' \| 'detailed'`, `controls`, `equalChoice` (zalecane `true`), `order`, `settingsActions`, `icon`, `classNames`; kolory z CSS vars `--ipal-*`. Nie pisz własnego banera. |
| `CookieButton` | `@intecion/ipal-kit/client` | Pływający przycisk ponownego otwarcia ustawień cookies (wycofanie zgody); ukryty, gdy baner widoczny. Prop `className`. |
| `ConsentScript` | `@intecion/ipal-kit/client` | Ładuje skrypt zewnętrzny (`src` lub `code`) dopiero po zgodzie na `category` — dla dostawców bez Consent Mode (czat, Plausible itp.). Wewnątrz `ConsentProvider`. |
| `CookieTable` | `@intecion/ipal-kit/rsc` | Server Component: tabela cookies na stronę polityki cookies — `{ rows, labels, categories?, caption?, classNames? }`; `rows` z `getCookieTable()`. |
| `useConsent(options?)` | `@intecion/ipal-kit/client` | Niskopoziomowy hook stanu zgody → `{ state, decided, consentId, acceptAll, rejectAll, savePreferences, reopen }`. Zwykle używaj `ConsentProvider` + `useConsentContext` (provider woła go sam). |
| `useConsentContext()` | `@intecion/ipal-kit/client` | Hook: wartość `useConsent` + `texts` z `ConsentProvider` — do własnego UI zależnego od zgody (np. `state.marketing`). Rzuca poza providerem. |
| `getConsentTexts({ payload, config, locale?, privacyPolicy?, settingsSlug? })` | `@intecion/ipal-kit` | Serwer: teksty banera z globalu CookieSettings (fallback EN per pole) + link do polityki prywatności ze stron systemowych → `Promise<ConsentTexts>`; przekaż do `ConsentProvider texts`. |
| `getCookieTable({ payload, locale? })` | `@intecion/ipal-kit` | Serwer: wiersze Cookie Settings → Cookies w jednym języku → `Promise<CookieTableRow[]>` (nie rzuca) — dla `CookieTable`. |
| `setDefaultConsent(state)` | `@intecion/ipal-kit` | Google Consent Mode `consent default` (z `wait_for_update`). `Analytics` woła sam przed załadowaniem tagów Google — nie wołaj. |
| `updateConsent(state)` | `@intecion/ipal-kit` | Google Consent Mode `consent update` po decyzji. `useConsent` woła sam — nie wołaj. |
| `parseConsent(raw, version?)` | `@intecion/ipal-kit` | Wartość cookie zgody → `ConsentState \| null` (null: brak, błąd lub inna wersja polityki). Do bramkowania po stronie serwera. |
| `readConsentRecord(raw, version?)` | `@intecion/ipal-kit` | Jak `parseConsent`, ale pełny rekord `{ id, state, timestamp, version } \| null`. |
| `serializeConsent(state, version?, id?)` | `@intecion/ipal-kit` | `ConsentState` → zakodowana wartość cookie (z timestampem i wersją). Zwykle robi to provider. |
| `CONSENT_COOKIE` | `@intecion/ipal-kit` | Nazwa cookie zgody: `'cookie-consent'`. |
| `CONSENT_VERSION` | `@intecion/ipal-kit` | Domyślna wersja polityki: `1` (nadpisywana w panelu: Cookie Settings → Policy version; zmiana unieważnia stare zgody). |
| `CONSENT_MAX_AGE` | `@intecion/ipal-kit` | Ważność cookie zgody w sekundach: 180 dni. |
| `CONSENT_CATEGORIES` | `@intecion/ipal-kit` | `['necessary', 'functional', 'analytics', 'marketing']`; `necessary` zawsze włączona. |
| `DEFAULT_CONSENT` | `@intecion/ipal-kit` | Stan przed decyzją: tylko `necessary: true`. |
| `ACCEPT_ALL_CONSENT` | `@intecion/ipal-kit` | Wszystkie kategorie `true`. |
| `REJECT_ALL_CONSENT` | `@intecion/ipal-kit` | Tylko `necessary: true` (kopia `DEFAULT_CONSENT`). |
| `CONSENT_LOG_SLUG` | `@intecion/ipal-kit` | Slug kolekcji logu zgód: `'consent-records'`. |
| `buildConsentLogCollection()` | `@intecion/ipal-kit` | Kolekcja logu zgód (id, wybory, wersja, czas — bez IP/danych osobowych; dowód zgody RODO art. 7(1)). Plugin podpina sam przy `consentLog: true` — nie wołaj. |
| `buildConsentLogEndpoint({ retentionDays? })` | `@intecion/ipal-kit` | Endpoint `POST /api/ipal/consent` zapisujący decyzje, czyści rekordy starsze niż `retentionDays` (domyślnie 1095). Plugin podpina sam przy `consentLog` — nie wołaj. |
| `ConsentProvider` | `@intecion/ipal-kit/client` | Consent provider: `{ texts, cookieMap?, logEndpoint? }` — consent state, cookie, Consent Mode, deleting cookies after consent is withdrawn, optional POST of the decision to the log (`'/api/ipal/consent'`). Wrap the layout once; required by the banner, `Analytics`, `ConsentScript`. |
| `CookieBanner` | `@intecion/ipal-kit/client` | Consent banner + category settings: `settings: 'inline' \| 'modal' \| 'detailed'`, `controls`, `equalChoice` (recommended `true`), `order`, `settingsActions`, `icon`, `classNames`; colours from `--ipal-*` CSS vars. Do not write your own banner. |
| `CookieButton` | `@intecion/ipal-kit/client` | Floating button that reopens the cookie settings (withdrawing consent); hidden while the banner is visible. Prop `className`. |
| `ConsentScript` | `@intecion/ipal-kit/client` | Loads an external script (`src` or `code`) only after consent for `category` — for vendors without Consent Mode (chat, Plausible etc.). Inside `ConsentProvider`. |
| `CookieTable` | `@intecion/ipal-kit/rsc` | Server Component: cookie table for the cookie policy page — `{ rows, labels, categories?, caption?, classNames? }`; `rows` from `getCookieTable()`. |
| `useConsent(options?)` | `@intecion/ipal-kit/client` | Low-level consent state hook → `{ state, decided, consentId, acceptAll, rejectAll, savePreferences, reopen }`. Usually use `ConsentProvider` + `useConsentContext` (the provider calls it itself). |
| `useConsentContext()` | `@intecion/ipal-kit/client` | Hook: the `useConsent` value + `texts` from `ConsentProvider` — for your own consent-dependent UI (e.g. `state.marketing`). Throws outside the provider. |
| `getConsentTexts({ payload, config, locale?, privacyPolicy?, settingsSlug? })` | `@intecion/ipal-kit` | Server: banner texts from the CookieSettings global (EN fallback per field) + privacy policy link from the system pages → `Promise<ConsentTexts>`; pass to `ConsentProvider texts`. |
| `getCookieTable({ payload, locale? })` | `@intecion/ipal-kit` | Server: Cookie Settings → Cookies rows in one language → `Promise<CookieTableRow[]>` (does not throw) — for `CookieTable`. |
| `setDefaultConsent(state)` | `@intecion/ipal-kit` | Google Consent Mode `consent default` (with `wait_for_update`). `Analytics` calls it itself before loading Google tags — do not call. |
| `updateConsent(state)` | `@intecion/ipal-kit` | Google Consent Mode `consent update` after the decision. `useConsent` calls it itself — do not call. |
| `parseConsent(raw, version?)` | `@intecion/ipal-kit` | Consent cookie value → `ConsentState \| null` (null: missing, error or a different policy version). For server-side gating. |
| `readConsentRecord(raw, version?)` | `@intecion/ipal-kit` | Like `parseConsent`, but the full record `{ id, state, timestamp, version } \| null`. |
| `serializeConsent(state, version?, id?)` | `@intecion/ipal-kit` | `ConsentState` → encoded cookie value (with timestamp and version). Usually the provider does this. |
| `CONSENT_COOKIE` | `@intecion/ipal-kit` | Consent cookie name: `'cookie-consent'`. |
| `CONSENT_VERSION` | `@intecion/ipal-kit` | Default policy version: `1` (overridden in the panel: Cookie Settings → Policy version; changing it invalidates old consents). |
| `CONSENT_MAX_AGE` | `@intecion/ipal-kit` | Consent cookie lifetime in seconds: 180 days. |
| `CONSENT_CATEGORIES` | `@intecion/ipal-kit` | `['necessary', 'functional', 'analytics', 'marketing']`; `necessary` always on. |
| `DEFAULT_CONSENT` | `@intecion/ipal-kit` | State before the decision: only `necessary: true`. |
| `ACCEPT_ALL_CONSENT` | `@intecion/ipal-kit` | All categories `true`. |
| `REJECT_ALL_CONSENT` | `@intecion/ipal-kit` | Only `necessary: true` (a copy of `DEFAULT_CONSENT`). |
| `CONSENT_LOG_SLUG` | `@intecion/ipal-kit` | Consent log collection slug: `'consent-records'`. |
| `buildConsentLogCollection()` | `@intecion/ipal-kit` | Consent log collection (id, choices, version, time — no IP/personal data; proof of consent under GDPR Art. 7(1)). The plugin wires it itself with `consentLog: true` — do not call. |
| `buildConsentLogEndpoint({ retentionDays? })` | `@intecion/ipal-kit` | `POST /api/ipal/consent` endpoint that saves decisions and deletes records older than `retentionDays` (default 1095). The plugin wires it itself with `consentLog` — do not call. |
**Typy:** `ConsentCategory`, `ConsentState`, `ConsentTexts`, `CookieTableRow`, `ConsentLogOptions` (root) — kategorie, stan zgody, teksty banera, wiersz tabeli cookies, opcje logu; `CookieBannerAction`, `CookieSettingsAction`, `CookieBannerClassNames` (`/client`) — przyciski i klasy `CookieBanner`; `CookieTableLabels` (`/rsc`) — nagłówki kolumn `CookieTable`.
**Types:** `ConsentCategory`, `ConsentState`, `ConsentTexts`, `CookieTableRow`, `ConsentLogOptions` (root) — categories, consent state, banner texts, cookie table row, log options; `CookieBannerAction`, `CookieSettingsAction`, `CookieBannerClassNames` (`/client`) — `CookieBanner` buttons and classes; `CookieTableLabels` (`/rsc`) — `CookieTable` column headers.
## Strona w budowie (`construction`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/construction.md`
## Under construction (`construction`) — details: `node_modules/@intecion/ipal-kit/docs/construction.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `ConstructionNotice` | `@intecion/ipal-kit/client` | Popup „strona w budowie”: `{ mode, classNames? }` — otwiera się po przekierowaniu z zablokowanego adresu (`?notice=construction`) i przy kliknięciu linku do niedostępnej strony; teksty z panelu, nic nie renderuje przy wyłączonym trybie. W `[locale]/layout.tsx` z `mode={await getConstructionMode(locale)}`. |
| `isPathAllowed(pathname, allowedPaths)` | `@intecion/ipal-kit` | Czy ścieżka jest dozwolona w trybie budowy (dokładne dopasowanie, bez końcowego `/`) → `boolean`. `createPageRoute` używa sam — ręcznie tylko we własnych trasach. |
| `constructionNoticeHref(homePath)` | `@intecion/ipal-kit` | Adres przekierowania zablokowanej strony: `${homePath}?notice=construction`. `createPageRoute` używa sam. |
| `CONSTRUCTION_NOTICE_PARAM` | `@intecion/ipal-kit` | Nazwa parametru zapytania otwierającego popup: `'notice'` (wartość `construction`). |
| `ConstructionNotice` | `@intecion/ipal-kit/client` | "Under construction" popup: `{ mode, classNames? }` — opens after a redirect from a blocked address (`?notice=construction`) and on a click on a link to an unavailable page; texts from the panel, renders nothing when the mode is off. In `[locale]/layout.tsx` with `mode={await getConstructionMode(locale)}`. |
| `isPathAllowed(pathname, allowedPaths)` | `@intecion/ipal-kit` | Whether the path is allowed in under-construction mode (exact match, no trailing `/`) → `boolean`. `createPageRoute` uses it itself — by hand only in your own routes. |
| `constructionNoticeHref(homePath)` | `@intecion/ipal-kit` | Redirect address for a blocked page: `${homePath}?notice=construction`. `createPageRoute` uses it itself. |
| `CONSTRUCTION_NOTICE_PARAM` | `@intecion/ipal-kit` | Name of the query parameter that opens the popup: `'notice'` (value `construction`). |
**Typy:** `ConstructionMode` (root i `/client`) — `{ enabled, allowedPaths, homePath, texts }` z `getConstructionMode(locale)`; `ConstructionNoticeClassNames` (`/client`) — klasy popupu.
**Types:** `ConstructionMode` (root and `/client`) — `{ enabled, allowedPaths, homePath, texts }` from `getConstructionMode(locale)`; `ConstructionNoticeClassNames` (`/client`) — popup classes.
## Treści i routing (`content`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/content.md`
## Content and routing (`content`) — details: `node_modules/@intecion/ipal-kit/docs/content.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `resolveRoute({ payload, locale, segments, page, content, draft? })` | `@intecion/ipal-kit` | rozstrzyga ścieżkę catch-all → `{ type: 'home'\|'page'\|'archive'\|'entry', doc, … }` albo `null` (404); zwykle przez `resolveRoute` z `createContentHelpers` |
| `getArchiveEntries({ payload, collection, locale, page, perPage, sort?, where?, depth?, draft? })` | `@intecion/ipal-kit` | pobiera stronę wpisów archiwum (`ArchiveEntries`); domyślne ustawienia ma `getEntries` z `createContentHelpers` |
| `archiveFieldName(slug)` | `@intecion/ipal-kit` | nazwa pola archiwum w System Pages (`'posts'` → `'postsArchive'`); plugin dodaje te pola sam |
| `buildEntryPath({ locale, archiveSlug, entrySlug })` | `@intecion/ipal-kit` | ścieżka wpisu `/pl/artykuly/moj-post` (zawsze z prefiksem locale) |
| `buildArchivePath({ locale, archiveSlug, page })` | `@intecion/ipal-kit` | ścieżka listingu z paginacją `?page=N` (strona 1 bez query) |
| `parsePageParam(value)` | `@intecion/ipal-kit` | `?page=` → liczba ≥ 1 (śmieci/brak → 1) |
| `resolveRedirect({ payload, locale, segments, config, homeSlug, collections? })` | `@intecion/ipal-kit` | szuka starego sluga w `slugHistory` → ścieżka do `permanentRedirect` albo `null`; para do `trackSlugHistoryHook` — nie pisz własnego lookupu |
| `resolveNotFoundPage({ payload, locale, pagesSlug?, settingsSlug? })` | `@intecion/ipal-kit` | strona przypisana jako 404 w System Pages albo `null`; nie rzuca (z helperami: `getNotFoundPage`) |
| `blocksToMarkdown(layout, { overrides? })` | `@intecion/ipal-kit` | bloki strony → Markdown po konwencji nazw pól (heading, body, items…) |
| `createMarkdownRenderer({ content, collection?, layoutField?, overrides?, frontmatter?, baseUrl?, config? })` | `@intecion/ipal-kit` | zwraca `render({ payload, locale, slug })` → Markdown strony (GEO) albo `null` |
| `createMarkdownRoute({ getCachedPayload, content, config, baseUrl })` | `@intecion/ipal-kit` | gotowy handler `GET` trasy `/md/...`; zwykle wystarczy `markdownRoute` z `createContentHelpers` |
| `markdownResponse(md, { canonical? })` | `@intecion/ipal-kit` | `Response` `text/markdown` (noindex, `s-maxage`) albo 404 dla `null` |
| `MARKDOWN_PREFIX` | `@intecion/ipal-kit` | stała `'/md'` — domyślny prefiks tras Markdown |
| `markdownHref(pathname, prefix?)` | `@intecion/ipal-kit` | ścieżka strony → adres wersji Markdown (`/pl/o-nas` → `/md/pl/o-nas`), np. do `alternates.types` |
| `prefersMarkdown(request \| headers \| accept)` | `@intecion/ipal-kit` | czy nagłówek `Accept` woli `text/markdown` (q-values); do własnego proxy — `createProxy({ markdown: true })` robi to sam |
| `searchContent({ payload, query, config, locale?, limit?, baseUrl?, collection?, summaryField? })` | `@intecion/ipal-kit` | wyszukiwanie opublikowanych, indeksowalnych stron po tytule/opisie → `SearchResult[]`; nie rzuca |
| `listContent({ payload, config, locale?, limit? })` | `@intecion/ipal-kit` | spis opublikowanych, indeksowalnych stron (bez zapytania) — używa go MCP `list_pages` |
| `createSearchRoute({ getCachedPayload, config, baseUrl, defaultLimit?, rateLimit?, clientIp? })` | `@intecion/ipal-kit` | handler `GET` endpointu JSON wyszukiwarki (`?q=&locale=&limit=`), z limitem zapytań per IP |
| `resolveRoute({ payload, locale, segments, page, content, draft? })` | `@intecion/ipal-kit` | resolves a catch-all path → `{ type: 'home'\|'page'\|'archive'\|'entry', doc, … }` or `null` (404); usually through `resolveRoute` from `createContentHelpers` |
| `getArchiveEntries({ payload, collection, locale, page, perPage, sort?, where?, depth?, draft? })` | `@intecion/ipal-kit` | fetches a page of archive entries (`ArchiveEntries`); `getEntries` from `createContentHelpers` has the defaults |
| `archiveFieldName(slug)` | `@intecion/ipal-kit` | name of the archive field in System Pages (`'posts'` → `'postsArchive'`); the plugin adds these fields itself |
| `buildEntryPath({ locale, archiveSlug, entrySlug })` | `@intecion/ipal-kit` | entry path `/pl/artykuly/moj-post` (always with the locale prefix) |
| `buildArchivePath({ locale, archiveSlug, page })` | `@intecion/ipal-kit` | listing path with `?page=N` pagination (page 1 without a query) |
| `parsePageParam(value)` | `@intecion/ipal-kit` | `?page=` → number ≥ 1 (junk/missing → 1) |
| `resolveRedirect({ payload, locale, segments, config, homeSlug, collections? })` | `@intecion/ipal-kit` | looks up an old slug in `slugHistory` → path for `permanentRedirect` or `null`; pairs with `trackSlugHistoryHook` — do not write your own lookup |
| `resolveNotFoundPage({ payload, locale, pagesSlug?, settingsSlug? })` | `@intecion/ipal-kit` | page assigned as 404 in System Pages or `null`; does not throw (with the helpers: `getNotFoundPage`) |
| `blocksToMarkdown(layout, { overrides? })` | `@intecion/ipal-kit` | page blocks → Markdown by field naming convention (heading, body, items…) |
| `createMarkdownRenderer({ content, collection?, layoutField?, overrides?, frontmatter?, baseUrl?, config? })` | `@intecion/ipal-kit` | returns `render({ payload, locale, slug })` → page Markdown (GEO) or `null` |
| `createMarkdownRoute({ getCachedPayload, content, config, baseUrl })` | `@intecion/ipal-kit` | ready `GET` handler for the `/md/...` route; usually `markdownRoute` from `createContentHelpers` is enough |
| `markdownResponse(md, { canonical? })` | `@intecion/ipal-kit` | `Response` `text/markdown` (noindex, `s-maxage`) or 404 for `null` |
| `MARKDOWN_PREFIX` | `@intecion/ipal-kit` | constant `'/md'` — default prefix of Markdown routes |
| `markdownHref(pathname, prefix?)` | `@intecion/ipal-kit` | page path → Markdown version address (`/pl/o-nas` → `/md/pl/o-nas`), e.g. for `alternates.types` |
| `prefersMarkdown(request \| headers \| accept)` | `@intecion/ipal-kit` | whether the `Accept` header prefers `text/markdown` (q-values); for your own proxy — `createProxy({ markdown: true })` does it itself |
| `searchContent({ payload, query, config, locale?, limit?, baseUrl?, collection?, summaryField? })` | `@intecion/ipal-kit` | searches published, indexable pages by title/description → `SearchResult[]`; does not throw |
| `listContent({ payload, config, locale?, limit? })` | `@intecion/ipal-kit` | list of published, indexable pages (no query) — used by MCP `list_pages` |
| `createSearchRoute({ getCachedPayload, config, baseUrl, defaultLimit?, rateLimit?, clientIp? })` | `@intecion/ipal-kit` | `GET` handler for the JSON search endpoint (`?q=&locale=&limit=`), with a per-IP rate limit |
**Typy:** `ContentOption`, `ContentCollectionOption` — opcja `content` pluginu (kolekcje archiwalne: `slug`, `label`, `perPage`); `ResolvedRoute` — wynik `resolveRoute`; `ArchiveEntries` — strona wpisów (`docs`, `page`, `totalDocs`, `totalPages`, `hasPrevPage`, `hasNextPage`); `SearchResult` — wynik wyszukiwania (`title`, `url`, `description?`, `slug`).
**Types:** `ContentOption`, `ContentCollectionOption` — the plugin's `content` option (archive collections: `slug`, `label`, `perPage`); `ResolvedRoute` — `resolveRoute` result; `ArchiveEntries` — a page of entries (`docs`, `page`, `totalDocs`, `totalPages`, `hasPrevPage`, `hasNextPage`); `SearchResult` — search result (`title`, `url`, `description?`, `slug`).
## E-mail (`email`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/email.md`
## E-mail (`email`) — details: `node_modules/@intecion/ipal-kit/docs/email.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `mailAdapter({ smtp?, graph?, fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | zalecany adapter do `buildConfig({ email })`: przy każdej wysyłce wybiera SMTP albo Graph wg ustawienia w panelu i zapisuje status integracji; plugin sam `config.email` nie ustawia |
| `panelSmtpAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | adapter Payloada wysyłający zawsze przez SMTP skonfigurowany w Site Integrations |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | adapter Payloada przez Microsoft Graph (Exchange/M365; dane `GRAPH_*` z env) |
| `sendEmail({ payload, to, subject, html, text?, from?, replyTo? })` | `@intecion/ipal-kit/server` | wysyłka własnego maila (Twój HTML) zawsze przez SMTP z panelu → `{ sent: true, messageId }` / `{ sent: false, error }`; nie rzuca; tylko kod serwerowy |
| `mailAdapter({ smtp?, graph?, fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | recommended adapter for `buildConfig({ email })`: on every send picks SMTP or Graph per the panel setting and saves the integration status; the plugin does not set `config.email` itself |
| `panelSmtpAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter that always sends through the SMTP configured in Site Integrations |
| `graphAdapter({ fallbackFromAddress?, fallbackFromName? })` | `@intecion/ipal-kit` | Payload adapter through Microsoft Graph (Exchange/M365; `GRAPH_*` credentials from env) |
| `sendEmail({ payload, to, subject, html, text?, from?, replyTo? })` | `@intecion/ipal-kit/server` | sends your own e-mail (your HTML) always through SMTP from the panel → `{ sent: true, messageId }` / `{ sent: false, error }`; does not throw; server code only |
**Typy:** `MailAdapterArgs`, `PanelSmtpAdapterArgs`, `GraphAdapterArgs` — opcje adapterów; `SendEmailArgs`, `SendEmailResult` (`/server`) — argumenty i wynik `sendEmail`.
**Types:** `MailAdapterArgs`, `PanelSmtpAdapterArgs`, `GraphAdapterArgs` — adapter options; `SendEmailArgs`, `SendEmailResult` (`/server`) — `sendEmail` arguments and result.
## Zmienne środowiskowe (`env`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/env.md`
## Environment variables (`env`) — details: `node_modules/@intecion/ipal-kit/docs/env.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `assertEnv(rules, { env?, label? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | waliduje `process.env` wg reguł na starcie; zbiera wszystkie braki i rzuca jeden błąd |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | gotowy zestaw reguł (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` wg używanych funkcji) do `assertEnv` |
| `assertEnv(rules, { env?, label? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | validates `process.env` against the rules at startup; collects every missing item and throws one error |
| `ipalEnvRules({ storage?, emailGraph?, ipHeader?, turnstile?, serverUrlVar?, secretVar?, databaseVar? })` | `@intecion/ipal-kit/env`, `@intecion/ipal-kit` | ready rule set (`DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL` + `R2_*`/`GRAPH_*`/Turnstile/`IPAL_IP_HEADER` depending on the features used) for `assertEnv` |
**Typy:** `EnvRule`, `EnvKind` — reguła zmiennej (`name`, `required`, `kind`, `oneOf`, `validate`); `AssertEnvOptions` — opcje `assertEnv`; `IpalEnvFeatures` — argument `ipalEnvRules` (wszystkie z `/env` i root).
**Types:** `EnvRule`, `EnvKind` — variable rule (`name`, `required`, `kind`, `oneOf`, `validate`); `AssertEnvOptions` — `assertEnv` options; `IpalEnvFeatures` — `ipalEnvRules` argument (all from `/env` and root).
## Warstwa frontu (`frontend`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/frontend.md`
## Frontend layer (`frontend`) — details: `node_modules/@intecion/ipal-kit/docs/frontend.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `createContentHelpers({ config, content?, i18n?, baseUrl?, … })` | `@intecion/ipal-kit` | fabryka `src/lib/content.ts`: cache'owane `getCachedPayload`, `getSettings`, `resolveRoute`, `getEntries`, `generatePageMetadata`, `getSiteShell`, `sitemap`, `robots`, `markdownRoute`, `healthRoute`, `mcpGET`/`mcpPOST`… — nie pisz tych wrapperów sam |
| `createPageRoute(content, { blocks, notFound, permanentRedirect, redirect?, … })` | `@intecion/ipal-kit/rsc` | gotowa strona catch-all `[[...slug]]` → `{ Page, generateMetadata, generateStaticParams }` (bloki, redirecty slug history, JSON-LD, tryb „w budowie”); nie paginuje `?page=` |
| `createNotFoundPage(content, { load } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | domyślny eksport `not-found.tsx` — strona 404 wybrana w panelu albo fallback (zalecany wariant leniwy z `load`) |
| `renderNotFoundView(content, { blocks, fallback?, blockProps?, layoutField? }, locale)` | `@intecion/ipal-kit/rsc` | treść 404 w jednym języku — wołana z server action dla leniwego `createNotFoundPage({ load })` (pages.md) |
| `SiteProviders` | `@intecion/ipal-kit/rsc` | komponent layoutu: `shell={await getSiteShell(locale)}` montuje consent, cookie banner, analytics, Turnstile, JSON-LD strony, theme script; nie montuje `AlternateLinksProvider` |
| `createContentHelpers({ config, content?, i18n?, baseUrl?, … })` | `@intecion/ipal-kit` | factory for `src/lib/content.ts`: cached `getCachedPayload`, `getSettings`, `resolveRoute`, `getEntries`, `generatePageMetadata`, `getSiteShell`, `sitemap`, `robots`, `markdownRoute`, `healthRoute`, `mcpGET`/`mcpPOST`… — do not write these wrappers yourself |
| `createPageRoute(content, { blocks, notFound, permanentRedirect, redirect?, … })` | `@intecion/ipal-kit/rsc` | ready `[[...slug]]` catch-all page → `{ Page, generateMetadata, generateStaticParams }` (blocks, slug history redirects, JSON-LD, under-construction mode); does not paginate `?page=` |
| `createNotFoundPage(content, { load } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended) |
| `renderNotFoundView(content, { blocks, fallback?, blockProps?, layoutField? }, locale)` | `@intecion/ipal-kit/rsc` | 404 content in one language — called from a server action for the lazy `createNotFoundPage({ load })` (pages.md) |
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script; does not mount `AlternateLinksProvider` |
Pełne listy opcji `createContentHelpers` / `createPageRoute` / `SiteProviders` i zwracanych kluczy `@/lib/content`: `node_modules/@intecion/ipal-kit/docs/frontend.md`.
Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders` and the returned `@/lib/content` keys: `node_modules/@intecion/ipal-kit/docs/frontend.md`.
**Typy:** `ContentHelpers` — wynik `createContentHelpers`; `SiteShell` — dane layoutu z `getSiteShell` (consent, analytics, theme, jsonLd, settings, formTexts, turnstileSiteKey); `PageJsonLdOptions`, `EntryJsonLdContext` — opcje `getPageJsonLd` / własne węzły JSON-LD wpisów (root); `PageRouteOptions`, `NotFoundPageOptions`, `NotFoundViewOptions`, `SiteProvidersProps` (`/rsc`) — opcje `createPageRoute`, `createNotFoundPage`, `renderNotFoundView` i propsy `SiteProviders`.
**Types:** `ContentHelpers` — `createContentHelpers` result; `SiteShell` — layout data from `getSiteShell` (consent, analytics, theme, jsonLd, settings, formTexts, turnstileSiteKey); `PageJsonLdOptions`, `EntryJsonLdContext` — `getPageJsonLd` options / your own JSON-LD nodes for entries (root); `PageRouteOptions`, `NotFoundPageOptions`, `NotFoundViewOptions`, `SiteProvidersProps` (`/rsc`) — options of `createPageRoute`, `createNotFoundPage`, `renderNotFoundView` and `SiteProviders` props.
## Health check (`health`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/deployment.md`
## Health check (`health`) — details: `node_modules/@intecion/ipal-kit/docs/deployment.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `createHealthRoute({ getCachedPayload, collection?, extra? })` | `@intecion/ipal-kit` | handler `GET` dla `app/api/health/route.ts`: round-trip do bazy → 200 `{ status: 'ok', db: 'up' }` / 503; zwykle wystarczy `healthRoute` z `createContentHelpers` |
| `createHealthRoute({ getCachedPayload, collection?, extra? })` | `@intecion/ipal-kit` | `GET` handler for `app/api/health/route.ts`: database round-trip → 200 `{ status: 'ok', db: 'up' }` / 503; usually `healthRoute` from `createContentHelpers` is enough |
## Hooki kolekcji (`hooks`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/hooks.md`
## Collection hooks (`hooks`) — details: `node_modules/@intecion/ipal-kit/docs/hooks.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `buildRevalidateHook({ revalidatePath, config, homeSlug? })` | `@intecion/ipal-kit` | → `{ afterChange, afterDelete }` odświeżające ISR ścieżek dokumentu we wszystkich językach; `revalidatePath` z `next/cache` wstrzykuje projekt |
| `setPublishedAtHook` | `@intecion/ipal-kit` | `beforeChange`: ustawia `publishedAt` przy pierwszej publikacji (nie nadpisuje istniejącej daty) |
| `trackSlugHistoryHook` | `@intecion/ipal-kit` | `beforeChange`: dopisuje stary slug do pola `slugHistory` (pole dodaj sam); odczyt robi `resolveRedirect` |
| `buildPreventDeleteSystemPage({ settingsSlug?, roleFields? })` | `@intecion/ipal-kit` | `beforeDelete`: blokuje usunięcie strony przypisanej do roli systemowej (homepage, polityki) |
| `buildValidateUniqueRole({ siblingFields })` | `@intecion/ipal-kit` | `beforeValidate` pola roli: jedna strona nie może mieć dwóch ról; plugin nie dokłada go do swoich pól — dopinasz sam |
| `buildCrossLocaleFieldSync({ config, collection, fields, arrayField?, guardFlag? })` | `@intecion/ipal-kit` | `afterChange`: kopiuje wskazane pola (np. obrazki) w lokalizowanych `blocks` do pozostałych języków |
| `buildRevalidateHook({ revalidatePath, config, homeSlug? })` | `@intecion/ipal-kit` | → `{ afterChange, afterDelete }` that revalidate ISR for the document paths in all languages; the project injects `revalidatePath` from `next/cache` |
| `setPublishedAtHook` | `@intecion/ipal-kit` | `beforeChange`: sets `publishedAt` on first publish (does not overwrite an existing date) |
| `trackSlugHistoryHook` | `@intecion/ipal-kit` | `beforeChange`: appends the old slug to the `slugHistory` field (add the field yourself); `resolveRedirect` reads it |
| `buildPreventDeleteSystemPage({ settingsSlug?, roleFields? })` | `@intecion/ipal-kit` | `beforeDelete`: blocks deleting a page assigned to a system role (homepage, policies) |
| `buildValidateUniqueRole({ siblingFields })` | `@intecion/ipal-kit` | `beforeValidate` for a role field: one page cannot have two roles; the plugin does not add it to its own fields — wire it yourself |
| `buildCrossLocaleFieldSync({ config, collection, fields, arrayField?, guardFlag? })` | `@intecion/ipal-kit` | `afterChange`: copies the given fields (e.g. images) in localized `blocks` to the other languages |
## Języki i i18n (`i18n`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/i18n.md`
## Languages and i18n (`i18n`) — details: `node_modules/@intecion/ipal-kit/docs/i18n.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `getLocaleCodes(config)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | lista kodów języków z `I18nConfig` |
| `getDefaultLocale(config)` | `@intecion/ipal-kit` | domyślny język z configu |
| `isValidLocale(code, config)` | `@intecion/ipal-kit` | czy kod jest skonfigurowanym językiem |
| `getLocaleDefinition(code, config)` | `@intecion/ipal-kit` | definicja języka `{ code, label, rtl? }` |
| `getLocalizedSlugs({ slugField, config })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | pole slug z `locale: 'all'` → mapa `{ pl, en }` |
| `buildLocalizedPath({ slugs, locale, config, homeSlug?, prefix? })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | ścieżka strony w języku (home → root, jeden język → bez `/pl`); `undefined` gdy brak sluga |
| `switchLocalePath({ slugs, targetLocale, config, homeSlug?, prefix? })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | adres po zmianie języka bez 404 (brak tłumaczenia → archiwum albo `/{locale}`) |
| `resolveLocalized(value, locale, fallback?)` | `@intecion/ipal-kit` | pole lokalizowane (string albo mapa) → tekst w danym języku |
| `negotiateLocale({ config, cookieLocale, acceptLanguage })` | `@intecion/ipal-kit` | wybór języka: cookie → Accept-Language → domyślny |
| `matchAcceptLanguage(header, config)` | `@intecion/ipal-kit` | dopasowanie nagłówka `Accept-Language` do skonfigurowanych języków |
| `LOCALE_COOKIE_NAME` | `@intecion/ipal-kit` | stała `'NEXT_LOCALE'` — cookie wybranego języka (functional, zapis tylko za zgodą) |
| `createProxy(i18nConfig, { NextResponse, markdown?, exposeHeaders?, consentCategory?, cookieName? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | zalecany `proxy.ts`: negocjacja języka, redirect `/` → `/{locale}`, cookie za zgodą, nagłówki `x-locale`/`x-pathname`, opcjonalnie trasy Markdown |
| `createLocaleMiddleware({ config, cookieName? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | niższy poziom: funkcja `req → LocaleMiddlewareResult` do własnego proxy |
| `DEFAULT_PROXY_MATCHER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | alias `DEFAULT_MIDDLEWARE_MATCHER` dla `createProxy`; w `config.matcher` wklej wartość jako literał |
| `DEFAULT_MIDDLEWARE_MATCHER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | tablica `['/((?!api\|admin\|_next\|.*\\..*).*)']` (wyklucza `api`, `admin`, `_next`, pliki); w `config.matcher` wklej jako literał — Next czyta matcher statycznie |
| `AlternateLinksProvider` | `@intecion/ipal-kit/client` | provider w layoutcie trzymający adresy bieżącej strony per język (dla `LanguageSwitcher`); `SiteProviders` go nie montuje |
| `AlternateLinksUpdater` | `@intecion/ipal-kit/client` | `<AlternateLinksUpdater links={{ pl, en }} />` na stronie — zgłasza jej adresy w innych językach |
| `LanguageSwitcher` | `@intecion/ipal-kit/client` | headless przełącznik języka (`config`, `currentLocale`, `classNames`, `renderLabel`) linkujący do adresów z kontekstu |
| `useAlternateLinks()` | `@intecion/ipal-kit/client` | hook: `{ [locale]: url }` bieżącej strony — do własnego przełącznika |
| `useSetAlternateLinks()` | `@intecion/ipal-kit/client` | hook-setter używany przez `AlternateLinksUpdater` (zwykle niepotrzebny) |
| `getLocaleCodes(config)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | list of language codes from `I18nConfig` |
| `getDefaultLocale(config)` | `@intecion/ipal-kit` | default language from the config |
| `isValidLocale(code, config)` | `@intecion/ipal-kit` | whether the code is a configured language |
| `getLocaleDefinition(code, config)` | `@intecion/ipal-kit` | language definition `{ code, label, rtl? }` |
| `getLocalizedSlugs({ slugField, config })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | slug field from `locale: 'all'` → map `{ pl, en }` |
| `buildLocalizedPath({ slugs, locale, config, homeSlug?, prefix? })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | page path in a language (home → root, single language → no `/pl`); `undefined` when the slug is missing |
| `switchLocalePath({ slugs, targetLocale, config, homeSlug?, prefix? })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | address after a language switch without a 404 (no translation → archive or `/{locale}`) |
| `resolveLocalized(value, locale, fallback?)` | `@intecion/ipal-kit` | localized field (string or map) → text in the given language |
| `negotiateLocale({ config, cookieLocale, acceptLanguage })` | `@intecion/ipal-kit` | language choice: cookie → Accept-Language → default |
| `matchAcceptLanguage(header, config)` | `@intecion/ipal-kit` | matches the `Accept-Language` header to the configured languages |
| `LOCALE_COOKIE_NAME` | `@intecion/ipal-kit` | constant `'NEXT_LOCALE'` — cookie with the chosen language (functional, saved only with consent) |
| `createProxy(i18nConfig, { NextResponse, markdown?, exposeHeaders?, consentCategory?, cookieName? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | recommended `proxy.ts`: language negotiation, redirect `/` → `/{locale}`, cookie with consent, `x-locale`/`x-pathname` headers, optional Markdown routes |
| `createLocaleMiddleware({ config, cookieName? })` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | lower level: a `req → LocaleMiddlewareResult` function for your own proxy |
| `DEFAULT_PROXY_MATCHER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | alias of `DEFAULT_MIDDLEWARE_MATCHER` for `createProxy`; paste the value into `config.matcher` as a literal |
| `DEFAULT_MIDDLEWARE_MATCHER` | `@intecion/ipal-kit/next/middleware`, `@intecion/ipal-kit` | array `['/((?!api\|admin\|_next\|.*\\..*).*)']` (excludes `api`, `admin`, `_next`, files); paste into `config.matcher` as a literal — Next reads the matcher statically |
| `AlternateLinksProvider` | `@intecion/ipal-kit/client` | layout provider that holds the current page's addresses per language (for `LanguageSwitcher`); `SiteProviders` does not mount it |
| `AlternateLinksUpdater` | `@intecion/ipal-kit/client` | `<AlternateLinksUpdater links={{ pl, en }} />` on a page — reports its addresses in other languages |
| `LanguageSwitcher` | `@intecion/ipal-kit/client` | headless language switcher (`config`, `currentLocale`, `classNames`, `renderLabel`) linking to the addresses from context |
| `useAlternateLinks()` | `@intecion/ipal-kit/client` | hook: `{ [locale]: url }` of the current page — for your own switcher |
| `useSetAlternateLinks()` | `@intecion/ipal-kit/client` | setter hook used by `AlternateLinksUpdater` (usually not needed) |
**Typy:** `I18nConfig`, `LocaleDefinition` — config języków (`defaultLocale`, `locales[{ code, label, rtl? }]`, `fallback`); `LocalizedSlugs` — mapa slugów per język; `LocaleMiddlewareResult` — wynik `createLocaleMiddleware` (`next`/`redirect` + cookie); `AlternateLinks`, `LanguageSwitcherClassNames` (`/client`) — mapa adresów per język i klasy przełącznika.
**Types:** `I18nConfig`, `LocaleDefinition` — language config (`defaultLocale`, `locales[{ code, label, rtl? }]`, `fallback`); `LocalizedSlugs` — map of slugs per language; `LocaleMiddlewareResult` — `createLocaleMiddleware` result (`next`/`redirect` + cookie); `AlternateLinks`, `LanguageSwitcherClassNames` (`/client`) — map of addresses per language and switcher classes.
## Status integracji (`integrations`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/integrations.md`
## Integration status (`integrations`) — details: `node_modules/@intecion/ipal-kit/docs/integrations.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `recordIntegrationStatus(payload, field, previous, { state, code?, message? })` | `@intecion/ipal-kit` | zapisuje stan własnej integracji w Site Integrations (tylko przy zmianie / co 10 min); nie rzuca. Dla e-maila i Turnstile plugin woła to sam — nie wołaj |
| `buildIntegrationStatusField(name)` | `@intecion/ipal-kit` | ukryte pole-grupa statusu (`state`, `code`, `message`, `since`, `checkedAt`) do `integrationsFields` |
| `buildIntegrationStatusBanner(statusField, label)` | `@intecion/ipal-kit` | pole UI z banerem statusu na zakładce integracji (`integrationsFields`; potem `pnpm generate:importmap`) |
| `IntegrationAlerts` | `@intecion/ipal-kit/admin` | alert na dashboardzie o integracjach w stanie `degraded`; wstrzykiwany przez plugin zawsze (`beforeDashboard`); własne integracje: drugi egzemplarz z `checks` |
| `IntegrationStatusBanner` | `@intecion/ipal-kit/admin` | baner statusu na zakładce; wstrzykiwany przez plugin / `buildIntegrationStatusBanner` przez import map (`pnpm generate:importmap`), projekt go nie importuje |
| `recordIntegrationStatus(payload, field, previous, { state, code?, message? })` | `@intecion/ipal-kit` | saves the state of your own integration in Site Integrations (only on change / every 10 min); does not throw. For e-mail and Turnstile the plugin calls it itself — do not call |
| `buildIntegrationStatusField(name)` | `@intecion/ipal-kit` | hidden status group field (`state`, `code`, `message`, `since`, `checkedAt`) for `integrationsFields` |
| `buildIntegrationStatusBanner(statusField, label)` | `@intecion/ipal-kit` | UI field with a status banner on the integration tab (`integrationsFields`; then `pnpm generate:importmap`) |
| `IntegrationAlerts` | `@intecion/ipal-kit/admin` | dashboard alert about integrations in the `degraded` state; always injected by the plugin (`beforeDashboard`); your own integrations: a second instance with `checks` |
| `IntegrationStatusBanner` | `@intecion/ipal-kit/admin` | status banner on the tab; injected by the plugin / `buildIntegrationStatusBanner` through the import map (`pnpm generate:importmap`), the project does not import it |
**Typy:** `IntegrationState` (`'ok' | 'degraded'`), `IntegrationStatus` — stan i zapisany status integracji.
**Types:** `IntegrationState` (`'ok' | 'degraded'`), `IntegrationStatus` — integration state and saved status.
## Formularze (`forms`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/forms.md`
## Forms (`forms`) — details: `node_modules/@intecion/ipal-kit/docs/forms.md`
Formularze buduje redaktor w panelu (kolekcja Forms). Projekt NIE pisze własnych formularzy: blok renderuje `<RenderForm>`, wysyłka idzie przez `sendForm = createSubmitAction(...)`.
The editor builds forms in the panel (Forms collection). The project does NOT write its own forms: the block renders `<RenderForm>`, submission goes through `sendForm = createSubmitAction(...)`.
### Konfiguracja i pola panelu (config-time)
### Configuration and panel fields (config-time)
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `buildFormsPlugin(forms)` | `@intecion/ipal-kit` | Wpina `@payloadcms/plugin-form-builder` (Forms + Form Submissions, typy pól, zamknięty REST dla zgłoszeń); plugin podpina sam przy opcji `forms` — nie wołaj |
| `stepBlock` | `@intecion/ipal-kit` | Blok form-buildera „Step” (podział formularza na kroki, z „Show only when”); plugin dodaje sam (`forms.fields.step`) — tylko do własnej konfiguracji form-buildera |
| `checkboxGroupBlock` | `@intecion/ipal-kit` | Blok „Checkbox group” (wielokrotny wybór, `minSelected`/`maxSelected`, wartość `string[]`); plugin dodaje sam (`forms.fields.checkboxGroup`) |
| `timeBlock` | `@intecion/ipal-kit` | Blok „Time” (`<input type="time">`, wartość `HH:MM`); plugin dodaje sam (`forms.fields.time`) |
| `placeholderField` | `@intecion/ipal-kit` | Pole Payload `placeholder` (lokalizowana podpowiedź w pustym polu) do własnych bloków formularza |
| `withPlaceholder(block)` | `@intecion/ipal-kit` | Dokleja `placeholderField` do bloku; wbudowane text/email/textarea/number plugin obsługuje sam — używaj dla własnego bloku (potem migracja) |
| `buildFormAnalyticsFields()` | `@intecion/ipal-kit` | Zwraca grupę pól `analytics` (Event name, domyślnie `form_submit`, + Event parameters) do `forms.formOverrides.fields` — event GTM po wysłaniu ustawiany z panelu |
| `buildFormsPlugin(forms)` | `@intecion/ipal-kit` | Wires `@payloadcms/plugin-form-builder` (Forms + Form Submissions, field types, closed REST for submissions); the plugin wires it itself with the `forms` option — do not call |
| `stepBlock` | `@intecion/ipal-kit` | Form-builder "Step" block (splits the form into steps, with "Show only when"); the plugin adds it itself (`forms.fields.step`) — only for your own form-builder configuration |
| `checkboxGroupBlock` | `@intecion/ipal-kit` | "Checkbox group" block (multiple choice, `minSelected`/`maxSelected`, value `string[]`); the plugin adds it itself (`forms.fields.checkboxGroup`) |
| `timeBlock` | `@intecion/ipal-kit` | "Time" block (`<input type="time">`, value `HH:MM`); the plugin adds it itself (`forms.fields.time`) |
| `placeholderField` | `@intecion/ipal-kit` | Payload `placeholder` field (localized hint in an empty field) for your own form blocks |
| `withPlaceholder(block)` | `@intecion/ipal-kit` | Appends `placeholderField` to a block; the plugin handles the built-in text/email/textarea/number itself — use it for your own block (then a migration) |
| `buildFormAnalyticsFields()` | `@intecion/ipal-kit` | Returns the `analytics` field group (Event name, default `form_submit`, + Event parameters) for `forms.formOverrides.fields` — GTM event after submit, set from the panel |
### Render (serwer → klient)
### Render (server → client)
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `RenderForm({ form, action, locale, texts, classNames?, values?, … })` | `@intecion/ipal-kit/rsc` | Formularz z panelu w bloku jedną linią (RSC): renderuje bloki message i potwierdzenie, wiąże `sendForm` z formularzem i językiem, rozwiązuje redirect, wysyła do przeglądarki tylko `publicForm`; `form` niepopulowany → nic |
| `prepareBuilderForm({ form, action, locale, … })` | `@intecion/ipal-kit/rsc` | Serwerowa połowa `RenderForm` bez markupu → `PreparedBuilderForm` (albo `null`) do rozłożenia w `<BuilderForm>` w komponencie klienckim (np. konfigurator ze zmiennym `values`) |
| `publicForm(form)` | `@intecion/ipal-kit/rsc` | Publiczna część dokumentu formularza (bez zakładki Emails, bez rich textu message, bezpieczny redirect URL) — gdy sam przekazujesz formularz do klienta; nigdy nie dawaj surowego dokumentu |
| `BuilderForm(props)` | `@intecion/ipal-kit/client` | Kliencki renderer dowolnego formularza z panelu (kroki, wszystkie typy pól, Turnstile, honeypot, a11y), bez stylów — wygląd przez `classNames`, podmiana pól przez `renderField`; zwykle używany pośrednio przez `RenderForm` |
| `useBuilderForm({ form, action, texts, values?, onSuccess?, navigate?, redirectHref? })` | `@intecion/ipal-kit/client` | Silnik formularza z panelu bez markupu (kroki, `next/back/goTo`, walidacja per krok, błędy z serwera, redirect, analityka, `getInputProps`/`getSelectProps`/…, `TurnstileWidget`) — dla własnego markupu formularza nietypowego |
| `RenderForm({ form, action, locale, texts, classNames?, values?, … })` | `@intecion/ipal-kit/rsc` | A panel form in a block in one line (RSC): renders message blocks and the confirmation, binds `sendForm` to the form and language, resolves the redirect, sends only `publicForm` to the browser; `form` not populated → nothing |
| `prepareBuilderForm({ form, action, locale, … })` | `@intecion/ipal-kit/rsc` | The server half of `RenderForm` without markup → `PreparedBuilderForm` (or `null`) to spread into `<BuilderForm>` in a client component (e.g. a configurator with changing `values`) |
| `publicForm(form)` | `@intecion/ipal-kit/rsc` | Public part of the form document (no Emails tab, no message rich text, safe redirect URL) — when you pass the form to the client yourself; never pass the raw document |
| `BuilderForm(props)` | `@intecion/ipal-kit/client` | Client renderer for any panel form (steps, all field types, Turnstile, honeypot, a11y), unstyled — look via `classNames`, field replacement via `renderField`; usually used indirectly through `RenderForm` |
| `useBuilderForm({ form, action, texts, values?, onSuccess?, navigate?, redirectHref? })` | `@intecion/ipal-kit/client` | Panel form engine without markup (steps, `next/back/goTo`, per-step validation, server errors, redirect, analytics, `getInputProps`/`getSelectProps`/…, `TurnstileWidget`) — for your own markup of an unusual form |
### Czysta logika formularza z panelu (klient i serwer)
### Pure panel form logic (client and server)
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `visibleFields(fields, values)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Pola (z krokami i message) widoczne dla danych wartości wg „Show only when” — wspólna reguła przeglądarki i serwera (ukryte = niewymagane i niezapisywane) |
| `splitSteps(fields, isShown?)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Dzieli listę pól na kroki po blokach `step` → `BuilderStep[]` (pomija ukryte, zachowuje oryginalny `index`) |
| `inputFields(fields)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Tylko pola niosące wartość (mają `name`, nie `message`/`step`) |
| `initialBuilderValues(fields)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Wartości startowe: checkbox → boolean, checkboxGroup → `string[]`, reszta → string (z `defaultValue`) |
| `validateBuilderFields(fields, values, texts)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Błędy klienta (required, email, number, min/max zaznaczeń) → `{ [name]: komunikat }`, `{}` = OK; tekst z `texts.validation` z `{field}` |
| `stepOfField(steps, name)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Indeks kroku zawierającego pole (powrót do kroku z błędem z serwera); brak → 0 |
| `autoCompleteFor(field)` | `@intecion/ipal-kit/client` | Podpowiedź `autoComplete` z typu/nazwy pola (`email`, `country-name`, `name`, `tel`, `organization`) albo `undefined` |
| `visibleFields(fields, values)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Fields (with steps and message) visible for the given values per "Show only when" — a rule shared by browser and server (hidden = not required and not saved) |
| `splitSteps(fields, isShown?)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Splits the field list into steps at `step` blocks → `BuilderStep[]` (skips hidden ones, keeps the original `index`) |
| `inputFields(fields)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Only fields that carry a value (have a `name`, not `message`/`step`) |
| `initialBuilderValues(fields)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Initial values: checkbox → boolean, checkboxGroup → `string[]`, the rest → string (from `defaultValue`) |
| `validateBuilderFields(fields, values, texts)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Client errors (required, email, number, min/max selected) → `{ [name]: message }`, `{}` = OK; text from `texts.validation` with `{field}` |
| `stepOfField(steps, name)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Index of the step containing the field (go back to the step with a server error); none → 0 |
| `autoCompleteFor(field)` | `@intecion/ipal-kit/client` | `autoComplete` hint from the field type/name (`email`, `country-name`, `name`, `tel`, `organization`) or `undefined` |
### Wysyłka (serwer)
### Submission (server)
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Tworzy server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → tekst z Notifications; zwraca `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` w `actions.ts` |
| `submitForm({ payload, formId, data, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName? })` | `@intecion/ipal-kit/server` | Serwerowy rdzeń: rate limit → Turnstile → walidacja wg definicji z panelu (+ zgoda RODO) → zapis zgłoszenia; zwraca kod `SubmitFormResult`, nie tekst. Zwykle przez `createSubmitAction`; tylko server-only |
| `createSubmitAction({ getCachedPayload, headers, … })` | `@intecion/ipal-kit/server` | Creates the server action `sendForm(formId, locale, values, token?)`: honeypot → `clientIp` → `submitForm` → text from Notifications; returns `SubmitActionResult`. Standard: `export const sendForm = createSubmitAction({ getCachedPayload, headers })` in `actions.ts` |
| `submitForm({ payload, formId, data, turnstileToken?, ip?, locale?, maxPerMinute?, consentFieldName? })` | `@intecion/ipal-kit/server` | Server core: rate limit → Turnstile → validation against the panel definition (+ GDPR consent) → saves the submission; returns a `SubmitFormResult` code, not text. Usually through `createSubmitAction`; server-only |
### Honeypot
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `HONEYPOT_FIELD` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Stała: domyślna nazwa pola-pułapki `'company_url'` |
| `honeypotInputProps(name?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Propsy ukrytego inputu (off-screen, `aria-hidden`, `tabIndex -1`) — `<input {...honeypotInputProps()} />`; `BuilderForm` dodaje sam |
| `isHoneypotTripped(values, name?)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `true`, gdy pułapka wypełniona → udawany sukces bez zapisu; `createSubmitAction` sprawdza sam |
| `HONEYPOT_FIELD` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Constant: default trap field name `'company_url'` |
| `honeypotInputProps(name?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Props of the hidden input (off-screen, `aria-hidden`, `tabIndex -1`) — `<input {...honeypotInputProps()} />`; `BuilderForm` adds it itself |
| `isHoneypotTripped(values, name?)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `true` when the trap is filled → fake success without saving; `createSubmitAction` checks it itself |
### Hooki niższego poziomu i walidatory (formularze spoza buildera)
### Lower-level hooks and validators (forms outside the builder)
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `useForm({ initialValues, submitAction, validate?, requireTurnstile?, onSuccess?, … })` | `@intecion/ipal-kit/client` | Generyczny silnik formularza bez markupu (stan, walidacja, token Turnstile, submit, sukces/błąd; `setField`, `handleSubmit`, `reset`) — dla formularzy spoza buildera (np. filtry); nie dla kontaktowych |
| `useContactForm({ submitAction, requireTurnstile?, requireTopic?, requireConsent?, onSuccess?, … })` | `@intecion/ipal-kit/client` | Preset `useForm` dla stałego formularza kontaktowego (`name, email, phone, topic, message, consent`) — tylko gdy świadomie nie używasz buildera |
| `buildValidator(schema)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Składa `Validator` z list reguł per pole (pierwsza błędna wygrywa); działa też na serwerze |
| `required(msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Reguła: niepuste, nie `null`, nie `false` |
| `email(msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Reguła: poprawny adres e-mail |
| `minLength(n, msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Reguła: string min. `n` znaków (po trim) |
| `maxLength(n, msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Reguła: string max. `n` znaków (po trim) |
| `checked(msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Reguła: checkbox musi być `true` |
| `pattern(re, msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Reguła: zgodność z regexem (puste pomijane — łącz z `required`) |
| `custom(test, msg)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Reguła z dowolnego predykatu `(value, values) => boolean` |
| `isEmail(v)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Samodzielne sprawdzenie e-maila → boolean |
| `useForm({ initialValues, submitAction, validate?, requireTurnstile?, onSuccess?, … })` | `@intecion/ipal-kit/client` | Generic form engine without markup (state, validation, Turnstile token, submit, success/error; `setField`, `handleSubmit`, `reset`) — for forms outside the builder (e.g. filters); not for contact forms |
| `useContactForm({ submitAction, requireTurnstile?, requireTopic?, requireConsent?, onSuccess?, … })` | `@intecion/ipal-kit/client` | `useForm` preset for a fixed contact form (`name, email, phone, topic, message, consent`) — only when you deliberately do not use the builder |
| `buildValidator(schema)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Builds a `Validator` from per-field rule lists (the first failing one wins); also works on the server |
| `required(msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Rule: non-empty, not `null`, not `false` |
| `email(msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Rule: valid e-mail address |
| `minLength(n, msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Rule: string of at least `n` characters (after trim) |
| `maxLength(n, msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Rule: string of at most `n` characters (after trim) |
| `checked(msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Rule: the checkbox must be `true` |
| `pattern(re, msg?)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Rule: matches a regex (empty values skipped — combine with `required`) |
| `custom(test, msg)` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit` | Rule from any predicate `(value, values) => boolean` |
| `isEmail(v)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Standalone e-mail check → boolean |
### Analityka
### Analytics
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `formAnalyticsOnSuccess(config)` | `@intecion/ipal-kit/client` | Z `form.analytics` (panel) robi handler `onSuccess`, który robi `pushDataLayer(event, params)` (wartość `$pole` z wysłanych danych; pusty event = no-op); `useBuilderForm` woła sam — ręcznie tylko przy `useForm`/`useContactForm` |
| `formAnalyticsOnSuccess(config)` | `@intecion/ipal-kit/client` | Turns `form.analytics` (panel) into an `onSuccess` handler that calls `pushDataLayer(event, params)` (a value like `$topic` — `$` + field name — is taken from the submitted data; empty event = no-op); `useBuilderForm` calls it itself — by hand only with `useForm`/`useContactForm` |
**Typy:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` tylko `/client`) — kształt formularza z panelu, pola, opcji, kroku, tekstów i warunku „Show only when”. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — propsy/klasy/`renderField` `BuilderForm`, związana akcja i wynik `useBuilderForm`. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — propsy `RenderForm`, sygnatura `sendForm`, wejście/wyjście `prepareBuilderForm`. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — argumenty i kody wyniku `submitForm` oraz wynik `sendForm` (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — typy `useForm`/`useContactForm` i walidatorów. `FormAnalyticsConfig` (`/client`) — konfiguracja analityki formularza z panelu. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — opcja `forms` pluginu i nadpisania kolekcji.
**Types:** `BuilderField`, `BuilderOption`, `BuilderStep`, `BuilderFormDoc`, `BuilderFormTexts`, `FieldCondition` (root, `/client`; `BuilderOption` only `/client`) — shape of the panel form, field, option, step, texts and the "Show only when" condition. `BuilderFormProps`, `BuilderFormClassNames`, `BuilderFieldRenderArgs`, `BuilderFormAction`, `BuilderFormApi`, `UseBuilderFormOptions` (`/client`) — `BuilderForm` props/classes/`renderField`, the bound action and the `useBuilderForm` result. `RenderFormProps`, `SendFormAction`, `PrepareBuilderFormArgs`, `PreparedBuilderForm` (`/rsc`) — `RenderForm` props, `sendForm` signature, `prepareBuilderForm` input/output. `SubmitFormArgs`, `SubmitFormResult`, `SubmitActionResult` (`/server`) — `submitForm` arguments and result codes, and the `sendForm` result (`{ success, message, reason?, field? }`). `FormErrors`, `FormSubmitAction`, `Validator`, `Rule` (root, `/client`), `ContactFormValues`, `ContactFormErrors`, `SubmitAction` (`/client`) — `useForm`/`useContactForm` and validator types. `FormAnalyticsConfig` (`/client`) — form analytics configuration from the panel. `FormsOption`, `FormsCollectionOverrides`, `FormsFieldsOverride` (root) — the plugin's `forms` option and collection overrides.
## Linki (`links`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/links.md`
## Links (`links`) — details: `node_modules/@intecion/ipal-kit/docs/links.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `buildLinkField(options?)` | `@intecion/ipal-kit` | JEDNO pole linku (grupa): strona / URL (też mailto:, tel:, #) / plik + label, nowa karta, `appearance`; typ `CmsLink*` w payload-types. Używaj do każdego CTA zamiast własnych `ctaLabel`/`buttonUrl` |
| `buildLinksField(options?)` | `@intecion/ipal-kit` | Tablica 0..N linków (`links`, domyślnie max 2, wiersze „Button”) — przyciski sekcji |
| `resolveLinkHref(link, { locale, config, homeSlug?, archives?, pagesSlug? })` | `@intecion/ipal-kit` | Wartość linku → href albo `null` (pusty / brak strony w języku / niebezpieczny URL); strona musi być populowana |
| `resolveLink(link, options)` | `@intecion/ipal-kit` | Link z panelu → `ResolvedLink` (`href`, `label`, `newTab`, `internal`, `targetProps`, `appearance`) albo `null` — do własnego `CMSLink` |
| `resolveNav(items, { locale, config, homeSlug?, linkField?, childrenField? })` | `@intecion/ipal-kit` | Pozycje menu z globala Header/Footer → serializowalne `NavItem[]` (dowolna głębokość, martwe linki pominięte) |
| `resolveSystemLinks(settings, { locale, config, roles?, … })` | `@intecion/ipal-kit` | Linki do stron systemowych z Site Settings (privacy/cookies/terms) z tytułem strony jako labelem → `SystemLink[]`; w projekcie zwykle `getSystemLinks` z `lib/content` |
| `homeSlugFrom(settings, field?)` | `@intecion/ipal-kit` | Slug strony głównej z `SiteSettings.homepage` (populowanej) albo `undefined` |
| `safeHref(url)` | `@intecion/ipal-kit` | URL, gdy bezpieczny (http(s), mailto, tel, sms, #, ścieżka `/`), inaczej `null` — blokuje `javascript:`/`data:` |
| `buildLinkField(options?)` | `@intecion/ipal-kit` | ONE link field (group): page / URL (also mailto:, tel:, #) / file + label, new tab, `appearance`; `CmsLink*` type in payload-types. Use it for every CTA instead of your own `ctaLabel`/`buttonUrl` |
| `buildLinksField(options?)` | `@intecion/ipal-kit` | Array of 0..N links (`links`, max 2 by default, "Button" rows) — section buttons |
| `resolveLinkHref(link, { locale, config, homeSlug?, archives?, pagesSlug? })` | `@intecion/ipal-kit` | Link value → href or `null` (empty / page missing in the language / unsafe URL); the page must be populated |
| `resolveLink(link, options)` | `@intecion/ipal-kit` | Panel link → `ResolvedLink` (`href`, `label`, `newTab`, `internal`, `targetProps`, `appearance`) or `null` — for your own `CMSLink` |
| `resolveNav(items, { locale, config, homeSlug?, linkField?, childrenField? })` | `@intecion/ipal-kit` | Menu items from the Header/Footer global → serializable `NavItem[]` (any depth, dead links skipped) |
| `resolveSystemLinks(settings, { locale, config, roles?, … })` | `@intecion/ipal-kit` | Links to system pages from Site Settings (privacy/cookies/terms) with the page title as the label → `SystemLink[]`; in a project usually `getSystemLinks` from `lib/content` |
| `homeSlugFrom(settings, field?)` | `@intecion/ipal-kit` | Homepage slug from `SiteSettings.homepage` (populated) or `undefined` |
| `safeHref(url)` | `@intecion/ipal-kit` | The URL when safe (http(s), mailto, tel, sms, #, `/` path), otherwise `null` — blocks `javascript:`/`data:` |
**Typy:** `BuildLinkFieldOptions`, `BuildLinksFieldOptions`, `LinkAppearance`, `LinkAppearanceOption` — opcje pól linku i style; `LinkValue`, `ResolveLinkHrefOptions`, `ResolvedLink`, `NavItem`, `ResolveNavOptions`, `SystemLink` — wartość linku z panelu, opcje i wyniki resolverów.
**Types:** `BuildLinkFieldOptions`, `BuildLinksFieldOptions`, `LinkAppearance`, `LinkAppearanceOption` — link field options and styles; `LinkValue`, `ResolveLinkHrefOptions`, `ResolvedLink`, `NavItem`, `ResolveNavOptions`, `SystemLink` — panel link value, resolver options and results.
## MCP (`mcp`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/mcp.md`
## MCP (`mcp`) — details: `node_modules/@intecion/ipal-kit/docs/mcp.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `createMcpRoute({ getCachedPayload, config, baseUrl?, serverName?, … })` | `@intecion/ipal-kit` | Read-only serwer MCP strony (JSON-RPC: `get_site_info`, `list_pages`, `search_content`, `get_page`) jako route handler → `{ GET, POST }` w `app/api/mcp/route.ts`; z rate limitem per IP. Zwykle przez `mcpGET`/`mcpPOST` z `lib/content` |
| `createMcpRoute({ getCachedPayload, config, baseUrl?, serverName?, … })` | `@intecion/ipal-kit` | Read-only MCP server for the site (JSON-RPC: `get_site_info`, `list_pages`, `search_content`, `get_page`) as a route handler → `{ GET, POST }` in `app/api/mcp/route.ts`; with a per-IP rate limit. Usually through `mcpGET`/`mcpPOST` from `lib/content` |
## Media (`media`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/media.md`
## Media (`media`) — details: `node_modules/@intecion/ipal-kit/docs/media.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `mediaImageProps(resource, { sizes?, priority?, alt?, placeholderColor? })` | `@intecion/ipal-kit` | Propsy `next/image` dla uploadu-obrazu (wymiary, focal point → `objectPosition`, blur placeholder, `preload` dla LCP) albo `null` (wideo/PDF/ID) — do własnego `<Media>` |
| `videoProps(resource, { mode?, poster?, reducedMotion? })` | `@intecion/ipal-kit` | Atrybuty `<video>` dla uploadu-wideo (`'background'`: autoplay/muted/loop; `'player'`: controls, `preload="none"`) albo `null` |
| `MEDIA_SIZES` | `@intecion/ipal-kit` | Stałe gotowe wartości `sizes`: `full`, `half`, `third`, `quarter`, `thumb` |
| `normalizeFilename(filename)` | `@intecion/ipal-kit` | Slugifikuje nazwę pliku z zachowaniem rozszerzenia (`"Zdjęcie 1.JPG"` → `"zdjecie-1.jpg"`) |
| `normalizeFilenameHook` | `@intecion/ipal-kit` | Hook `beforeOperation` kolekcji upload (Media) normalizujący nazwę pliku; projekt dopina w swojej kolekcji Media |
| `buildOptimizeUploadHook(options?)` | `@intecion/ipal-kit` | Hook `beforeOperation`: blokuje za duże JPG/PNG/wideo, po zgodzie redaktora konwertuje obraz do WebP (sharp z `buildConfig`); dopina projekt w Media |
| `buildOptimizeUploadField(name?)` | `@intecion/ipal-kit` | Checkbox zgody „Optimize this upload” (domyślnie `optimizeOnUpload`) do Media, w parze z `buildOptimizeUploadHook` |
| `buildMediaPlaceholderHook({ field?, size? })` | `@intecion/ipal-kit` | Hook `beforeOperation` liczący przy uploadzie mini-podgląd blur (base64 WebP) i kolor dominujący; dopina projekt w Media |
| `buildMediaPlaceholderField(name?)` | `@intecion/ipal-kit` | Ukryta grupa pól na placeholder (czytana przez `mediaImageProps`), w parze z `buildMediaPlaceholderHook` |
| `mediaImageProps(resource, { sizes?, priority?, alt?, placeholderColor? })` | `@intecion/ipal-kit` | `next/image` props for an image upload (dimensions, focal point → `objectPosition`, blur placeholder, `preload` for LCP) or `null` (video/PDF/ID) — for your own `<Media>` |
| `videoProps(resource, { mode?, poster?, reducedMotion? })` | `@intecion/ipal-kit` | `<video>` attributes for a video upload (`'background'`: autoplay/muted/loop; `'player'`: controls, `preload="none"`) or `null` |
| `MEDIA_SIZES` | `@intecion/ipal-kit` | Ready constant `sizes` values: `full`, `half`, `third`, `quarter`, `thumb` |
| `normalizeFilename(filename)` | `@intecion/ipal-kit` | Slugifies a file name, keeping the extension (`"Zdjęcie 1.JPG"` → `"zdjecie-1.jpg"`) |
| `normalizeFilenameHook` | `@intecion/ipal-kit` | `beforeOperation` hook for an upload collection (Media) that normalizes the file name; the project adds it to its Media collection |
| `buildOptimizeUploadHook(options?)` | `@intecion/ipal-kit` | `beforeOperation` hook: blocks oversized JPG/PNG/video, converts the image to WebP after the editor agrees (sharp from `buildConfig`); the project adds it to Media |
| `buildOptimizeUploadField(name?)` | `@intecion/ipal-kit` | "Optimize this upload" consent checkbox (default `optimizeOnUpload`) for Media, paired with `buildOptimizeUploadHook` |
| `buildMediaPlaceholderHook({ field?, size? })` | `@intecion/ipal-kit` | `beforeOperation` hook that computes a tiny blur preview (base64 WebP) and the dominant colour on upload; the project adds it to Media |
| `buildMediaPlaceholderField(name?)` | `@intecion/ipal-kit` | Hidden field group for the placeholder (read by `mediaImageProps`), paired with `buildMediaPlaceholderHook` |
**Typy:** `MediaImageOptions`, `MediaImageProps`, `VideoMode`, `VideoProps` — opcje i wynik `mediaImageProps`/`videoProps`; `OptimizeUploadOptions` — limity i jakość `buildOptimizeUploadHook`.
**Types:** `MediaImageOptions`, `MediaImageProps`, `VideoMode`, `VideoProps` — options and result of `mediaImageProps`/`videoProps`; `OptimizeUploadOptions` — limits and quality of `buildOptimizeUploadHook`.
## Powiadomienia (`notifications`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/notifications.md`
## Notifications (`notifications`) — details: `node_modules/@intecion/ipal-kit/docs/notifications.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `getNotificationTexts({ payload, locale? })` | `@intecion/ipal-kit` | Czyta global Notifications w języku → `NotificationTexts` (`form.success`, `error`, `validation`, `next`, `back`, `stepOf`, …) z fallbackiem EN per pole; źródło `texts` dla `RenderForm` (zwykle `getFormTexts` z `lib/content`) |
| `resolveFormMessage(result, texts)` | `@intecion/ipal-kit` | Kod `SubmitFormResult` → tekst z panelu (`{field}` wstawiane przy `validation`, `error` bez szczegółów wyjątku); `createSubmitAction` woła sam |
| `NOTIFICATION_FALLBACK` | `@intecion/ipal-kit` | Stała: wbudowane angielskie teksty `form.*` używane, gdy pole w panelu jest puste |
| `getNotificationTexts({ payload, locale? })` | `@intecion/ipal-kit` | Reads the Notifications global in a language → `NotificationTexts` (`form.success`, `error`, `validation`, `next`, `back`, `stepOf`, …) with an EN fallback per field; source of `texts` for `RenderForm` (usually `getFormTexts` from `lib/content`) |
| `resolveFormMessage(result, texts)` | `@intecion/ipal-kit` | `SubmitFormResult` code → text from the panel (`{field}` filled in for `validation`, `error` without exception details); `createSubmitAction` calls it itself |
| `NOTIFICATION_FALLBACK` | `@intecion/ipal-kit` | Constant: built-in English `form.*` texts used when a panel field is empty |
**Typy:** `NotificationTexts`, `FormNotificationTexts` — rozwiązane teksty powiadomień (grupa `form`).
**Types:** `NotificationTexts`, `FormNotificationTexts` — resolved notification texts (`form` group).
## Strony systemowe (`pages`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/pages.md`
## System pages (`pages`) — details: `node_modules/@intecion/ipal-kit/docs/pages.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `getSystemPagePath({ page, locale, config, homeSlug? })` | `@intecion/ipal-kit` | Strona przypisana w Site Settings (czytana z `locale: 'all'`) → ścieżka w języku (`/pl` dla strony głównej, `/en/privacy-policy`) albo `undefined` |
| `ALL_SYSTEM_PAGE_ROLES` | `@intecion/ipal-kit` | Stała: wszystkie role stron systemowych w stałej kolejności: `homepage`, `notFound`, `privacyPolicy`, `cookiePolicy`, `termsOfService` |
| `LocaleView({ views, defaultLocale })` | `@intecion/ipal-kit/client` | Wybiera z gotowych widoków per język ten z URL (`/en/...`) — w `not-found.tsx` bez `headers()` (trasa zostaje statyczna); używany przez `createNotFoundPage` |
| `NotFoundLoader({ load, locales, defaultLocale })` | `@intecion/ipal-kit/client` | Leniwa treść 404: pobiera widok z server action dopiero przy wyświetleniu 404 (mniejszy payload RSC każdej strony); używany przez `createNotFoundPage(content, { load })` |
| `getSystemPagePath({ page, locale, config, homeSlug? })` | `@intecion/ipal-kit` | Page assigned in Site Settings (read with `locale: 'all'`) → path in the language (`/pl` for the homepage, `/en/privacy-policy`) or `undefined` |
| `ALL_SYSTEM_PAGE_ROLES` | `@intecion/ipal-kit` | Constant: all system page roles in a fixed order: `homepage`, `notFound`, `privacyPolicy`, `cookiePolicy`, `termsOfService` |
| `LocaleView({ views, defaultLocale })` | `@intecion/ipal-kit/client` | Picks, from ready per-language views, the one from the URL (`/en/...`) — in `not-found.tsx` without `headers()` (the route stays static); used by `createNotFoundPage` |
| `NotFoundLoader({ load, locales, defaultLocale })` | `@intecion/ipal-kit/client` | Lazy 404 content: fetches the view from a server action only when the 404 is shown (smaller RSC payload on every page); used by `createNotFoundPage(content, { load })` |
**Typy:** `PagesOption` (opcja `pages: { slug, roles? }` pluginu), `SystemPageRole` (rola strony systemowej).
**Types:** `PagesOption` (the plugin's `pages: { slug, roles? }` option), `SystemPageRole` (system page role).
## Globale Payload (`payload`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/payload-helpers.md`
## Payload globals (`payload`) — details: `node_modules/@intecion/ipal-kit/docs/payload-helpers.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `getSiteSettings<T>(payload, { locale?, depth? })` | `@intecion/ipal-kit` | Czyta global Site Settings (typ generowany `SiteSetting` jako `T`) |
| `getSiteIntegrations<T>(payload, { locale?, depth? })` | `@intecion/ipal-kit` | Czyta global Site Integrations z sekretami (Local API omija access) — tylko serwer, nigdy surowo do klienta |
| `getGlobal<T>(payload, slug, { locale?, depth? })` | `@intecion/ipal-kit` | Cienki wrapper `payload.findGlobal` dla dowolnego globala (też projektu) |
| `SITE_SETTINGS_SLUG` | `@intecion/ipal-kit` | Stała: slug globala `'site-settings'` |
| `SITE_INTEGRATIONS_SLUG` | `@intecion/ipal-kit` | Stała: slug globala `'site-integrations'` |
| `getSiteSettings<T>(payload, { locale?, depth? })` | `@intecion/ipal-kit` | Reads the Site Settings global (generated type `SiteSetting` as `T`) |
| `getSiteIntegrations<T>(payload, { locale?, depth? })` | `@intecion/ipal-kit` | Reads the Site Integrations global with secrets (the Local API bypasses access) — server only, never raw to the client |
| `getGlobal<T>(payload, slug, { locale?, depth? })` | `@intecion/ipal-kit` | Thin `payload.findGlobal` wrapper for any global (the project's too) |
| `SITE_SETTINGS_SLUG` | `@intecion/ipal-kit` | Constant: global slug `'site-settings'` |
| `SITE_INTEGRATIONS_SLUG` | `@intecion/ipal-kit` | Constant: global slug `'site-integrations'` |
**Typy:** `GlobalQueryOptions` — `{ locale?, depth? }` helperów globali.
**Types:** `GlobalQueryOptions` — `{ locale?, depth? }` of the global helpers.
## Rich text (`richtext`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/richtext.md`
## Rich text (`richtext`) — details: `node_modules/@intecion/ipal-kit/docs/richtext.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `RenderRichText({ data, converters?, className?, headingIds? })` | `@intecion/ipal-kit/rsc` | Renderuje pole richText (Lexical) przez oficjalny konwerter Payloada; własne klasy przez `converters`, `headingIds` dodaje kotwice na nagłówkach (te same id co `extractHeadings`). Zamiast ręcznego renderera. |
| `extractHeadings(data, { levels? })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/rsc` | Lista `{ id, level, text }` nagłówków (domyślnie h2) do spisu treści — id zgodne z `RenderRichText headingIds`. |
| `headingText(node)` | `@intecion/ipal-kit` | Czysty tekst węzła Lexical (nagłówek z pogrubieniami, linkami…). |
| `buildTableOfContentsField({ name? })` | `@intecion/ipal-kit` | Pole grupy `tableOfContents` (show + lokalizowana etykieta) do bloku/sekcji tekstu — przełącznik spisu treści w panelu. |
| `TableOfContents({ items, label?, classNames?, offset? })` | `@intecion/ipal-kit/client` | Spis treści bez stylów (`<nav>` z linkami); w przeglądarce podświetla czytaną sekcję (`aria-current`, `classNames.linkActive`). Karm `extractHeadings`. |
| `lexicalToMarkdown(data)` | `@intecion/ipal-kit` | Lexical → Markdown (bez zależności) — dla wyjścia dla AI (Markdown stron, llms-full.txt); nie do renderowania na stronie. |
| `RenderRichText({ data, converters?, className?, headingIds? })` | `@intecion/ipal-kit/rsc` | Renders a richText (Lexical) field through Payload's official converter; your own classes via `converters`, `headingIds` adds anchors to headings (the same ids as `extractHeadings`). Instead of a hand-written renderer. |
| `extractHeadings(data, { levels? })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/rsc` | List of headings `{ id, level, text }` (h2 by default) for a table of contents — ids match `RenderRichText headingIds`. |
| `headingText(node)` | `@intecion/ipal-kit` | Plain text of a Lexical node (a heading with bold, links…). |
| `buildTableOfContentsField({ name? })` | `@intecion/ipal-kit` | `tableOfContents` group field (show + localized label) for a text block/section — table of contents toggle in the panel. |
| `TableOfContents({ items, label?, classNames?, offset? })` | `@intecion/ipal-kit/client` | Unstyled table of contents (`<nav>` with links); in the browser it highlights the section being read (`aria-current`, `classNames.linkActive`). Feed it `extractHeadings`. |
| `lexicalToMarkdown(data)` | `@intecion/ipal-kit` | Lexical → Markdown (no dependencies) — for AI output (page Markdown, llms-full.txt); not for rendering on the page. |
**Typy:** `ExtractHeadingsOptions`, `HeadingItem`, `HeadingLevel` (root) — opcje i wynik ekstrakcji nagłówków; `RenderRichTextProps` (`/rsc`) — propsy renderera; `TableOfContentsProps`, `TableOfContentsClassNames` (`/client`) — propsy i klasy spisu treści.
**Types:** `ExtractHeadingsOptions`, `HeadingItem`, `HeadingLevel` (root) — heading extraction options and result; `RenderRichTextProps` (`/rsc`) — renderer props; `TableOfContentsProps`, `TableOfContentsClassNames` (`/client`) — table of contents props and classes.
## Bezpieczeństwo (`security`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/security.md`
## Security (`security`) — details: `node_modules/@intecion/ipal-kit/docs/security.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `buildSecurityHeaders({ hsts?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Zwraca `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; przy `IPAL_NOINDEX` także `X-Robots-Tag`) do `headers()` w `next.config.ts`. CSP dokładasz przez `additional`. |
| `buildCsp({ mode?, r2Url?, turnstile?, analytics?, googleMaps?, youtube?, extra? })` | `@intecion/ipal-kit` | Zwraca `{ key, value }` z utwardzonym CSP (`base-uri`, `object-src` itd.) + źródła dla włączonych integracji; wrzuć do `additional`. Zacznij od `mode: 'report-only'`. |
| `buildUploadSecurityHeaders({ collections? })` | `@intecion/ipal-kit` | Wpisy `headers()` dla `/api/<upload>/file/*` (domyślnie `media`): pliki z dysku wyświetlane, nigdy wykonywane (sandbox). Potrzebne przy mediach bez R2. |
| `buildSecurityHeaders({ hsts?, additional?, coop?, frameOptions?, permissionsPolicy?, referrerPolicy?, … })` | `@intecion/ipal-kit` | Returns `SecurityHeader[]` (HSTS, X-Frame-Options, nosniff, Referrer-Policy, Permissions-Policy, COOP; with `IPAL_NOINDEX` also `X-Robots-Tag`) for `headers()` in `next.config.ts`. Add CSP via `additional`. |
| `buildCsp({ mode?, r2Url?, turnstile?, analytics?, googleMaps?, youtube?, extra? })` | `@intecion/ipal-kit` | Returns `{ key, value }` with a hardened CSP (`base-uri`, `object-src` etc.) + sources for the enabled integrations; put it into `additional`. Start with `mode: 'report-only'`. |
| `buildUploadSecurityHeaders({ collections? })` | `@intecion/ipal-kit` | `headers()` entries for `/api/<upload>/file/*` (`media` by default): files from disk are displayed, never executed (sandbox). Needed for media without R2. |
**Typy:** `BuildCspArgs`, `BuildSecurityHeadersArgs` — opcje builderów; `SecurityHeader` — `{ key, value }` w kształcie Next.js.
**Types:** `BuildCspArgs`, `BuildSecurityHeadersArgs` — builder options; `SecurityHeader` — `{ key, value }` in the Next.js shape.
## SEO (`seo`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/seo.md`
## SEO (`seo`) — details: `node_modules/@intecion/ipal-kit/docs/seo.md`
Większość tras i metadanych jest już gotowa w `createContentHelpers` (`generatePageMetadata`, `sitemap`, `sitemapRoute`, `robots`, `llmsRoute`, `llmsFullRoute`, `manifest`, `indexNowKeyRoute`, `getPageJsonLd`, `getSiteShell().jsonLd`) — funkcje niżej są ich klockami; sięgaj po nie, gdy trasa nie trzyma się konwencji.
Most routes and metadata are already ready in `createContentHelpers` (`generatePageMetadata`, `sitemap`, `sitemapRoute`, `robots`, `llmsRoute`, `llmsFullRoute`, `manifest`, `indexNowKeyRoute`, `getPageJsonLd`, `getSiteShell().jsonLd`) — the functions below are their building blocks; reach for them when a route does not follow the conventions.
### Metadane (generateMetadata)
### Metadata (generateMetadata)
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `createPageMetadata({ config, baseUrl, content?, … })` | `@intecion/ipal-kit` | Generator metadanych strony z podpiętymi resolverami konwencji pluginu (Pages, SiteSettings, `meta`, System Pages, archiwa); wołasz z `{ payload, locale, slug }`. Normalnie przez `generatePageMetadata` z `createContentHelpers`. |
| `createMetadataGenerator({ config, baseUrl, resolveDocument, … })` | `@intecion/ipal-kit` | Jak wyżej, ale z własnymi resolverami — dla tras o niestandardowych konwencjach. |
| `buildMetadata({ meta, siteName, locale, config, slugs, baseUrl, … })` | `@intecion/ipal-kit` | Składa obiekt `Metadata` Next.js (title, canonical, hreflang, OG, Twitter, robots) z gotowych danych; nic nie pobiera. Najniższy poziom. |
| `composeTitle({ pageTitle, siteName, separator?, order? })` | `@intecion/ipal-kit` | Pełny tytuł „Strona \| Firma” (lub odwrotnie), bez dublowania nazwy serwisu. |
| `buildHreflangAlternates({ slugs, config, baseUrl? })` | `@intecion/ipal-kit` | Mapa locale → URL do `alternates.languages`. |
| `slugsAcrossLocales({ payload, collection, id, config })` | `@intecion/ipal-kit` | Slug dokumentu we wszystkich językach (osobne zapytanie, depth 0) — wejście do hreflang. |
| `readSiteMetaConfig({ payload, locale, pagesSlug?, settingsSlug?, settings? })` | `@intecion/ipal-kit` | Czyta z SiteSettings: nazwę serwisu, separator (z paddingiem), kolejność tytułu, slug strony głównej per język, domyślny opis i obraz OG. |
| `buildIconsMetadata(favicon)` | `@intecion/ipal-kit` | `icons` (favicon, apple-touch-icon) z uploadu faviconu w panelu — raz w `generateMetadata` root layoutu. |
| `createManifestHandler({ getCachedPayload, config, settingsSlug? })` | `@intecion/ipal-kit` | Handler `app/manifest.ts` z SiteSettings; bez bazy przy buildzie zwraca minimalny manifest. Zwykle `manifest` z `createContentHelpers`. |
| `NoSnippet({ as?, children })` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit/rsc` | Opakowanie z `data-nosnippet` — trzyma powtarzalny tekst (stopka: adres, godziny, telefon) poza snippetami Google. Nie owijaj `<main>`. |
| `createPageMetadata({ config, baseUrl, content?, … })` | `@intecion/ipal-kit` | Page metadata generator with the plugin's convention resolvers wired in (Pages, SiteSettings, `meta`, System Pages, archives); call it with `{ payload, locale, slug }`. Normally through `generatePageMetadata` from `createContentHelpers`. |
| `createMetadataGenerator({ config, baseUrl, resolveDocument, … })` | `@intecion/ipal-kit` | As above, but with your own resolvers — for routes with non-standard conventions. |
| `buildMetadata({ meta, siteName, locale, config, slugs, baseUrl, … })` | `@intecion/ipal-kit` | Builds a Next.js `Metadata` object (title, canonical, hreflang, OG, Twitter, robots) from ready data; fetches nothing. The lowest level. |
| `composeTitle({ pageTitle, siteName, separator?, order? })` | `@intecion/ipal-kit` | Full title "Page \| Company" (or the other way round), without duplicating the site name. |
| `buildHreflangAlternates({ slugs, config, baseUrl? })` | `@intecion/ipal-kit` | Map locale → URL for `alternates.languages`. |
| `slugsAcrossLocales({ payload, collection, id, config })` | `@intecion/ipal-kit` | Document slug in all languages (separate query, depth 0) — input for hreflang. |
| `readSiteMetaConfig({ payload, locale, pagesSlug?, settingsSlug?, settings? })` | `@intecion/ipal-kit` | Reads from SiteSettings: site name, separator (with padding), title order, homepage slug per language, default description and OG image. |
| `buildIconsMetadata(favicon)` | `@intecion/ipal-kit` | `icons` (favicon, apple-touch-icon) from the favicon upload in the panel — once in the root layout `generateMetadata`. |
| `createManifestHandler({ getCachedPayload, config, settingsSlug? })` | `@intecion/ipal-kit` | `app/manifest.ts` handler from SiteSettings; without a database at build time it returns a minimal manifest. Usually `manifest` from `createContentHelpers`. |
| `NoSnippet({ as?, children })` | `@intecion/ipal-kit/client`, `@intecion/ipal-kit/rsc` | Wrapper with `data-nosnippet` — keeps repeated text (footer: address, hours, phone) out of Google snippets. Do not wrap `<main>`. |
### JSON-LD (schema.org)
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `JsonLdGraph({ schemas })` | `@intecion/ipal-kit/rsc` | Renderuje węzły jako jeden `@graph` w `<script type="application/ld+json">` z bezpieczną serializacją; pomija null. Zamiast ręcznego `<script>`. |
| `buildWebSiteJsonLd({ name, url, search? })` | `@intecion/ipal-kit` | WebSite (opcjonalnie SearchAction). Site-wide; `getSiteShell().jsonLd` już go zawiera. |
| `buildOrganizationJsonLd({ name, url, logo?, sameAs? })` | `@intecion/ipal-kit` | Organization (marka, logo, profile). Site-wide; `getSiteShell().jsonLd` już go zawiera. |
| `sameAsUrls(settings)` | `@intecion/ipal-kit` | URL-e profili z SiteSettings → `sameAs` dla Organization/LocalBusiness. |
| `buildLocalBusinessJsonLd({ name, url, telephone?, address?, openingHours?, … })` | `@intecion/ipal-kit` | LocalBusiness (local SEO); dane z panelu, `@type` możesz nadpisać podtypem. |
| `formatOpeningHours(input)` | `@intecion/ipal-kit` | Godziny wpisane po ludzku (PL/EN/DE) → `string[]` w formacie schema.org `openingHours`; nieczytelne pomija. |
| `buildWebPageJsonLd({ name, url, description?, inLanguage?, dateModified?, … })` | `@intecion/ipal-kit` | WebPage dla jednej strony; `getPageJsonLd` z `createContentHelpers` buduje go sam. |
| `buildBreadcrumbJsonLd(crumbs)` | `@intecion/ipal-kit` | BreadcrumbList z `[{ name, url }]`; null dla ≤1 elementu. `getPageJsonLd` buduje go sam. |
| `buildFaqJsonLd(items)` | `@intecion/ipal-kit` | FAQPage z `[{ question, answer }]` widocznych na stronie; null dla pustej listy. |
| `buildArticleJsonLd({ headline, url, datePublished, author?, image?, type?, … })` | `@intecion/ipal-kit` | Article/BlogPosting dla wpisów; `getPageJsonLd` buduje go dla kolekcji treści. |
| `buildProductJsonLd({ name, url, sku?, image?, price?, … })` | `@intecion/ipal-kit` | Product (Offer tylko gdy jest cena — „na zapytanie” bez Offer). |
| `buildServiceJsonLd({ name, providerName, url, areaServed?, … })` | `@intecion/ipal-kit` | Service dla strony usługi. |
| `buildSpeakableJsonLd({ url, cssSelectors?, id? })` | `@intecion/ipal-kit` | WebPage ze `speakable` — wskazuje fragmenty do czytania/cytowania przez asystentów. |
| `buildSiteNavigationJsonLd(items)` | `@intecion/ipal-kit` | SiteNavigationElement z `[{ name, url }]`; null dla pustej nawigacji. |
| `buildNavigationJsonLd({ items, baseUrl, locale, config, homeSlug })` | `@intecion/ipal-kit` | To samo prosto z `navItems` globala Header (rozwiązuje linki per język, pomija zewnętrzne, deduplikuje). |
| `JsonLdGraph({ schemas })` | `@intecion/ipal-kit/rsc` | Renders nodes as one `@graph` in `<script type="application/ld+json">` with safe serialization; skips null. Instead of a hand-written `<script>`. |
| `buildWebSiteJsonLd({ name, url, search? })` | `@intecion/ipal-kit` | WebSite (optionally SearchAction). Site-wide; `getSiteShell().jsonLd` already includes it. |
| `buildOrganizationJsonLd({ name, url, logo?, sameAs? })` | `@intecion/ipal-kit` | Organization (brand, logo, profiles). Site-wide; `getSiteShell().jsonLd` already includes it. |
| `sameAsUrls(settings)` | `@intecion/ipal-kit` | Profile URLs from SiteSettings → `sameAs` for Organization/LocalBusiness. |
| `buildLocalBusinessJsonLd({ name, url, telephone?, address?, openingHours?, … })` | `@intecion/ipal-kit` | LocalBusiness (local SEO); data from the panel, you can override `@type` with a subtype. |
| `formatOpeningHours(input)` | `@intecion/ipal-kit` | Hours typed in human form (PL/EN/DE) → `string[]` in the schema.org `openingHours` format; skips unreadable ones. |
| `buildWebPageJsonLd({ name, url, description?, inLanguage?, dateModified?, … })` | `@intecion/ipal-kit` | WebPage for a single page; `getPageJsonLd` from `createContentHelpers` builds it itself. |
| `buildBreadcrumbJsonLd(crumbs)` | `@intecion/ipal-kit` | BreadcrumbList from `[{ name, url }]`; null for ≤1 item. `getPageJsonLd` builds it itself. |
| `buildFaqJsonLd(items)` | `@intecion/ipal-kit` | FAQPage from `[{ question, answer }]` visible on the page; null for an empty list. |
| `buildArticleJsonLd({ headline, url, datePublished, author?, image?, type?, … })` | `@intecion/ipal-kit` | Article/BlogPosting for entries; `getPageJsonLd` builds it for content collections. |
| `buildProductJsonLd({ name, url, sku?, image?, price?, … })` | `@intecion/ipal-kit` | Product (Offer only when there is a price — "price on request" without Offer). |
| `buildServiceJsonLd({ name, providerName, url, areaServed?, … })` | `@intecion/ipal-kit` | Service for a service page. |
| `buildSpeakableJsonLd({ url, cssSelectors?, id? })` | `@intecion/ipal-kit` | WebPage with `speakable` — points to the parts for assistants to read/quote. |
| `buildSiteNavigationJsonLd(items)` | `@intecion/ipal-kit` | SiteNavigationElement from `[{ name, url }]`; null for empty navigation. |
| `buildNavigationJsonLd({ items, baseUrl, locale, config, homeSlug })` | `@intecion/ipal-kit` | The same straight from the Header global's `navItems` (resolves links per language, skips external ones, deduplicates). |
### Sitemap, robots, llms.txt
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `buildSitemapEntries({ payload, config, baseUrl, content? })` | `@intecion/ipal-kit` | Wszystkie publiczne URL-e (strony + archiwa) z hreflang i lastmod; pomija drafty i noindex. Zwykle `sitemap` z `createContentHelpers`. |
| `buildSitemapXml(entries, { cssUrl? })` | `@intecion/ipal-kit` | Serializuje wpisy do XML (opcjonalnie z `xml-stylesheet`). |
| `createSitemapRouteHandler(sitemap, { style?, cssUrl? })` | `@intecion/ipal-kit` | Handler `GET /sitemap.xml` (XML + wbudowany CSS pod `?style`). Zwykle `sitemapRoute` z `createContentHelpers`; nie trzymaj obok `app/sitemap.ts`. |
| `buildSitemapCss({ title?, credit?, accent? })` | `@intecion/ipal-kit` | CSS wyglądu sitemapy w przeglądarce (serwowany przez handler). |
| `SITEMAP_STYLE_PARAM` | `@intecion/ipal-kit` | `'style'` — parametr URL sitemapy zwracający CSS zamiast XML. |
| `DEFAULT_SITEMAP_CREDIT` | `@intecion/ipal-kit` | `'Technology by Intecion.com'` — domyślna linia pod nagłówkiem sitemapy. |
| `buildRobots({ baseUrl, aiBots?, disallowParams?, extraDisallow?, … })` | `@intecion/ipal-kit` | Reguły `app/robots.ts`: blokuje admin/API, wskazuje sitemapę, jawnie wpuszcza boty AI (`aiBots: 'allow' \| 'block-training' \| 'disallow'`); przy `IPAL_NOINDEX` blokuje wszystko. Zwykle `robots` z `createContentHelpers`. |
| `AI_ASSISTANT_BOTS` | `@intecion/ipal-kit` | Lista user-agentów botów asystentów/wyszukiwarek AI (ClaudeBot, PerplexityBot…). |
| `AI_TRAINING_BOTS` | `@intecion/ipal-kit` | Lista user-agentów crawlerów trenujących modele (GPTBot, Google-Extended…). |
| `buildLlmsTxt({ payload, config, baseUrl, full?, content?, summaryField?, … })` | `@intecion/ipal-kit` | Treść `/llms.txt` (lub `llms-full.txt` przy `full`) z panelu, te same reguły co sitemap. |
| `createLlmsTxtRoute({ getCachedPayload, config, baseUrl, full?, … })` | `@intecion/ipal-kit` | Gotowy handler `GET` dla `/llms.txt` / `/llms-full.txt`. Zwykle `llmsRoute` / `llmsFullRoute` z `createContentHelpers`. |
| `collectSiteIndex({ payload, config, baseUrl?, content?, locales?, … })` | `@intecion/ipal-kit` | Wspólny indeks publicznych dokumentów per język (URL, tytuł, opis, daty) — źródło dla llms.txt, MCP `list_pages`, IndexNow. Użyj, zanim napiszesz własne listowanie serwisu. |
| `buildSitemapEntries({ payload, config, baseUrl, content? })` | `@intecion/ipal-kit` | All public URLs (pages + archives) with hreflang and lastmod; skips drafts and noindex. Usually `sitemap` from `createContentHelpers`. |
| `buildSitemapXml(entries, { cssUrl? })` | `@intecion/ipal-kit` | Serializes entries to XML (optionally with `xml-stylesheet`). |
| `createSitemapRouteHandler(sitemap, { style?, cssUrl? })` | `@intecion/ipal-kit` | `GET /sitemap.xml` handler (XML + built-in CSS under `?style`). Usually `sitemapRoute` from `createContentHelpers`; do not keep `app/sitemap.ts` next to it. |
| `buildSitemapCss({ title?, credit?, accent? })` | `@intecion/ipal-kit` | CSS for how the sitemap looks in a browser (served by the handler). |
| `SITEMAP_STYLE_PARAM` | `@intecion/ipal-kit` | `'style'` — sitemap URL parameter that returns CSS instead of XML. |
| `DEFAULT_SITEMAP_CREDIT` | `@intecion/ipal-kit` | `'Technology by Intecion.com'` — default line below the sitemap heading. |
| `buildRobots({ baseUrl, aiBots?, disallowParams?, extraDisallow?, … })` | `@intecion/ipal-kit` | `app/robots.ts` rules: blocks admin/API, points to the sitemap, explicitly allows AI bots (`aiBots: 'allow' \| 'block-training' \| 'disallow'`); with `IPAL_NOINDEX` blocks everything. Usually `robots` from `createContentHelpers`. |
| `AI_ASSISTANT_BOTS` | `@intecion/ipal-kit` | List of user agents of AI assistant/search bots (ClaudeBot, PerplexityBot…). |
| `AI_TRAINING_BOTS` | `@intecion/ipal-kit` | List of user agents of model-training crawlers (GPTBot, Google-Extended…). |
| `buildLlmsTxt({ payload, config, baseUrl, full?, content?, summaryField?, … })` | `@intecion/ipal-kit` | `/llms.txt` content (or `llms-full.txt` with `full`) from the panel, same rules as the sitemap. |
| `createLlmsTxtRoute({ getCachedPayload, config, baseUrl, full?, … })` | `@intecion/ipal-kit` | Ready `GET` handler for `/llms.txt` / `/llms-full.txt`. Usually `llmsRoute` / `llmsFullRoute` from `createContentHelpers`. |
| `collectSiteIndex({ payload, config, baseUrl?, content?, locales?, … })` | `@intecion/ipal-kit` | Shared index of public documents per language (URL, title, description, dates) — the source for llms.txt, MCP `list_pages`, IndexNow. Use it before you write your own site listing. |
### IndexNow
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `buildIndexNowHook({ config, contentCollection?, baseUrl?, settingsSlug? })` | `@intecion/ipal-kit` | Hook `afterChange`: po publikacji wysyła URL-e we wszystkich językach do IndexNow (w tle, tylko produkcja). Przy `ipalKit({ indexNow: true })` plugin podpina sam na pages i kolekcjach treści — nie wołaj. |
| `submitToIndexNow({ payload, urls, baseUrl? })` | `@intecion/ipal-kit` | Ręczny POST paczki URL-i do IndexNow; nigdy nie rzuca, zwraca `boolean`. |
| `createIndexNowKeyRoute({ getCachedPayload })` | `@intecion/ipal-kit` | Handler `GET` pliku klucza (`/indexnow-key.txt`) do weryfikacji. Zwykle `indexNowKeyRoute` z `createContentHelpers`. |
| `getIndexNowKey(payload)` | `@intecion/ipal-kit` | Klucz IndexNow: env `INDEXNOW_KEY`, potem Site Integrations; `''` gdy brak. |
| `INDEXNOW_KEY_ENV` | `@intecion/ipal-kit` | `'INDEXNOW_KEY'` — nazwa zmiennej env z kluczem. |
| `INDEXNOW_KEY_PATH` | `@intecion/ipal-kit` | `'/indexnow-key.txt'` — ścieżka trasy pliku klucza. |
| `buildIndexNowHook({ config, contentCollection?, baseUrl?, settingsSlug? })` | `@intecion/ipal-kit` | `afterChange` hook: after publish, sends the URLs in all languages to IndexNow (in the background, production only). With `ipalKit({ indexNow: true })` the plugin wires it itself on pages and content collections — do not call. |
| `submitToIndexNow({ payload, urls, baseUrl? })` | `@intecion/ipal-kit` | Manual POST of a batch of URLs to IndexNow; never throws, returns `boolean`. |
| `createIndexNowKeyRoute({ getCachedPayload })` | `@intecion/ipal-kit` | `GET` handler for the key file (`/indexnow-key.txt`) for verification. Usually `indexNowKeyRoute` from `createContentHelpers`. |
| `getIndexNowKey(payload)` | `@intecion/ipal-kit` | IndexNow key: env `INDEXNOW_KEY`, then Site Integrations; `''` when missing. |
| `INDEXNOW_KEY_ENV` | `@intecion/ipal-kit` | `'INDEXNOW_KEY'` — name of the env variable with the key. |
| `INDEXNOW_KEY_PATH` | `@intecion/ipal-kit` | `'/indexnow-key.txt'` — path of the key file route. |
### Pola, auto-fill, admin
### Fields, auto-fill, admin
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `buildNoindexField(args?)` | `@intecion/ipal-kit` | Checkbox `noindex` w sidebarze kolekcji: wyklucza stronę z sitemap, llms.txt, wyszukiwarki i daje `robots: noindex, follow`. Dodajesz do `fields` kolekcji (plugin tego nie robi). |
| `buildSummaryField(args?)` | `@intecion/ipal-kit` | Lokalizowane pole `aiSummary` (auto-fill z treści, gdy puste) — opis dla AI; potem `summaryField: 'aiSummary'` w llms/search/MCP. |
| `buildAutoFillMetaHook(mapping?)` | `@intecion/ipal-kit` | Hook `beforeChange` wypełniający puste `meta.title`/`meta.description` z treści. Plugin podpina sam na kolekcjach `seo.collections` (opcja `seo.autoFill`) — nie wołaj. |
| `injectAutoFillMeta(config, seo)` | `@intecion/ipal-kit` | Wstrzykuje powyższy hook do kolekcji SEO. Plugin podpina sam — nie wołaj. |
| `SKIP_AUTO_FILL` | `@intecion/ipal-kit` | `'ipalSkipAutoFill'` — klucz `context` (`context: { [SKIP_AUTO_FILL]: true }`) wyłączający auto-fill meta i AI summary przy zapisie (migracje, skrypty). |
| `validateFaviconField` | `@intecion/ipal-kit` | `FieldHook` ostrzegający, gdy favicon < 48×48 lub nie kwadratowy. Plugin podpina sam na polu faviconu w SiteSettings — wołaj tylko przy własnym polu faviconu. |
| `MetaDescriptionCheck` | `@intecion/ipal-kit/admin` | Podpowiedź pod meta description w zakładce SEO (opis zdublowany z globalnym lub innym dokumentem). Wstrzykiwany przez plugin; po włączeniu opcji `pnpm generate:importmap`. |
| `buildNoindexField(args?)` | `@intecion/ipal-kit` | `noindex` checkbox in the collection sidebar: excludes the page from the sitemap, llms.txt, search, and gives `robots: noindex, follow`. Add it to the collection's `fields` (the plugin does not). |
| `buildSummaryField(args?)` | `@intecion/ipal-kit` | Localized `aiSummary` field (auto-filled from content when empty) — a description for AI; then `summaryField: 'aiSummary'` in llms/search/MCP. |
| `buildAutoFillMetaHook(mapping?)` | `@intecion/ipal-kit` | `beforeChange` hook that fills empty `meta.title`/`meta.description` from content. The plugin wires it itself on the `seo.collections` collections (option `seo.autoFill`) — do not call. |
| `injectAutoFillMeta(config, seo)` | `@intecion/ipal-kit` | Injects the hook above into the SEO collections. The plugin wires it itself — do not call. |
| `SKIP_AUTO_FILL` | `@intecion/ipal-kit` | `'ipalSkipAutoFill'` — `context` key (`context: { [SKIP_AUTO_FILL]: true }`) that turns off meta auto-fill and the AI summary on save (migrations, scripts). |
| `validateFaviconField` | `@intecion/ipal-kit` | `FieldHook` that warns when the favicon is < 48×48 or not square. The plugin wires it itself on the favicon field in SiteSettings — call it only for your own favicon field. |
| `MetaDescriptionCheck` | `@intecion/ipal-kit/admin` | Hint below the meta description in the SEO tab (description duplicated from the global or another document). Injected by the plugin; after turning the option on, `pnpm generate:importmap`. |
**Typy:** `PageMetadata`, `OgImage` — wynik `buildMetadata` i obraz OG; `SeoMeta`, `SeoOption`, `AutoFillMapping` — grupa `meta`, opcja `seo` pluginu i mapowanie auto-fill; `SiteMetaConfig` — wynik `readSiteMetaConfig`; `RobotsOptions`, `RobotsRules` — opcje i wynik `buildRobots`; `SitemapEntry`, `SitemapRouteOptions`, `SitemapStyleOptions` — wpis sitemapy, opcje handlera i wyglądu; `CollectSiteIndexArgs`, `SiteIndexEntry` — argumenty i wpis `collectSiteIndex`; `NoSnippetProps` (`/client`, `/rsc`) — propsy `NoSnippet`.
**Types:** `PageMetadata`, `OgImage` — `buildMetadata` result and OG image; `SeoMeta`, `SeoOption`, `AutoFillMapping` — the `meta` group, the plugin's `seo` option and the auto-fill mapping; `SiteMetaConfig` — `readSiteMetaConfig` result; `RobotsOptions`, `RobotsRules` — `buildRobots` options and result; `SitemapEntry`, `SitemapRouteOptions`, `SitemapStyleOptions` — sitemap entry, handler and style options; `CollectSiteIndexArgs`, `SiteIndexEntry` — `collectSiteIndex` arguments and entry; `NoSnippetProps` (`/client`, `/rsc`) — `NoSnippet` props.
## Rate limit i IP klienta (`shared`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/forms.md`
## Rate limit and client IP (`shared`) — details: `node_modules/@intecion/ipal-kit/docs/forms.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `clientIp(source, { header?, trustedProxies? })` | `@intecion/ipal-kit` | IP klienta z `Request` lub `Headers` (`clientIp(await headers())` w server action): `cf-connecting-ip`, `x-real-ip`, potem XFF liczone od prawej; `''` gdy brak. W produkcji przypnij `header` (lub env `IPAL_IP_HEADER`). |
| `setRateLimitStore(store \| null)` | `@intecion/ipal-kit` | Wspólny magazyn (np. Redis) dla wszystkich limiterów pluginu (formularze, zgody, MCP…); `null` = pamięć procesu. Wołaj raz przy starcie, gdy działa kilka instancji. |
| `clientIp(source, { header?, trustedProxies? })` | `@intecion/ipal-kit` | Client IP from a `Request` or `Headers` (`clientIp(await headers())` in a server action): `cf-connecting-ip`, `x-real-ip`, then XFF counted from the right; `''` when missing. In production pin `header` (or env `IPAL_IP_HEADER`). |
| `setRateLimitStore(store \| null)` | `@intecion/ipal-kit` | Shared store (e.g. Redis) for all plugin limiters (forms, consents, MCP…); `null` = process memory. Call once at startup when several instances run. |
**Typy:** `ClientIpOptions` — opcje `clientIp`; `RateLimitStore` — kontrakt magazynu (`hit(id, cost, windowMs)` → `{ count, resetAt }`).
**Types:** `ClientIpOptions` — `clientIp` options; `RateLimitStore` — store contract (`hit(id, cost, windowMs)` → `{ count, resetAt }`).
## Slug (`slug`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/slug.md`
## Slug (`slug`) — details: `node_modules/@intecion/ipal-kit/docs/slug.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `buildSlugField({ from?, name?, localized?, required?, overrides? })` | `@intecion/ipal-kit` | Pole slug generowane z `title` (domyślnie) tylko gdy puste, per język — nigdy nie nadpisuje ręcznego. Do `fields` kolekcji. |
| `toSlug(input)` | `@intecion/ipal-kit` | String → slug URL (diakrytyki, np. „Strona główna” → `strona-glowna`). |
| `buildSlugField({ from?, name?, localized?, required?, overrides? })` | `@intecion/ipal-kit` | Slug field generated from `title` (by default) only when empty, per language — never overwrites a manual one. For the collection's `fields`. |
| `toSlug(input)` | `@intecion/ipal-kit` | String → URL slug (diacritics, e.g. "Strona główna" → `strona-glowna`). |
## Statystyki (`stats`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/stats.md`
## Stats (`stats`) — details: `node_modules/@intecion/ipal-kit/docs/stats.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `PageStats({ locale?, endpoint? })` | `@intecion/ipal-kit/client` | Beacon odsłony do `/api/ipal/hit` (bez zgody anonimowo, ze zgodą analytics cookie `ipal_vid`). Montuj raz w layoucie wewnątrz `<ConsentProvider>` albo przez `stats` w `<SiteProviders>`. |
| `STATS_SLUG` | `@intecion/ipal-kit` | `'stats-visits'` — slug kolekcji wizyt (dodawanej przez `ipalKit({ stats })`). |
| `VISITOR_COOKIE` | `@intecion/ipal-kit/client` | `'ipal_vid'` — cookie identyfikatora odwiedzającego (tylko po zgodzie analytics). |
| `StatsView` | `@intecion/ipal-kit/admin` | Widok `/admin/stats` (30 dni, top strony, referrery, urządzenia, historia odwiedzającego). Wstrzykiwany przez plugin; po włączeniu opcji `pnpm generate:importmap`. |
| `StatsWidget` | `@intecion/ipal-kit/admin` | Karta z wykresem 30 dni na dashboardzie (`stats.dashboard`). Wstrzykiwany przez plugin; po włączeniu opcji `pnpm generate:importmap`. |
| `StatsNavLink` | `@intecion/ipal-kit/admin` | Link do `/admin/stats` w nawigacji panelu. Wstrzykiwany przez plugin; po włączeniu opcji `pnpm generate:importmap`. |
| `PageStats({ locale?, endpoint? })` | `@intecion/ipal-kit/client` | Page view beacon to `/api/ipal/hit` (anonymous without consent, with analytics consent the `ipal_vid` cookie). Mount once in the layout inside `<ConsentProvider>` or via `stats` in `<SiteProviders>`. |
| `STATS_SLUG` | `@intecion/ipal-kit` | `'stats-visits'` — slug of the visits collection (added by `ipalKit({ stats })`). |
| `VISITOR_COOKIE` | `@intecion/ipal-kit/client` | `'ipal_vid'` — visitor ID cookie (only after analytics consent). |
| `StatsView` | `@intecion/ipal-kit/admin` | `/admin/stats` view (30 days, top pages, referrers, devices, visitor history). Injected by the plugin; after turning the option on, `pnpm generate:importmap`. |
| `StatsWidget` | `@intecion/ipal-kit/admin` | Dashboard card with a 30-day chart (`stats.dashboard`). Injected by the plugin; after turning the option on, `pnpm generate:importmap`. |
| `StatsNavLink` | `@intecion/ipal-kit/admin` | Link to `/admin/stats` in the panel nav. Injected by the plugin; after turning the option on, `pnpm generate:importmap`. |
**Typy:** `StatsOptions` — opcja `ipalKit({ stats })` (`dashboard`, `retentionDays`, `timeZone`); `StatsVisit`, `StatsPage` — dokument wizyty i odsłona w nim; `PageStatsProps` (`/client`) — propsy `PageStats`.
**Types:** `StatsOptions` — the `ipalKit({ stats })` option (`dashboard`, `retentionDays`, `timeZone`); `StatsVisit`, `StatsPage` — visit document and a page view in it; `PageStatsProps` (`/client`) — `PageStats` props.
## Media i storage (`storage`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/storage.md`
## Media and storage (`storage`) — details: `node_modules/@intecion/ipal-kit/docs/storage.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `buildR2Storage(collections, { s3Storage })` | `@intecion/ipal-kit` | Plugin storage Cloudflare R2 z env (`R2_*`); bez env no-op (dysk lokalny). `s3Storage` z `@payloadcms/storage-s3` wstrzykuje projekt. Do `plugins` w configu. |
| `buildImagesConfig({ publicUrl?, serverUrl?, extraHosts?, production? })` | `@intecion/ipal-kit` | Domyślne `images` dla `next.config.ts`: AVIF/WebP, `remotePatterns` dla R2 i mediów z aplikacji, cache 31 dni. |
| `MediaPreconnect()` | `@intecion/ipal-kit/rsc` | `<link rel="preconnect">` + `dns-prefetch` do domeny `R2_PUBLIC_URL`; nic, gdy brak env. W `<head>` layoutu. |
| `YouTubeEmbed({ videoId, title, playLabel, poster?, note?, classNames? })` | `@intecion/ipal-kit/client` | Lekki YouTube: poster + przycisk, player `youtube-nocookie` dopiero po kliknięciu (bez cookies i JS przy ładowaniu). Bez stylów. |
| `buildR2Storage(collections, { s3Storage })` | `@intecion/ipal-kit` | Cloudflare R2 storage plugin from env (`R2_*`); without env a no-op (local disk). The project injects `s3Storage` from `@payloadcms/storage-s3`. For `plugins` in the config. |
| `buildImagesConfig({ publicUrl?, serverUrl?, extraHosts?, production? })` | `@intecion/ipal-kit` | Default `images` for `next.config.ts`: AVIF/WebP, `remotePatterns` for R2 and media from the app, 31-day cache. |
| `MediaPreconnect()` | `@intecion/ipal-kit/rsc` | `<link rel="preconnect">` + `dns-prefetch` to the `R2_PUBLIC_URL` domain; nothing when the env is missing. `SiteProviders` already renders it (`preconnect={false}` turns it off); by hand: top of `<body>`, never an explicit `<head>`. |
| `YouTubeEmbed({ videoId, title, playLabel, poster?, note?, classNames? })` | `@intecion/ipal-kit/client` | Lightweight YouTube: poster + button, the `youtube-nocookie` player only after a click (no cookies or JS on load). Unstyled. |
**Typy:** `ImagesConfig` — wynik `buildImagesConfig`.
**Types:** `ImagesConfig` — `buildImagesConfig` result.
## Motyw jasny/ciemny (`theme`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/theme.md`
## Light/dark theme (`theme`) — details: `node_modules/@intecion/ipal-kit/docs/theme.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `ThemeScript({ allowToggle?, defaultTheme? })` | `@intecion/ipal-kit/rsc` | Inline script ustawiający `data-theme` na `<html>` przed malowaniem (bez mignięcia). Pierwszy w `<body>` lub `theme` w `<SiteProviders>`; `<html suppressHydrationWarning>`. |
| `ThemeSwitcher({ label?, classNames?, renderIcon? })` | `@intecion/ipal-kit/client` | Przełącznik bez stylów (`<button role="switch">`, ikony light/dark); aktywną ikonę stylujesz z CSS (`[data-theme=dark]`). |
| `useTheme()` | `@intecion/ipal-kit/client` | Hook `{ theme, setTheme, toggle }`; `theme` = null na serwerze — nie styluj od niego. |
| `applyTheme(theme, { persist?, transitionMs? })` | `@intecion/ipal-kit/client` | Ustawia motyw na `<html>` i zapamiętuje w localStorage. |
| `readDocumentTheme()` | `@intecion/ipal-kit/client` | Aktualny motyw z `<html>` lub null. |
| `themeConfigFrom(settings)` | `@intecion/ipal-kit` | Opcje motywu z dokumentu SiteSettings (to, co trzyma `getSiteShell(locale).theme`). |
| `themeScript({ allowToggle, defaultTheme })` | `@intecion/ipal-kit` | Treść skryptu, którą renderuje `ThemeScript` — gdy wstawiasz ją sam. |
| `ThemeScript({ allowToggle?, defaultTheme? })` | `@intecion/ipal-kit/rsc` | Inline script that sets `data-theme` on `<html>` before paint (no flash). First in `<body>` or `theme` in `<SiteProviders>`; `<html suppressHydrationWarning>`. |
| `ThemeSwitcher({ label?, classNames?, renderIcon? })` | `@intecion/ipal-kit/client` | Unstyled switcher (`<button role="switch">`, light/dark icons); style the active icon in CSS (`[data-theme=dark]`). |
| `useTheme()` | `@intecion/ipal-kit/client` | Hook `{ theme, setTheme, toggle }`; `theme` = null on the server — do not style from it. |
| `applyTheme(theme, { persist?, transitionMs? })` | `@intecion/ipal-kit/client` | Sets the theme on `<html>` and remembers it in localStorage. |
| `readDocumentTheme()` | `@intecion/ipal-kit/client` | Current theme from `<html>` or null. |
| `themeConfigFrom(settings)` | `@intecion/ipal-kit` | Theme options from the SiteSettings document (what `getSiteShell(locale).theme` holds). |
| `themeScript({ allowToggle, defaultTheme })` | `@intecion/ipal-kit` | The script content that `ThemeScript` renders — when you insert it yourself. |
| `isTheme(value)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Type guard `'light' \| 'dark'`. |
| `isThemeSetting(value)` | `@intecion/ipal-kit` | Type guard `'system' \| 'light' \| 'dark'`. |
| `THEME_ATTRIBUTE` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `'data-theme'` — atrybut na `<html>` (wariant Tailwind `dark`). |
| `THEME_STORAGE_KEY` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `'ipal-theme'` — klucz localStorage z wyborem odwiedzającego. |
| `THEME_SWITCHING_ATTRIBUTE` | `@intecion/ipal-kit/client` | `'data-theme-switching'` — chwilowo na `<html>` przy przełączaniu (do przejścia kolorów). |
| `THEME_ATTRIBUTE` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `'data-theme'` — attribute on `<html>` (Tailwind `dark` variant). |
| `THEME_STORAGE_KEY` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | `'ipal-theme'` — localStorage key with the visitor's choice. |
| `THEME_SWITCHING_ATTRIBUTE` | `@intecion/ipal-kit/client` | `'data-theme-switching'` — briefly on `<html>` while switching (for the colour transition). |
**Typy:** `Theme`, `ThemeSetting`, `ThemeConfig` (root, `/client`) — motyw, ustawienie z panelu i opcje motywu; `ThemeScriptProps` (`/rsc`), `ThemeSwitcherProps`, `ThemeSwitcherClassNames` (`/client`) — propsy komponentów.
**Types:** `Theme`, `ThemeSetting`, `ThemeConfig` (root, `/client`) — theme, setting from the panel and theme options; `ThemeScriptProps` (`/rsc`), `ThemeSwitcherProps`, `ThemeSwitcherClassNames` (`/client`) — component props.
## Turnstile (`turnstile`) — szczegóły: `node_modules/@intecion/ipal-kit/docs/turnstile.md`
## Turnstile (`turnstile`) — details: `node_modules/@intecion/ipal-kit/docs/turnstile.md`
| Eksport | Import z | Do czego / kiedy |
| Export | Import from | What it does / when |
|---|---|---|
| `getTurnstileConfig(payload)` | `@intecion/ipal-kit` | `{ enabled, siteKey }` z Site Integrations (fallback env); włączone tylko gdy są oba klucze. W layoucie serwerowym → `TurnstileProvider`. |
| `TurnstileProvider({ siteKey, children })` | `@intecion/ipal-kit/client` | Dostarcza site key całej aplikacji; przy `siteKey` null widgety nic nie renderują. |
| `useTurnstile()` | `@intecion/ipal-kit/client` | W formularzu: `{ token, TurnstileWidget, reset, … }`; token przekazujesz do `submitForm`. Wymaga providera. |
| `useOptionalTurnstile()` | `@intecion/ipal-kit/client` | Jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać — dla współdzielonych komponentów. |
| `Turnstile({ siteKey, onToken, theme? })` | `@intecion/ipal-kit/client` | Surowy widget z jawnym kluczem — gdy nie używasz providera. |
| `verifyTurnstile({ token, payload, ip?, onConfigError? })` | `@intecion/ipal-kit/server` | Weryfikacja tokenu po stronie serwera → `boolean` (`degraded` domyślnie przepuszcza). `submitForm` robi to sam — wołaj tylko we własnych akcjach. |
| `checkTurnstile({ token, payload, ip? })` | `@intecion/ipal-kit/server` | Jak wyżej, ale zwraca `{ outcome: 'pass' \| 'reject' \| 'degraded', code? }` i aktualizuje status integracji w panelu. |
| `getTurnstileConfig(payload)` | `@intecion/ipal-kit` | `{ enabled, siteKey }` from Site Integrations (env fallback); enabled only when both keys are set. In the server layout → `TurnstileProvider`. |
| `TurnstileProvider({ siteKey, children })` | `@intecion/ipal-kit/client` | Provides the site key to the whole app; with `siteKey` null the widgets render nothing. |
| `useTurnstile()` | `@intecion/ipal-kit/client` | In a form: `{ token, TurnstileWidget, reset, … }`; pass the token to `submitForm`. Requires the provider. |
| `useOptionalTurnstile()` | `@intecion/ipal-kit/client` | Like `useTurnstile`, but without a provider it returns `enabled: false` instead of throwing — for shared components. |
| `Turnstile({ siteKey, onToken, theme? })` | `@intecion/ipal-kit/client` | Raw widget with an explicit key — when you do not use the provider. |
| `verifyTurnstile({ token, payload, ip?, onConfigError? })` | `@intecion/ipal-kit/server` | Server-side token verification → `boolean` (`degraded` lets it through by default). `submitForm` does this itself — call it only in your own actions. |
| `checkTurnstile({ token, payload, ip? })` | `@intecion/ipal-kit/server` | As above, but returns `{ outcome: 'pass' \| 'reject' \| 'degraded', code? }` and updates the integration status in the panel. |
**Typy:** `TurnstileConfig` (root) — wynik `getTurnstileConfig`; `TurnstileCheck`, `TurnstileOutcome` (`/server`) — wynik weryfikacji; `TurnstileProps`, `TurnstileTheme` (`/client`) — propsy i motyw widgetu.
**Types:** `TurnstileConfig` (root) — `getTurnstileConfig` result; `TurnstileCheck`, `TurnstileOutcome` (`/server`) — verification result; `TurnstileProps`, `TurnstileTheme` (`/client`) — widget props and theme.
+265 -244
View File
@@ -5,33 +5,33 @@ description: Complete start-to-finish install of @intecion/ipal-kit in a Payload
# ipal-setup
**Cel: OBOWIĄZKOWY KOMPLET z AGENT.md §0b (18 pozycji), bez niczego „do odkrycia”.** Etap 11
sprawdza wszystko; nie kończysz z brakami (wyjątek: linia `ipal-audit-skip:` z decyzji klienta, AGENT.md §0b).
**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).
**Jeden etap = jeden commit** (`git commit -m "ipal-setup <N>: <etap>"`). Nie czekasz na OK między
etapami (AGENT.md §0a); pytania zbierasz w **jedną listę na początku**: klient, domena, rynek, języki,
baza (Postgres/Mongo), dane R2, klucze Turnstile, mail (SMTP czy Graph), firma lokalna (LocalBusiness?),
tryb okna cookies (`inline`/`modal`/`detailed`; brief milczy → `detailed`), `DESIGN.md`. Brak danych nie
blokuje: wpinasz kod, wartość trafia do `.env`/panelu później, brak — do raportu. Tryb „krok po kroku”
tylko na prośbę. Pełna budowa strony: **ipal-site**.
**One stage = one commit** (`git commit -m "ipal-setup <N>: <stage>"`). Do not wait for an OK between
stages (AGENT.md §0a); collect questions in **one list at the start**: client, domain, market, languages,
database (Postgres/Mongo), R2 credentials, Turnstile keys, mail (SMTP or Graph), local business (LocalBusiness?),
cookie dialog mode (`inline`/`modal`/`detailed`; brief says nothing → `detailed`), `DESIGN.md`. Missing data does not
block you: wire the code, the value goes into `.env`/the panel later, anything missing goes into the report. Step-by-step mode
only on request. Full site build: **ipal-site**.
**ipal-kit pomaga, nie ogranicza:** każdy moduł wyłączysz osobno, każdy domyślny element nadpiszesz —
**config projektu wygrywa**. Każdy etap ma linię **Wyłącz / nadpisz**; „obecnie zawsze” = kod pluginu
jeszcze nie ma opcji. Brak opcji = **ipal-plugin-gap**, nigdy łatka w `node_modules`.
**ipal-kit helps, never limits:** you can turn off every module separately and override every default —
**the project config wins**. Every stage has a **Turn off / override** line; "currently always" = the plugin code
has no option for it yet. No option = **plugin gap** (`ipal-plugin-gap`), never a patch in `node_modules`.
Każdy etap: **Kroki** → **Kod** (minimum, importy zweryfikowane z `exports`) → **Sprawdź** → **Wyłącz / nadpisz**.
Entry pointy: `@intecion/ipal-kit` (config, buildery, helpery), `/rsc` (komponenty serwerowe), `/client`
Every stage: **Steps** → **Code** (minimum, imports verified against `exports`) → **Check** → **Turn off / override**.
Entry points: `@intecion/ipal-kit` (config, builders, helpers), `/rsc` (server components), `/client`
(`'use client'`), `/server` (server actions), `/env` (instrumentation), `/admin`, `/fluid.css`, `/fluid-wide.css`.
---
## 1. Instalacja
## 1. Installation
**Kroki.** Szkielet: `npx create-payload-app@latest <projekt>` (Blank, Postgres/Mongo), usuń starter
`src/app/(frontend)/layout.tsx` i `page.tsx` (rootem frontu zostaje `[locale]/layout.tsx`). Nie twórz
`middleware.ts` (Next 16 = `proxy.ts`; istniejący usuń). Nigdy instalacja z gita (`git+https://…`).
**Steps.** Scaffold: `npx create-payload-app@latest <project>` (Blank, Postgres/Mongo), delete the starter
`src/app/(frontend)/layout.tsx` and `page.tsx` (the frontend root becomes `[locale]/layout.tsx`). Do not create
`middleware.ts` (Next 16 = `proxy.ts`; delete an existing one). Never install from git (`git+https://…`).
```ini
# .npmrc (commituj — bez sekretu)
# .npmrc (commit it — no secret)
legacy-peer-deps=true
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
```
@@ -39,57 +39,57 @@ legacy-peer-deps=true
pnpm add @intecion/ipal-kit @payloadcms/plugin-seo @payloadcms/plugin-form-builder \
@payloadcms/storage-s3 @clocklimited/payload-2fa@3.0.0-beta.7 tailwindcss @tailwindcss/postcss
```
`nodemailer`, `lucide-react`, `slugify`, `server-only` przychodzą z pluginem — nie dodawaj (własny
`lucide-react` tylko `~0.400.0`). W `package.json`: każdy `@payloadcms/*` (ui, next, db-*, richtext-lexical,
plugin-seo, plugin-form-builder, storage-s3) w `pnpm.overrides` **na dokładną wersję `payload`**, potem
`rm -rf node_modules pnpm-lock.yaml && pnpm install`. Build przez webpack:
`nodemailer`, `lucide-react`, `slugify`, `server-only` come with the plugin — do not add them (your own
`lucide-react` only `~0.400.0`). In `package.json`: pin every `@payloadcms/*` (ui, next, db-*, richtext-lexical,
plugin-seo, plugin-form-builder, storage-s3) in `pnpm.overrides` **to the exact `payload` version**, then
`rm -rf node_modules pnpm-lock.yaml && pnpm install`. Build with webpack:
`"build": "cross-env NODE_OPTIONS=\"--max-old-space-size=3072\" next build --webpack"`.
**Sprawdź.** `ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` istnieje;
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — jedna, ta sama wersja; `ls src/middleware.ts` → brak.
404 przy `pnpm add` = brak linii `@intecion:registry`; 401 = stary `_authToken` w `~/.npmrc` (PROGRAMISTA §1).
**Check.** `ls node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` exists;
`pnpm ls payload @payloadcms/ui @payloadcms/plugin-seo` — one, identical version; `ls src/middleware.ts` → not found.
404 on `pnpm add` = missing `@intecion:registry` line; 401 = stale `_authToken` in `~/.npmrc` (PROGRAMISTA §1).
**Wyłącz / nadpisz.** `@payloadcms/storage-s3` i `@clocklimited/payload-2fa` to opcjonalne peery — zbędne tylko
przy `twoFactor: false` / bez `buildR2Storage` (oba w §0b obowiązkowe). Wersji `@payloadcms/*` nie rozjeżdżasz.
**Turn off / override.** `@payloadcms/storage-s3` and `@clocklimited/payload-2fa` are optional peers — only unneeded
with `twoFactor: false` / without `buildR2Storage` (both mandatory in §0b). Never let `@payloadcms/*` versions drift apart.
## 2. Skille, wskaźnik i lektura — zanim napiszesz kod
## 2. Skills, pointer and reading — before you write code
**Kroki.**
1. `pnpm exec ipal-skills` — kopiuje skille `ipal-*` do `.agents/skills/` **i** dopisuje blok wskaźnika
ipal-kit do `AGENTS.md` / `CLAUDE.md` projektu. Dodaj skrypt `"ipal:skills": "ipal-skills"`; uruchamiasz po
każdej aktualizacji pakietu. `.agents/skills/` commitujesz.
2. `tsconfig.json`: `"exclude": ["node_modules", ".agents"]` (skille mają szablony `.ts`/`.tsx`; bez tego
`tsc`/`next build` padają, a `ipal-skills` kończy się kodem 1).
3. **Przeczytaj w całości:** `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` oraz skill **ipal-reference**
(`.agents/skills/ipal-reference/SKILL.md` — mapa wpięcia; `resources/api.md` — indeks każdego eksportu).
Każdą nazwę spoza tego skilla sprawdzasz tam, nie z pamięci.
4. `AGENTS.md` wg AGENT.md §13: linia projektu (klient, domena, rynek, języki, media, mail) i „Ustalenia projektu”
(tryb okna cookies, decyzje z listy pytań) — **poza** blokiem `<!-- ipal-kit:start -->…<!-- ipal-kit:end -->`
(nadpisywany przy każdym `ipal-skills`). Brak `CLAUDE.md` → `ipal-skills` tworzy go z linią `@AGENTS.md`.
**Steps.**
1. `pnpm exec ipal-skills` — copies the `ipal-*` skills to `.agents/skills/` **and** appends the ipal-kit pointer
block to the project's `AGENTS.md` / `CLAUDE.md`. Add the script `"ipal:skills": "ipal-skills"`; run it after
every package update. Commit `.agents/skills/`.
2. `tsconfig.json`: `"exclude": ["node_modules", ".agents"]` (skills contain `.ts`/`.tsx` templates; without this
`tsc`/`next build` fail and `ipal-skills` exits with code 1).
3. **Read in full:** `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` and the **ipal-reference** skill
(`.agents/skills/ipal-reference/SKILL.md` — wiring map; `resources/api.md` — index of every export).
Check every name not in this skill there, not from memory.
4. `AGENTS.md` per AGENT.md §13: project line (client, domain, market, languages, media, mail) and "Project decisions"
(cookie dialog mode, decisions from the question list) — **outside** the `<!-- ipal-kit:start -->…<!-- ipal-kit:end -->` block
(overwritten on every `ipal-skills` run). No `CLAUDE.md` → `ipal-skills` creates it with an `@AGENTS.md` line.
**Sprawdź.** `ls .agents/skills | grep -c '^ipal-'` > 0 (w tym `ipal-reference`); `grep -c 'ipal-kit:start' AGENTS.md` = 1;
`CLAUDE.md` ma `@AGENTS.md` albo własny blok; `pnpm exec ipal-skills --dry-run` bez ostrzeżenia o `tsconfig`.
**Check.** `ls .agents/skills | grep -c '^ipal-'` > 0 (including `ipal-reference`); `grep -c 'ipal-kit:start' AGENTS.md` = 1;
`CLAUDE.md` has `@AGENTS.md` or its own block; `pnpm exec ipal-skills --dry-run` without a `tsconfig` warning.
**Wyłącz / nadpisz.** `--no-pointer` — bez bloku w AGENTS.md/CLAUDE.md (wtedy sekcję „Reguły” z §13 wpisujesz
sam); `--dest .claude/skills` — inny katalog (wtedy wyklucz `.claude` i podmieniaj ścieżki `.agents/skills` w
komendach); `--dry-run` — podgląd. Własne skille nazywaj bez prefiksu `ipal-` — nie są ruszane.
**Turn off / override.** `--no-pointer` — no block in AGENTS.md/CLAUDE.md (then write the "Rules" section from §13
yourself); `--dest .claude/skills` — another directory (then exclude `.claude` and replace the `.agents/skills` paths in
commands); `--dry-run` — preview. Name your own skills without the `ipal-` prefix — they are left untouched.
## 3. Konfiguracja
## 3. Configuration
**Kod.**
**Code.**
```ts
// src/i18n.config.ts — JEDYNE źródło języków
// src/i18n.config.ts — the ONLY source of languages
import type { I18nConfig } from '@intecion/ipal-kit'
export const i18nConfig = {
defaultLocale: 'pl',
locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }],
} as const satisfies I18nConfig
// src/content.config.ts — kolekcje z archiwum (blog…) dopisuje skill ipal-collection
// src/content.config.ts — collections with an archive (blog…) are added by the ipal-collection skill
import type { ContentOption } from '@intecion/ipal-kit'
export const contentConfig: ContentOption = { collections: [] }
// src/hooks/revalidateGlobals.ts — plugin NIE rewaliduje globali (hooks.md)
// src/hooks/revalidateGlobals.ts — the plugin does NOT revalidate globals (hooks.md)
import { revalidatePath } from 'next/cache'
import type { GlobalAfterChangeHook } from 'payload'
export const revalidateEverything: GlobalAfterChangeHook = ({ doc, context }) => {
@@ -99,7 +99,7 @@ export const revalidateEverything: GlobalAfterChangeHook = ({ doc, context }) =>
}
```
```ts
// src/payload.config.ts — zostaw z create-payload-app: db, editor, secret, sharp, typescript, admin.importMap
// src/payload.config.ts — keep from create-payload-app: db, editor, secret, sharp, typescript, admin.importMap
import { buildConfig, type Plugin } from 'payload'
import { buildR2Storage, ipalKit, mailAdapter } from '@intecion/ipal-kit'
import { payloadTotp } from '@clocklimited/payload-2fa'
@@ -118,9 +118,9 @@ const revalidatePluginGlobals: Plugin = (config) => ({
})
export default buildConfig({
// …db, editor, secret, sharp, typescript z create-payload-app…
collections: [Pages, Media], // users wstrzykuje ipalKit
email: mailAdapter(), // bez tego maile form-buildera nie wyjdą
// …db, editor, secret, sharp, typescript from create-payload-app…
collections: [Pages, Media], // ipalKit injects users
email: mailAdapter(), // without this form-builder emails are not sent
plugins: [
ipalKit({
i18n: i18nConfig,
@@ -129,52 +129,52 @@ export default buildConfig({
content: contentConfig,
seo: { collections: ['pages'] },
forms: { redirectRelationships: ['pages'] },
twoFactor: { issuer: '<Nazwa klienta>', plugin: payloadTotp },
twoFactor: { issuer: '<Client name>', plugin: payloadTotp },
whiteLabel: true,
indexNow: true,
consentLog: true, // bez tego nie ma POST /api/ipal/consent
consentLog: true, // without this there is no POST /api/ipal/consent
}),
revalidatePluginGlobals, // PO ipalKit — globale pluginu już istnieją
buildR2Storage(['media'], { s3Storage }), // ZAWSZE: R2 przy komplecie R2_*, bez nich dysk lokalny
revalidatePluginGlobals, // AFTER ipalKit — the plugin globals already exist
buildR2Storage(['media'], { s3Storage }), // ALWAYS: R2 with the full R2_* set, local disk without it
],
})
```
`.env.example` (bez wartości, w repo): `DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL`, `R2_BUCKET`,
`R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL`, `IPAL_IP_HEADER` (`cf-connecting-ip`
za Cloudflare, `x-forwarded-for` za samym proxy), `IPAL_NOINDEX` (puste; `1` tylko staging), `INDEXNOW_KEY`,
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (fallback panelu), przy Graph `GRAPH_TENANT_ID`,
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. `.env` lokalnie z `PAYLOAD_SECRET` ≥ 32 znaki.
Jeden język: jeden wpis w `locales`, bez folderu `[locale]` (i18n.md).
`.env.example` (no values, in the repo): `DATABASE_URI`, `PAYLOAD_SECRET`, `NEXT_PUBLIC_SERVER_URL`, `R2_BUCKET`,
`R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL` (empty = media through the app — the default), `IPAL_IP_HEADER` (`cf-connecting-ip`
behind Cloudflare, `x-forwarded-for` behind a plain proxy), `IPAL_NOINDEX` (empty; `1` on staging only), `INDEXNOW_KEY`,
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` (panel fallback), with Graph `GRAPH_TENANT_ID`,
`GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER`. Local `.env` with `PAYLOAD_SECRET` ≥ 32 characters.
One language: one entry in `locales`, no `[locale]` folder (i18n.md).
**Sprawdź.** `pnpm payload generate:importmap` (whiteLabel dodaje komponenty admina) i `pnpm generate:types` bez
błędów; `pnpm dev`, `/admin`: ekran pierwszego użytkownika → po zapisie wymuszona konfiguracja TOTP (QR);
w panelu są Site Settings, Site Integrations, Cookie Settings, Notifications, grupa Forms, Consent records.
**Check.** `pnpm payload generate:importmap` (whiteLabel adds admin components) and `pnpm generate:types` without
errors; `pnpm dev`, `/admin`: first-user screen → after saving, TOTP setup is enforced (QR);
the panel shows Site Settings, Site Integrations, Cookie Settings, Notifications, the Forms group, Consent records.
`curl -s -o /dev/null -w '%{http_code}' -X POST localhost:3000/api/ipal/consent -H 'content-type: application/json'
-d '{"id":"0123456789abcdef","version":1,"state":{"necessary":true,"functional":false,"analytics":false,"marketing":false}}'` → `201`.
**Wyłącz / nadpisz.**
- `enabled: false` — `ipalKit` zwraca config bez zmian: kolekcje i globale pluginu **znikają z configu**
(Postgres: nie zatwierdzaj migracji/push usuwającej tabele).
- Pominięta opcja = moduł wyłączony: `seo`, `forms`, `pages` (bez niego `content` nie działa), `content`,
**Turn off / override.**
- `enabled: false` — `ipalKit` returns the config unchanged: the plugin's collections and globals **disappear from the config**
(Postgres: do not approve a migration/push that drops tables).
- Omitted option = module off: `seo`, `forms`, `pages` (without it `content` does not work), `content`,
`consentLog`, `indexNow`, `whiteLabel`, `access`, `stats`.
- `twoFactor`: **pominięcie rzuca błąd** (`issuer` wymagany) — wyłączenie tylko jawnie `twoFactor: false`
(odradzane); bez wstrzykniętego `plugin: payloadTotp` też błąd. `forceSetup` obecnie zawsze `true`.
- `users`: własna kolekcja o tym slugu wygrywa (plugin dokłada tylko `roles`). `localization` obecnie zawsze
nadpisywane z `i18n`.
- Globale `site-settings`, `site-integrations`, `cookie-settings`, `notifications`, endpoint
`/api/ipal/test-email` i alerty na dashboardzie — obecnie zawsze; rozszerzasz `siteSettingsFields` /
`integrationsFields`, usuwasz/podmieniasz własnym pluginem po `ipalKit` (jak `revalidatePluginGlobals`).
- `whiteLabel: { credit: false, titleSuffix, settingsSlug, logoField, … }`; przy `whiteLabel` plugin nadpisuje
`graphics.Logo/Icon` — własne grafiki tylko bez niego.
- Mail: dowolny adapter Payloada zamiast `mailAdapter()`; `mailAdapter({ fallbackFromAddress, smtp, graph })`.
- R2: inne opcje storage-s3 (prefix, clientUploads) → wywołaj `s3Storage` sam zamiast `buildR2Storage`.
- `twoFactor`: **omitting it throws** (`issuer` is required) — turn it off only explicitly with `twoFactor: false`
(discouraged); without an injected `plugin: payloadTotp` it also throws. `forceSetup` currently always `true`.
- `users`: your own collection with that slug wins (the plugin only adds `roles`). `localization` currently always
overridden from `i18n`.
- The `site-settings`, `site-integrations`, `cookie-settings`, `notifications` globals, the
`/api/ipal/test-email` endpoint and dashboard alerts — currently always; extend `siteSettingsFields` /
`integrationsFields`, remove/replace them with your own plugin after `ipalKit` (like `revalidatePluginGlobals`).
- `whiteLabel: { credit: false, titleSuffix, settingsSlug, logoField, … }`; with `whiteLabel` the plugin overrides
`graphics.Logo/Icon` — your own graphics only without it.
- Mail: any Payload adapter instead of `mailAdapter()`; `mailAdapter({ fallbackFromAddress, smtp, graph })`.
- R2: other storage-s3 options (prefix, clientUploads) → call `s3Storage` yourself instead of `buildR2Storage`.
- `forms: { adminGroup, fields, formOverrides, formSubmissionOverrides, beforeEmail, emailLayout }` (forms.md).
- `adminRoute: '/its'` — wymaga przeniesienia `app/(payload)/admin` → `its`, matchera proxy z `its` (etap 6)
i `robots: { adminRoute: false }` (etap 7).
- `adminRoute: '/its'` — requires moving `app/(payload)/admin` → `its`, a proxy matcher with `its` (stage 6)
and `robots: { adminRoute: false }` (stage 7).
## 4. Rdzeń — Pages, Media, rejestr bloków, prymitywy
## 4. Core — Pages, Media, block registry, primitives
**Kod.**
**Code.**
```ts
// src/collections/Pages.ts
import type { CollectionConfig } from 'payload'
@@ -205,67 +205,68 @@ export const Pages: CollectionConfig = {
},
}
```
`src/collections/Media.ts` = „Pełna kolekcja” z media.md 1:1 (`focalPoint: true`, `mimeTypes` obrazy + PDF + wideo,
`src/collections/Media.ts` = the "Full collection" from media.md 1:1 (`focalPoint: true`, `mimeTypes` images + PDF + video,
`alt` required+localized, `beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()]`,
pola `buildOptimizeUploadField()`, `buildMediaPlaceholderField()`); hooki używają `sharp` z `buildConfig`.
Bloki: `src/blocks/configs.ts` (`export const pageBlocks: Block[] = [HeroBlock]`) i `src/blocks/registry.ts`
(`export const blockRegistry = { hero: Hero }` — mapa `BlockComponentMap` z `/rsc`). Pierwszy blok (Hero) i prymitywy
`src/components/ui/` (CMSLink na `resolveLink`, Button, Media przez `mediaImageProps`/`videoProps`, Section,
SectionHeader) tworzysz **1:1** z `.agents/skills/ipal-block/resources/kod-sekcji.md` — przed każdym innym blokiem.
Żadnych innych kolekcji (treść z URL-ami → **ipal-collection**).
fields `buildOptimizeUploadField()`, `buildMediaPlaceholderField()`) plus `access: { read: () => true }` — media are
served through the app (`/api/media/file/…`, storage.md), whose file route checks `read`; the hooks use `sharp` from `buildConfig`.
Blocks: `src/blocks/configs.ts` (`export const pageBlocks: Block[] = [HeroBlock]`) and `src/blocks/registry.ts`
(`export const blockRegistry = { hero: Hero }` — a `BlockComponentMap` map from `/rsc`). Create the first block (Hero) and the
`src/components/ui/` primitives (CMSLink on `resolveLink`, Button, Media via `mediaImageProps`/`videoProps`, Section,
SectionHeader) **1:1** from `.agents/skills/ipal-block/resources/section-code.md` — before any other block.
No other collections (content with URLs → **ipal-collection**).
**Sprawdź.** `pnpm generate:types` → `payload-types.ts` ma `Page`, `Media`, `CmsLink`; panel → Media: plik
`Zdjęcie Test.JPG` zapisuje się jako `zdjecie-test.jpg`; Pages: zapis strony z blokiem Hero, slug wygenerowany
z tytułu, w sidebarze noindex, pole AI summary; zmiana sluga dopisuje `slugHistory`.
**Check.** `pnpm generate:types` → `payload-types.ts` has `Page`, `Media`, `CmsLink`; panel → Media: the file
`Zdjęcie Test.JPG` is saved as `zdjecie-test.jpg`; Pages: a page with a Hero block saves, the slug is generated
from the title, noindex in the sidebar, an AI summary field; changing the slug appends to `slugHistory`.
**Wyłącz / nadpisz.** Każde pole/hook jest opt-in (nie wpinasz = nie działa); `buildSlugField({ overrides })`
(np. `unique`), nazwy pól parametrami (`buildSummaryField` → inne pole + `summaryField` w etapie 6), progi
`buildOptimizeUploadHook({…})`; zamiast hooka sama funkcja (`normalizeFilename`). `buildRevalidateHook`
odświeża tylko kolekcje (globale — etap 3; wpisy archiwów — własny hook, hooks.md).
**Turn off / override.** Every field/hook is opt-in (not wired = not active); `buildSlugField({ overrides })`
(e.g. `unique`), field names via parameters (`buildSummaryField` → another field + `summaryField` in stage 6), thresholds of
`buildOptimizeUploadHook({…})`; the bare function instead of the hook (`normalizeFilename`). `buildRevalidateHook`
refreshes collections only (globals — stage 3; archive entries — your own hook, hooks.md).
## 5. Style
## 5. Styles
**Kod.** `postcss.config.mjs`: `export default { plugins: { '@tailwindcss/postcss': {} } }`.
**Code.** `postcss.config.mjs`: `export default { plugins: { '@tailwindcss/postcss': {} } }`.
```css
/* src/app/(frontend)/styles.css */
@import "tailwindcss";
@import "@intecion/ipal-kit/fluid.css"; /* albo fluid-wide.css (do 1920 px) — jeden z dwóch */
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js"; /* bez tego baner/Turnstile bez stylów */
@import "@intecion/ipal-kit/fluid.css"; /* or fluid-wide.css (up to 1920 px) — one of the two */
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js"; /* without this the banner/Turnstile have no styles */
@theme inline {
--text-display: var(--ipal-fs-display); --text-h1: var(--ipal-fs-h1); --text-h2: var(--ipal-fs-h2);
--text-h3: var(--ipal-fs-h3); --text-lead: var(--ipal-fs-lg);
--spacing-section: var(--ipal-space-section); --spacing-gutter: var(--ipal-space-gutter); --spacing-gap: var(--ipal-space-gap);
}
@theme { /* kolory, fonty, promienie z DESIGN.md (brak → zapytaj o Impeccable albo neutralne tokeny) */ }
:root { --ipal-primary: var(--color-primary); --ipal-radius: 0.5rem; /* liczby z DESIGN.md: --ipal-fs-h1: clamp(…) */ }
@theme { /* colors, fonts, radii from DESIGN.md (none → ask about Impeccable or use neutral tokens) */ }
:root { --ipal-primary: var(--color-primary); --ipal-radius: 0.5rem; /* numbers from DESIGN.md: --ipal-fs-h1: clamp(…) */ }
```
Fonty przez `next/font` z `subsets: ['latin', 'latin-ext']`, zmienną CSS podpiętą w `@theme` i na `<html>`
(AGENT.md §6.11, przykład w kod-sekcji.md → „Style”). Hero na `--ipal-hero-min-h` (§6.11a).
Fonts via `next/font` with `subsets: ['latin', 'latin-ext']`, a CSS variable wired in `@theme` and on `<html>`
(AGENT.md §6.11, example in section-code.md → "Styles"). Hero on `--ipal-hero-min-h` (§6.11a).
**Sprawdź.** Po etapie 6: `/pl` ma klasy `text-h1`/`py-section` działające, baner cookies ostylowany (kolor
`--ipal-primary`), polskie znaki w foncie; ekrany 360, 768, 1366×768, 1920 bez poziomego scrolla.
**Check.** After stage 6: on `/pl` the `text-h1`/`py-section` classes work, the cookie banner is styled (color
`--ipal-primary`), Polish characters render in the font; screens 360, 768, 1366×768, 1920 without horizontal scroll.
**Wyłącz / nadpisz.** `fluid*.css` opcjonalne (własna skala = nadpisane zmienne w `:root`, formuł nie piszesz od
zera); komponenty pluginu: tokeny `--ipal-*` (każdy z wariantem `-dark`) i `classNames` (consent.md).
**Turn off / override.** `fluid*.css` is optional (your own scale = overridden variables in `:root`; never write the formulas from
scratch); plugin components: `--ipal-*` tokens (each with a `-dark` variant) and `classNames` (consent.md).
## 6. Routing — proxy, warstwa danych, layout, catch-all, 404
## 6. Routing — proxy, data layer, layout, catch-all, 404
**Kod.**
**Code.**
```ts
// src/proxy.ts
import { NextResponse } from 'next/server'
import { createProxy } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
export const proxy = createProxy(i18nConfig, { NextResponse, markdown: true })
// LITERAŁ inline (import DEFAULT_PROXY_MATCHER = 500 na /admin); przy adminRoute '/its' wpisz `its` zamiast `admin`
// Inline LITERAL (importing DEFAULT_PROXY_MATCHER = 500 on /admin); with adminRoute '/its' write `its` instead of `admin`
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
```
`src/lib/content.ts` = PROGRAMISTA §2.7 1:1: `createContentHelpers({ config, content: contentConfig, i18n: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL, markdownAlternate: true, summaryField: 'aiSummary', mcp: { serverName:
'<klient>-site' } })` z destrukturyzacją wszystkich kluczy (dane, layout, linki, trasy). Firma lokalna:
`siteJsonLd` z `buildLocalBusinessJsonLd` + `formatOpeningHours` (seo.md). Pełna lista kluczy: ipal-reference.
'<client>-site' } })` destructuring all keys (data, layout, links, routes). Local business:
`siteJsonLd` with `buildLocalBusinessJsonLd` + `formatOpeningHours` (seo.md). Full key list: ipal-reference.
```tsx
// src/app/(frontend)/[locale]/layout.tsx — BEZ <head>, bez headers()
// src/app/(frontend)/[locale]/layout.tsx — NO <head>, no headers()
import { notFound } from 'next/navigation'
import { CookieBanner } from '@intecion/ipal-kit/client'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
@@ -281,7 +282,7 @@ export default async function LocaleLayout({ children, params }: Props) {
<body>
<SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent"
banner={<CookieBanner equalChoice settings="detailed" />}>
<main>{children}</main>{/* Header/Footer — etap 10 */}
<main>{children}</main>{/* Header/Footer — stage 10 */}
</SiteProviders>
</body>
</html>
@@ -289,38 +290,38 @@ export default async function LocaleLayout({ children, params }: Props) {
}
```
`src/app/(frontend)/[locale]/actions.ts` = `.agents/skills/ipal-form/resources/actions.ts` 1:1
(`createSubmitAction({ getCachedPayload, headers })` z `@intecion/ipal-kit/server`, eksport `sendForm`).
`src/app/(frontend)/[locale]/[[...slug]]/page.tsx` (**podwójne** nawiasy) = PROGRAMISTA §2.8 1:1:
`export const revalidate = 3600` (literał), `createPageRoute(content, { blocks: blockRegistry, notFound,
(`createSubmitAction({ getCachedPayload, headers })` from `@intecion/ipal-kit/server`, exports `sendForm`).
`src/app/(frontend)/[locale]/[[...slug]]/page.tsx` (**double** brackets) = PROGRAMISTA §2.8 1:1:
`export const revalidate = 3600` (literal), `createPageRoute(content, { blocks: blockRegistry, notFound,
permanentRedirect, blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }) })`,
eksporty `route.Page`, `route.generateMetadata`, `route.generateStaticParams`.
exports `route.Page`, `route.generateMetadata`, `route.generateStaticParams`.
`notFoundView.ts` (`'use server'`, `loadNotFoundView(locale)` → `renderNotFoundView(content, { blocks: blockRegistry }, locale)`)
i `not-found.tsx` (`export default createNotFoundPage(content, { load: loadNotFoundView })`) — oba z `/rsc`, PROGRAMISTA §2.8.
and `not-found.tsx` (`export default createNotFoundPage(content, { load: loadNotFoundView })`) — both from `/rsc`, PROGRAMISTA §2.8.
**Sprawdź.** `curl -sI localhost:3000/ | grep -i location` → `/pl`; po etapie 11 (Homepage w System Pages)
`curl -s -A Googlebot localhost:3000/pl | grep -o '<link rel="canonical"[^>]*>'` — w `<head>`, plus `hreflang`
i `rel="alternate" type="text/markdown"`; `/pl/nie-ma-takiej` → 404 z treścią z panelu; `/admin` i `/_next` → bez 500;
`pnpm build` pokazuje `●` (SSG) przy `[[...slug]]`.
**Check.** `curl -sI localhost:3000/ | grep -i location` → `/pl`; after stage 11 (Homepage in System Pages)
`curl -s -A Googlebot localhost:3000/pl | grep -o '<link rel="canonical"[^>]*>'` — in `<head>`, plus `hreflang`
and `rel="alternate" type="text/markdown"`; `/pl/nie-ma-takiej` → 404 with content from the panel; `/admin` and `/_next` → no 500;
`pnpm build` shows `●` (SSG) next to `[[...slug]]`.
**Wyłącz / nadpisz.**
- `createProxy`: `markdown: '/ai'` (inny prefiks), `exposeHeaders: false`, `cookieName`, `consentCategory`;
w pełni własne proxy na `createLocaleMiddleware`. Matcher należy do projektu.
- `createContentHelpers`: każdy klucz pomijasz albo zastępujesz własną funkcją o tej nazwie w `lib/content.ts`;
`siteJsonLd: false` (bez WebSite/Organization), `pageJsonLd`, `robots`, `sitemapStyle`, `markdownAlternate: false`.
- `createPageRoute`: `render` (własny widok, np. archiwum), `onMissing: 'redirectHome'`, `jsonLd: false`,
`homeAlias: false`, `layoutField`; całkiem własna strona na `resolveRoute` (pages.md).
`generateStaticParams` obejmuje **tylko kolekcję stron, do 1000 na język** — zakres obecnie stały (wpisy → ISR).
- `SiteProviders`: `banner={false}` / własny, `cookieButton={false}`, `analytics={false}` / `{{ defer: true }}`,
`preconnect={false}`, `jsonLd={[…]}` (dodaje), `cookieMap`, `theme`, `stats`; `JsonLdGraph` i
`TurnstileProvider` obecnie zawsze (Turnstile sam się wyłącza bez kluczy). Całkiem własny układ: providery z `/client`
z danymi z `shell` (consent.md).
- 404: `createNotFoundPage` z `blocks` / `fallback` albo własny `not-found.tsx`.
**Turn off / override.**
- `createProxy`: `markdown: '/ai'` (another prefix), `exposeHeaders: false`, `cookieName`, `consentCategory`;
a fully custom proxy on `createLocaleMiddleware`. The matcher belongs to the project.
- `createContentHelpers`: skip any key or replace it with your own function of that name in `lib/content.ts`;
`siteJsonLd: false` (no WebSite/Organization), `pageJsonLd`, `robots`, `sitemapStyle`, `markdownAlternate: false`.
- `createPageRoute`: `render` (your own view, e.g. an archive), `onMissing: 'redirectHome'`, `jsonLd: false`,
`homeAlias: false`, `layoutField`; a fully custom page on `resolveRoute` (pages.md).
`generateStaticParams` covers **only the pages collection, up to 1000 per language** — the scope is currently fixed (entries → ISR).
- `SiteProviders`: `banner={false}` / your own, `cookieButton={false}`, `analytics={false}` / `{{ defer: true }}`,
`preconnect={false}`, `jsonLd={[…]}` (adds), `cookieMap`, `theme`, `stats`; `JsonLdGraph` and
`TurnstileProvider` currently always (Turnstile turns itself off without keys). A fully custom layout: providers from `/client`
with data from `shell` (consent.md).
- 404: `createNotFoundPage` with `blocks` / `fallback`, or your own `not-found.tsx`.
## 7. SEO, bezpieczeństwo, operacje
## 7. SEO, security, operations
**Kod.** Każda trasa to re-eksport z `lib/content` (bez nic w `public/`, jeden sitemap — nigdy obok `sitemap.ts`):
**Code.** Every route is a re-export from `lib/content` (nothing in `public/`, one sitemap — never next to `sitemap.ts`):
| Plik | Treść |
| File | Content |
|---|---|
| `src/app/sitemap.xml/route.ts` | `export { sitemapRoute as GET } from '@/lib/content'` + `export const dynamic = 'force-dynamic'` |
| `src/app/robots.ts` | `export { robots as default } from '@/lib/content'` |
@@ -345,147 +346,167 @@ export default withPayload({
})
```
```ts
// src/instrumentation.ts — import z /env (root ciągnie Payload → crash Edge/Turbopack)
// src/instrumentation.ts — import from /env (the root pulls in Payload → Edge/Turbopack crash)
import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'
export function register() {
if (process.env.NEXT_RUNTIME !== 'nodejs') return
assertEnv(ipalEnvRules({ storage: true, ipHeader: true /* , emailGraph: true przy Graph */ }))
// R2_PUBLIC_URL optional: media served through the app by default (storage.md, env.md)
assertEnv(
ipalEnvRules({ storage: true, ipHeader: true /* , emailGraph: true with Graph */ }).map((r) =>
r.name === 'R2_PUBLIC_URL' ? { ...r, required: false } : r,
),
)
}
```
**Sprawdź.** `curl -s localhost:3000/sitemap.xml | head` → `<urlset` z `xhtml:link hreflang`; w przeglądarce
styl „XML Sitemap”; `curl -s localhost:3000/robots.txt` → `Sitemap:`, `Disallow: /admin`, boty AI (GPTBot,
ClaudeBot…) z `Allow`; `/manifest.webmanifest` → JSON z nazwą z Site Settings; `/api/health` → `200`
(`503` bez bazy); `curl -sI localhost:3000/pl | grep -i 'x-frame-options\|content-security-policy-report-only'`;
pusty `PAYLOAD_SECRET` w `.env` → `pnpm dev` kończy się listą brakujących zmiennych (przywróć).
**Check.** `curl -s localhost:3000/sitemap.xml | head` → `<urlset` with `xhtml:link hreflang`; in the browser
the "XML Sitemap" style; `curl -s localhost:3000/robots.txt` → `Sitemap:`, `Disallow: /admin`, AI bots (GPTBot,
ClaudeBot…) with `Allow`; `/manifest.webmanifest` → JSON with the name from Site Settings; `/api/health` → `200`
(`503` without a database); `curl -sI localhost:3000/pl | grep -i 'x-frame-options\|content-security-policy-report-only'`;
an empty `PAYLOAD_SECRET` in `.env` → `pnpm dev` exits with a list of missing variables (restore it).
**Wyłącz / nadpisz.** `robots`: `aiBots: 'block-training' | 'disallow' | false` (tylko z decyzji klienta →
`ipal-audit-skip: aibots`), `adminRoute: false` (ukryty panel), `extraDisallow`; `sitemapStyle: false` (surowy XML)
lub własny tekst; `buildSecurityHeaders({ frameOptions, coop, hsts, additional })` — `additional` z tym samym kluczem
nadpisuje domyślny; CSP: flagi `buildCsp` (`youtube`, `googleMaps`, `extra`), po czystej konsoli `mode: 'enforce'`;
`buildImagesConfig({ extraHosts })`; walidacja env w pełni opt-in — reguły filtrujesz/dopisujesz
**Turn off / override.** `robots`: `aiBots: 'block-training' | 'disallow' | false` (only on a client decision →
`ipal-audit-skip: aibots`), `adminRoute: false` (hidden panel), `extraDisallow`; `sitemapStyle: false` (raw XML)
or your own text; `buildSecurityHeaders({ frameOptions, coop, hsts, additional })` — an `additional` entry with the same key
overrides the default; CSP: `buildCsp` flags (`youtube`, `googleMaps`, `extra`), after a clean console `mode: 'enforce'`;
`buildImagesConfig({ extraHosts })`; env validation is fully opt-in — filter/add rules
(`ipalEnvRules(…).filter(…)`). Staging: `IPAL_NOINDEX=1`.
## 8. GEO (obowiązkowe)
## 8. GEO (mandatory)
**Kod.** Re-eksporty z `lib/content`, każdy z `export const dynamic = 'force-dynamic'`:
**Code.** Re-exports from `lib/content`, each with `export const dynamic = 'force-dynamic'`:
| Plik | Treść |
| File | Content |
|---|---|
| `src/app/llms.txt/route.ts` | `export { llmsRoute as GET } from '@/lib/content'` |
| `src/app/llms-full.txt/route.ts` | `export { llmsFullRoute as GET } from '@/lib/content'` |
| `src/app/md/[locale]/[[...slug]]/route.ts` (jeden język: `src/app/md/[[...slug]]/route.ts`) | `export { markdownRoute as GET } from '@/lib/content'` |
| `src/app/api/mcp/route.ts` (publiczny) | `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` |
| `src/app/md/[locale]/[[...slug]]/route.ts` (one language: `src/app/md/[[...slug]]/route.ts`) | `export { markdownRoute as GET } from '@/lib/content'` |
| `src/app/api/mcp/route.ts` (public) | `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` |
| `src/app/indexnow-key.txt/route.ts` | `export { indexNowKeyRoute as GET } from '@/lib/content'` |
Wymagane już wpięte: `markdown: true` (etap 6 proxy), `markdownAlternate`, `summaryField`, `mcp` (lib/content),
`buildSummaryField` (Pages), `indexNow: true` (payload.config), boty AI w robots (etap 7).
Already wired and required: `markdown: true` (stage 6 proxy), `markdownAlternate`, `summaryField`, `mcp` (lib/content),
`buildSummaryField` (Pages), `indexNow: true` (payload.config), AI bots in robots (stage 7).
**Sprawdź.** `curl -s localhost:3000/llms.txt` → nazwa strony i lista stron z opisami (`aiSummary`);
`/llms-full.txt` → treść stron; `curl -s localhost:3000/md/pl` → Markdown strony głównej; `curl -s -H 'Accept:
text/markdown' localhost:3000/pl` → ten sam Markdown; `curl -s -X POST localhost:3000/api/mcp -H 'content-type:
**Check.** `curl -s localhost:3000/llms.txt` → site name and a list of pages with descriptions (`aiSummary`);
`/llms-full.txt` → page content; `curl -s localhost:3000/md/pl` → Markdown of the home page; `curl -s -H 'Accept:
text/markdown' localhost:3000/pl` → the same Markdown; `curl -s -X POST localhost:3000/api/mcp -H 'content-type:
application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'` → `get_site_info`, `list_pages`,
`search_content`, `get_page`; `/indexnow-key.txt` → `404` do czasu wygenerowania klucza w panelu, potem klucz.
`search_content`, `get_page`; `/indexnow-key.txt` → `404` until the key is generated in the panel, then the key.
**Wyłącz / nadpisz.** Brak pliku trasy = brak funkcji (dozwolone tylko z `ipal-audit-skip: llms | llms-full |
markdown | mcp`); prefiks Markdown: `createProxy({ markdown: '/ai' })` + własny folder; MCP: `mcp: { rateLimit:
false | { max, windowMs }, serverVersion, maxBatch, clientIp }`, więcej opcji → `createMcpRoute` (mcp.md), lista
narzędzi obecnie stała; Markdown bloków: `markdown: { overrides }` w `createContentHelpers`; IndexNow: bez
`indexNow` (działa tylko na produkcji), klucz z panelu albo `INDEXNOW_KEY`.
**Turn off / override.** No route file = no feature (allowed only with `ipal-audit-skip: llms | llms-full |
markdown | mcp`); Markdown prefix: `createProxy({ markdown: '/ai' })` + your own folder; MCP: `mcp: { rateLimit:
false | { max, windowMs }, serverVersion, maxBatch, clientIp }`, more options → `createMcpRoute` (mcp.md), the tool
list is currently fixed; block Markdown: `markdown: { overrides }` in `createContentHelpers`; IndexNow: without
`indexNow` (works only in production), key from the panel or `INDEXNOW_KEY`.
## 9. Formularze i cookies
## 9. Forms and cookies
**Kroki.** Skill **ipal-form**: blok z `<RenderForm>` (`/rsc`), `src/components/forms/formClasses.ts`, akcja z etapu 6
(jedna na projekt), każdy formularz z **seeda** `scripts/seed-form-*.ts` (mail do firmy + potwierdzenie do klienta,
każdy język, checkbox zgody). Cookies: skill **ipal-consent-check** — `cookie-scan.mjs` → `import-cookies.ts` do
Cookie Settings → Cookies; na stronie polityki cookies blok z `<CookieTable>` (`/rsc`, dane z `getCookieTable`);
ta sama lista jest w oknie `settings="detailed"` (podpisy: Cookie Settings → Detail labels, każdy język).
**Steps.** Skill **ipal-form**: a block with `<RenderForm>` (`/rsc`), `src/components/forms/formClasses.ts`, the action from stage 6
(one per project), every form from a **seed** `scripts/seed-form-*.ts` (email to the company + confirmation to the customer,
every language, consent checkbox). Cookies: skill **ipal-consent-check** — `cookie-scan.mjs` → `import-cookies.ts` into
Cookie Settings → Cookies; on the cookie policy page a block with `<CookieTable>` (`/rsc`, data from `getCookieTable`);
the same list appears in the `settings="detailed"` dialog (labels: Cookie Settings → Detail labels, every language).
**Sprawdź.** Panel → Forms: formularz z seeda; wysłanie na `/pl` → wpis w Form Submissions + 2 maile (SMTP:
Site Integrations → SMTP → Send test); z testowymi kluczami Turnstile widget widoczny, bez tokenu odrzucenie;
`node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl` = 0 błędów;
po decyzji w banerze nowy rekord w Consent records.
**Check.** Panel → Forms: the seeded form; a submission on `/pl` → an entry in Form Submissions + 2 emails (SMTP:
Site Integrations → SMTP → Send test); with Turnstile test keys the widget is visible, without a token the submission is rejected;
`node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl` = 0 errors;
after a choice in the banner a new record in Consent records.
**Wyłącz / nadpisz.** Turnstile: puste oba klucze (panel i env) → bez widgetu i weryfikacji; fail-closed
`turnstileOnConfigError: 'reject'`; pola Turnstile/SMTP w Site Integrations obecnie zawsze. Wygląd formularza:
`formClasses`, nietypowy → `useBuilderForm` (bez kopii silnika). Baner: `settings`, `controls`, `order`,
`equalChoice`, `classNames`, tokeny; brak `consentLog` = brak rejestru i endpointu (`logEndpoint` wtedy usuń).
**GA4/GTM ładują się przed zgodą w Consent Mode v2 z `denied`** (piksele i Clarity dopiero po zgodzie) — obecnie
zawsze, trybu basic nie da się włączyć opcją; klient wymagający zera żądań do Google → zapisz w raporcie /
**ipal-plugin-gap**. Analityka: puste ID w panelu albo `analytics={false}`.
**Turn off / override.** Turnstile: both keys empty (panel and env) → no widget and no verification; fail-closed
`turnstileOnConfigError: 'reject'`; the Turnstile/SMTP fields in Site Integrations currently always. Form look:
`formClasses`, unusual ones → `useBuilderForm` (no copy of the engine). Banner: `settings`, `controls`, `order`,
`equalChoice`, `classNames`, tokens; no `consentLog` = no register and no endpoint (then remove `logEndpoint`).
**GA4/GTM load before consent in Consent Mode v2 with `denied`** (pixels and Clarity only after consent) — currently
always, basic mode cannot be turned on by an option; a client requiring zero requests to Google → note it in the report /
**plugin gap** (`ipal-plugin-gap`). Analytics: empty IDs in the panel or `analytics={false}`.
## 10. Nawigacja
## 10. Navigation
**Kroki.** Skill **ipal-nav**: globale Header/Footer/Company (`buildLinkField`/`buildLinksField`, `resolveNav`,
linki prawne przez `getSystemLinks(locale)`), `afterChange` z `revalidatePath('/', 'layout')` na **własnych**
globalach (`revalidateEverything` z etapu 3), Header/Footer w layoucie, opcjonalnie
**Steps.** Skill **ipal-nav**: Header/Footer/Company globals (`buildLinkField`/`buildLinksField`, `resolveNav`,
legal links via `getSystemLinks(locale)`), `afterChange` with `revalidatePath('/', 'layout')` on **your own**
globals (`revalidateEverything` from stage 3), Header/Footer in the layout, optionally
`<SiteProviders jsonLd={[buildNavigationJsonLd(…)]}>`.
**Sprawdź.** Zmiana pozycji menu w panelu widoczna na `/pl` od razu po zapisie; link do strony w EN prowadzi na
`/en/…`; stopka ma linki prawne w języku strony.
**Check.** A menu item change in the panel is visible on `/pl` right after saving; a link to a page in EN leads to
`/en/…`; the footer has legal links in the page language.
**Wyłącz / nadpisz.** Nawigacja jest w całości kodem projektu (plugin daje pola i resolvery); `buildLinkField({
relationTo, appearances: false, disableLabel })`, `LanguageSwitcher` (`classNames`, `renderLabel`) albo własny na
**Turn off / override.** Navigation is entirely project code (the plugin provides fields and resolvers); `buildLinkField({
relationTo, appearances: false, disableLabel })`, `LanguageSwitcher` (`classNames`, `renderLabel`) or your own on
`useAlternateLinks()`.
### Moduły na życzenie (poza kompletem; osobny commit, wpis w „Ustaleniach”)
- Statystyki: `stats: true` + `<SiteProviders stats>` + `pnpm payload generate:importmap`; `/admin/stats`.
Off: bez opcji; `stats: { dashboard: false }` chowa tylko wykres.
- Motyw jasny/ciemny: `<SiteProviders theme>` + `<ThemeSwitcher>` (theme.md). Off: bez propa.
- Ukryty panel: `adminRoute` (etap 3) — folder `app/(payload)/<route>`, matcher proxy, `robots.adminRoute: false`.
- Tryb budowy (construction.md), widżet dostępności (accessibility.md — tylko gdy wymagany, EAA).
### Optional modules (outside the set; separate commit, entry in "Project decisions")
- Statistics: `stats: true` + `<SiteProviders stats>` + `pnpm payload generate:importmap`; `/admin/stats`.
Off: no option; `stats: { dashboard: false }` hides only the chart.
- Light/dark theme: `<SiteProviders theme>` + `<ThemeSwitcher>` (theme.md). Off: no prop.
- Hidden panel: `adminRoute` (stage 3) — folder `app/(payload)/<route>`, proxy matcher, `robots.adminRoute: false`.
- Under-construction mode (construction.md), accessibility widget (accessibility.md — only when required, EAA).
## 11. Kontrola kompletu
## 11. Completeness check
**Komendy (wszystko musi przejść):**
**Commands (all must pass):**
```bash
pnpm generate:types && pnpm payload generate:importmap
pnpm payload migrate:create # tylko Postgres z migracjami
bash .agents/skills/ipal-audit/scripts/audit.sh # pełny: §0b „missing: …” = 0, tsc, build
pnpm payload migrate:create # Postgres with migrations only
bash .agents/skills/ipal-audit/scripts/audit.sh # full: §0b "missing: …" = 0, tsc, build
pnpm build && pnpm start
node .agents/skills/ipal-seo-check/scripts/seo-check.mjs http://localhost:3000 # 0 błędów
node .agents/skills/ipal-seo-check/scripts/seo-check.mjs http://localhost:3000 # 0 errors
node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/pl
```
Lista §0b z kontrolą: proxy + catch-all + 404 (etap 6) · meta, sitemap, robots, manifest (7) · JSON-LD (6, 10) ·
llms, llms-full, Markdown, MCP, boty AI, IndexNow (8) · Media/R2 (3–4) · formularze z seeda (9) · Turnstile (9) ·
zgoda + rejestr + analityka (6, 9) · nagłówki, 2FA, CSP report-only, `IPAL_IP_HEADER` (3, 7) · health, env,
`IPAL_NOINDEX` na stagingu (7) · strony systemowe (panel niżej) · zero hardkodów (audit) · treść (AGENT.md §0c) ·
skalowanie (5). Trasy `●` przy stronach wymagają bazy w czasie buildu (PROGRAMISTA §4.3).
The §0b list with its checks: proxy + catch-all + 404 (stage 6) · meta, sitemap, robots, manifest (7) · JSON-LD (6, 10) ·
llms, llms-full, Markdown, MCP, AI bots, IndexNow (8) · Media/R2 (3–4) · seeded forms (9) · Turnstile (9) ·
consent + register + analytics (6, 9) · headers, 2FA, CSP report-only, `IPAL_IP_HEADER` (3, 7) · health, env,
`IPAL_NOINDEX` on staging (7) · system pages (panel below) · zero hardcoding (audit) · content (AGENT.md §0c) ·
scaling (5). `●` routes for pages need the database at build time (PROGRAMISTA §4.3).
**Kroki w panelu dla użytkownika** (`/admin`, wklej mu tę listę z brakami z raportu):
1. Pierwszy użytkownik z rolą **admin** + konfiguracja 2FA (aplikacja TOTP).
2. **Site Settings → General**: nazwa witryny, logo, favicon (PNG), opis.
3. **Pages**: strona główna (tytuł i slug **w każdym języku**, inaczej `/en` → 404), 404, polityka prywatności,
polityka cookies (z blokiem `CookieTable`), regulamin jeśli potrzebny; `noindex` na politykach; AI summary.
4. **Site Settings → System Pages**: Homepage (bez tego `/pl` → 404), 404, polityki; archiwa kolekcji treści.
5. **Cookie Settings**: teksty banera, Privacy link label, Policy version, Cookies (import ze skanu), Detail labels —
w każdym języku.
6. **Notifications**: komunikaty formularzy w każdym języku.
7. **Site Integrations**: SMTP albo Graph (From Name/Address; Send test), Turnstile (testowo site
`1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; produkcyjne od klienta), ID
analityki/pikseli, IndexNow → generuj klucz. Błędy maila/Turnstile pokazuje alert na dashboardzie.
8. **Forms**: sprawdź adresy w zakładce Emails formularzy z seeda.
**Panel steps for the user** (`/admin`, paste them this list with the gaps from the report):
1. First user with the **admin** role + 2FA setup (TOTP app).
2. **Site Settings → General**: site name, logo, favicon (PNG), description.
3. **Pages**: home page (title and slug **in every language**, otherwise `/en` → 404), 404, privacy policy,
cookie policy (with the `CookieTable` block), terms if needed; `noindex` on the policies; AI summary.
4. **Site Settings → System Pages**: Homepage (without it `/pl` → 404), 404, policies; content collection archives.
5. **Cookie Settings**: banner texts, Privacy link label, Policy version, Cookies (import from the scan), Detail labels —
in every language.
6. **Notifications**: form messages in every language.
7. **Site Integrations**: SMTP or Graph (From Name/Address; Send test), Turnstile (for testing site
`1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`; production keys from the client), analytics/pixel
IDs, IndexNow → generate key. Mail/Turnstile errors show up as a dashboard alert.
8. **Forms**: check the addresses in the Emails tab of the seeded forms.
**Rekordy DNS dla zespołu** (strefy prowadzi nasz zespół; plugin niczego w DNS nie ustawia — Ty
przygotowujesz listę z wartościami, człowiek dodaje, Ty sprawdzasz `dig`). Pełna tabela:
**Deployment (Coolify — the only path; the user/team does it, you prepare the inputs).** Full procedure:
`node_modules/@intecion/ipal-kit/docs/deployment.md` §4. Hand over:
- the env list for the Coolify app, each marked **build time** and/or **runtime** — `NEXT_PUBLIC_*` both; secrets
(`PAYLOAD_SECRET`, `R2_*`, `GRAPH_*`, `TURNSTILE_SECRET_KEY`, `IPAL_IP_HEADER`) runtime; `DATABASE_URI` /
`PAYLOAD_SECRET` also build time when pages are prerendered from the database (§3a3);
- domains `https://client.pl,https://www.client.pl` with the www ↔ apex redirect matching `NEXT_PUBLIC_SERVER_URL`;
port 3000; health check `/api/health`;
- Postgres: migrations run on container start — `postgresAdapter({ …, prodMigrations: migrations })` (import from
`./migrations`) or the start command `pnpm payload migrate && pnpm start`; never Coolify's Pre-/Post-deployment
command (pre = old container, skipped on the first deploy; post = after traffic switched). Backward-compatible
migrations only. Mongo: none;
- scheduled database backups to S3/R2 and **Backup now** before a production seed (Coolify Terminal: dry run →
backup → real run; rules: `node_modules/@intecion/ipal-kit/docs/seeding.md`) or a big migration; rollback (Coolify → Rollback) does not undo migrations;
- no R2 → a Coolify persistent volume for the media directory.
**DNS records for the team** (our team manages the zones; the plugin sets nothing in DNS — you
prepare the list with values, a human adds them, you verify with `dig`). Full table:
`node_modules/@intecion/ipal-kit/docs/deployment.md` §6.
| Rekord | Wartość | Sprawdź |
| Record | Value | Check |
|---|---|---|
| `A`/`AAAA` apex + `CNAME www` | host z hostingu | `dig +short klient.pl A`, `dig +short www.klient.pl` |
| `CAA` (tylko gdy strefa ma CAA) | `0 issue "letsencrypt.org"` / CA hostingu | `dig +short klient.pl CAA` |
| `TXT` apex — Search Console (usługa *Domena*) | `google-site-verification=<kod>` | `dig +short TXT klient.pl \| grep google-site` → GSC → Zweryfikuj |
| Bing (jeśli używany) | import z GSC w Bing (bez DNS) albo `CNAME <kod>` → `verify.bing.com` | `dig +short CNAME <kod>.klient.pl` |
| `TXT` SPF domeny From | `v=spf1 include:<dostawca> -all` — jeden rekord na domenę | `dig +short TXT <domena> \| grep v=spf1` |
| DKIM | `CNAME selector1._domainkey` / `selector2…` (M365) lub `TXT <selektor>._domainkey` | `dig +short CNAME selector1._domainkey.<domena>` |
| `TXT _dmarc` | `v=DMARC1; p=none; rua=mailto:dmarc@<domena>` → później `p=quarantine` | `dig +short TXT _dmarc.<domena>` |
| Media R2 (`media.klient.pl`) | Custom Domain w Cloudflare R2 — wymaga strefy w Cloudflare | `curl -sI https://media.klient.pl/<plik>` → 200 |
| `A`/`AAAA` apex + `CNAME www` (or `A`) | IP of the Coolify server running the app | `dig +short client.pl A`, `dig +short www.client.pl`; `curl -sI https://www.client.pl` → 301/308 to the `NEXT_PUBLIC_SERVER_URL` host |
| `CAA` (only when the zone has CAA) | `0 issue "letsencrypt.org"` — Coolify's proxy uses Let's Encrypt (HTTP challenge: port 80 open) | `dig +short client.pl CAA` |
| `TXT` apex — Search Console (*Domain* property) | `google-site-verification=<code>` | `dig +short TXT client.pl \| grep google-site` → GSC → Verify |
| Bing (if used) | import from GSC in Bing (no DNS) or `CNAME <code>` → `verify.bing.com` | `dig +short CNAME <code>.client.pl` |
| `TXT` SPF of the From domain | `v=spf1 include:<provider> -all` — one record per domain | `dig +short TXT <domain> \| grep v=spf1` |
| DKIM | `CNAME selector1._domainkey` / `selector2…` (M365) or `TXT <selector>._domainkey` | `dig +short CNAME selector1._domainkey.<domain>` |
| `TXT _dmarc` | `v=DMARC1; p=none; rua=mailto:dmarc@<domain>` → later `p=quarantine` | `dig +short TXT _dmarc.<domain>` |
| R2 media | **none by default** — `R2_PUBLIC_URL` empty, media through the app. An R2 Custom Domain needs the zone in our Cloudflare account (CNAME setup = Business/Enterprise), so `media.client.pl` on our DNS does not work; media-heavy site → a separate media domain on Cloudflare. `*.r2.dev` = dev only | `curl -sI https://client.pl/api/media/file/<file>` → 200 without login |
Domena From: SMTP z panelu → domena z *From address* (rekordy od dostawcy skrzynki); Graph → From to
zawsze `GRAPH_SENDER` (domena agencji, ustawiona raz — w projekcie nic). Po DNS: *Send test* i w odebranym
mailu `Authentication-Results: spf=pass dkim=pass dmarc=pass`. Search Console weryfikujemy **DNS-em** —
pola weryfikacji meta tagiem w Site Settings (jeśli są) zostają **puste**; mapę `https://klient.pl/sitemap.xml`
zgłaszasz raz ręcznie w GSC i Bing (bez API). Turnstile, IndexNow, llms, MCP — bez DNS.
From domain: SMTP from the panel → the domain of the *From address* (records from the mailbox provider); Graph → From is
always `GRAPH_SENDER` (agency domain, set once — nothing in the project). After DNS: *Send test* and in the received
email `Authentication-Results: spf=pass dkim=pass dmarc=pass`. We verify Search Console **via DNS** —
meta-tag verification fields in Site Settings (if any) stay **empty**; submit the sitemap `https://client.pl/sitemap.xml`
once by hand in GSC and Bing (no API). Turnstile, IndexNow, llms, MCP — no DNS.
Raport końcowy: co wpięte, czego brakuje (dane, klucze, decyzje), lista rekordów DNS z wartościami (status `dig`), każdy `ipal-audit-skip`, ewentualne
**ipal-plugin-gap**. Dalej: bloki (**ipal-block**), kolekcje treści (**ipal-collection**).
Final report: what is wired, what is missing (data, keys, decisions), the DNS record list with values (`dig` status), every `ipal-audit-skip`, any
**plugin gap** (`ipal-plugin-gap`). Next: blocks (**ipal-block**), content collections (**ipal-collection**).
+106 -103
View File
@@ -5,128 +5,131 @@ description: Builds a complete client website on ipal-kit from a brief to handov
# ipal-site
Prowadzisz projekt jak samodzielny wykonawca (AGENT.md §0a): decyzje techniczne
podejmujesz sam, pytasz raz o brakujące dane, przewidujesz problemy, sprawdzasz
swoją pracę, a na końcu oddajesz raport. Użytkownik nie powinien musieć Cię
prowadzić ani poprawiać.
You run the project as an independent contractor (AGENT.md §0a): you make technical
decisions yourself, ask once for missing data, anticipate problems, check
your own work, and hand over a report at the end. The user should not have to
guide or correct you.
**Rytm:** jedna faza = jeden commit (`feat(site): faza N — <co>`). Nie czekasz na OK
między fazami. Przed fazą przejdź tabelę „Przewidujesz” z AGENT.md §0a.
**Rhythm:** one phase = one commit (`feat(site): phase N — <what>`). Do not wait for an OK
between phases. Before each phase, go through the "Anticipate" table in AGENT.md §0a.
## Faza 0 — Rozpoznanie i jedna lista pytań
1. Przeczytaj: brief (wszystkie załączniki), `AGENTS.md`, `DESIGN.md`/`PRODUCT.md`,
`package.json` (wersja ipal-kit), istniejący kod. Nowy projekt czy dokończenie?
2. Spisz w `AGENTS.md` → „Mapa strony”: strony (z briefu), sekcje na każdej,
formularze, języki, kolekcje (tylko jeśli są listy z URL-ami — ipal-collection).
3. **Jedna lista pytań** — tylko to, czego nie ma w briefie i nie da się ustalić
samemu, każde z **domyślną odpowiedzią**, którą przyjmiesz bez odpowiedzi:
## Phase 0 — Discovery and one question list
1. Read: the brief (all attachments), `AGENTS.md`, `DESIGN.md`/`PRODUCT.md`,
`package.json` (ipal-kit version), existing code. New project or finishing one?
2. Write into `AGENTS.md` → "Site map": pages (from the brief), sections on each,
forms, languages, collections (only if there are lists with URLs — ipal-collection).
3. **One question list** — only what is not in the brief and cannot be settled
yourself, each with a **default answer** you will use if there is no reply:
```
Zanim skończę, potrzebuję (jeśli nie odpowiesz, przyjmuję wartość w nawiasie):
1. Języki strony? (pl + en — jak w briefie)
2. Domena produkcyjna? (placeholder w .env, canonical ustawię po wdrożeniu)
3. Dane firmy: NIP, adres, telefon? ([DO UZUPEŁNIENIA] w panelu)
4. Na jaki adres wysyłać zgłoszenia z formularza? (bez tego seed formularza się nie uruchomi — to jedyne pytanie, bez którego nie oddam formularzy)
5. Analityka: ID GA4/GTM/pikseli? (wyłączona do czasu wpisania ID w panelu)
6. Dane R2: bucket, endpoint, klucze, domena mediów? (R2 jest wpięty zawsze; do czasu kluczy media lokalnie w dev)
7. Klucze Turnstile? (testowe w dev; produkcyjne wpiszesz w Site Integrations)
8. Dostęp AI do treści (llms.txt, Markdown, MCP, boty AI)? (włączony — wyłączam tylko na Twoje wyraźne życzenie)
9. Tłumaczenia: robię wersje robocze do akceptacji? (tak, oznaczone w raporcie)
Before I finish, I need (if you don't answer, I'll use the value in brackets):
1. Site languages? (pl + en — as in the brief)
2. Production domain? (placeholder in .env, I'll set canonical after deployment)
3. Company data: tax ID (NIP), address, phone? ([TO FILL] in the panel)
4. Which address should form submissions go to? (without it the form seed won't run — the only question without which I can't deliver forms)
5. Analytics: GA4/GTM/pixel IDs? (off until the IDs are entered in the panel)
6. R2 details: bucket, endpoint, keys, media domain? (R2 is always wired; until the keys arrive, media stay local in dev)
7. Turnstile keys? (test keys in dev; you'll enter production keys in Site Integrations)
8. AI access to content (llms.txt, Markdown, MCP, AI bots)? (on — I turn it off only at your explicit request)
9. Translations: should I make drafts for approval? (yes, marked in the report)
```
Wyślij listę i **pracuj dalej** na wartościach domyślnych. Odpowiedzi wpisujesz,
gdy przyjdą. Zatrzymujesz się tylko przed decyzją nieodwracalną (AGENT §0a).
Send the list and **keep working** on the default values. Fill in the answers
when they arrive. Stop only before an irreversible decision (AGENT §0a).
## Faza 1 — Fundament
- Nowy projekt → **ipal-setup** (całość, z `ipal-skills`, `AGENTS.md`).
- Istniejący na starszym ipal-kit → **ipal-upgrade** przed czymkolwiek innym.
- Wyjście: `pnpm build` przechodzi, `/admin` działa, `ipal-audit --quick` = 0 błędów —
**także zero „missing: …”**, czyli komplet AGENT.md §0b (SEO, GEO, R2, Turnstile,
formularze, consent, bezpieczeństwo) wpięty od pierwszej fazy, nie na końcu.
## Phase 1 — Foundation
- New project → **ipal-setup** (all of it, with `ipal-skills`, `AGENTS.md`).
- 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,
forms, consent, security) wired from the first phase, not at the end.
## Faza 2 — Model treści
- Strony = `Pages` + bloki. Kolekcje tylko dla list z URL-ami (**ipal-collection**).
- Globale: Header, Footer, Company (**ipal-nav**), Site Settings, System Pages.
- Każda sekcja z mapy strony → blok istniejący, wariant istniejącego (`variant`)
albo nowy blok. Cel: jak najmniej bloków, maksimum wariantów.
- Zmiana schematu z treścią w bazie → **ipal-migrate-fields**, nigdy „na żywo”.
## Phase 2 — Content model
- Pages = `Pages` + blocks. Collections only for lists with URLs (**ipal-collection**).
- Globals: Header, Footer, Company (**ipal-nav**), Site Settings, System Pages.
- Every section from the site map → an existing block, a variant of an existing one (`variant`)
or a new block. Goal: as few blocks as possible, as many variants as possible.
- Schema change with content in the database → **ipal-migrate-fields**, never "live".
## Faza 3 — Nawigacja i dane firmy → **ipal-nav**
## Phase 3 — Navigation and company data → **ipal-nav**
## Faza 4 — Sekcje → **ipal-block** dla każdego bloku
Kolejność: Hero → sekcje powtarzalne (FeatureGrid, CTA, FAQ…) → specyficzne.
Każdy blok: schemat ze słownika pól, kompozycja prymitywów, zero tekstu w JSX
(`ipal-audit --quick` po każdym bloku — błędy naprawiasz od razu).
## Phase 4 — Sections → **ipal-block** for every block
Order: Hero → recurring sections (FeatureGrid, CTA, FAQ…) → specific ones.
Every block: schema from the field dictionary, composition of primitives, zero text in JSX
(`ipal-audit --quick` after every block — fix errors right away).
## Faza 5 — Formularze → **ipal-form**
Każdy formularz = seed z `ipal-form/resources/seed-form.template.ts` (pola, potwierdzenie, mail do
firmy **i** potwierdzenie do klienta, każdy język) — kod renderera i akcji piszesz raz. **Nigdy** własny
formularz z polami w JSX, trasa `api/contact`, `nodemailer`, reCAPTCHA (AGENT.md §0b).
## Phase 5 — Forms → **ipal-form**
Every form = a seed from `ipal-form/resources/seed-form.template.ts` (fields, confirmation, email to the
company **and** confirmation to the customer, every language) — the renderer and action code you write once. **Never** a custom
form with fields in JSX, an `api/contact` route, `nodemailer`, reCAPTCHA (AGENT.md §0b).
## Faza 6 — Treść w panelu, każdy język
1. Skopiuj `resources/seed-content.template.ts` → `scripts/seed-content.ts`,
wpisz treść z briefu: strony, bloki, linki (`{ $page: 'slug' }`), globale —
wszystkie języki obok siebie (`{ pl, en }`). Brak danych → `[DO UZUPEŁNIENIA: …]`.
Nie wymyślaj danych firmy, cen, opinii, liczb, certyfikatów, nazwisk.
2. `pnpm payload run scripts/seed-content.ts` → lista placeholderów trafia do raportu.
3. System Pages: Homepage, 404, polityka prywatności (strona istnieje; treść
polityki od klienta → placeholder). Cookie Settings (z Detail labels i listą Cookies
ze skanu), Notifications — teksty w każdym języku.
4. **ipal-locale-add → `locale-coverage`** = 0 braków (albo świadome w raporcie).
5. Obrazy: zostawiasz puste pola upload (redaktor dodaje) albo wgrywasz pliki z
briefu przez panel — przygotowane (WebP/JPG ≤ 1.5 MB, ≤ 2560 px).
## Phase 6 — Content in the panel, every language
1. Copy `resources/seed-content.template.ts` → `scripts/seed-content.ts`,
enter content from the brief: pages, blocks, links (`{ $page: 'slug' }`), globals —
all languages side by side (`{ pl, en }`). Missing data → `[TO FILL: …]`.
Never invent company data, prices, reviews, numbers, certificates, names.
2. `pnpm payload run scripts/seed-content.ts` → the placeholder list goes into the report.
On production (rules: `node_modules/@intecion/ipal-kit/docs/seeding.md`): `SEED_DRY_RUN=1` first, back up the
database, then the real run. It only creates what is missing; `SEED_UPDATE=1` there is refused without
`IPAL_SEED_ALLOW_PROD_UPDATE=1` and still skips pages an editor changed (`skip (edited)`).
3. System Pages: Homepage, 404, privacy policy (the page exists; the policy
text comes from the client → placeholder). Cookie Settings (with Detail labels and the Cookies list
from the scan), Notifications — texts in every language.
4. **ipal-locale-add → `locale-coverage`** = 0 gaps (or deliberate ones listed in the report).
5. Images: leave upload fields empty (the editor adds them) or upload files from
the brief via the panel — prepared (WebP/JPG ≤ 1.5 MB, ≤ 2560 px).
## Faza 7 — Integracje (panel, nie kod)
Site Integrations: transport e-mail + **Send test**, Turnstile (oba klucze — jeden
klucz = Turnstile wyłączony i czerwony alert na dashboardzie), analityka/piksele
(tylko z ID od klienta), consent (kategorie zgodne z użytymi narzędziami).
Site Settings: nazwa, opis (zasila llms.txt i MCP), OG image, favicon. SEO tab: meta
title/description każdej strony (≤ 60 / ≤ 155 znaków, unikalne); `aiSummary` —
zostaw auto-fill albo popraw, gdy streszczenie jest słabe.
## Phase 7 — Integrations (panel, not code)
Site Integrations: email transport + **Send test**, Turnstile (both keys — one
key = Turnstile off and a red alert on the dashboard), analytics/pixels
(only with IDs from the client), consent (categories matching the tools in use).
Site Settings: name, description (feeds llms.txt and MCP), OG image, favicon. SEO tab: meta
title/description of every page (≤ 60 / ≤ 155 characters, unique); `aiSummary` —
keep the auto-fill or fix it when the summary is weak.
## Faza 8 — Wygląd
`DESIGN.md` istnieje → tokeny w `@theme`. Brak → neutralne tokeny + w raporcie
rekomendacja Impeccable. Nie dopieszczaj stylów ad hoc w komponentach.
Responsywność: 360 px, 768 px, 1280 px — bez poziomego scrolla.
## Phase 8 — Design
`DESIGN.md` exists → tokens in `@theme`. None → neutral tokens + an Impeccable
recommendation in the report. Do not polish styles ad hoc in components.
Responsiveness: 360 px, 768 px, 1280 px — no horizontal scroll.
## Faza 9 — Weryfikacja (wszystko sam, wyniki do raportu)
## Phase 9 — Verification (all by yourself, results go into the report)
```bash
pnpm generate:types && pnpm tsc --noEmit
bash .agents/skills/ipal-audit/scripts/audit.sh # pełny: + tsc + build
pnpm build && pnpm start & # trasy stron ● (SSG), nie ƒ
bash .agents/skills/ipal-audit/scripts/audit.sh # full: + tsc + build
pnpm build && pnpm start & # page routes ● (SSG), not ƒ
node .agents/skills/ipal-seo-check/scripts/seo-check.mjs http://localhost:3000
node .agents/skills/ipal-consent-check/scripts/consent-check.mjs http://localhost:3000/<locale>
pnpm payload run .agents/skills/ipal-locale-add/scripts/locale-coverage.ts
```
`ipal-seo-check` sprawdza też GEO: `/llms.txt`, `/llms-full.txt`, `/md/…`, `/api/mcp`,
JSON-LD, boty AI w robots — każdy brak to `[ERROR]` do naprawy.
Plus ręcznie: test redaktora (AGENT §11) w każdym języku, formularz (lista w
ipal-form §6), klawiatura (Tab przez menu, baner, formularz; widoczny focus),
404 w każdym języku. Każdy `[ERROR]` naprawiasz (**ipal-debug**) i uruchamiasz
kontrolę ponownie. Nie oddajesz z błędami — wyjątek: blokujący błąd ipal-kit
(raport ipal-plugin-gap + obejście).
`ipal-seo-check` also checks GEO: `/llms.txt`, `/llms-full.txt`, `/md/…`, `/api/mcp`,
JSON-LD, AI bots in robots — every gap is an `[ERROR]` to fix.
Plus by hand: the editor test (AGENT §11) in every language, the form (list in
ipal-form §6), keyboard (Tab through the menu, banner, form; visible focus),
404 in every language. Fix every `[ERROR]` (**ipal-debug**) and run the
check again. Never hand over with errors — exception: a blocking ipal-kit bug
(plugin gap report, `ipal-plugin-gap`, + workaround).
## Faza 10 — Raport końcowy (jedyna duża wiadomość do użytkownika)
## Phase 10 — Final report (the only big message to the user)
```markdown
# <Klient> — strona gotowa do przeglądu
## Zrobione
- strony: <lista z URL-ami per język> · bloki: <lista> · formularze: <lista>
- języki: <…> · integracje: <e-mail ✓ Send test, Turnstile ✓, analityka: czeka na ID>
## Kontrole
build ✓ (n tras ●) · ipal-audit 0/0 · seo-check <e>/<w> · consent-check 0 naruszeń · locale-coverage 0
## Komplet (AGENT.md §0b)
SEO ✓ · JSON-LD ✓ · llms.txt + llms-full ✓ · Markdown ✓ · MCP ✓ · R2 <✓ / czeka na klucze> ·
Turnstile <✓ / czeka na klucze> · formularze z panelu ✓ · consent ✓ · 2FA ✓ · health ✓
(pominięte z decyzji klienta: <ipal-audit-skip albo „brak”>)
## Do uzupełnienia przez Ciebie / klienta (w panelu)
- [DO UZUPEŁNIENIA: NIP] → Company · … (pełna lista z seeda)
- tłumaczenia robocze do akceptacji: <strony>
## Decyzje, które podjąłem
- <decyzja> — <dlaczego> (pełna lista w AGENTS.md)
## Naprawione po drodze
- <problem → przyczyna → poprawka> (krótko, tylko istotne)
## Dla ipal-kit
- [błąd|usprawnienie] <temat> → docs/plugin-requests/<plik> (obejście: <plik:linia>)
## Następny krok
- <jedna rzecz, np. „podaj domenę → wdrożenie wg PROGRAMISTA §4”>
# <Client> — site ready for review
## Done
- pages: <list with URLs per language> · blocks: <list> · forms: <list>
- languages: <…> · integrations: <email ✓ Send test, Turnstile ✓, analytics: waiting for IDs>
## Checks
build ✓ (n routes ●) · ipal-audit 0/0 · seo-check <e>/<w> · consent-check 0 violations · locale-coverage 0
## Mandatory set (AGENT.md §0b)
SEO ✓ · JSON-LD ✓ · llms.txt + llms-full ✓ · Markdown ✓ · MCP ✓ · R2 <✓ / waiting for keys> ·
Turnstile <✓ / waiting for keys> · forms from the panel ✓ · consent ✓ · 2FA ✓ · health ✓
(skipped by client decision: <ipal-audit-skip or "none">)
## To fill in by you / the client (in the panel)
- [TO FILL: tax ID (NIP)] → Company · … (full list from the seed)
- draft translations for approval: <pages>
## Decisions I made
- <decision> — <why> (full list in AGENTS.md)
## Fixed along the way
- <problem → cause → fix> (briefly, only what matters)
## For ipal-kit
- [bug|improvement] <topic> → docs/plugin-requests/<file> (workaround: <file:line>)
## Next step
- <one thing, e.g. "give me the domain → deployment per PROGRAMISTA §4">
```
Nie raportujesz postępu w trakcie. Wyjątki: lista pytań z fazy 0, blokujący błąd
ipal-kit, decyzja nieodwracalna.
Do not report progress along the way. Exceptions: the question list from phase 0, a blocking
ipal-kit bug, an irreversible decision.
@@ -1,23 +1,35 @@
/**
* Content seed from the brief — skill ipal-site, phase 6.
* Content seed from the brief — skill ipal-site, phase 6. Rules: docs/seeding.md.
*
* pnpm payload run scripts/seed-content.ts # creates what's missing, never overwrites
* SEED_UPDATE=1 pnpm payload run scripts/seed-content.ts # also updates existing docs (asks nobody — use before handover only)
* SEED_DRY_RUN=1 pnpm payload run scripts/seed-content.ts # no writes: prints create / skip / update per record
* pnpm payload run scripts/seed-content.ts # creates what's missing, never overwrites
* SEED_UPDATE=1 pnpm payload run scripts/seed-content.ts # also updates records nobody edited since seeding
* (`--dry-run` after the script path works too, e.g. `pnpm seed:content --dry-run`.)
*
* Safety (docs/seeding.md):
* - Create-only and idempotent. Pages match by their DEFAULT-locale slug; globals
* get only the fields that are still empty. Nothing is ever deleted.
* - SEED_UPDATE=1 is refused when NODE_ENV=production or the database is not local,
* unless IPAL_SEED_ALLOW_PROD_UPDATE=1 is also set. Back up the database first.
* - An update skips every record an editor changed since seeding and reports it
* ("skip (edited)"). How a record counts as untouched: see SAFETY below.
* - Never seed users, passwords or secrets (SMTP, Turnstile, API keys) — panel / env.
*
* Write content ONCE, all languages side by side:
* heading: { pl: 'Nasze usługi', en: 'Our services' } → localized value
* heading: 'Nasze usługi' → same in every locale / non-localized field
* page: { $page: 'kontakt' } → ID of the page whose DEFAULT-locale slug is 'kontakt'
* Missing data: '[DO UZUPEŁNIENIA: NIP]' — never invent company data, prices, reviews, numbers.
* Missing data: '[TO FILL: tax ID (NIP)]' — never invent company data, prices, reviews, numbers.
*
* The default locale creates the structure (blocks, array rows); other locales are
* written onto the SAME row ids, so nothing is duplicated. Media: leave empty or
* reference existing uploads by ID — the editor adds images.
* reference existing uploads by ID — the editor adds images. Never upload here.
*
* GOTCHA (Payload, localization.fallback: true): an update in locale X without
* `fallbackLocale: false` merges the FALLBACK values into X — the default-locale
* text gets saved as the X translation. Every non-default write below sets it.
* text gets saved as the X translation. Every non-default read and write below sets it.
*/
import { createHash } from 'node:crypto'
import { getPayload } from 'payload'
import config from '@payload-config'
@@ -44,10 +56,68 @@ const GLOBALS: { slug: string; data: { [k: string]: Json } }[] = [
const COLLECTION = 'pages'
// ----------------------------------------------------------------- /CONTENT --
// ------------------------------------------------------------------- SAFETY --
// Defaults — the project may change them here or through env (docs/seeding.md).
/** Env var that holds the database URL (ipal-kit projects: DATABASE_URI). */
const DB_URL_ENV = process.env.SEED_DB_URL_ENV || 'DATABASE_URI'
/** Hosts that count as a local database. Add more with SEED_LOCAL_HOSTS=db,postgres. */
const LOCAL_HOSTS = ['localhost', '127.0.0.1', '::1', ...(process.env.SEED_LOCAL_HOSTS ?? '').split(',').map((h) => h.trim()).filter(Boolean)]
/**
* "Untouched since seeding", primary method: updatedAt is at most this many seconds
* after createdAt (the seed's own writes in one run). After one seeded update the
* record counts as edited — use SEED_HASH_FIELD for repeated updates.
*/
const UNTOUCHED_SECONDS = Number(process.env.SEED_UNTOUCHED_SECONDS ?? 120)
/**
* Optional method: a hidden text field with a hash of the seeded values. Used only
* when the collection/global has a top-level field with this name; it then decides
* instead of the timestamps and allows repeated updates.
*/
const HASH_FIELD = process.env.SEED_HASH_FIELD ?? 'seedHash'
/** SEED_FORCE=1 also overwrites edited records — refused outside a local database. */
const FORCE_ONLY_LOCAL = true
// ------------------------------------------------------------------ /SAFETY --
const DRY = process.argv.includes('--dry-run') || process.env.SEED_DRY_RUN === '1'
const UPDATE = process.env.SEED_UPDATE === '1'
// ipalSeed: for the project's own hooks. ipalSkipIndexNow: no IndexNow ping for seeded
// (placeholder) content when run with NODE_ENV=production and ipalKit({ indexNow: true }).
const CTX = { ipalSeed: true, ipalSkipIndexNow: true }
const FORCE = UPDATE && process.env.SEED_FORCE === '1'
function dbIsLocal(): boolean {
const url = (process.env[DB_URL_ENV] ?? '').trim()
if (!url) return false
if (/^file:/i.test(url) || /\.(db|sqlite3?)$/i.test(url)) return true // SQLite file
try {
const u = new URL(url)
if (u.protocol === 'mongodb+srv:') return false
if (u.searchParams.get('host')?.startsWith('/')) return true // ?host=/var/run/postgresql
const host = decodeURIComponent(u.hostname).replace(/^\[|\]$/g, '')
if (!host || host.startsWith('/')) return true // postgres:///db = unix socket
return LOCAL_HOSTS.includes(host)
} catch {
return false // unparsable (e.g. several Mongo hosts) = not local
}
}
const local = dbIsLocal()
const prodLike = process.env.NODE_ENV === 'production' || !local
if (UPDATE && prodLike && process.env.IPAL_SEED_ALLOW_PROD_UPDATE !== '1') {
console.error(
`[seed] SEED_UPDATE=1 refused: ${process.env.NODE_ENV === 'production' ? 'NODE_ENV=production' : `${DB_URL_ENV} is not a local database`}.\n` +
' 1. Back up the database (Coolify → database → Backups → Backup now, or pg_dump -Fc "$DATABASE_URI" > before-seed.dump).\n' +
' 2. Run with SEED_DRY_RUN=1 and read the plan.\n' +
' 3. Run again with IPAL_SEED_ALLOW_PROD_UPDATE=1. Edited records are still skipped.',
)
process.exit(1)
}
if (FORCE && FORCE_ONLY_LOCAL && prodLike) {
console.error('[seed] SEED_FORCE=1 refused: it overwrites editors\' changes and works only on a local database.')
process.exit(1)
}
if (UPDATE && prodLike) console.warn('[seed] Updating a production-like database (IPAL_SEED_ALLOW_PROD_UPDATE=1). Did you back it up?')
// disableRevalidate + ipalSkipIndexNow: the plugin's hooks skip cache revalidation and the
// IndexNow ping for seeded (placeholder) content. ipalSeed: for the project's own hooks.
const CTX = { ipalSeed: true, disableRevalidate: true, ipalSkipIndexNow: true }
const payload = await getPayload({ config })
const loc = payload.config.localization
const def = loc ? loc.defaultLocale : undefined
@@ -88,59 +158,161 @@ function pick(v: Json, locale: string | undefined, existing: unknown): Json | un
const defSlug = (p: { [k: string]: Json }) => String(isLocalized(p.slug) ? (p.slug as { [k: string]: Json })[def as string] : p.slug)
const hasPageRef = (v: Json): boolean =>
Array.isArray(v) ? v.some(hasPageRef) : !!v && typeof v === 'object' ? typeof v.$page === 'string' || Object.values(v).some(hasPageRef) : false
// Existing pages first, so $page works regardless of order.
const { docs: existingPages } = await payload.find({ collection: COLLECTION as never, depth: 0, limit: 0, pagination: false, ...(def ? { locale: def as never } : {}) })
for (const d of existingPages as { id: string | number; slug?: string }[]) if (d.slug) ids.set(d.slug, d.id)
const hasContent = (v: unknown): boolean =>
typeof v === 'string' ? v.trim() !== '' : typeof v === 'number' || v === true ? true
: Array.isArray(v) ? v.some(hasContent) : !!v && typeof v === 'object' ? Object.entries(v).some(([k, x]) => k !== 'id' && hasContent(x)) : false
const log: string[] = []
const writeLocales = async (write: (locale: string | undefined, existing: unknown) => Promise<unknown>, read: (l: string) => Promise<unknown>) => {
for (const l of others) await write(l, await read(def as string))
// --- "edited since seeding" -------------------------------------------------
/** JSON with sorted keys, no row ids, null = missing — so equal content gives an equal hash. */
const stable = (v: unknown): string =>
Array.isArray(v) ? `[${v.map(stable).join(',')}]`
: v && typeof v === 'object'
? `{${Object.keys(v).filter((k) => k !== 'id' && (v as Record<string, unknown>)[k] != null).sort()
.map((k) => `${JSON.stringify(k)}:${stable((v as Record<string, unknown>)[k])}`).join(',')}}`
: JSON.stringify(v ?? null)
const hashOf = (v: unknown) => createHash('sha256').update(stable(v)).digest('hex').slice(0, 32)
/** The current values at the keys the seed writes (everything else in the record is ignored). */
function project(seed: unknown, cur: unknown): unknown {
if (Array.isArray(seed)) return Array.isArray(cur) && cur.length === seed.length ? seed.map((s, i) => project(s, cur[i])) : cur
if (seed && typeof seed === 'object') {
if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return cur
return Object.fromEntries(Object.keys(seed).map((k) => [k, project((seed as Record<string, unknown>)[k], (cur as Record<string, unknown>)[k])]))
}
return cur
}
const localesOrDefault = codes.length ? codes : [undefined]
/** Seed values per locale (refs resolved). */
const seedPerLocale = (v: Json) => Object.fromEntries(localesOrDefault.map((l) => [l ?? '-', pick(v, l, undefined)]))
const hasField = (fields: unknown[] | undefined) => !!HASH_FIELD && !!fields?.some((f) => (f as { name?: string }).name === HASH_FIELD)
const pagesHaveHash = hasField(payload.collections[COLLECTION as never]?.config.fields as unknown[] | undefined)
const globalHasHash = (slug: string) => hasField(payload.config.globals.find((g) => g.slug === slug)?.fields as unknown[] | undefined)
/** null = untouched; a string = why it counts as edited. */
async function editedReason(
doc: Record<string, unknown>,
seed: Json,
withHash: boolean,
readLocale: (l: string | undefined) => Promise<unknown>,
): Promise<string | null> {
const stored = withHash ? doc[HASH_FIELD] : undefined
if (typeof stored === 'string' && stored) {
const seeded = seedPerLocale(seed)
const current: Record<string, unknown> = {}
for (const l of localesOrDefault) current[l ?? '-'] = project(seeded[l ?? '-'], await readLocale(l))
return hashOf(current) === stored ? null : `${HASH_FIELD} differs`
}
const c = Date.parse(String(doc.createdAt)), u = Date.parse(String(doc.updatedAt))
if (!Number.isFinite(c) || !Number.isFinite(u)) return 'no createdAt/updatedAt'
const s = Math.round((u - c) / 1000)
return s <= UNTOUCHED_SECONDS ? null : `updated ${s}s after creation`
}
// --- report -----------------------------------------------------------------
type Status = 'create' | 'skip (exists)' | 'update' | 'skip (edited)' | 'error'
const counts: Record<Status, number> = { create: 0, 'skip (exists)': 0, update: 0, 'skip (edited)': 0, error: 0 }
const report = (status: Status, what: string, note = '') => {
counts[status]++
console.log(`${status.padEnd(14)} ${what}${note ? ` — ${note}` : ''}`)
}
const readOpts = (l: string | undefined) => (l ? { locale: l as never, fallbackLocale: false as never } : {})
console.log(`[seed] ${DRY ? 'DRY RUN — nothing is written' : 'writing'} · ${UPDATE ? `updates on${FORCE ? ' (FORCE: edited records too)' : ''}` : 'create-only'} · database ${local ? 'local' : 'NOT local'}\n`)
// Existing pages first, so $page works regardless of order.
const { docs: existingPages } = await payload.find({ collection: COLLECTION as never, depth: 0, limit: 0, pagination: false, ...readOpts(def) })
const existingIds = new Set<string | number>()
for (const d of existingPages as { id: string | number; slug?: string }[]) if (d.slug) { ids.set(d.slug, d.id); existingIds.add(d.id) }
// Plan: one status per page, decided before anything is written.
const plan = new Map<string, 'create' | 'update'>()
for (const p of PAGES) {
const slug = defSlug(p)
const id = ids.get(slug)
if (id === undefined) { plan.set(slug, 'create'); if (DRY) ids.set(slug, `(new:${slug})`); continue }
if (!UPDATE) { report('skip (exists)', `${COLLECTION} "${slug}"`, 'SEED_UPDATE=1 to update untouched records'); continue }
try {
const readDoc = (l: string | undefined) => payload.findByID({ collection: COLLECTION as never, id: id as never, depth: 0, ...readOpts(l) })
const why = await editedReason((await readDoc(def)) as Record<string, unknown>, p, pagesHaveHash, readDoc)
if (why && !FORCE) { report('skip (edited)', `${COLLECTION}/${String(id)} "${slug}"`, why); continue }
plan.set(slug, 'update')
} catch (e) {
report('error', `${COLLECTION} "${slug}"`, (e as Error).message)
}
}
// Pass 1: create missing pages without layout links (targets may not exist yet), pass 2: full content.
for (const pass of [1, 2] as const) {
for (const p of PAGES) {
const slug = defSlug(p)
let id = ids.get(slug)
if (pass === 1) {
if (id !== undefined) continue
const data = pick(hasPageRef(p) ? { ...p, layout: [] } : p, def, undefined) as Record<string, unknown>
const created = await payload.create({ collection: COLLECTION as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX })
id = (created as { id: string | number }).id
ids.set(slug, id)
log.push(`created ${COLLECTION}/${String(id)} "${slug}"`)
const action = plan.get(slug)
if (!action || (pass === 1 && action !== 'create')) continue
if (DRY) {
if (pass === 1) continue
try { pick(p, def, undefined); report(action, `${COLLECTION} "${slug}"`, `[${codes.join(', ') || '-'}]`) } // resolves $page refs
catch (e) { report('error', `${COLLECTION} "${slug}"`, (e as Error).message) }
continue
}
const fresh = log.includes(`created ${COLLECTION}/${String(id)} "${slug}"`)
if (!fresh && !UPDATE) { log.push(`skipped "${slug}" (exists — SEED_UPDATE=1 to overwrite)`); continue }
const readDoc = (l: string) => payload.findByID({ collection: COLLECTION as never, id: id as never, depth: 0, locale: l as never, fallbackLocale: false as never })
await payload.update({ collection: COLLECTION as never, id: id as never, data: pick(p, def, undefined) as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX })
await writeLocales(
(l, ex) => payload.update({ collection: COLLECTION as never, id: id as never, data: pick(p, l, ex) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: CTX }),
readDoc,
)
log.push(`${fresh ? 'filled' : 'updated'} "${slug}" [${codes.join(', ') || '-'}]`)
try {
if (pass === 1) {
const data = pick(hasPageRef(p) ? { ...p, layout: [] } : p, def, undefined) as Record<string, unknown>
const created = await payload.create({ collection: COLLECTION as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX })
ids.set(slug, (created as { id: string | number }).id)
continue
}
const id = ids.get(slug)
if (id === undefined) continue // pass 1 failed — already reported
const readDoc = (l: string) => payload.findByID({ collection: COLLECTION as never, id: id as never, depth: 0, locale: l as never, fallbackLocale: false as never })
const base = pick(p, def, undefined) as Record<string, unknown>
const data = pagesHaveHash ? { ...base, [HASH_FIELD]: hashOf(seedPerLocale(p)) } : base
await payload.update({ collection: COLLECTION as never, id: id as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX })
for (const l of others) {
await payload.update({ collection: COLLECTION as never, id: id as never, data: pick(p, l, await readDoc(def as string)) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: CTX })
}
report(action, `${COLLECTION}/${String(id)} "${slug}"`, `[${codes.join(', ') || '-'}]`)
} catch (e) {
report('error', `${COLLECTION} "${slug}"`, (e as Error).message)
plan.delete(slug)
}
}
}
// Globals: only empty fields are filled. With SEED_UPDATE=1 an untouched global gets every seeded field.
for (const g of GLOBALS) {
const readG = (l: string) => payload.findGlobal({ slug: g.slug as never, depth: 0, locale: l as never, fallbackLocale: false as never })
if (!UPDATE && def) {
try {
const readG = (l: string | undefined) => payload.findGlobal({ slug: g.slug as never, depth: 0, ...readOpts(l) })
const cur = (await readG(def)) as Record<string, unknown>
const filled = Object.keys(g.data).some((k) => hasContent(cur[k]))
if (filled) { log.push(`skipped global ${g.slug} (has content — SEED_UPDATE=1 to overwrite)`); continue }
const empty = Object.keys(g.data).filter((k) => !hasContent(cur[k]))
let keys = empty
let edited: string | null = null
if (UPDATE) {
edited = await editedReason(cur, g.data, globalHasHash(g.slug), readG)
if (!edited || FORCE) keys = Object.keys(g.data)
}
if (!keys.length) {
if (edited) report('skip (edited)', `global ${g.slug}`, edited)
else report('skip (exists)', `global ${g.slug}`, 'every seeded field has content')
continue
}
const all = keys.length === Object.keys(g.data).length
const status: Status = keys !== empty ? 'update' : edited ? 'skip (edited)' : 'create'
const note = keys !== empty ? `[${codes.join(', ') || '-'}]` : `${edited ? `${edited}; ` : ''}empty fields filled: ${keys.join(', ')}`
if (!DRY) {
const part = Object.fromEntries(keys.map((k) => [k, g.data[k]])) as { [k: string]: Json }
const base = pick(part, def, cur) as Record<string, unknown>
// The hash describes the whole seeded set — store it only when every seeded field was written.
const data = all && globalHasHash(g.slug) ? { ...base, [HASH_FIELD]: hashOf(seedPerLocale(g.data)) } : base
await payload.updateGlobal({ slug: g.slug as never, data: data as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX })
for (const l of others) {
await payload.updateGlobal({ slug: g.slug as never, data: pick(part, l, await readG(def)) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: CTX })
}
}
report(status, `global ${g.slug}`, note)
} catch (e) {
report('error', `global ${g.slug}`, (e as Error).message)
}
await payload.updateGlobal({ slug: g.slug as never, data: pick(g.data, def, undefined) as never, depth: 0, ...(def ? { locale: def as never } : {}), context: CTX })
await writeLocales((l, ex) => payload.updateGlobal({ slug: g.slug as never, data: pick(g.data, l, ex) as never, depth: 0, locale: l as never, fallbackLocale: false as never, context: CTX }), readG)
log.push(`global ${g.slug} [${codes.join(', ') || '-'}]`)
}
for (const line of log) console.log(line)
const todo = JSON.stringify({ PAGES, GLOBALS }).match(/\[DO UZUPEŁNIENIA:[^\]]*\]/g) ?? []
console.log(`\n[seed] summary${DRY ? ' (dry run — nothing written)' : ''}`)
console.table({ created: counts.create, skipped: counts['skip (exists)'], updated: counts.update, 'skipped-edited': counts['skip (edited)'], errors: counts.error })
const todo = JSON.stringify({ PAGES, GLOBALS }).match(/\[TO FILL:[^\]]*\]/g) ?? []
if (todo.length) console.log(`\n${todo.length} placeholder(s) for the final report:\n ${[...new Set(todo)].join('\n ')}`)
process.exit(0)
process.exit(counts.error ? 1 : 0)
+53 -53
View File
@@ -5,72 +5,72 @@ description: Upgrades an existing project to the latest @intecion/ipal-kit and r
# ipal-upgrade
Co się zmieniło w wersji: `node_modules/@intecion/ipal-kit/docs/CHANGELOG.md` (sekcje
„Wymaga zmian w projekcie” — zrób wszystkie). Lista zmian: `…/docs/dev/PROGRAMISTA.md` §6.
Zasada: gdy plugin dostarcza coś, co projekt ma ręcznie — **usuń lokalną wersję**.
What changed in the version: `node_modules/@intecion/ipal-kit/docs/CHANGELOG.md` (the
"Requires project changes" sections — do all of them). List of changes: `…/docs/dev/PROGRAMISTA.md` §6.
Rule: when the plugin provides something the project has written by hand — **remove the local version**.
## 1. Aktualizacja pakietu
## 1. Update the package
```bash
pnpm add @intecion/ipal-kit@latest
pnpm payload generate:importmap # nowe komponenty panelu z pluginu (np. RowLabel)
pnpm payload generate:importmap # new admin panel components from the plugin (e.g. RowLabel)
rm -rf .next
```
Skopiuj skille na nowo (AGENT.md §14) — mogły się zmienić.
Postgres z migracjami: nowe pola pluginu (np. `privacyLinkLabel`) →
Copy the skills again (AGENT.md §14) — they may have changed.
Postgres with migrations: new plugin fields (e.g. `privacyLinkLabel`) →
`pnpm payload migrate:create`.
## 1a. Komplet AGENT.md §0b
Po aktualizacji pełny **ipal-audit** pokaże sekcję „missing: …” — brakujące pozycje
obowiązkowego kompletu (GEO: llms-full, Markdown, MCP; R2; Turnstile przez
`getTurnstileConfig`…). Każdą wpinasz wg PROGRAMISTA §2 — to część aktualizacji,
nie dodatek. Pomijasz tylko z decyzją klienta w `AGENTS.md` (`ipal-audit-skip:`).
## 1a. AGENT.md §0b set
After the update, a full **ipal-audit** shows a "missing: …" section — the missing items of
the MANDATORY SET (GEO: llms-full, Markdown, MCP; R2; Turnstile through
`getTurnstileConfig`…). Wire each one according to PROGRAMISTA §2 — it is part of the update,
not an extra. Skip one only with a client decision in `AGENTS.md` (`ipal-audit-skip:`).
**1.8.x → 1.9.0 (PROGRAMISTA §6, poz. 17–21):** `twoFactor.plugin` wymagany;
`getTurnstileConfig` zamiast `turnstileSiteKey` (przy obu kluczach token jest
wymagany — sprawdź, że każdy formularz ma widget); `clientIp(await headers())` w
akcji formularza + `IPAL_IP_HEADER` w env produkcji; `buildR2Storage` wpięty.
**1.8.x → 1.9.0 (PROGRAMISTA §6, items 17–21):** `twoFactor.plugin` required;
`getTurnstileConfig` instead of `turnstileSiteKey` (with both keys set the token is
required — check that every form has the widget); `clientIp(await headers())` in
the form action + `IPAL_IP_HEADER` in the production env; `buildR2Storage` wired.
**→ 1.9.2 (PROGRAMISTA §6, poz. 28–33) — import zamiast kodu, zacznij od poz. 28 (bezpieczeństwo):**
własny `FormRenderer` przekazywał do HTML zakładkę Emails (adresy firmy) → blok z `<RenderForm>` +
`formClasses.ts`, usuń renderer. Potem: layout → `SiteProviders`, strona i 404 → `createPageRoute` /
`createNotFoundPage`, trasy GEO → re-eksporty z `lib/content`, `src/fields/section*.ts` i
`lib/navigation.ts` → `buildSection*Field`, `resolveNav`, `resolveLink`. Każdą pozycję sprawdź w
przeglądarce (formularz: wysyłka + mail; strona: 200, 404, metadata). Postgres: `migrate:create`
(nowe typy pól formularza i teksty w Notifications).
**→ 1.9.2 (PROGRAMISTA §6, items 28–33) — import instead of code, start with item 28 (security):**
a custom `FormRenderer` passed the Emails tab (company addresses) to the HTML → a block with `<RenderForm>` +
`formClasses.ts`, remove the renderer. Then: layout → `SiteProviders`, page and 404 → `createPageRoute` /
`createNotFoundPage`, GEO routes → re-exports from `lib/content`, `src/fields/section*.ts` and
`lib/navigation.ts` → `buildSection*Field`, `resolveNav`, `resolveLink`. Check every item in
the browser (form: submission + email; page: 200, 404, metadata). Postgres: `migrate:create`
(new form field types and texts in Notifications).
**→ 1.11.0 (PROGRAMISTA §6, poz. 34–37):** usuń obejścia — kopię `publicForm` (→ `RenderForm values` /
`prepareBuilderForm`), ręczne `remotePatterns`/`dangerouslyAllowLocalIP` (→ `buildImagesConfig()`), warunkowe
`storage` w `ipalEnvRules`, własny graf JSON-LD produktów (→ `pageJsonLd.entries` + `buildProductJsonLd`),
własny RenderBlocks dla `h1` (→ `isFirst`). Linki do wpisów: `buildLinkField({ relationTo: [...] })` z migracją danych.
**→ 1.11.0 (PROGRAMISTA §6, items 34–37):** remove the workarounds — a copy of `publicForm` (→ `RenderForm values` /
`prepareBuilderForm`), manual `remotePatterns`/`dangerouslyAllowLocalIP` (→ `buildImagesConfig()`), conditional
`storage` in `ipalEnvRules`, a custom product JSON-LD graph (→ `pageJsonLd.entries` + `buildProductJsonLd`),
a custom RenderBlocks for `h1` (→ `isFirst`). Links to posts: `buildLinkField({ relationTo: [...] })` with a data migration.
**→ 1.11.1 (PROGRAMISTA §6, poz. 38–45):** usuń obejścia (komentarze `WORKAROUND ipal-kit`) — warunek
`NEXT_RUNTIME` wokół `revalidatePath` wstrzykiwanego do `buildRevalidateHook` (własny hook `afterChange` globalu go zachowuje — ipal-nav), strażnik fokusu formularza, własny motyw (→ `ThemeScript`/`ThemeSwitcher`),
własny spis treści (→ `extractHeadings` + `TableOfContents` + `headingIds`), łapanie `notFound` dla przekierowania
(→ `onMissing: 'redirectHome'`), kolor tła tylko dla JPEG w `<Media>`, własny typ zamiast `CmsLink['appearance']`
(→ typy per kształt z `generate:types`: `CmsLink`, `CmsLinkPlain`, `CmsLinkNoLabel`, `CmsLinkPlainNoLabel`; styl: `LinkAppearance`). Cookie Settings: `buttons.save` →
`buttons.savePreferences` — w `migrate:create` wybierz **rename** kolumny, żeby zachować teksty.
**→ 1.11.1 (PROGRAMISTA §6, items 38–45):** remove the workarounds (`WORKAROUND ipal-kit` comments) — the
`NEXT_RUNTIME` condition around the `revalidatePath` injected into `buildRevalidateHook` (a global's own `afterChange` hook keeps it — ipal-nav), the form focus guard, a custom theme (→ `ThemeScript`/`ThemeSwitcher`),
a custom table of contents (→ `extractHeadings` + `TableOfContents` + `headingIds`), catching `notFound` for a redirect
(→ `onMissing: 'redirectHome'`), background colour only for JPEG in `<Media>`, a custom type instead of `CmsLink['appearance']`
(→ per-shape types from `generate:types`: `CmsLink`, `CmsLinkPlain`, `CmsLinkNoLabel`, `CmsLinkPlainNoLabel`; style: `LinkAppearance`). Cookie Settings: `buttons.save` →
`buttons.savePreferences` — in `migrate:create` choose **rename** for the column to keep the texts.
**→ 1.12.3 (PROGRAMISTA §6, poz. 46):** Postgres/SQLite: `migrate:create` (nowa grupa Cookie Settings →
`detailLabels`, same nowe kolumny — bez rename). Własne okno ustawień cookies albo lista ciasteczek dopisana do
banera → `<CookieBanner settings="detailed">` i usuń kopię. Przy `detailed`: Cookie Settings → Cookies wypełnione
(skan, **ipal-consent-check**) i Detail labels w każdym języku.
**→ 1.12.3 (PROGRAMISTA §6, item 46):** Postgres/SQLite: `migrate:create` (new Cookie Settings group →
`detailLabels`, only new columns — no rename). A custom cookie settings window or a cookie list added to
the banner → `<CookieBanner settings="detailed">` and remove the copy. With `detailed`: Cookie Settings → Cookies filled in
(scan, **ipal-consent-check**) and Detail labels in every language.
## 2. Inwentaryzacja (bez zmian w kodzie)
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
Wynik: lista do zrobienia z priorytetem — realizujesz ją od razu. Zatrzymujesz się
tylko przed zmianą nieodwracalną (migracja danych z treścią → **ipal-migrate-fields**,
zmiana opublikowanych slugów).
## 2. Inventory (no code changes)
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
only before an irreversible change (data migration with content → **ipal-migrate-fields**,
changing published slugs).
## 3. Pozycja po pozycji
Jedna pozycja = jedna zmiana = jeden commit:
1. przeczytaj wskazany plik docs,
2. zastąp lokalny kod funkcją pluginu, usuń stary kod (nie zostawiaj obu),
3. `pnpm build` — przechodzi, zanim weźmiesz następną pozycję.
## 3. Item by item
One item = one change = one commit:
1. read the docs file it points to,
2. replace the local code with the plugin function, remove the old code (do not keep both),
3. `pnpm build` — it passes before you take the next item.
Pozycje zmieniające nazwy pól w bazie (np. refaktor `ctaLabel` → `links`)
wymagają **migracji danych przed** usunięciem starych pól — zapytaj
użytkownika, czy projekt ma już treść.
Items that rename fields in the database (e.g. the `ctaLabel` → `links` refactor)
need a **data migration before** the old fields are removed — ask
the user whether the project already has content.
## 4. Koniec
Pełny **ipal-audit** bez błędów + lista rzeczy do sprawdzenia w panelu.
## 4. Finish
A full **ipal-audit** with no errors + a list of things to check in the admin panel.