Merge main (security-perf + SEO) into docs; finish English docs and agent guide

- Resolve conflicts in analytics, consent, content, i18n, mcp and stats,
  keeping the docs fixes and the new code behaviour, verified against src
- Translate the remaining 14 module pages, ipal-seo-check skill and script
- Integrate the security-perf and SEO agent-guide text: getRobots,
  isPathVisible, Search & AI (DNS verification first, meta fields optional),
  sitemap index/cache/503, consentMode basic/advanced, policyVersion,
  globalOverrides, revalidatePath / buildGlobalRevalidateHook, authAccess,
  firstUserAdmin, allowCollectionMismatch, unknown-IP rate limit; stale
  claims fixed across AGENT.md, skills, frontend, developer guide, vibe
- docsConsistency: pending list removed (all docs English); relative links
  now also check #anchors

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 17:59:52 +02:00
co-authored by Claude Opus 5.5
107 changed files with 5476 additions and 2541 deletions
+207 -195
View File
@@ -1,31 +1,31 @@
# content
Kolekcje, których wpisy żyją pod stroną-archiwum — blog, realizacje, aktualności,
cokolwiek z listingiem. Wpisy trafiają pod adres w rodzaju `/pl/artykuly/moj-post`,
a segment `artykuly` nie jest osobną konfiguracją — to slug strony, którą edytor
wskazał jako archiwum tej kolekcji.
Collections whose entries live under an archive page — blog, portfolio, news,
anything with a listing. Entries get an address like `/pl/artykuly/moj-post`,
and the `artykuly` segment is not separate configuration — it is the slug of the page the editor
picked as this collection's archive.
## Model — kto czym jest
## Model — who is what
```
kolekcja posts ──(config)──► „to kolekcja archiwalna”
strona „Artykuły” ──(System Pages)──► „jestem archiwum kolekcji posts”
wpis ──► należy do posts, i tyle
posts collection ──(config)──► "this is an archive collection"
"Artykuły" page ──(System Pages)──► "I am the archive of the posts collection"
entry ──► belongs to posts, nothing more
```
Wpis niczego nie wie o swoim adresie. O adresie decyduje przypisanie strony —
jedno dla całej kolekcji. Zmiana tytułu strony „Artykuły" na „Wpisy" przenosi
całą sekcję na `/pl/wpisy`, per locale, bez deploya. To jak folder: pliki nie
tagują się nazwą folderu, folder ma nazwę.
An entry knows nothing about its address. The page assignment decides the address —
one for the whole collection. Renaming the "Artykuły" page to "Wpisy" moves
the whole section to `/pl/wpisy`, per locale, without a deploy. It works like a folder: files do not
tag themselves with the folder name, the folder has the name.
**Kolekcji nie da się dodać z panelu** — Payload trzyma schemat w kodzie. Nowy
typ treści to zawsze zmiana w kodzie (nowa kolekcja + wpis w configu). Edytor
zarządza tylko przypisaniem archiwum i jego adresem.
**You cannot add a collection from the admin panel** — Payload keeps the schema in code. A new
content type is always a code change (a new collection + an entry in the config). The editor
manages only the archive assignment and its address.
## Config
```ts
// content.config.ts — współdzielony przez payload.config i front
// content.config.ts — shared by payload.config and the front end
import type { ContentOption } from '@intecion/ipal-kit'
export const contentConfig: ContentOption = {
@@ -39,33 +39,33 @@ export const contentConfig: ContentOption = {
```ts
// payload.config.ts
ipalKit({
pages: { slug: 'pages' }, // wymagane — archiwum jest stroną
pages: { slug: 'pages' }, // required — the archive is a page
content: contentConfig,
seo: { collections: ['pages', 'posts', 'projects'] }, // wpisy też chcą meta
seo: { collections: ['pages', 'posts', 'projects'] }, // entries want meta too
})
```
Każda pozycja dodaje w **Site Settings → System Pages** pole relacji
„{label} — archive page" o nazwie `{slug}Archive` (`archiveFieldName('posts')` →
`'postsArchive'`), wskazujące kolekcję z `pages.slug`.
Each item adds to **Site Settings → System Pages** a relationship field
"{label} — archive page" named `{slug}Archive` (`archiveFieldName('posts')` →
`'postsArchive'`), pointing at the `pages.slug` collection.
| Pole | Domyślnie | Co robi |
| Field | Default | What it does |
|---|---|---|
| `slug` | — (wymagane) | slug kolekcji klienta |
| `label` | `slug` | etykieta pola archiwum w panelu |
| `perPage` | `10` | wpisów na stronę listingu (`route.perPage`) |
| `slug` | — (required) | slug of the client's collection |
| `label` | `slug` | label of the archive field in the admin panel |
| `perPage` | `10` | entries per listing page (`route.perPage`) |
Bez opcji `pages` pola archiwów **nie są dodawane** (plugin pomija `content` po cichu,
`src/plugin.ts` ~210) — routing wpisów wtedy nie działa.
Without the `pages` option the archive fields are **not added** (the plugin silently skips `content`,
`src/plugin.ts` ~275) — entry routing then does not work.
Osobny plik `content.config.ts` (jak `i18n.config.ts`) jest potrzebny, bo tę samą
deklarację czytają dwa miejsca: payload.config (żeby dodać pola archiwum) i front
(router). Jedno źródło prawdy.
A separate `content.config.ts` file (like `i18n.config.ts`) is needed because two places read
the same declaration: payload.config (to add the archive fields) and the front end
(the router). One source of truth.
## Rozstrzyganie tras — resolveRoute
## Resolving routes — resolveRoute
Serce modułu. Catch-all `[[...slug]]` łapie wszystko, a `resolveRoute` mówi, czym
dana ścieżka jest:
The heart of the module. The catch-all `[[...slug]]` catches everything, and `resolveRoute` says what
a given path is:
```ts
import { resolveRoute } from '@intecion/ipal-kit'
@@ -74,38 +74,38 @@ const route = await resolveRoute({
payload,
locale: 'pl',
segments: ['artykuly', 'moj-post'],
page: 1, // z ?page=
page: 1, // from ?page=
content: contentConfig,
// pagesSlug: 'pages', settingsSlug: 'site-settings', settings (już odczytane, depth ≥ 1),
// draft: false (true = podgląd: najnowszy draft, też nieopublikowane)
// pagesSlug: 'pages', settingsSlug: 'site-settings', settings (already read, depth ≥ 1),
// draft: false (true = preview: latest draft, unpublished too)
})
// null gdy 404, inaczej:
// null on 404, otherwise:
// { type: 'home' | 'page', doc }
// { type: 'archive', doc, collection, page, perPage }
// { type: 'entry', doc, collection, archive } (archive = strona-archiwum)
// { type: 'entry', doc, collection, archive } (archive = the archive page)
```
Bez `draft: true` dokumenty z `_status` innym niż `published` (strona, archiwum,
wpis) dają `null`. Strona przypisana jako 404 w System Pages też daje `null`
(prawdziwy 404 zamiast soft-404).
Without `draft: true`, documents with a `_status` other than `published` (page, archive,
entry) give `null`. The page assigned as 404 in System Pages also gives `null`
(a real 404 instead of a soft 404).
Logika: pierwszy segment dopasowywany jest do slugów stron-archiwów z System
Pages. Trafienie → wiadomo, której kolekcji dotyczy. `['artykuly']` → listing
`posts`; `['artykuly','moj-post']` → wpis w `posts`; brak trafienia → zwykła
strona.
Logic: the first segment is matched against the slugs of the archive pages from System
Pages. A match → we know which collection it is about. `['artykuly']` → listing of
`posts`; `['artykuly','moj-post']` → an entry in `posts`; no match → a regular
page.
**Archiwum ma pierwszeństwo przed stroną o tym samym slugu** — inaczej strona
„artykuly" przesłaniałaby własne wpisy.
**The archive takes precedence over a page with the same slug** — otherwise the page
"artykuly" would hide its own entries.
**Głębokość tylko `{archiwum}/{wpis}`** — kategorie w ścieżce robiłyby canonical
niejednoznacznym (ten sam wpis pod wieloma URL-ami), więc `/a/b/c` → null.
**Depth is only `{archive}/{entry}`** — categories in the path would make the canonical
ambiguous (the same entry under many URLs), so `/a/b/c` → null.
**Kolizja slugów:** dwie kolekcje z archiwum o tym samym slugu → wygrywa pierwsza
z listy `collections`. Błąd konfiguracji, router nie ostrzega.
**Slug collision:** two collections with an archive with the same slug → the first one
in the `collections` list wins. A configuration error; the router does not warn.
## Helpery frontu — createContentHelpers
## Front-end helpers — createContentHelpers
Zamiast pisać cache'owane wrappery w każdym projekcie:
Instead of writing cached wrappers in every project:
```ts
// src/lib/content.ts
@@ -117,28 +117,35 @@ export const { getCachedPayload, getConfiguredLocales, getSettings, resolveRoute
createContentHelpers({ config, content: contentConfig })
```
Fabryka zwraca dużo więcej (metadane, sitemap, linki, route handlery) — pełna lista
opcji i kluczy `@/lib/content`: [frontend.md](./frontend.md).
The factory returns much more (metadata, sitemap, links, route handlers) — the full list of
options and `@/lib/content` keys: [frontend.md](./frontend.md).
Wszystko owinięte w React `cache()`, a instancja Payloada powstaje **raz** w
fabryce i jest współdzielona — dlatego to fabryka, nie luźne funkcje. Bez tego
`cache()` nie dedupikowałby między helperami, a Next woła generateMetadata i
komponent strony osobno.
Everything is wrapped in React `cache()`, and the Payload instance is created **once** in
the factory and shared — that is why it is a factory, not loose functions. Without it
`cache()` would not dedupe across helpers, and Next calls generateMetadata and
the page component separately.
`resolveRoute` z fabryki przyjmuje `(locale, segments, page)` — rozstrzyga
trasę. Pobranie wpisów to osobna funkcja `getEntries` (patrz niżej), bo
routing i pobieranie danych to dwie różne odpowiedzialności.
`getSettings(locale)` reads Site Settings with **`depth: 1`** — relationships (logo, pages in menus,
system pages) arrive as documents (`slug`, `title`), but **their** relationships arrive as IDs.
The page that `resolveRoute` renders (home page, archive, regular page) is fetched
separately with `depth: 2`. Need more depth in the layout (e.g. the image of a page linked in the menu)?
Fetch that one document yourself instead of raising the depth of the whole global on every request — or,
deliberately, `createContentHelpers({ settingsDepth: 2 })` (a cost on every request).
## Routing i pobieranie — osobno
`resolveRoute` from the factory takes `(locale, segments, page)` — it resolves
the route. Fetching entries is a separate function, `getEntries` (see below), because
routing and data fetching are two different responsibilities.
Archiwum potrzebuje listy wpisów; metadane nie. Rozstrzyganie trasy i pobieranie
wpisów to dwie funkcje, składane jawnie tam, gdzie trzeba obu:
## Routing and fetching — separately
An archive needs a list of entries; metadata does not. Resolving the route and fetching
entries are two functions, composed explicitly where you need both:
```ts
// generateMetadata — sama trasa (nie płaci za zapytanie o wpisy)
// generateMetadata — the route only (does not pay for the entries query)
const route = await resolveRoute(locale, slug, page)
// komponent strony — trasa, a potem wpisy, jeśli to archiwum
// page component — the route, then entries if it is an archive
const route = await resolveRoute(locale, slug, page)
const entries = route?.type === 'archive'
? await getEntries(route.collection, locale, route.page, route.perPage)
@@ -146,22 +153,22 @@ const entries = route?.type === 'archive'
// entries: { docs, page, totalDocs, totalPages, hasPrevPage, hasNextPage }
```
`getEntries` = `getArchiveEntries` z ustawieniami domyślnymi: najnowsze pierwsze
(`sort: '-createdAt'`), `depth: 1`, tylko opublikowane (filtr `_status` dodawany
tylko w kolekcjach z draftami). Własne sortowanie/filtr: `getArchiveEntries({ payload,
`getEntries` = `getArchiveEntries` with default settings: newest first
(`sort: '-createdAt'`), `depth: 1`, published only (the `_status` filter is added
only in collections with drafts). Your own sort/filter: `getArchiveEntries({ payload,
collection, locale, page, perPage, sort, where, depth, draft })`.
`resolveRoute` zwraca `collection` i `perPage` — czyli CO i ILE pobrać — ale
pobierania nie robi. Dzięki temu zmiana sortowania czy filtrowania listingu nie
dotyka reguł routingu, a metadane nie pobierają wpisów, których i tak nie użyją.
`resolveRoute` returns `collection` and `perPage` — i.e. WHAT and HOW MANY to fetch — but
does not fetch. Thanks to that, changing the listing's sort or filter does not
touch the routing rules, and metadata does not fetch entries it would not use anyway.
## Listing
Strona-archiwum to zwykła strona z blokami, więc listing jest **blokiem** (Twoim
— plugin nie decyduje o wyglądzie listy). Blok dostaje wpisy przez enhanceProps:
The archive page is a regular page with blocks, so the listing is a **block** (yours
— the plugin does not decide how the list looks). The block gets the entries through enhanceProps:
```tsx
// w page.tsx — route nie niesie wpisów, pobierz je getEntries
// in page.tsx — the route does not carry entries, fetch them with getEntries
const entries = route.type === 'archive'
? await getEntries(route.collection, locale, route.page, route.perPage)
: null
@@ -173,16 +180,16 @@ const enhanceProps = ({ block }) => {
}
```
**`createPageRoute` (`/rsc`) nie paginuje** — zawsze woła `resolveRoute(locale, segments, 1)`
i nie czyta `searchParams` (`src/modules/frontend/pageRoute.tsx` ~122). Archiwum
z `?page=` wymaga własnej strony (albo osobnej trasy archiwum) czytającej `searchParams`
— patrz pages.md „PUŁAPKA: await searchParams” i [frontend.md](./frontend.md).
**`createPageRoute` (`/rsc`) does not paginate** — it always calls `resolveRoute(locale, segments, 1)`
and does not read `searchParams` (`src/modules/frontend/pageRoute.tsx` ~121). An archive
with `?page=` needs its own page (or a separate archive route) that reads `searchParams`
— see pages.md "TRAP: await searchParams" and [frontend.md](./frontend.md).
Blok nie wie, co listuje — wpisy wstrzykuje trasa na podstawie tego, której
kolekcji ta strona jest archiwum. Ten sam blok obsługuje `/pl/artykuly` i
The block does not know what it lists — the route injects the entries based on which
collection this page is the archive of. The same block serves `/pl/artykuly` and
`/pl/realizacje`.
## Ścieżki i paginacja
## Paths and pagination
```ts
import { buildEntryPath, buildArchivePath, parsePageParam } from '@intecion/ipal-kit'
@@ -191,48 +198,48 @@ buildEntryPath({ locale: 'pl', archiveSlug: 'artykuly', entrySlug: 'moj-post' })
// '/pl/artykuly/moj-post'
buildArchivePath({ locale: 'pl', archiveSlug: 'artykuly', page: 2 })
// '/pl/artykuly?page=2' (strona 1 bez query)
// '/pl/artykuly?page=2' (page 1 without a query)
parsePageParam(searchParams.page) // '2' → 2; śmieci/undefined → 1
parsePageParam(searchParams.page) // '2' → 2; junk/undefined → 1
```
`buildEntryPath` / `buildArchivePath` **zawsze** dokładają `/{locale}` — także na
stronie jednojęzycznej, gdzie adresy nie mają prefiksu — tam składaj ścieżkę sam.
Ten sam prefiks dostają linki do wpisów z `resolveLink`/`resolveNav` (links.md).
`buildEntryPath` / `buildArchivePath` **always** add `/{locale}` — also on
a single-language site, where addresses have no prefix — there build the path yourself.
Links to entries from `resolveLink`/`resolveNav` (links.md) get the same prefix.
Paginacja przez `?page=`, nie `/2`. Segment ścieżki gryzłby się z wpisem o slugu
„2", a `/strona/2` dodawałby kolejny zlokalizowany segment do konfiguracji.
Google rozumie `?page=` od lat, a `rel=next/prev` zostało wycofane.
Pagination uses `?page=`, not `/2`. A path segment would clash with an entry with the slug
"2", and `/strona/2` would add another localized segment to the configuration.
Google has understood `?page=` for years, and `rel=next/prev` has been retired.
Canonical strony 2 wskazuje **na siebie** (`?page=2`), nie na stronę 1 — inaczej
Google uznałby, że wpisów z dalszych stron nie ma. Hreflangi niosą ten sam numer
(`/en/articles?page=2`). To ogarnia `createPageMetadata` automatycznie, gdy
przekażesz mu `page` i `content`.
The canonical of page 2 points **to itself** (`?page=2`), not to page 1 — otherwise
Google would assume the entries on later pages do not exist. Hreflangs carry the same number
(`/en/articles?page=2`). `createPageMetadata` handles this automatically when
you pass it `page` and `content`.
## Metadane wpisów
## Entry metadata
`createPageMetadata` z opcją `content` sam rozpoznaje wpisy i buduje im poprawny
canonical/hreflang z prefiksem (patrz seo.md):
`createPageMetadata` with the `content` option recognizes entries by itself and builds a correct
canonical/hreflang with the prefix for them (see seo.md):
```ts
const pageMetadata = createPageMetadata({
config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
content: contentConfig, // ← bez tego wpisy dostają zły adres
content: contentConfig, // ← without this, entries get the wrong address
})
```
## Przełącznik języka
## Language switcher
`switchLocalePath` (z i18n) uwzględnia prefiks: polski wpis bez tłumaczenia EN
prowadzi do archiwum EN (`/en/articles`), nie na stronę główną — najbliżej tego,
czego szuka odwiedzający.
`switchLocalePath` (from i18n) takes the prefix into account: a Polish entry with no EN translation
leads to the EN archive (`/en/articles`), not to the home page — closest to what
the visitor is looking for.
## Redirecty ze slug history — resolveRedirect
## Redirects from slug history — resolveRedirect
Para do `trackSlugHistoryHook` (patrz [hooks.md](./hooks.md)): hook zapisuje
stare slugi, `resolveRedirect` zamienia je z powrotem na 301/308, żeby zmiana
slug nie dawała 404. Wywołujesz w catch-all, gdy `resolveRoute` nic nie znajdzie:
The pair to `trackSlugHistoryHook` (see [hooks.md](./hooks.md)): the hook saves
old slugs, `resolveRedirect` turns them back into 301/308, so a slug change
does not give a 404. Call it in the catch-all when `resolveRoute` finds nothing:
```tsx
import { resolveRoute, resolveRedirect } from '@intecion/ipal-kit'
@@ -242,29 +249,31 @@ const route = await resolveRoute({ /* … */ })
if (!route) {
const dest = await resolveRedirect({
payload, locale, segments: slug, config: i18nConfig, homeSlug,
collections: [{ slug: 'pages' }], // domyślnie [{ slug: 'pages' }]
collections: [{ slug: 'pages' }], // default [{ slug: 'pages' }]
})
if (dest) permanentRedirect(dest) // HTTP 308 — pod SEO równoważne 301
if (dest) permanentRedirect(dest) // HTTP 308 — equivalent to 301 for SEO
notFound()
}
```
Zwraca docelową ścieżkę (zlokalizowaną, z collapsowaniem home przez `homeSlug`)
albo `null`. Plugin tylko liczy — `permanentRedirect` woła projekt (plugin nie
importuje `next/navigation`). Każda kolekcja bez pola historii jest pomijana
bezpiecznie. `collections[].historyField` (domyślnie `'slugHistory'`) i
`slugField` (domyślnie `'slug'`) konfigurowalne.
Returns the target path (localized, with home collapsed via `homeSlug`)
or `null`. The plugin only computes — the project calls `permanentRedirect` (the plugin does not
import `next/navigation`). Any collection without a history field is skipped
safely. `collections[].historyField` (default `'slugHistory'`) and
`slugField` (default `'slug'`) are configurable. A never-published document (`_status: 'draft'`)
does not redirect — its new slug does not leak through a redirect. Preview (`draftMode()`):
`resolveRedirect({ …, draft: true })`.
Ograniczenia: tylko kolekcje „płaskie" (slug → ścieżka). Wpisy w archiwach
(`/artykuly/<wpis>`) nie są jeszcze obsługiwane. Jeśli `slug` jest `localized`,
rozważ `slugHistory` też `localized`, by historie języków się nie nakładały.
Limitations: only "flat" collections (slug → path). Entries in archives
(`/artykuly/<entry>`) are not supported yet. If `slug` is `localized`,
consider making `slugHistory` `localized` too, so the language histories do not overlap.
## Markdown per strona — czytelność dla AI (GEO)
## Markdown per page — readability for AI (GEO)
Agenci (WebFetch Claude'a, GPT, Perplexity) czytają stronę rzetelnie, gdy dostają
czysty Markdown zamiast parsować HTML. `createMarkdownRenderer` renderuje stronę
(tytuł + meta description + `blocks`) do Markdown; wpinasz go w route, który
serwuje np. `/md/pl/o-nas`:
Agents (Claude's WebFetch, GPT, Perplexity) read a page reliably when they get
clean Markdown instead of parsing HTML. `createMarkdownRenderer` renders a page
(title + meta description + `blocks`) to Markdown; you wire it into a route that
serves e.g. `/md/pl/o-nas`:
```ts
// app/md/[locale]/[[...slug]]/route.ts
@@ -272,24 +281,24 @@ import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit'
import { getPayload } from 'payload'
import config from '@payload-config'
const render = createMarkdownRenderer({ content }) // content = ta sama opcja co w pluginie
const render = createMarkdownRenderer({ content }) // content = the same option as in the plugin
export const dynamic = 'force-dynamic'
export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) {
const { locale, slug } = await params
const md = await render({ payload: await getPayload({ config }), locale, slug })
return markdownResponse(md) // text/markdown albo 404
return markdownResponse(md) // text/markdown or 404
}
```
Jak to działa pod spodem:
- **`blocksToMarkdown(layout)`** — ekstrakcja po KONWENCJI nazw pól (heading→`##`,
subheading→`###`, body/content→tekst/richtext, image→`![]()`, tablice
items/faq/… rekurencyjnie). Pola nawigacyjne (ctaTarget, id, slug) są pomijane.
Bloki nietypowe: `overrides` per blockType.
- **`lexicalToMarkdown(data)`** — konwerter pojedynczego pola richText (bold, kursywa,
linki, listy, cytaty, obrazy). Samodzielny, bez zależności od eksportu MD Payloada
(odporny na bump wersji). Szczegóły: [richtext.md](./richtext.md).
How it works under the hood:
- **`blocksToMarkdown(layout)`** — extraction by field-name CONVENTION (heading→`##`,
subheading→`###`, body/content→text/richtext, image→`![]()`, arrays
items/faq/… recursively). Navigation fields (ctaTarget, id, slug) are skipped.
Unusual blocks: `overrides` per blockType.
- **`lexicalToMarkdown(data)`** — a converter for a single richText field (bold, italics,
links, lists, quotes, images). Standalone, no dependency on Payload's MD export
(survives version bumps). Details: [richtext.md](./richtext.md).
```ts
blocksToMarkdown(page.layout, {
@@ -297,52 +306,54 @@ blocksToMarkdown(page.layout, {
})
```
Opcje `createMarkdownRenderer`: `content`, `collection` (`'pages'`),
`createMarkdownRenderer` options: `content`, `collection` (`'pages'`),
`settingsSlug` (`'site-settings'`), `layoutField` (`'layout'`), `overrides`, `frontmatter`
(domyślnie true — blok YAML `locale`, `title`, `description`, `url`, `updated`), `baseUrl`
(daje `url:` — kanoniczny adres HTML), `config` (i18n — przy jednym języku `url:` bez `/pl`).
(default true — a YAML block with `locale`, `title`, `description`, `url`, `updated`), `baseUrl`
(gives `url:` — the canonical HTML address), `config` (i18n — with one language `url:` has no `/pl`).
`markdownResponse(md, { canonical? })` — `null` → 404 `text/plain`; inaczej `text/markdown`,
`x-robots-tag: noindex`, `s-maxage=3600`, opcjonalny nagłówek `Link: <…>; rel="canonical"`.
`markdownResponse(md, { canonical? })` — `null` → 404 `text/plain`; otherwise `text/markdown`,
`x-robots-tag: noindex`, `s-maxage=3600`, optional `Link: <…>; rel="canonical"` header.
Krócej — cały route w jednej linii:
Shorter — the whole route in one line:
```ts
// app/md/[locale]/[[...slug]]/route.ts (jednojęzyczny: app/md/[[...slug]]/route.ts)
export { markdownRoute as GET } from '@/lib/content' // opcje: createContentHelpers({ markdown })
// app/md/[locale]/[[...slug]]/route.ts (single-language: app/md/[[...slug]]/route.ts)
export { markdownRoute as GET } from '@/lib/content' // options: createContentHelpers({ markdown })
export const dynamic = 'force-dynamic'
// albo bez lib/content:
// export const { GET } = createMarkdownRoute({ getCachedPayload, content, config: i18nConfig, baseUrl })
// or without lib/content:
// export const { GET } = createMarkdownRoute({ getCachedPayload, content, config: i18nConfig, baseUrl, isPathVisible })
```
`createMarkdownRoute` / `markdownRoute`: 404 dla nieznanych/nieopublikowanych stron, błąd bazy → 503.
`createMarkdownRoute` / `markdownRoute`: 404 for unknown/unpublished pages, database error → 503.
Under-construction mode: with `isPathVisible` (`markdownRoute` from `createContentHelpers` passes it by itself),
pages hidden by Site Settings → Under construction also give 404.
Komplet pod AI: ten endpoint + `llms.txt` (patrz [seo.md](./seo.md)) + wpuszczenie
botów w robots.txt.
The full AI set: this endpoint + `llms.txt` (see [seo.md](./seo.md)) + letting
bots in through robots.txt.
### Wykrywalność i negocjacja treści
### Discoverability and content negotiation
Żeby agent WIEDZIAŁ o wersji Markdown, ogłoś ją w `<head>` strony jako alternatę
(`markdownHref` trzyma prefiks `/md` w jednym miejscu):
So that an agent KNOWS about the Markdown version, announce it in the page `<head>` as an alternate
(`markdownHref` keeps the `/md` prefix in one place):
```ts
// generateMetadata strony
// the page's generateMetadata
import { markdownHref } from '@intecion/ipal-kit'
return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }
// → <link rel="alternate" type="text/markdown" href="/md/pl/o-nas">
```
Najprościej: `createContentHelpers({ …, markdownAlternate: true })` — wtedy
`generatePageMetadata` dokłada ten link sam (tylko strony indeksowalne; prefiks:
Simplest: `createContentHelpers({ …, markdownAlternate: true })` — then
`generatePageMetadata` adds this link by itself (indexable pages only; prefix:
`markdownAlternate: '/ai'`).
**Proxy (obowiązkowe, AGENT.md §0b):** `createProxy(i18nConfig, { NextResponse, markdown: true })`.
Bez tego na stronie wielojęzycznej proxy przekierowuje `/md/pl/o-nas` na
`/pl/md/pl/o-nas` (traktuje `md` jak ścieżkę bez języka), więc trasa Markdown nie
działa. Opcja przepuszcza ścieżki `/md/…` i robi negocjację `Accept` poniżej.
**Proxy (mandatory, AGENT.md §0b):** `createProxy(i18nConfig, { NextResponse, markdown: true })`.
Without it, on a multi-language site the proxy redirects `/md/pl/o-nas` to
`/pl/md/pl/o-nas` (it treats `md` as a path without a language), so the Markdown route does not
work. The option lets `/md/…` paths through and does the `Accept` negotiation below.
Ręcznie (gdy masz własny proxy): ten sam URL serwuje Markdown przy negocjacji nagłówkiem `Accept`
(rewrite w proxy):
Manually (when you have your own proxy): the same URL serves Markdown on negotiation with the `Accept` header
(a rewrite in the proxy):
```ts
// proxy.ts
@@ -352,63 +363,64 @@ if (prefersMarkdown(request)) {
}
```
`prefersMarkdown` respektuje q-values (wyżej ważony `text/html` wygrywa). Prefiks
zmienisz drugim argumentem `markdownHref(path, '/ai')` — pamiętaj wtedy o tym
samym w nazwie katalogu route'a.
`prefersMarkdown` respects q-values (a higher-weighted `text/html` wins). Change the prefix
with the second argument, `markdownHref(path, '/ai')` — then remember to use the same
in the route's folder name.
## Wyszukiwanie treści — searchContent / createSearchRoute
## Content search — searchContent / createSearchRoute
Jedna logika wyszukiwania (po `title` i `meta.description`, tylko kolekcja
`collection` — domyślnie `pages`; wpisy kolekcji `content` NIE są przeszukiwane) zasila i wyszukiwarkę
na stronie, i agentów, i narzędzie `search_content` serwera MCP — to samo
rankowanie wszędzie. `createSearchRoute` wystawia endpoint JSON:
One search logic (by `title` and `meta.description`, only the `collection` collection
— `pages` by default; entries of `content` collections are NOT searched) powers the on-site search,
the agents, and the MCP server's `search_content` tool — the same
ranking everywhere. `createSearchRoute` exposes a JSON endpoint:
```ts
// app/api/search/route.ts
import { createSearchRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content'
import { getCachedPayload, isPathVisible } from '@/lib/content'
import { i18nConfig } from '@/i18n.config'
export const dynamic = 'force-dynamic'
export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, isPathVisible })
```
Query: `?q=` (wymagane), `?locale=`, `?limit=`. Odpowiedź:
Query: `?q=` (required), `?locale=`, `?limit=`. Response:
```json
{ "query": "nas", "locale": "pl", "count": 1,
"results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] }
```
Brak `q` → 400. Tylko opublikowane, bez `noindex` (`noindex` albo `meta.noindex`),
domyślnie 10 (`defaultLimit`), maks. 50 wyników. Błąd/baza
offline → pusty wynik (200), nie 500. **Limit zapytań:** 120/min na IP (w pamięci,
per instancja) → `429` z `Retry-After`; zmiana: `rateLimit: { max, windowMs }`,
wyłączenie (limiter z przodu, np. Cloudflare WAF): `rateLimit: false`.
Kolizja z `@payloadcms/plugin-search` (kolekcja `search` → REST pod `/api/search/...`):
przenieś route, np. `app/api/site-search/route.ts`. Niska wartość `s-maxage` (60s) — wyniki świeże, ale z
cache'em CDN.
No `q` → 400. Published only, without `noindex` (`noindex` or `meta.noindex`),
10 by default (`defaultLimit`), max 50 results. Under-construction mode:
pass `isPathVisible` from `createContentHelpers`, and hidden pages drop out of the results. Error/database
offline → empty result (200), not 500. **Rate limit:** 120/min per IP (in memory,
per instance) → `429` with `Retry-After`; change it: `rateLimit: { max, windowMs }`,
turn it off (a limiter in front, e.g. Cloudflare WAF): `rateLimit: false`.
Collision with `@payloadcms/plugin-search` (the `search` collection → REST under `/api/search/...`):
move the route, e.g. `app/api/site-search/route.ts`. Low `s-maxage` (60s) — fresh results, but with
CDN caching.
Sam helper (do własnej wyszukiwarki po stronie serwera):
The helper itself (for your own server-side search):
```ts
import { searchContent } from '@intecion/ipal-kit'
const results = await searchContent({ payload, query, config, locale, limit, baseUrl })
// SearchResult[] = { title, url, description?, slug }[]
```
Opcje `searchContent`: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `locale`
(domyślnie/nieprawidłowy → `defaultLocale`), `limit` (10, przycinane do 1–50),
`summaryField` (np. `'aiSummary'` — preferuje bogatszy opis z
`buildSummaryField` nad `meta.description`; patrz [seo.md](./seo.md)). Nigdy nie rzuca
(błąd → `[]`).
`searchContent` options: `collection` (`'pages'`), `baseUrl`, `homeSlug`, `locale`
(default/invalid → `defaultLocale`), `limit` (10, clamped to 1–50),
`summaryField` (e.g. `'aiSummary'` — prefers the richer description from
`buildSummaryField` over `meta.description`; see [seo.md](./seo.md)). Never throws
(error → `[]`).
`createSearchRoute` przyjmuje dodatkowo `getCachedPayload`, `config` (wymagane),
`defaultLimit` (10), `rateLimit`, `clientIp` (patrz `clientIp()` w security.md).
`createSearchRoute` additionally takes `getCachedPayload`, `config` (required),
`defaultLimit` (10), `rateLimit`, `clientIp` (see `clientIp()` in security.md), `isPathVisible`.
`listContent({ payload, config, locale, limit, … })` — te same wyniki bez zapytania:
wszystkie opublikowane, indeksowalne strony po tytule (`limit` 50, max 200). To spis
stron dla narzędzia MCP `list_pages`.
`listContent({ payload, config, locale, limit, … })` — the same results without a query:
all published, indexable pages by title (`limit` 50, max 200). A list
of pages, like the MCP `list_pages` tool.
## Eksport
## Exports
```ts
import {
@@ -436,11 +448,11 @@ import {
import type { ContentOption, ContentCollectionOption, ResolvedRoute, ArchiveEntries, SearchResult } from '@intecion/ipal-kit'
```
## Wyłączenie, nadpisanie, rozszerzenie
## Turn off, override, extend
- Wyłączenie: pomiń opcję `content` — pola archiwów nie powstają, `resolveRoute` rozpoznaje tylko strony.
- Per kolekcja nadpisujesz `label` i `perPage`; nazwa pola archiwum (`{slug}Archive`) jest stała.
- Listing: `getArchiveEntries` przyjmuje `sort`, `where`, `depth`, `draft` — własne sortowanie/filtry bez zmiany routingu.
- Markdown: `createMarkdownRenderer({ overrides, layoutField, frontmatter, collection })`, `blocksToMarkdown(…, { overrides })`; prefiks inny niż `/md` przez `markdownHref(path, '/ai')` + `createProxy({ markdown: '/ai' })`.
- Wyszukiwanie: `searchContent` / `listContent` do własnego endpointu; `createSearchRoute({ rateLimit: false | { max, windowMs }, collection, summaryField })`.
- Głębokość tras (`{archiwum}/{wpis}`) i paginacja przez `?page=` są obecnie stałe — inny schemat URL wymaga własnego routera.
- Turn off: omit the `content` option — the archive fields are not created, `resolveRoute` recognizes only pages.
- Per collection you override `label` and `perPage`; the archive field name (`{slug}Archive`) is fixed.
- Listing: `getArchiveEntries` takes `sort`, `where`, `depth`, `draft` — your own sorting/filters without changing routing.
- Markdown: `createMarkdownRenderer({ overrides, layoutField, frontmatter, collection })`, `blocksToMarkdown(…, { overrides })`; a prefix other than `/md` via `markdownHref(path, '/ai')` + `createProxy({ markdown: '/ai' })`; `createMarkdownRoute({ isPathVisible })` for construction mode.
- Search: `searchContent` / `listContent` for your own endpoint; `createSearchRoute({ rateLimit: false | { max, windowMs }, collection, summaryField, isPathVisible })`.
- Route depth (`{archive}/{entry}`) and pagination via `?page=` are currently fixed — a different URL scheme needs your own router.