Merge SEO, GEO and Search Console track

Conflict in createContentHelpers.ts resolved by keeping both: isPathVisible (per-path, security track) and constructionPaths (per-list, SEO track).

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

# Conflicts:
#	src/modules/frontend/createContentHelpers.ts
This commit is contained in:
Radosław Smoliński
2026-10-22 17:48:22 +02:00
25 changed files with 1255 additions and 78 deletions
+10 -3
View File
@@ -1,6 +1,6 @@
---
name: ipal-seo-check
description: Checks a running ipal-kit site the way Googlebot and AI agents see it — metadata inside <head> (not streamed to body), title, description, self canonical, hreflang with x-default, noindex pages leaking into the sitemap, error pages in the sitemap, robots.txt, soft 404s, favicon, JSON-LD, and GEO (llms.txt, llms-full.txt, Markdown version, text/markdown alternate, MCP server, AI bots in robots, health). Use after building pages, before handing over, after deploys, after an ipal-kit upgrade, and whenever SEO, indexing, Search Console or "Google doesn't see" problems come up.
description: Checks a running ipal-kit site the way Googlebot and AI agents see it — metadata inside <head> (not streamed to body), title, description, self canonical, hreflang with x-default, noindex pages leaking into the sitemap, error pages in the sitemap, sitemap index parts, Search Console / Bing verification tags, robots.txt, soft 404s, favicon, JSON-LD, and GEO (llms.txt, llms-full.txt, Markdown version, text/markdown alternate, MCP server, AI bots in robots, health). Use after building pages, before handing over, after deploys, after an ipal-kit upgrade, and whenever SEO, indexing, Search Console or "Google doesn't see" problems come up.
---
# ipal-seo-check
@@ -31,11 +31,18 @@ Sprawdza **działającą** aplikację, nie kod — dokładnie to, co dostaje Goo
| no JSON-LD structured data | brak `<SiteProviders>` / `<JsonLdGraph>` w `[locale]/layout.tsx` albo pusta nazwa w Site Settings |
| `/llms.txt` / `/llms-full.txt` → 404 | brak trasy (`export { llmsRoute as GET }` / `llmsFullRoute` z `lib/content`) |
| Markdown version `/md/…` → 404 | brak `src/app/md/[locale]/[[...slug]]/route.ts`; strona noindex/draft |
| `sitemap.xml → 503` | baza niedostępna przy budowaniu sitemapy (`sitemapRoute` zwraca 503 + Retry-After zamiast pustej) — sprawdź `DATABASE_URL` / zdrowie bazy |
| sitemap index parts not 200 | serwis > `maxUrls` (10 000) → `/sitemap.xml` to index; części `?part=N` muszą odpowiadać 200 — własna trasa bez obsługi `part` albo cache CDN ze starą liczbą części |
| MCP not answering initialize | brak `src/app/api/mcp/route.ts` albo Cloudflare Access bez Bypass (mcp.md) |
3. `[WARNING]` oceń: brak opisu / zduplikowane tytuły to **treść w panelu** —
3. `no verification meta tag` (INFO — not counted as an error or warning) — with domain
verification by DNS (recommended) this is the correct state; do nothing. Only for
URL-prefix verification, paste the code in **Site Settings → Search & AI**.
`robots.txt blocks AI bots` — sprawdź też Site Settings → Search & AI → AI crawlers
(gdy projekt używa `getRobots`, redaktor mógł zmienić politykę).
4. `[WARNING]` oceń: brak opisu / zduplikowane tytuły to **treść w panelu** —
uzupełnij z briefu albo wypisz w raporcie dla klienta.
4. Uruchom ponownie aż `0 error(s)`.
5. Uruchom ponownie aż `0 error(s)`.
## Czego skrypt nie sprawdzi
Search Console (indeksacja, ręczne działania), Core Web Vitals, poprawność
@@ -29,7 +29,8 @@ let warnings = 0
const findings = []
const report = (level, title, rule, items = []) => {
if (level === 'ERROR') errors += Math.max(items.length, 1)
else warnings += Math.max(items.length, 1)
else if (level === 'WARNING') warnings += Math.max(items.length, 1)
// INFO: shown, never counted — a note, not a problem
findings.push({ level, title, rule, items })
}
const get = async (path, opts = {}) => {
@@ -73,14 +74,30 @@ else {
const sitemap = await get('/sitemap.xml')
let urls = []
let hasAlternates = false
if (sitemap.res.status !== 200) report('ERROR', `sitemap.xml → ${sitemap.res.status}`, 'export sitemap from lib/content + force-dynamic')
const locs = (xml) => [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/&amp;/g, '&'))
if (sitemap.res.status === 503) report('ERROR', 'sitemap.xml → 503', 'the database was unreachable while building it (sitemapRoute answers 503 + Retry-After) — check DATABASE_URL / DB health')
else if (sitemap.res.status !== 200) report('ERROR', `sitemap.xml → ${sitemap.res.status}`, 'export sitemapRoute (or sitemap) from lib/content + force-dynamic')
else {
urls = [...new Set([...sitemap.text.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1]))]
hasAlternates = /hreflang=/.test(sitemap.text)
let xml = sitemap.text
// Large sites: /sitemap.xml is a <sitemapindex> of parts (?part=N) — read every part.
if (/<sitemapindex/i.test(xml)) {
const parts = locs(xml)
const broken = []
xml = ''
for (const part of parts.slice(0, 50)) {
const r = await get(part).catch(() => null)
if (!r || r.res.status !== 200) broken.push(`${part} → ${r?.res.status ?? 'unreachable'}`)
else xml += r.text
}
console.log(`sitemap index: ${parts.length} part(s)`)
if (broken.length) report('ERROR', 'sitemap index parts not 200', 'every <sitemap><loc> must answer 200 (seo.md → Duży serwis)', broken)
}
urls = [...new Set(locs(xml))]
hasAlternates = /hreflang=/.test(xml)
if (urls.length === 0) report('ERROR', 'sitemap.xml is empty', 'DB unreachable at build without force-dynamic, or no published pages')
const foreign = urls.filter((u) => !u.startsWith('http') || /localhost|127\.0\.0\.1/.test(u) !== /localhost|127\.0\.0\.1/.test(origin))
if (foreign.length) report('ERROR', 'sitemap URLs relative or on another host', 'NEXT_PUBLIC_SERVER_URL / baseUrl', foreign.slice(0, 5))
if (/(\/404|\/500|not-found)(\/|<|$)/.test(sitemap.text)) report('ERROR', 'error pages listed in the sitemap', 'pages.md — 404 page is excluded by ID')
if (/(\/404|\/500|not-found)(\/|<|$)/.test(xml)) report('ERROR', 'error pages listed in the sitemap', 'pages.md — 404 page is excluded by ID')
}
// --- 4. sampled pages -----------------------------------------------------
@@ -209,6 +226,17 @@ if (issues.noLinks.length) report('WARNING', 'pages without internal links', 'li
if (!skipped('jsonld') && issues.jsonLd.length) report('ERROR', 'no JSON-LD structured data', '<JsonLdGraph> WebSite + Organization in [locale]/layout.tsx (AGENT.md §0b.4)', issues.jsonLd.slice(0, 5))
if (!skipped('markdown') && issues.mdAlt.length) report('WARNING', 'no text/markdown alternate link in head', 'createContentHelpers({ markdownAlternate: true }) (AGENT.md §0b.6)', issues.mdAlt.slice(0, 3))
// --- 4b. Search Console / Bing verification tags (Site Settings → Search & AI) ----
// INFO only: domain (DNS) verification — the recommended route — leaves the tags empty.
if (!skipped('verification') && sample.length) {
const page = await get(sample[0]).catch(() => null)
const head = page?.text.split(/<\/head>/i)[0] ?? ''
const missing = [['google-site-verification', 'Google Search Console'], ['msvalidate.01', 'Bing Webmaster Tools']]
.filter(([name]) => !new RegExp(`<meta[^>]+name="${name}"`, 'i').test(head))
.map(([, label]) => label)
if (missing.length) report('INFO', 'no verification meta tag (fine with DNS / domain verification)', 'only for URL-prefix verification: paste the code in Site Settings → Search & AI', missing)
}
// --- 5. 404 ---------------------------------------------------------------
const firstLocale = [...byLocale.keys()].find((l) => l && l.length <= 5) ?? ''
for (const path of [`/${firstLocale ? firstLocale + '/' : ''}ipal-seo-check-${Date.now()}`]) {
+158 -6
View File
@@ -306,7 +306,16 @@ Co zawiera sitemapa:
- `lastModified` z realnego `updatedAt` dokumentu
- wpisy bloga z prefiksem archiwum (`/pl/artykuly/moj-post`)
Pomija: drafty (`_status !== 'published'`) i dokumenty z `meta.noindex`.
Pomija: drafty (`_status !== 'published'`) i dokumenty z `meta.noindex`. Gdy
**Site Settings → Under construction** jest włączone — wszystko poza stronami, które
zostają otwarte (strona główna + „Pages still available”), bo reszta przekierowuje na
komunikat i crawler zaindeksowałby go zamiast treści. To samo robi `llms.txt`.
Duże kolekcje (1.13): dokumenty czytane partiami po 500 (`SITEMAP_BATCH_SIZE`), tylko
opublikowane (`where _status` przy kolekcji z draftami) i tylko potrzebne pola
(`select`: slug, updatedAt, noindex, meta). Własne `sitemapImages` może czytać dowolne
pole, więc wtedy czytany jest cały dokument (`buildSitemapEntries({ select: true })`
wymusza select).
Niskopoziomowo (własna trasa zamiast handlera z fabryki):
@@ -318,8 +327,47 @@ const entries = await buildSitemapEntries({
})
```
Przy dziesiątkach tysięcy URL-i Next ma `generateSitemaps` do dzielenia na
części — dodasz, gdyby realnie było ich tyle. Jedna sitemapa wystarcza do ~50k.
### Duży serwis — sitemap index, cache, błędy (1.13)
`sitemapRoute` (`createSitemapRouteHandler`) dzieli sitemapę sam, gdy URL-i jest więcej
niż `maxUrls` (domyślnie 10 000 — protokół pozwala 50 000 / 50 MB, ale hreflang robi
z każdego URL-a kilka linii):
- `/sitemap.xml` → `<sitemapindex>` z częściami `/sitemap.xml?part=1`, `?part=2`…;
każda część ma `lastmod` = najnowszy `lastmod` jej URL-i.
- robots.txt i Search Console zostają przy jednym adresie `/sitemap.xml`.
- Nieistniejąca część → 404.
| Opcja | Domyślnie | Co robi |
|---|---|---|
| `maxUrls` | `10000` | URL-i w jednym pliku; powyżej — index + części |
| `cacheControl` | `public, max-age=0, s-maxage=3600, stale-while-revalidate=86400` | CDN trzyma godzinę, przeglądarka sprawdza za każdym razem; `false` = bez nagłówka |
| `memoSeconds` | `300` | ile sekund proces trzyma zbudowaną listę (index i części nie budują jej od nowa); `0` = wyłączone |
```ts
createContentHelpers({ …, sitemapOptions: { maxUrls: 5000, memoSeconds: 0 } }) // sitemapRoute
createSitemapRouteHandler(sitemap, { maxUrls: 5000, memoSeconds: 0 }) // własna trasa
```
Ostatnie słowo ma projekt — `sitemapEntries` dostaje wpisy pluginu i zwraca listę do
publikacji (dodaj adresy własnych tras, usuń, ustaw `priority`):
```ts
createContentHelpers({ …,
sitemapEntries: (entries) => [...entries, { url: `${origin}/kalkulator`, lastModified: new Date() }],
})
```
Filtr „Under construction” w sitemapie i llms.txt wyłączasz `underConstructionSeo: false`.
Błąd bazy w runtime → **503 + `Retry-After: 300`** (crawler wróci), nie pusta sitemapa
z 200 („strona nie ma podstron”). Pusta odpowiedź i błąd nigdy nie idą z cache.
Wyjątek: `next build` (`NEXT_PHASE=phase-production-build`) dalej dostaje pustą,
poprawną sitemapę, żeby build bez bazy nie padł. `sitemap()` z `createContentHelpers`
też rzuca błąd w runtime (wcześniej zwracał `[]`).
`app/sitemap.ts` (MetadataRoute) nie dzieli — przy dużym serwisie użyj `sitemapRoute`.
Własna trasa: `buildSitemapIndexXml([{ url, lastModified }], { cssUrl })` składa sam index.
## Favicon w Google + Organization (branding w wyszukiwarce)
@@ -557,7 +605,7 @@ export const revalidate = 3600 // cache 1h, regeneracja w tle
> pokaże zmian redaktora od razu (czeka do rewalidacji). Dla treści zmienianej
> rzadko OK. Jeśli redaktor ma widzieć zmiany natychmiast — użyj **on-demand
> revalidation**: hook `afterChange` w kolekcji → `revalidatePath(path)` (patrz
> HOOKS.md). Albo krótszy `revalidate` (np. 300 = 5 min). NIE łącz ISR z
> [hooks.md](./hooks.md)). Albo krótszy `revalidate` (np. 300 = 5 min). NIE łącz ISR z
> `force-dynamic` — wykluczają się.
### Rozwiązanie DRUGIE — usuń jawny <head> z layoutu
@@ -1036,6 +1084,15 @@ Wymaga wypełnionego siteDescription i sensownych meta.description stron
(inaczej llms.txt będzie ubogi) — albo pola `aiSummary` (niżej), bogatszego niż
meta description.
Od 1.13:
- pod opisem trafia notka redaktora z **Site Settings → Search & AI → About the site for
AI assistants** (fakty do cytowania, per język) — sekcja „Search & AI” niżej;
- lista nie jest już ucinana na 1000 dokumentów (czytanie partiami; `collectSiteIndex({ limit })`
dalej przycina, jeśli chcesz);
- `llmsRoute` / `llmsFullRoute` z `createContentHelpers` przy włączonym „Under construction”
pokazują tylko otwarte strony (`createLlmsTxtRoute({ getIncludedPaths })` niskopoziomowo);
- odpowiedź ma `Cache-Control` jak sitemap (CDN godzinę), awaryjna — `no-store`.
### buildSummaryField — streszczenie dla AI (bogatsze niż meta)
Pole `aiSummary` (localized textarea) — zwięzły opis strony dla agentów,
@@ -1111,7 +1168,41 @@ Tryby `aiBots`:
Listy botów: `AI_ASSISTANT_BOTS`, `AI_TRAINING_BOTS` (eksportowane; nadpisujesz
przez `aiAssistantAgents` / `aiTrainingAgents`). `Next` akceptuje `rules` jako
tablicę — przy aktywnych botach AI zwracana jest tablica reguł.
tablicę — przy aktywnych botach AI zwracana jest tablica reguł. 1.13 dopisało
asystentów `Claude-User`, `MistralAI-User`, `DuckAssistBot`.
Wyjątki per bot — `aiBotRules` wygrywa z `aiBots`: bot z listy wychodzi ze swojej grupy
i dostaje własną regułę (można dopisać bota spoza list):
```ts
buildRobots({
baseUrl,
aiBots: 'block-training',
aiBotRules: [
{ userAgent: 'GPTBot', access: 'allow' }, // trening OpenAI jednak tak
{ userAgent: 'Bytespider', access: 'disallow' },
],
})
```
### Boty AI z panelu — getRobots (1.13)
Redaktor ustawia politykę i wyjątki w **Site Settings → Search & AI → AI crawlers**.
Żeby robots.txt je czytał, zamień `robots` na `getRobots` (async, czyta Site Settings
per żądanie):
```ts
// app/robots.ts
export { getRobots as default } from '@/lib/content'
export const dynamic = 'force-dynamic'
```
- Polityka „As set by the developer” (domyślna) = to, co w `createContentHelpers({ robots })`.
- Wyjątki z panelu dochodzą do `robots.aiBotRules` z kodu (panel na końcu, więc wygrywa).
- User agent z panelu: jeden token (`[\w\-.*/]`), bez spacji i nowych linii — wpis
„Bot\nDisallow: /” jest odrzucany, nie wstrzyknie reguły.
- Baza niedostępna → opcje z kodu. `IPAL_NOINDEX=1` dalej wygrywa ze wszystkim.
- `robots` (sync) zostaje bez zmian — ignoruje panel.
## Sitemap — czytelny w przeglądarce, zero plików w projekcie
@@ -1154,6 +1245,66 @@ Dwa sitemapy pod różnymi ścieżkami mylą crawlery. Wybierz jeden:
Oba tak samo dobre dla Google — to kwestia czytelności dla człowieka, nie SEO.
## Search & AI — weryfikacja Search Console, boty AI, notka llms.txt (1.13)
Zakładka **Site Settings → Search & AI** (włączona domyślnie; puste pola nic nie
zmieniają; `ipalKit({ seo: { …, searchSettings: false } })` ją usuwa; funkcja
`searchSettings: (fields) => fields` dostaje pola pluginu i zwraca własne — dodaj, usuń,
zmień etykiety; nazwy `searchVerification` / `aiCrawlers` / `llmsIntro` czytają helpery):
| Pole | Gdzie trafia |
|---|---|
| `searchVerification.google` | `<meta name="google-site-verification">` na każdej stronie |
| `searchVerification.bing` | `<meta name="msvalidate.01">` (Bing Webmaster — indeks Binga zasila ChatGPT Search i Copilot) |
| `searchVerification.yandex` | `<meta name="yandex-verification">` |
| `aiCrawlers.policy`, `aiCrawlers.rules` | robots.txt przez `getRobots` (wyżej) |
| `llmsIntro` (per język) | `/llms.txt` pod opisem strony |
Weryfikacja: redaktor wkleja sam kod **albo cały tag** `<meta … content="…">` z Search
Console — zapisuje się tylko kod; coś, co nie jest prostym tokenem, jest odrzucane
(wartość ląduje w `<head>` każdej strony). `generatePageMetadata` / `createPageMetadata`
dodają `verification` same — zero kodu w projekcie. Własny generator:
`verificationFrom(settings)` → `Metadata.verification`; robots: `robotsOptionsFrom(settings)`.
**Domain verification by DNS (recommended)** — a TXT record at the registrar. It needs
nothing from the plugin: leave the verification fields empty, and nothing warns. The
fields are only for URL-prefix verification (HTML tag).
Po wklejeniu kodu: Search Console → Zweryfikuj. Strona musi być zbudowana dynamicznie
albo po rewalidacji (ISR), żeby nowy tag był w HTML. Weryfikacja DNS dalej działa
niezależnie — pola zostaw puste.
Migracja: nowe kolumny w `site_settings` — projekt na Postgresie generuje migrację
(`payload migrate:create`) jak przy każdej aktualizacji z nowymi polami.
### Search Console API (dane w panelu) — nie wbudowane
Kliknięcia/zapytania z Search Console w adminie wymagają konta usługi Google (JSON z
kluczem prywatnym) dodanego jako użytkownik w usłudze GSC, i biblioteki `googleapis`
albo podpisu JWT. Plugin tego nie robi (decyzja: weryfikacja domeny, dane w samej Search Console).
## GEO — co plugin rozumie przez „widoczność w AI” (założenia)
GEO (generative engine optimization) = strona jest **znaleziona, przeczytana i
zacytowana** przez asystentów AI (ChatGPT, Claude, Perplexity, Gemini, Copilot). Plugin
przyjmuje, że realnie działają cztery rzeczy — nie ma ukrytych „rankingów AI”:
1. **Dostęp** — bot AI może pobrać stronę: robots.txt z jawnymi regułami (`aiBots`,
panel), brak blokady w CDN/WAF (tego plugin nie widzi — sprawdź Cloudflare
„Block AI bots”). Asystent (pobiera na żądanie użytkownika) ≠ crawler treningowy.
2. **Indeks, z którego asystent szuka** — Bing (ChatGPT Search, Copilot) → IndexNow +
weryfikacja Bing; Google (AI Overviews, Gemini) → sitemap + Search Console.
3. **Czytelna treść** — HTML renderowany na serwerze, Markdown (`/md/…`, `Link
rel=alternate`), `llms.txt` / `llms-full.txt` jako spis i pełna treść. `llms.txt` to
konwencja (llmstxt.org), nie standard — nic nie szkodzi, nie obiecuje ruchu.
4. **Sygnały do cytowania** — jednoznaczne fakty: Organization/LocalBusiness z `sameAs`,
`dateModified`/`datePublished` (Article, WebPage), okruszki, FAQ, `speakable`,
`aiSummary`, notka `llmsIntro` (kto, co, gdzie, od kiedy — zdania, które da się
zacytować bez kontekstu).
Plugin NIE: generuje treści „pod AI”, ukrywa treści przed ludźmi, serwuje botom AI innej
wersji niż ludziom (cloaking) ani mierzy cytowań (brak publicznego API).
## JsonLdGraph — opakowanie @graph (bez modelu firmy)
Plugin dostarcza klocki Schema.org (buildWebSiteJsonLd, buildOrganizationJsonLd,
@@ -1255,7 +1406,8 @@ Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
obsługuje IndexNow — dla niego sitemap.
Trasa klucza z `lib/content`: `export { indexNowKeyRoute as GET } from '@/lib/content'`.
Ręcznie (np. import treści skryptem): `submitToIndexNow({ payload, urls })` (klucz: `getIndexNowKey(payload)`)
— nigdy nie rzuca, tylko loguje.
— nigdy nie rzuca, tylko loguje. Z `IPAL_NOINDEX=1` (staging) nic nie wysyła, nawet przy
`NODE_ENV=production` (1.13).
- **llms.txt / llms-full.txt** obejmują wpisy kolekcji treści (`content`) i wszystkie języki; MCP
`list_pages` też. Wspólne źródło: `collectSiteIndex`.
+4
View File
@@ -11,6 +11,8 @@ type BuildSiteSettingsArgs = {
constructionFields?: Field[]
/** "Emails" tab — given with `forms: { emailLayout: true }`. */
emailFields?: Field[]
/** "Search & AI" tab — search-engine verification, AI crawlers, llms.txt note (seo module). */
searchFields?: Field[]
/**
* Fields for the "System Pages" tab — page assignments by role (homepage,
* privacy policy, collection archives). Assembled by the caller, which is the
@@ -37,6 +39,7 @@ export function buildSiteSettings({
additionalFields,
constructionFields,
emailFields,
searchFields,
systemPageFields,
}: BuildSiteSettingsArgs = {}): GlobalConfig {
return {
@@ -65,6 +68,7 @@ export function buildSiteSettings({
...(systemPageFields?.length
? [{ fields: systemPageFields, label: 'System Pages' }]
: []),
...(searchFields?.length ? [{ fields: searchFields, label: 'Search & AI' }] : []),
...(emailFields?.length ? [{ fields: emailFields, label: 'Emails' }] : []),
...(constructionFields?.length ? [{ fields: constructionFields, label: 'Under construction' }] : []),
...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),
+4 -1
View File
@@ -219,7 +219,10 @@ export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd, buildProductJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js'
export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
// Site Settings → Search & AI: verification codes and AI crawler rules, for custom metadata/robots routes.
export { robotsOptionsFrom, verificationFrom } from './modules/seo/index.js'
export type { AiBotRule, AiBotsPolicy, VerificationMetadata } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapIndexXml, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
+90 -9
View File
@@ -12,11 +12,12 @@ import type { I18nConfig } from '../i18n/index.js'
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
import type { CreateMcpRouteArgs } from '../mcp/createMcpRoute.js'
import type { FormNotificationTexts } from '../notifications/types.js'
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapStyleOptions } from '../seo/index.js'
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapRouteOptions, SitemapStyleOptions } from '../seo/index.js'
import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js'
import { getConsentTexts } from '../consent/getConsentTexts.js'
import { isPathVisibleIn } from '../construction/logic.js'
import { isPathAllowed, isPathVisibleIn } from '../construction/logic.js'
import { pathOf } from '../construction/visibility.js'
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
@@ -32,6 +33,7 @@ import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
import { createIndexNowKeyRoute } from '../seo/indexNow.js'
import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
import { robotsOptionsFrom } from '../seo/searchSettings.js'
import { type ThemeConfig, themeConfigFrom } from '../theme/theme.js'
import { getTurnstileConfig } from '../turnstile/config.js'
@@ -93,8 +95,19 @@ type CreateContentHelpersArgs = {
* LocalBusiness from the Company global); `false` = none.
*/
siteJsonLd?: ((ctx: { baseUrl: string; locale: string; settings: Record<string, unknown> }) => Promise<Record<string, unknown>[]> | Record<string, unknown>[]) | false
/**
* Last word on the sitemap: gets the plugin's entries (after the construction
* filter) and returns the list to publish — add URLs from your own routes,
* drop or reorder some, set priority. Used by `sitemap` and `sitemapRoute`.
*/
sitemapEntries?: (entries: SitemapEntry[]) => Promise<SitemapEntry[]> | SitemapEntry[]
/** Image URLs of a document for the sitemap (Google Images). Default: its SEO share image. */
sitemapImages?: (doc: Record<string, unknown>) => (null | string | undefined)[]
/**
* `sitemapRoute` behaviour: `maxUrls` (split into an index, default 10 000),
* `cacheControl` (string or false), `memoSeconds` (default 300, 0 = off).
*/
sitemapOptions?: Pick<SitemapRouteOptions, 'cacheControl' | 'maxUrls' | 'memoSeconds'>
/**
* Browser look of `sitemapRoute` (/sitemap.xml). Default: built-in style,
* header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML.
@@ -102,6 +115,11 @@ type CreateContentHelpersArgs = {
sitemapStyle?: false | SitemapStyleOptions
/** Field with the AI summary (buildSummaryField) — llms.txt and MCP prefer it. */
summaryField?: string
/**
* While Site Settings → Under construction is on, the sitemap and llms.txt
* list only the pages still open. Default true; false lists everything.
*/
underConstructionSeo?: boolean
}
/** What an entry's own JSON-LD builder gets (PageJsonLdOptions.entries). */
@@ -180,9 +198,12 @@ export function createContentHelpers({
settingsDepth = 1,
settingsSlug = 'site-settings',
siteJsonLd,
sitemapEntries: transformSitemap,
sitemapImages,
sitemapOptions,
sitemapStyle,
summaryField,
underConstructionSeo = true,
}: CreateContentHelpersArgs) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
const getCachedPayload = cache(
@@ -438,7 +459,7 @@ export function createContentHelpers({
)
}
try {
return await buildSitemapEntries({
const entries = await buildSitemapEntries({
baseUrl: origin,
config: i18n,
content,
@@ -447,10 +468,20 @@ export function createContentHelpers({
payload: await getCachedPayload(),
settingsSlug,
})
// Under construction: list only the pages visitors can still open — the
// rest redirect to the homepage notice, which crawlers would index.
// Same check as isPathVisibleIn(mode, pathOf(url)) (security-perf branch), with the
// mode read once for the whole list.
const open = await constructionPaths()
const visible = open ? entries.filter((e) => isPathAllowed(pathOf(e.url), open)) : entries
return transformSitemap ? await transformSitemap(visible) : visible
} catch (error) {
// DB unreachable (typically a container build with no DB network) — return
// an empty sitemap instead of failing the build. Runtime regeneration will
// produce the real one once the DB is reachable. See dynamic='force-dynamic'.
// At runtime a failure is an error (the sitemap route answers 503, so
// crawlers retry) — an empty sitemap would read as "no pages".
if (process.env.NEXT_PHASE !== 'phase-production-build') {throw error}
// DB unreachable during `next build` (container with no DB network) —
// return an empty sitemap instead of failing the build. Runtime regeneration
// produces the real one. See dynamic='force-dynamic'.
console.warn(
'[ipal] sitemap: could not reach the database, returning empty entries ' +
"(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to " +
@@ -471,6 +502,37 @@ export function createContentHelpers({
*/
const robots = (): RobotsRules => buildRobots({ ...robotsOptions, baseUrl: origin })
/**
* `robots` plus what editors set in Site Settings → Search & AI (AI bot policy
* and per-bot exceptions), read per request. Use it instead of `robots` to
* let the panel manage AI crawlers:
*
* ```ts
* // app/robots.ts
* export { getRobots as default } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* ```
*
* Database unreachable → the options from code, as `robots` returns.
*/
const getRobots = async (): Promise<RobotsRules> => {
let fromPanel: ReturnType<typeof robotsOptionsFrom> = {}
try {
const payload = await getCachedPayload()
fromPanel = robotsOptionsFrom(
(await payload.findGlobal({ slug: settingsSlug as never, depth: 0 })) as Record<string, unknown>,
)
} catch {
// keep the code options
}
return buildRobots({
...robotsOptions,
...fromPanel,
aiBotRules: [...(robotsOptions?.aiBotRules ?? []), ...(fromPanel.aiBotRules ?? [])],
baseUrl: origin,
})
}
/**
* Next.js generateStaticParams for the [[...slug]] route (or
* [locale]/[[...slug]]). Returns every routable page as a params object, so
@@ -599,7 +661,7 @@ export function createContentHelpers({
* export { sitemapRoute as GET } from '@/lib/content'
* export const dynamic = 'force-dynamic'
*/
const sitemapRoute = createSitemapRouteHandler(sitemap, { style: sitemapStyle ?? {} })
const sitemapRoute = createSitemapRouteHandler(sitemap, { ...sitemapOptions, style: sitemapStyle ?? {} })
const needI18n = (what: string): I18nConfig => {
if (!i18n) {throw new Error(`[ipal] createContentHelpers: pass \`i18n\` to use ${what}.`)}
@@ -713,6 +775,24 @@ export function createContentHelpers({
return isPathVisibleIn(await mode, path)
}
/**
* While Site Settings → Under construction is on: the paths still open (every
* language), which the sitemap and llms.txt list instead of everything.
* null when the site is open or the setting can't be read. Same rule as
* `isPathVisible`, but resolved ONCE per list: the sitemap may hold tens of
* thousands of URLs, and in a route handler React `cache` doesn't dedupe a
* per-URL settings read.
*/
const constructionPaths = async (): Promise<null | string[]> => {
if (!i18n || !underConstructionSeo) {return null}
try {
const mode = await getConstructionMode(i18n.defaultLocale)
return mode.enabled ? mode.allowedPaths : null
} catch {
return null
}
}
// ── Layout ────────────────────────────────────────────────────────────────
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
@@ -763,8 +843,8 @@ export function createContentHelpers({
let value: T | undefined
return () => (value ??= make())
}
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, isPathVisible, settingsSlug, ...markdownOptions }))
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, isPathVisible, settingsSlug, summaryField, ...mcpOptions }))
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
@@ -799,6 +879,7 @@ export function createContentHelpers({
getLinkOptions,
getNotFoundPage,
getPageJsonLd,
getRobots,
getSettings,
getSiteShell,
getSystemLinks,
+1
View File
@@ -212,6 +212,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
baseUrl: origin,
config,
content,
limit: 1000, // list_pages shows at most 200 — no need to read a huge site whole
locales: [locale],
pagesSlug: collection,
payload,
+11 -1
View File
@@ -6,6 +6,7 @@ import type { SiteIndexEntry } from './siteIndex.js'
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
import { getLocaleDefinition, isValidLocale } from '../i18n/index.js'
import { llmsIntroFrom } from './searchSettings.js'
import { collectSiteIndex } from './siteIndex.js'
type BuildLlmsTxtArgs = {
@@ -25,6 +26,8 @@ type BuildLlmsTxtArgs = {
* convention. Default false = the compact index (links + descriptions).
*/
full?: boolean
/** Only pages whose path passes — e.g. those open while the site is under construction. */
include?: (path: string) => boolean
/** Field holding the block layout (full mode only). Default 'layout'. */
layoutField?: string
/**
@@ -45,6 +48,7 @@ type BuildLlmsTxtArgs = {
}
type SettingsShape = {
[key: string]: unknown
siteDescription?: null | string
siteName?: null | string
}
@@ -57,7 +61,8 @@ const day = (iso?: string) => (iso ? iso.slice(0, 10) : undefined)
* buildSitemapEntries: the plugin already knows the site's name, description,
* and pages, so it can generate this automatically.
*
* Structure (llmstxt.org): H1 site name, a blockquote summary, then — per
* Structure (llmstxt.org): H1 site name, a blockquote summary, the editor's
* note from Site Settings → Search & AI (when set), then — per
* language when the site has several — one list per collection (pages first,
* then archive collections such as a blog) of Markdown links with descriptions.
* Section names are the project's own locale and collection labels; the plugin
@@ -74,6 +79,7 @@ export async function buildLlmsTxt({
config,
content,
full = false,
include,
layoutField = 'layout',
locale,
pagesSlug = 'pages',
@@ -99,6 +105,7 @@ export async function buildLlmsTxt({
config,
content,
depth: full ? 1 : 0,
include,
locales,
pagesSlug,
payload,
@@ -108,6 +115,9 @@ export async function buildLlmsTxt({
const lines: string[] = [`# ${name}`, '']
if (description) {lines.push(`> ${description}`, '')}
// Site Settings → Search & AI: facts the editor wants assistants to know and quote.
const intro = llmsIntroFrom(settings)
if (intro) {lines.push(intro, '')}
const multi = locales.length > 1
for (const loc of locales) {
+7
View File
@@ -1,5 +1,6 @@
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import type { TitleOrder } from './composeTitle.js'
import type { VerificationMetadata } from './searchSettings.js'
import type { SeoMeta } from './types.js'
import { buildLocalizedPath } from '../i18n/index.js'
@@ -59,6 +60,8 @@ export type PageMetadata = {
images?: string[]
title: string
}
/** Search console ownership tags (google-site-verification, msvalidate.01, yandex-verification). */
verification?: VerificationMetadata
}
type BuildMetadataArgs = {
@@ -122,6 +125,8 @@ type BuildMetadataArgs = {
siteName?: null | string
/** slug per locale for this document — drives canonical + hreflang. */
slugs: LocalizedSlugs
/** Site Settings → Search & AI verification codes; rendered as <meta> tags by Next. */
verification?: VerificationMetadata
}
/**
@@ -151,6 +156,7 @@ export function buildMetadata({
siteDescription,
siteName,
slugs,
verification,
}: BuildMetadataArgs): PageMetadata {
// Title source priority: titleOverride (exact, wins outright) > meta.title
// (SEO title an editor set) > pageTitle (the document's own name). This means
@@ -203,6 +209,7 @@ export function buildMetadata({
...(description && { description }),
...(ogImage ? { images: [ogImage.url] } : {}),
},
...(verification ? { verification } : {}),
// robots: noindex pages are excluded (follow keeps link authority). Indexed
// pages get generous snippet/preview limits so Google can show rich results
// (long snippets, large image previews, full video previews).
+39 -9
View File
@@ -12,12 +12,15 @@ type RobotRule = { allow?: string; disallow?: string[]; userAgent: string | stri
*/
export const AI_ASSISTANT_BOTS = [
'ClaudeBot',
'Claude-User',
'Claude-Web',
'Claude-SearchBot',
'ChatGPT-User',
'OAI-SearchBot',
'PerplexityBot',
'Perplexity-User',
'MistralAI-User',
'DuckAssistBot',
] as const
export const AI_TRAINING_BOTS = [
@@ -30,7 +33,10 @@ export const AI_TRAINING_BOTS = [
'Meta-ExternalAgent',
] as const
type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false
export type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false
/** One bot treated differently from the policy, e.g. { userAgent: 'Bytespider', access: 'disallow' }. */
export type AiBotRule = { access: 'allow' | 'disallow'; userAgent: string }
export type RobotsOptions = {
/**
@@ -41,6 +47,12 @@ export type RobotsOptions = {
adminRoute?: false | string
/** Override the assistant/search bot list. */
aiAssistantAgents?: readonly string[]
/**
* Per-bot exceptions that win over `aiBots` — a listed bot leaves its policy
* group and gets its own allow or block. Unknown bots can be added this way.
* Site Settings → Search & AI fills it when you use `getRobots`.
*/
aiBotRules?: readonly AiBotRule[]
/**
* How to treat AI crawlers (assistant/search + training). Default 'allow' —
* explicitly welcome them so the site stays visible to Claude, ChatGPT,
@@ -118,6 +130,7 @@ export type RobotsRules = {
export function buildRobots({
adminRoute = '/admin',
aiAssistantAgents = AI_ASSISTANT_BOTS,
aiBotRules = [],
aiBots = 'allow',
aiTrainingAgents = AI_TRAINING_BOTS,
baseUrl,
@@ -139,15 +152,32 @@ export function buildRobots({
const baseRule: RobotRule = { allow: '/', disallow, userAgent: '*' }
const aiRules: RobotRule[] = []
if (aiBots === 'allow') {
aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents, ...aiTrainingAgents] })
} else if (aiBots === 'block-training') {
aiRules.push({ allow: '/', disallow, userAgent: [...aiAssistantAgents] })
aiRules.push({ disallow: ['/'], userAgent: [...aiTrainingAgents] })
} else if (aiBots === 'disallow') {
aiRules.push({ disallow: ['/'], userAgent: [...aiAssistantAgents, ...aiTrainingAgents] })
// Exceptions: last rule per bot wins; those bots leave the policy groups.
const exceptions = new Map<string, AiBotRule>()
for (const r of aiBotRules) {
const ua = r.userAgent.trim()
if (ua) {exceptions.set(ua.toLowerCase(), { access: r.access, userAgent: ua })}
}
const notExcepted = (list: readonly string[]) => list.filter((ua) => !exceptions.has(ua.toLowerCase()))
const assistants = notExcepted(aiAssistantAgents)
const training = notExcepted(aiTrainingAgents)
const aiRules: RobotRule[] = []
const push = (rule: RobotRule) => {
if (rule.userAgent.length) {aiRules.push(rule)}
}
if (aiBots === 'allow') {
push({ allow: '/', disallow, userAgent: [...assistants, ...training] })
} else if (aiBots === 'block-training') {
push({ allow: '/', disallow, userAgent: assistants })
push({ disallow: ['/'], userAgent: training })
} else if (aiBots === 'disallow') {
push({ disallow: ['/'], userAgent: [...assistants, ...training] })
}
const allowed = [...exceptions.values()].filter((r) => r.access === 'allow').map((r) => r.userAgent)
const blocked = [...exceptions.values()].filter((r) => r.access === 'disallow').map((r) => r.userAgent)
push({ allow: '/', disallow, userAgent: allowed })
push({ disallow: ['/'], userAgent: blocked })
return {
rules: aiRules.length > 0 ? [baseRule, ...aiRules] : baseRule,
+59 -10
View File
@@ -52,10 +52,19 @@ type BuildSitemapArgs = {
/** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
payload: BasePayload
/**
* Read only the fields the sitemap needs (slug, dates, status, noindex, meta).
* Default: on with the default `images`, off with a custom `images` (it may
* read any field). `false` reads whole documents.
*/
select?: boolean
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
/** Documents read per query — keeps memory flat on large collections. */
export const SITEMAP_BATCH_SIZE = 500
type DocRow = {
[key: string]: unknown
_status?: string
@@ -140,6 +149,51 @@ function defaultImages(doc: Record<string, unknown>): (null | string | undefined
return image && typeof image === 'object' ? [(image as { url?: string }).url] : []
}
type CollectionConfigShape = {
flattenedFields?: { name?: string }[]
versions?: { drafts?: unknown } | false
}
/**
* Query shape for one collection: published only (when it has drafts) and,
* with `select`, just the fields entryFor/isIndexable read. Fields the
* collection doesn't have are left out of the select.
*/
function queryFor(payload: BasePayload, slug: string, select: boolean) {
const cfg = (payload.collections as Record<string, { config?: CollectionConfigShape }> | undefined)?.[slug]?.config
const hasDrafts = Boolean(cfg?.versions && cfg.versions.drafts)
const names = new Set((cfg?.flattenedFields ?? []).map((f) => f.name))
const pick = select && cfg?.flattenedFields
? Object.fromEntries(
['slug', 'updatedAt', 'noindex', 'meta']
.filter((n) => n === 'updatedAt' || names.has(n))
.concat(hasDrafts ? ['_status'] : [])
.map((n) => [n, true]),
)
: undefined
return {
...(hasDrafts ? { where: { _status: { equals: 'published' } } } : {}),
...(pick ? { select: pick } : {}),
}
}
/** Every document of a collection, SITEMAP_BATCH_SIZE at a time. */
async function* readAll(payload: BasePayload, slug: string, select: boolean): AsyncGenerator<DocRow> {
const query = queryFor(payload, slug, select)
for (let page = 1; ; page++) {
const result = await payload.find({
collection: slug as never,
depth: 1, // populate uploads so image URLs are available
limit: SITEMAP_BATCH_SIZE,
locale: 'all' as never,
page,
...(query as object),
})
yield* result.docs as DocRow[]
if (!result.hasNextPage) {return}
}
}
/**
* Collects every public URL — pages and archive entries — as sitemap entries
* with per-URL hreflang and lastmod.
@@ -170,6 +224,7 @@ export async function buildSitemapEntries({
images: imagesOf = defaultImages,
pagesSlug = 'pages',
payload,
select = imagesOf === defaultImages,
settingsSlug = 'site-settings',
}: BuildSitemapArgs): Promise<SitemapEntry[]> {
const origin = baseUrl.replace(/\/$/, '')
@@ -212,16 +267,10 @@ export async function buildSitemapEntries({
for (const collection of collections) {
// Read every doc once, across locales, so one row yields all its language
// alternates without re-querying per locale.
const result = await payload.find({
collection: collection.slug as never,
depth: 1, // populate uploads so image URLs are available
limit: 0, // no pagination — sitemap wants everything
locale: 'all' as never,
pagination: false as never,
})
for (const raw of result.docs as DocRow[]) {
// alternates without re-querying per locale. Batched, published only, and
// (by default) only the fields used here — a 20k-entry blog no longer
// loads every block of every post into memory at once.
for await (const raw of readAll(payload, collection.slug, select)) {
if (!isIndexable(raw)) {continue}
const images = [...new Set(imagesOf(raw).map(absolute).filter((u): u is string => Boolean(u)))]
+37 -11
View File
@@ -43,27 +43,53 @@ type BuildSitemapXmlOptions = {
* NOTE: if you use this custom route, DON'T also keep app/sitemap.ts — pick one.
* Two sitemaps confuse crawlers.
*/
const esc = (s: string): string =>
s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;')
const isoOf = (d: Date | string): string => (d instanceof Date ? d.toISOString() : String(d))
/** One child sitemap listed in a sitemap index. */
export type SitemapIndexItem = { lastModified?: Date | string; url: string }
/**
* Sitemap index (`<sitemapindex>`) — what /sitemap.xml returns once a site has
* more URLs than one file should hold. Each child carries the newest lastmod
* of its URLs, so crawlers re-read only the parts that changed.
*/
export function buildSitemapIndexXml(items: SitemapIndexItem[], opts: BuildSitemapXmlOptions = {}): string {
const stylesheet = opts.cssUrl ? `<?xml-stylesheet type="text/css" href="${esc(opts.cssUrl)}"?>\n` : ''
const body = items
.map((i) => {
const parts = [` <loc>${esc(i.url)}</loc>`]
if (i.lastModified) {parts.push(` <lastmod>${esc(isoOf(i.lastModified))}</lastmod>`)}
return ` <sitemap>\n${parts.join('\n')}\n </sitemap>`
})
.join('\n')
return (
`<?xml version="1.0" encoding="UTF-8"?>\n` +
stylesheet +
`<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n` +
body +
`\n</sitemapindex>`
)
}
export function buildSitemapXml(
entries: SitemapEntry[],
opts: BuildSitemapXmlOptions = {},
): string {
const { cssUrl } = opts
const esc = (s: string): string =>
s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;')
const urls = entries
.map((e) => {
const parts = [` <loc>${esc(e.url)}</loc>`]
if (e.lastModified) {
const iso =
e.lastModified instanceof Date ? e.lastModified.toISOString() : String(e.lastModified)
parts.push(` <lastmod>${esc(iso)}</lastmod>`)
parts.push(` <lastmod>${esc(isoOf(e.lastModified))}</lastmod>`)
}
if (e.changeFrequency) {parts.push(` <changefreq>${e.changeFrequency}</changefreq>`)}
if (typeof e.priority === 'number') {parts.push(` <priority>${e.priority}</priority>`)}
+3 -1
View File
@@ -145,6 +145,7 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
// fallback opisu: strona bez meta.description dostaje Site Settings → siteDescription (seo.md)
siteDescription: site.siteDescription,
siteName: site.siteName,
verification: site.verification,
}
const route = loaders?.resolveRoute
@@ -162,8 +163,9 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
// Unknown route (the page component will 404) — still return something
// coherent rather than throwing during metadata generation.
// noindex: a 404 must never be indexed, even if a host serves it with 200.
if (!route) {
return buildMetadata({ ...base, meta: null, slugs: {} })
return buildMetadata({ ...base, meta: null, noindex: true, slugs: {} })
}
const doc = route.doc as DocShape
+5 -2
View File
@@ -13,11 +13,12 @@ export { buildNoindexField } from './buildNoindexField.js'
export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js'
export { buildProductJsonLd } from './buildProductJsonLd.js'
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
export type { AiBotRule, AiBotsPolicy } from './buildRobots.js'
export type { RobotsOptions, RobotsRules } from './buildRobots.js'
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
export { buildSitemapEntries } from './buildSitemapEntries.js'
export type { SitemapEntry } from './buildSitemapEntries.js'
export { buildSitemapXml } from './buildSitemapXml.js'
export { buildSitemapIndexXml, buildSitemapXml } from './buildSitemapXml.js'
export { buildNavigationJsonLd, buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'
export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'
export { buildSummaryField } from './buildSummaryField.js'
@@ -42,8 +43,10 @@ export { injectSeoTabs } from './injectSeoTabs.js'
export { JsonLdGraph } from './JsonLdGraph.js'
export { readSiteMetaConfig } from './readSiteMetaConfig.js'
export type { SiteMetaConfig } from './readSiteMetaConfig.js'
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'
export { createLlmsTxtRoute, createSitemapRouteHandler, DEFAULT_SITEMAP_CACHE_CONTROL, DEFAULT_SITEMAP_MAX_URLS, SITEMAP_PART_PARAM } from './routeHandlers.js'
export type { SitemapRouteOptions } from './routeHandlers.js'
export { normalizeVerificationToken, robotsOptionsFrom, searchSettingsFields, verificationFrom } from './searchSettings.js'
export type { VerificationMetadata } from './searchSettings.js'
export { buildSeoPlugin } from './seoPluginConfig.js'
export { collectSiteIndex } from './siteIndex.js'
export type { CollectSiteIndexArgs, SiteIndexEntry } from './siteIndex.js'
+7 -1
View File
@@ -4,6 +4,7 @@ import type { I18nConfig } from '../i18n/index.js'
import { archiveFieldName } from '../content/types.js'
import { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs } from '../i18n/index.js'
import { isSiteNoindex } from './siteNoindex.js'
/**
* IndexNow — tell search engines a URL changed the moment it's published
@@ -76,9 +77,14 @@ export function createIndexNowKeyRoute({ getCachedPayload }: { getCachedPayload:
}
}
/** True when submissions may leave this machine: production + a public https origin. */
/**
* True when submissions may leave this machine: production + a public https
* origin, and not a staging copy (IPAL_NOINDEX) — a staging build runs with
* NODE_ENV=production too, and its URLs must not reach Bing.
*/
function publicOrigin(baseUrl?: string): null | string {
const origin = (baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '').replace(/\/$/, '')
if (isSiteNoindex()) {return null}
if (process.env.NODE_ENV !== 'production' || !/^https:\/\//i.test(origin)) {return null}
if (/localhost|127\.0\.0\.1|\.local\b|\.test\b/i.test(origin)) {return null}
return origin
+7
View File
@@ -1,6 +1,9 @@
import type { BasePayload } from 'payload'
import type { TitleOrder } from './composeTitle.js'
import type { VerificationMetadata } from './searchSettings.js'
import { verificationFrom } from './searchSettings.js'
type SettingsShape = {
[key: string]: unknown
@@ -25,6 +28,8 @@ export type SiteMetaConfig = {
/** Global fallback meta description. */
siteDescription?: null | string
siteName: null | string
/** Site Settings → Search & AI → verification codes (Search Console, Bing, Yandex). */
verification?: VerificationMetadata
}
/**
@@ -102,7 +107,9 @@ export async function readSiteMetaConfig({
}
const share = settings.defaultShareImage
const verification = verificationFrom(settings)
return {
...(verification ? { verification } : {}),
defaultShareImage: share && typeof share === 'object' ? (share as Record<string, unknown>) : null,
siteDescription: (settings.siteDescription as string | undefined) ?? null,
siteName: (settings[siteNameField] as string | undefined) ?? null,
+106 -9
View File
@@ -4,8 +4,9 @@ import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { SitemapEntry } from './buildSitemapEntries.js'
import { normalizePath } from '../construction/logic.js'
import { buildLlmsTxt } from './buildLlmsTxt.js'
import { buildSitemapXml } from './buildSitemapXml.js'
import { buildSitemapIndexXml, buildSitemapXml } from './buildSitemapXml.js'
import { buildSitemapCss, SITEMAP_STYLE_PARAM, type SitemapStyleOptions } from './sitemapStyle.js'
/**
@@ -35,6 +36,11 @@ export function createLlmsTxtRoute(opts: {
/** Inline every page's full Markdown (llms-full.txt). Default false. */
full?: boolean
getCachedPayload: () => Promise<BasePayload>
/**
* Paths to list, read per request — null lists everything. createContentHelpers
* passes the pages still open while the site is under construction.
*/
getIncludedPaths?: () => Promise<null | readonly string[]>
pagesSlug?: string
settingsSlug?: string
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
@@ -43,11 +49,14 @@ export function createLlmsTxtRoute(opts: {
return async () => {
try {
const payload = await opts.getCachedPayload()
const paths = opts.getIncludedPaths ? await opts.getIncludedPaths() : null
const allowed = paths ? new Set(paths.map(normalizePath)) : null
const body = await buildLlmsTxt({
baseUrl: opts.baseUrl,
config: opts.config,
content: opts.content,
full: opts.full,
...(allowed ? { include: (path: string) => allowed.has(normalizePath(path)) } : {}),
pagesSlug: opts.pagesSlug,
payload,
settingsSlug: opts.settingsSlug,
@@ -56,22 +65,61 @@ export function createLlmsTxtRoute(opts: {
return new Response(body, {
// For AI agents, not a search result: keep it (and the full-content
// copy, a duplicate of every page) out of search indexes.
headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex' },
headers: {
// Same as the sitemap: a CDN keeps it an hour; llms-full renders every page.
'Cache-Control': DEFAULT_SITEMAP_CACHE_CONTROL,
'Content-Type': 'text/plain; charset=utf-8',
'X-Robots-Tag': 'noindex',
},
})
} catch (err) {
// DB unreachable at build (container) — return a minimal valid file so the
// route doesn't 500; it fills in at runtime. No per-project try/catch.
console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err)
return new Response('# llms.txt\n', {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
headers: { 'Cache-Control': 'no-store', 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex' },
})
}
}
}
/** Query parameter of a sitemap part: /sitemap.xml?part=2. */
export const SITEMAP_PART_PARAM = 'part'
export const DEFAULT_SITEMAP_MAX_URLS = 10_000
export const DEFAULT_SITEMAP_CACHE_CONTROL = 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400'
/** Newest lastModified of a batch — the part's own lastmod in the index. */
function newest(entries: SitemapEntry[]): string | undefined {
let best: number | undefined
for (const e of entries) {
const t = e.lastModified ? new Date(e.lastModified).getTime() : NaN
if (!Number.isNaN(t) && (best === undefined || t > best)) {best = t}
}
return best === undefined ? undefined : new Date(best).toISOString()
}
export type SitemapRouteOptions = {
/**
* Cache-Control of the XML. Default: browsers revalidate, shared caches (CDN)
* keep it an hour and may serve a stale copy for a day while refreshing.
* `false` sends no header. An error response is never cached.
*/
cacheControl?: false | string
/** Legacy: your own stylesheet URL (e.g. '/sitemap.css'). Overrides `style`. */
cssUrl?: string
/**
* Max URLs in one file. Above it /sitemap.xml becomes a sitemap index of
* parts at `?part=1`, `?part=2`… (the protocol allows 50 000 URLs / 50 MB;
* hreflang alternates make each URL large, hence the lower default).
* Default 10 000.
*/
maxUrls?: number
/**
* Seconds the built entries are reused inside this server process, so the
* index and its parts (and repeated crawler hits) don't rebuild from the
* database each time. Default 300; 0 turns it off.
*/
memoSeconds?: number
/**
* Built-in browser look (default ON): the XML points at `<this route>?style`
* and the same handler serves the CSS — nothing to copy into /public.
@@ -90,6 +138,8 @@ export type SitemapRouteOptions = {
* export const dynamic = 'force-dynamic'
*
* `GET /sitemap.xml` → XML (crawlers), `GET /sitemap.xml?style` → its CSS.
* Over `maxUrls` URLs, /sitemap.xml is an index and the URLs sit in
* `/sitemap.xml?part=N` — robots.txt and Search Console keep the one address.
* Don't keep app/sitemap.ts next to it — two sitemaps confuse crawlers.
*/
export function createSitemapRouteHandler(
@@ -97,6 +147,25 @@ export function createSitemapRouteHandler(
opts: SitemapRouteOptions = {},
): (req: Request) => Promise<Response> {
const style = opts.cssUrl ? false : opts.style === false ? false : (opts.style ?? {})
const maxUrls = Math.max(1, Math.floor(opts.maxUrls ?? DEFAULT_SITEMAP_MAX_URLS))
const memoMs = Math.max(0, opts.memoSeconds ?? 300) * 1000
const cacheControl = opts.cacheControl === undefined ? DEFAULT_SITEMAP_CACHE_CONTROL : opts.cacheControl
const xmlHeaders = {
'Content-Type': 'application/xml; charset=utf-8',
...(cacheControl ? { 'Cache-Control': cacheControl } : {}),
}
let memo: { at: number; entries: Promise<SitemapEntry[]> } | undefined
const entries = (): Promise<SitemapEntry[]> => {
if (memoMs && memo && Date.now() - memo.at < memoMs) {return memo.entries}
const fresh = sitemap()
// A failed or empty build (sitemap() returns [] when the database is
// unreachable) is not reused — the next request tries again.
const forget = () => { if (memo?.entries === fresh) {memo = undefined} }
fresh.then((list) => { if (!list.length) {forget()} }, forget)
if (memoMs) {memo = { at: Date.now(), entries: fresh }}
return fresh
}
// `req` is required: Next 16 type-checks the first argument of a route handler
// (`Request | undefined` fails the build). A zero-argument call is not supported.
@@ -121,19 +190,47 @@ export function createSitemapRouteHandler(
const cssUrl = opts.cssUrl ?? (style ? `${url.pathname}?${SITEMAP_STYLE_PARAM}` : undefined)
try {
const entries = await sitemap()
const xml = buildSitemapXml(entries, { cssUrl })
return new Response(xml, {
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
})
const all = await entries()
const parts = Math.ceil(all.length / maxUrls)
const partParam = url.searchParams.get(SITEMAP_PART_PARAM)
if (partParam !== null) {
const part = Number(partParam)
if (!Number.isInteger(part) || part < 1 || part > Math.max(parts, 1)) {
return new Response('Not found', { headers: { 'Cache-Control': 'no-store' }, status: 404 })
}
const slice = all.slice((part - 1) * maxUrls, part * maxUrls)
return new Response(buildSitemapXml(slice, { cssUrl }), { headers: xmlHeaders })
}
if (parts > 1) {
const items = Array.from({ length: parts }, (_, i) => {
const slice = all.slice(i * maxUrls, (i + 1) * maxUrls)
return { lastModified: newest(slice), url: `${url.origin}${url.pathname}?${SITEMAP_PART_PARAM}=${i + 1}` }
})
return new Response(buildSitemapIndexXml(items, { cssUrl }), { headers: xmlHeaders })
}
// Empty usually means the database was unreachable — don't let a CDN keep it.
const headers = all.length ? xmlHeaders : { ...xmlHeaders, 'Cache-Control': 'no-store' }
return new Response(buildSitemapXml(all, { cssUrl }), { headers })
} catch (err) {
console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err)
// At runtime: 503 + Retry-After — crawlers come back later, while an empty
// sitemap with 200 would tell them the site has no pages.
if (process.env.NEXT_PHASE !== 'phase-production-build') {
return new Response('Sitemap temporarily unavailable', {
headers: { 'Cache-Control': 'no-store', 'Content-Type': 'text/plain; charset=utf-8', 'Retry-After': '300' },
status: 503,
})
}
// Valid empty urlset so the route doesn't 500 during a DB-less build.
const empty =
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>'
return new Response(empty, {
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
// Never let a CDN keep the empty fallback.
headers: { 'Cache-Control': 'no-store', 'Content-Type': 'application/xml; charset=utf-8' },
})
}
}
+170
View File
@@ -0,0 +1,170 @@
import type { Field } from 'payload'
import type { AiBotRule, AiBotsPolicy, RobotsOptions } from './buildRobots.js'
/**
* Site Settings → Search & AI: what editors set for search engines and AI
* assistants without a deploy — Search Console / Bing verification codes, the
* AI crawler policy for robots.txt, and a note for llms.txt. Empty fields
* change nothing: verification tags appear only once a code is pasted, and the
* robots policy stays the one set in code until an editor picks another.
*/
export const SEARCH_VERIFICATION_FIELD = 'searchVerification'
export const AI_CRAWLERS_FIELD = 'aiCrawlers'
export const LLMS_INTRO_FIELD = 'llmsIntro'
/** Next `Metadata.verification` — site ownership tags for search consoles. */
export type VerificationMetadata = {
google?: string
other?: Record<string, string>
yandex?: string
}
/**
* Accepts the bare code or the whole tag an editor copies from Search Console
* (`<meta name="google-site-verification" content="abc…" />`) and keeps only
* the code. Anything that isn't a plain token is dropped — the value ends up
* in every page's <head>.
*/
export function normalizeVerificationToken(raw: unknown): string {
if (typeof raw !== 'string') {return ''}
let value = raw.trim()
const content = /content\s*=\s*["']([^"']*)["']/i.exec(value)
if (content) {value = content[1].trim()}
value = value.replace(/^["']|["']$/g, '')
return /^[\w\-.:+/=]{1,200}$/.test(value) ? value : ''
}
const tokenField = (name: string, label: string, description: string): Field => ({
name,
type: 'text',
admin: { description },
hooks: { beforeChange: [({ value }) => normalizeVerificationToken(value) || null] },
label,
})
const AI_POLICY_OPTIONS = [
{ label: 'As set by the developer (default)', value: 'default' },
{ label: 'Allow all AI assistants and AI training', value: 'allow' },
{ label: 'Allow AI assistants and AI search, block AI training', value: 'block-training' },
{ label: 'Block all known AI bots', value: 'disallow' },
] as const
/** The "Search & AI" tab fields. Not localized, except the llms.txt note. */
export const searchSettingsFields: Field[] = [
{
name: SEARCH_VERIFICATION_FIELD,
type: 'group',
admin: {
description:
'Proves to search engines that you own this site. Paste the code (or the whole <meta> tag) from the search engine; it is added to every page. Leave empty if you verify another way (DNS, file).',
},
fields: [
tokenField('google', 'Google Search Console', 'Search Console → Settings → Ownership verification → HTML tag.'),
tokenField('bing', 'Bing Webmaster Tools', 'Bing Webmaster Tools → Add site → HTML Meta Tag (msvalidate.01). Bing also powers ChatGPT Search and Copilot.'),
tokenField('yandex', 'Yandex Webmaster', 'Yandex Webmaster → Site verification → Meta tag.'),
],
label: 'Search engine verification',
},
{
name: AI_CRAWLERS_FIELD,
type: 'group',
admin: {
description:
'Which AI bots may read the site (robots.txt). Assistants (ClaudeBot, ChatGPT-User, PerplexityBot…) fetch pages to answer questions and cite you; training crawlers (GPTBot, Google-Extended, CCBot…) collect pages to train models. Blocking assistants removes the site from AI answers.',
},
fields: [
{
name: 'policy',
type: 'select',
defaultValue: 'default',
label: 'AI bots',
options: AI_POLICY_OPTIONS.map((o) => ({ ...o })),
},
{
name: 'rules',
type: 'array',
admin: {
description:
'Exceptions for single bots, by user agent exactly as the bot announces itself (e.g. GPTBot, Bytespider). Wins over the setting above.',
initCollapsed: true,
},
fields: [
{ name: 'userAgent', type: 'text', label: 'User agent', required: true },
{
name: 'access',
type: 'select',
defaultValue: 'disallow',
options: [
{ label: 'Allow', value: 'allow' },
{ label: 'Block', value: 'disallow' },
],
required: true,
},
],
label: 'Per-bot exceptions',
},
],
label: 'AI crawlers',
},
{
name: LLMS_INTRO_FIELD,
type: 'textarea',
admin: {
description:
'Shown at the top of /llms.txt, under the site description: key facts an AI assistant should know and may quote — what you do, where, for whom, since when. Plain sentences, no marketing slogans.',
},
label: 'About the site for AI assistants (llms.txt)',
localized: true,
},
]
type SettingsLike = null | Record<string, unknown> | undefined
/** Site Settings → verification codes as Next `Metadata.verification`; undefined when none is set. */
export function verificationFrom(settings: SettingsLike): undefined | VerificationMetadata {
const group = settings?.[SEARCH_VERIFICATION_FIELD] as null | Record<string, unknown> | undefined
if (!group || typeof group !== 'object') {return undefined}
const google = normalizeVerificationToken(group.google)
const bing = normalizeVerificationToken(group.bing)
const yandex = normalizeVerificationToken(group.yandex)
if (!google && !bing && !yandex) {return undefined}
return {
...(google ? { google } : {}),
...(yandex ? { yandex } : {}),
...(bing ? { other: { 'msvalidate.01': bing } } : {}),
}
}
const POLICIES = new Set<string>(['allow', 'block-training', 'disallow'])
/**
* Site Settings → AI crawlers as buildRobots options. Only what the editor
* changed: policy 'default' keeps the option from code, no rules adds none.
*/
export function robotsOptionsFrom(settings: SettingsLike): Pick<RobotsOptions, 'aiBotRules' | 'aiBots'> {
const group = settings?.[AI_CRAWLERS_FIELD] as { policy?: unknown; rules?: unknown } | null | undefined
if (!group || typeof group !== 'object') {return {}}
const policy = typeof group.policy === 'string' && POLICIES.has(group.policy) ? (group.policy as AiBotsPolicy) : undefined
const rules: AiBotRule[] = Array.isArray(group.rules)
? group.rules.flatMap((r: unknown) => {
const row = r as { access?: unknown; userAgent?: unknown } | null
// A user agent is one token — no spaces, colons or newlines that could
// inject other robots.txt lines.
const ua = typeof row?.userAgent === 'string' ? row.userAgent.trim() : ''
if (!/^[\w\-.*/]{1,100}$/.test(ua)) {return []}
return [{ access: row?.access === 'allow' ? ('allow' as const) : ('disallow' as const), userAgent: ua }]
})
: []
return {
...(policy ? { aiBots: policy } : {}),
...(rules.length ? { aiBotRules: rules } : {}),
}
}
/** Site Settings → llms.txt note in the locale it was read in. Empty string when unset. */
export function llmsIntroFrom(settings: SettingsLike): string {
const v = settings?.[LLMS_INTRO_FIELD]
return typeof v === 'string' ? v.trim() : ''
}
+37 -5
View File
@@ -38,7 +38,12 @@ export type CollectSiteIndexArgs = {
content?: ContentOption
/** Population depth of `doc`. Default 0 (1 when you render blocks with images). */
depth?: number
/** Max documents per collection and locale. Default 1000. */
/**
* Only paths this returns true for — e.g. the pages still open while the site
* is under construction. Default: every path.
*/
include?: (path: string) => boolean
/** Max documents per collection and locale. Default: no limit (read in batches of 500). */
limit?: number
/** Only these locales. Default: every configured locale. */
locales?: string[]
@@ -80,6 +85,33 @@ function slugMap(rel: unknown, locales: string[]): Record<string, string> | unde
return Object.keys(map).length ? map : undefined
}
const BATCH = 500
/** Published documents of one collection in one locale, BATCH at a time, up to `limit`. */
async function readDocs(
payload: BasePayload,
collection: string,
{ depth, limit, locale }: { depth: number; limit?: number; locale: string },
): Promise<Row[]> {
const cfg = (payload.collections as Record<string, { config?: { versions?: { drafts?: unknown } | false } }> | undefined)?.[collection]?.config
const drafts = Boolean(cfg?.versions && cfg.versions.drafts)
const docs: Row[] = []
const size = limit === undefined ? BATCH : Math.max(1, Math.min(BATCH, limit))
for (let page = 1; limit === undefined || docs.length < limit; page++) {
const res = await payload.find({
collection: collection as never,
depth,
limit: size,
locale: locale as never,
page,
...(drafts ? { where: { _status: { equals: 'published' } } } : {}),
})
docs.push(...((res?.docs ?? []) as Row[]))
if (!res?.hasNextPage) {break}
}
return limit === undefined ? docs : docs.slice(0, limit)
}
/**
* Every public page and archive entry, per language, with its URL, title,
* description and dates — ONE source for everything that lists the site to
@@ -95,7 +127,8 @@ export async function collectSiteIndex({
config,
content,
depth = 0,
limit = 1000,
include,
limit,
locales,
pagesSlug = 'pages',
payload,
@@ -127,8 +160,7 @@ export async function collectSiteIndex({
if (collection !== pagesSlug && !prefix?.[locale]) {continue}
let docs: Row[] = []
try {
const res = await payload.find({ collection: collection as never, depth, limit, locale: locale as never })
docs = (res?.docs ?? []) as Row[]
docs = await readDocs(payload, collection, { depth, limit, locale })
} catch {
continue
}
@@ -142,7 +174,7 @@ export async function collectSiteIndex({
const slug = typeof doc.slug === 'string' ? doc.slug : ''
if (!title || !slug || EXCLUDED_SLUGS.has(slug)) {continue}
const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs: { [locale]: slug } })
if (!path) {continue}
if (!path || (include && !include(path))) {continue}
const summary = summaryField && typeof doc[summaryField] === 'string' ? (doc[summaryField]).trim() : ''
const metaDescription = typeof doc.meta?.description === 'string' ? doc.meta.description.trim() : ''
const description = summary || metaDescription
+5 -5
View File
@@ -46,28 +46,28 @@ export function buildSitemapCss({ accent, credit, title }: SitemapStyleOptions =
--badge-bg: #1a1c26; --badge-border: #282b3d; --badge-text: #9ca3af;
}
}
urlset {
urlset, sitemapindex {
display: flex; flex-direction: column; box-sizing: border-box; min-height: 100vh;
max-width: 1040px; margin: 0 auto; padding: 3rem 1.5rem; line-height: 1.5;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, Helvetica, Arial, sans-serif;
background-color: var(--bg); color: var(--text-main);
}
urlset::before {
urlset::before, sitemapindex::before {
content: ${cssString(heading)};
display: block; order: -2; font-size: 1.35rem; font-weight: 600; letter-spacing: -0.02em;
color: var(--text-main); ${note ? 'padding-bottom: 0.4rem;' : divider}
}
${note ? `urlset::after {
${note ? `urlset::after, sitemapindex::after {
content: ${cssString(note)};
display: block; order: -1; font-size: 0.8rem; color: var(--text-muted); ${divider}
}
` : ''}url {
` : ''}url, sitemap {
display: block; width: 100%; order: 0; box-sizing: border-box;
background-color: var(--card); border: 1px solid var(--border); border-radius: 8px;
padding: 1rem 1.25rem; margin-bottom: 0.65rem;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
url:hover { border-color: var(--accent); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03); }
url:hover, sitemap:hover { border-color: var(--accent); box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03); }
loc {
display: block; margin-bottom: 0.45rem; word-break: break-all; line-height: 1.45;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
+9
View File
@@ -36,6 +36,15 @@ export type SeoOption = {
generateDescription?: (args: { doc: Record<string, unknown> }) => string
/** Optional: customize how meta titles are generated in the admin preview. */
generateTitle?: (args: { doc: Record<string, unknown> }) => string
/**
* Site Settings → "Search & AI" tab: Search Console / Bing / Yandex
* verification, AI crawler policy for robots.txt (getRobots), llms.txt note.
* On by default (empty fields change nothing); false removes the tab; a
* function gets the plugin's fields and returns the tab's fields (add, drop,
* relabel). Keep the field names the readers use (searchVerification,
* aiCrawlers, llmsIntro) or read your own fields in your routes.
*/
searchSettings?: ((defaults: Field[]) => Field[]) | false
}
/**
+9
View File
@@ -20,6 +20,7 @@ import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/inde
import { buildSystemPagesFields } from './modules/pages/index.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
/**
@@ -281,6 +282,14 @@ export const ipalKit = (options: IpalOptions): Plugin => {
additionalFields: options.siteSettingsFields,
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}),
...(options.seo?.searchSettings === false
? {}
: {
searchFields:
typeof options.seo?.searchSettings === 'function'
? options.seo.searchSettings(searchSettingsFields)
: searchSettingsFields,
}),
systemPageFields,
}),
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
+6
View File
@@ -74,6 +74,12 @@ describe('IndexNow hook', () => {
await run({})
expect(fetchSpy).not.toHaveBeenCalled()
})
test('staging copy (IPAL_NOINDEX) sends nothing even in production', async () => {
vi.stubEnv('IPAL_NOINDEX', '1')
await run({ _status: 'published' })
expect(fetchSpy).not.toHaveBeenCalled()
})
})
describe('IndexNow key', () => {
+118
View File
@@ -0,0 +1,118 @@
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'node:os'
import path from 'node:path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
/**
* Sitemap, llms.txt and robots against a real (SQLite) Payload: the batched,
* `select`-ed, published-only reads must work with the database adapter, and
* Site Settings → Search & AI / Under construction must reach the output.
*/
describe('SEO outputs against a real database', () => {
let payload: Payload
let configPromise: Parameters<typeof getPayload>[0]['config']
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const
const helpers = () => createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
const urls = async () => (await helpers().sitemap()).map((e) => e.url).sort()
beforeAll(async () => {
configPromise = buildConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{
slug: 'pages',
fields: [
{ name: 'title', type: 'text' },
{ name: 'slug', type: 'text', index: true, localized: true },
{ name: 'noindex', type: 'checkbox' },
],
versions: { drafts: true },
},
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seo') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
secret: 'seo-integration-test-secret',
telemetry: false,
})
payload = await getPayload({ config: configPromise })
const create = async (slug: Record<string, string>, extra: Record<string, unknown> = {}) => {
const doc = await payload.create({
collection: 'pages' as never,
data: { slug: slug.pl, _status: 'published', title: slug.pl, ...extra } as never,
locale: 'pl' as never,
})
await payload.update({ id: doc.id, collection: 'pages' as never, data: { slug: slug.en } as never, locale: 'en' as never })
return doc
}
const home = await create({ en: 'home', pl: 'start' })
await create({ en: 'about', pl: 'o-nas' })
await create({ en: 'hidden', pl: 'ukryta' }, { noindex: true })
await create({ en: 'draft', pl: 'szkic' }, { _status: 'draft' })
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
test('sitemap: published and indexable pages in every language', async () => {
expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/en/about', 'https://acme.pl/pl', 'https://acme.pl/pl/o-nas'])
})
test('project overrides: sitemapEntries has the last word', async () => {
const h = createContentHelpers({
baseUrl: 'https://acme.pl',
config: configPromise,
i18n,
sitemapEntries: (entries) => [...entries.filter((e) => !e.url.endsWith('/en')), { url: 'https://acme.pl/custom' }],
})
const list = (await h.sitemap()).map((e) => e.url)
expect(list).toContain('https://acme.pl/custom')
expect(list).not.toContain('https://acme.pl/en')
})
test('verification codes and AI crawler rules from Site Settings → Search & AI', async () => {
await payload.updateGlobal({
slug: 'site-settings' as never,
data: {
aiCrawlers: { policy: 'block-training', rules: [{ access: 'disallow', userAgent: 'PerplexityBot' }] },
searchVerification: { google: '<meta name="google-site-verification" content="G-tok_1" />' },
} as never,
})
const stored = (await payload.findGlobal({ slug: 'site-settings' as never })) as { searchVerification?: { google?: string } }
expect(stored.searchVerification?.google).toBe('G-tok_1')
const meta = await helpers().generatePageMetadata('pl', ['o-nas'])
expect(meta.verification).toEqual({ google: 'G-tok_1' })
const rules = (await helpers().getRobots()).rules as { disallow?: string[]; userAgent: string | string[] }[]
expect(rules).toContainEqual({ disallow: ['/'], userAgent: ['PerplexityBot'] })
const assistants = rules.find((r) => Array.isArray(r.userAgent) && r.userAgent.includes('ClaudeBot'))
expect(assistants?.userAgent).not.toContain('PerplexityBot')
// the code-only handler ignores the panel
expect(helpers().robots().rules).not.toContainEqual({ disallow: ['/'], userAgent: ['PerplexityBot'] })
})
test('under construction: sitemap and llms.txt list only the open pages', async () => {
await payload.updateGlobal({ slug: 'site-settings' as never, data: { construction: { enabled: true } } as never, locale: 'pl' as never })
expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/pl'])
const llms = await (await helpers().llmsRoute()).text()
expect(llms).not.toContain('o-nas')
const unfiltered = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, underConstructionSeo: false })
expect(await unfiltered.sitemap()).toHaveLength(4)
await payload.updateGlobal({ slug: 'site-settings' as never, data: { construction: { enabled: false } } as never, locale: 'pl' as never })
expect(await urls()).toHaveLength(4)
})
})
+320
View File
@@ -0,0 +1,320 @@
import type { Config } from 'payload'
import { afterEach, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import type { SitemapEntry } from '../src/modules/seo/buildSitemapEntries.js'
import { buildLlmsTxt } from '../src/modules/seo/buildLlmsTxt.js'
import { buildMetadata } from '../src/modules/seo/buildMetadata.js'
import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js'
import { buildSitemapEntries } from '../src/modules/seo/buildSitemapEntries.js'
import { buildSitemapIndexXml } from '../src/modules/seo/buildSitemapXml.js'
import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js'
import { createLlmsTxtRoute, createSitemapRouteHandler, DEFAULT_SITEMAP_CACHE_CONTROL } from '../src/modules/seo/routeHandlers.js'
import { llmsIntroFrom, normalizeVerificationToken, robotsOptionsFrom, verificationFrom } from '../src/modules/seo/searchSettings.js'
import { collectSiteIndex } from '../src/modules/seo/siteIndex.js'
import { ipalKit } from '../src/plugin.js'
const config: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const single: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
type Rule = { allow?: string; disallow?: string[]; userAgent: string | string[] }
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
describe('search verification (Site Settings → Search & AI)', () => {
test('keeps the code from a bare value or a pasted <meta> tag', () => {
expect(normalizeVerificationToken(' abc-123_XYZ ')).toBe('abc-123_XYZ')
expect(normalizeVerificationToken('<meta name="google-site-verification" content="Tok_9-x" />')).toBe('Tok_9-x')
expect(normalizeVerificationToken("<meta name='msvalidate.01' content='ABCDEF0123' />")).toBe('ABCDEF0123')
})
test('drops anything that is not a plain token', () => {
expect(normalizeVerificationToken('"><script>alert(1)</script>')).toBe('')
expect(normalizeVerificationToken('two words')).toBe('')
expect(normalizeVerificationToken(42)).toBe('')
})
test('maps to Next Metadata.verification; empty group → undefined', () => {
expect(verificationFrom({ searchVerification: { bing: 'B1', google: 'G1', yandex: null } })).toEqual({
google: 'G1',
other: { 'msvalidate.01': 'B1' },
})
expect(verificationFrom({ searchVerification: { bing: '', google: null } })).toBeUndefined()
expect(verificationFrom({})).toBeUndefined()
})
test('every page gets the tags from Site Settings', async () => {
const pageMetadata = createPageMetadata({
baseUrl: 'https://acme.pl',
config,
loaders: {
getSettings: async () => ({ homepage: null, searchVerification: { google: 'G1' }, siteName: 'Acme' }),
resolveRoute: async () => null,
},
})
const metadata = await pageMetadata({ slug: ['x'], locale: 'pl', payload: {} as never })
expect(metadata.verification).toEqual({ google: 'G1' })
})
test('an unknown route is noindex', async () => {
const pageMetadata = createPageMetadata({
config,
loaders: { getSettings: async () => ({ homepage: null, siteName: 'Acme' }), resolveRoute: async () => null },
})
const metadata = await pageMetadata({ slug: ['nope'], locale: 'pl', payload: {} as never })
expect(metadata.robots?.index).toBe(false)
})
test('no verification → no key in metadata', () => {
const m = buildMetadata({ config, locale: 'pl', slugs: { pl: 'a' } })
expect('verification' in m).toBe(false)
})
})
describe('AI crawlers (robots)', () => {
test('panel policy and exceptions become buildRobots options; "default" changes nothing', () => {
expect(robotsOptionsFrom({ aiCrawlers: { policy: 'default', rules: [] } })).toEqual({})
expect(
robotsOptionsFrom({
aiCrawlers: {
policy: 'block-training',
rules: [
{ access: 'allow', userAgent: ' GPTBot ' },
{ access: 'disallow', userAgent: 'Evil\nDisallow: /' },
{ access: 'disallow', userAgent: 'Bad Bot' },
],
},
}),
).toEqual({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], aiBots: 'block-training' })
})
test('an exception takes the bot out of its policy group', () => {
const rules = buildRobots({
aiBotRules: [
{ access: 'allow', userAgent: 'gptbot' },
{ access: 'disallow', userAgent: 'SomeNewBot' },
],
aiBots: 'block-training',
baseUrl: 'https://acme.pl',
}).rules as Rule[]
const training = rules.find((r) => Array.isArray(r.userAgent) && r.userAgent.includes(AI_TRAINING_BOTS[1]))
expect(training?.disallow).toEqual(['/'])
expect(training?.userAgent).not.toContain('GPTBot')
expect(rules).toContainEqual({ allow: '/', disallow: ['/admin', '/api'], userAgent: ['gptbot'] })
expect(rules).toContainEqual({ disallow: ['/'], userAgent: ['SomeNewBot'] })
})
test('exceptions still apply with aiBots: false', () => {
const rules = buildRobots({ aiBotRules: [{ access: 'disallow', userAgent: 'Bytespider' }], aiBots: false, baseUrl: 'https://acme.pl' })
.rules as Rule[]
expect(rules).toHaveLength(2)
expect(rules[1]).toEqual({ disallow: ['/'], userAgent: ['Bytespider'] })
})
test('IPAL_NOINDEX still wins over every exception', () => {
vi.stubEnv('IPAL_NOINDEX', '1')
const r = buildRobots({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], baseUrl: 'https://acme.pl' })
expect(r.rules).toEqual({ disallow: ['/'], userAgent: '*' })
})
})
/** Payload stub: `docs` per collection, served in pages of the requested limit. */
function fakePayload(docs: Record<string, Record<string, unknown>[]>, opts: { drafts?: string[]; fields?: string[] } = {}) {
const find = vi.fn(async ({ collection, limit, page = 1 }: { collection: string; limit: number; page?: number }) => {
const all = docs[collection] ?? []
const start = (page - 1) * limit
return { docs: all.slice(start, start + limit), hasNextPage: start + limit < all.length }
})
const collections = Object.fromEntries(
Object.keys(docs).map((slug) => [
slug,
{
config: {
flattenedFields: (opts.fields ?? ['slug', 'title', 'meta']).map((name) => ({ name })),
labels: { plural: slug },
versions: opts.drafts?.includes(slug) ? { drafts: true } : false,
},
},
]),
)
return { collections, find, findGlobal: vi.fn(async () => ({})) }
}
describe('buildSitemapEntries at scale', () => {
const pages = Array.from({ length: 1203 }, (_, i) => ({
id: i,
slug: { en: `p${i}`, pl: `s${i}` },
_status: 'published',
updatedAt: '2026-01-01T00:00:00.000Z',
}))
test('reads in batches, published only, selected fields', async () => {
const payload = fakePayload({ pages }, { drafts: ['pages'], fields: ['slug', 'title', 'meta', 'noindex', 'layout'] })
const entries = await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never })
expect(entries).toHaveLength(1203 * 2)
expect(payload.find).toHaveBeenCalledTimes(3)
const args = payload.find.mock.calls[0][0] as unknown as Record<string, unknown>
expect(args.limit).toBe(500)
expect(args.where).toEqual({ _status: { equals: 'published' } })
expect(args.select).toEqual({ slug: true, _status: true, meta: true, noindex: true, updatedAt: true })
})
test('custom images → whole documents (no select)', async () => {
const payload = fakePayload({ pages: pages.slice(0, 2) })
await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, images: () => [], payload: payload as never })
const args = payload.find.mock.calls[0][0] as unknown as Record<string, unknown>
expect(args.select).toBeUndefined()
expect(args.where).toBeUndefined()
})
})
describe('sitemap route: split, cache, errors', () => {
const make = (n: number): SitemapEntry[] =>
Array.from({ length: n }, (_, i) => ({ lastModified: `2026-01-${String((i % 28) + 1).padStart(2, '0')}T00:00:00.000Z`, url: `https://acme.pl/p${i}` }))
test('small site: one urlset with the default Cache-Control', async () => {
const res = await createSitemapRouteHandler(async () => make(3), { style: false })(new Request('https://acme.pl/sitemap.xml'))
expect(res.headers.get('cache-control')).toBe(DEFAULT_SITEMAP_CACHE_CONTROL)
const xml = await res.text()
expect(xml).toContain('<urlset')
expect(xml.match(/<url>/g)).toHaveLength(3)
})
test('over maxUrls: an index, parts by ?part=N, unknown part 404', async () => {
const handler = createSitemapRouteHandler(async () => make(5), { maxUrls: 2, style: false })
const index = await (await handler(new Request('https://acme.pl/sitemap.xml'))).text()
expect(index).toContain('<sitemapindex')
expect(index.match(/<sitemap>/g)).toHaveLength(3)
expect(index).toContain('<loc>https://acme.pl/sitemap.xml?part=3</loc>')
expect(index).toContain('<lastmod>2026-01-02T00:00:00.000Z</lastmod>')
const part = await (await handler(new Request('https://acme.pl/sitemap.xml?part=3'))).text()
expect(part.match(/<url>/g)).toHaveLength(1)
expect(part).toContain('https://acme.pl/p4')
expect((await handler(new Request('https://acme.pl/sitemap.xml?part=4'))).status).toBe(404)
expect((await handler(new Request('https://acme.pl/sitemap.xml?part=x'))).status).toBe(404)
})
test('entries are reused within memoSeconds, rebuilt when 0', async () => {
const source = vi.fn(async () => make(1))
const memo = createSitemapRouteHandler(source, { style: false })
await memo(new Request('https://acme.pl/sitemap.xml'))
await memo(new Request('https://acme.pl/sitemap.xml'))
expect(source).toHaveBeenCalledTimes(1)
const fresh = vi.fn(async () => make(1))
const noMemo = createSitemapRouteHandler(fresh, { memoSeconds: 0, style: false })
await noMemo(new Request('https://acme.pl/sitemap.xml'))
await noMemo(new Request('https://acme.pl/sitemap.xml'))
expect(fresh).toHaveBeenCalledTimes(2)
})
test('runtime error → 503 Retry-After; empty → not cached and not reused', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const failing = await createSitemapRouteHandler(async () => {
throw new Error('db down')
})(new Request('https://acme.pl/sitemap.xml'))
expect(failing.status).toBe(503)
expect(failing.headers.get('retry-after')).toBe('300')
const empty = vi.fn(async () => [] as SitemapEntry[])
const handler = createSitemapRouteHandler(empty, { style: false })
const res = await handler(new Request('https://acme.pl/sitemap.xml'))
expect(res.headers.get('cache-control')).toBe('no-store')
await handler(new Request('https://acme.pl/sitemap.xml'))
expect(empty).toHaveBeenCalledTimes(2)
})
test('during next build an error still gives an empty urlset', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.stubEnv('NEXT_PHASE', 'phase-production-build')
const res = await createSitemapRouteHandler(async () => {
throw new Error('no db')
})(new Request('https://acme.pl/sitemap.xml'))
expect(res.status).toBe(200)
expect(await res.text()).toContain('<urlset')
})
test('buildSitemapIndexXml escapes', () => {
expect(buildSitemapIndexXml([{ url: 'https://acme.pl/s.xml?a=1&b=2' }])).toContain('?a=1&amp;b=2')
})
})
describe('collectSiteIndex and llms.txt', () => {
const pages = Array.from({ length: 1205 }, (_, i) => ({ id: i, slug: `p${i}`, title: `Page ${i}` }))
test('no silent 1000 cap; limit still caps', async () => {
const payload = fakePayload({ pages })
expect(await collectSiteIndex({ config: single, payload: payload as never })).toHaveLength(1205)
expect(await collectSiteIndex({ config: single, limit: 10, payload: payload as never })).toHaveLength(10)
})
test('include filters by path', async () => {
const payload = fakePayload({ pages: pages.slice(0, 5) })
const index = await collectSiteIndex({ config: single, include: (p) => p === '/p2', payload: payload as never })
expect(index.map((e) => e.path)).toEqual(['/p2'])
})
test('llms.txt carries the editor note under the summary', async () => {
const payload = fakePayload({ pages: pages.slice(0, 1) })
payload.findGlobal.mockResolvedValue({ llmsIntro: 'Acme repairs boilers in Kraków since 1998.', siteDescription: 'Boilers', siteName: 'Acme' })
const body = await buildLlmsTxt({ baseUrl: 'https://acme.pl', config: single, payload: payload as never })
expect(body.startsWith('# Acme\n\n> Boilers\n\nAcme repairs boilers in Kraków since 1998.\n')).toBe(true)
expect(llmsIntroFrom({ llmsIntro: ' ' })).toBe('')
})
test('llms route: only included paths, cached for a CDN', async () => {
const payload = fakePayload({ pages: pages.slice(0, 3) })
const res = await createLlmsTxtRoute({
baseUrl: 'https://acme.pl',
config: single,
getCachedPayload: async () => payload as never,
getIncludedPaths: async () => ['/p1/'],
})()
const body = await res.text()
expect(body).toContain('(https://acme.pl/p1)')
expect(body).not.toContain('/p0')
expect(res.headers.get('cache-control')).toBe(DEFAULT_SITEMAP_CACHE_CONTROL)
})
})
describe('plugin: Search & AI tab', () => {
const base = (): Config => ({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config
const tabs = (c: Config) => {
const settings = c.globals?.find((g) => g.slug === 'site-settings')
const field = settings?.fields[0] as { tabs: { label: string }[] }
return field.tabs.map((t) => t.label)
}
test('on by default, off with seo.searchSettings: false', async () => {
const on = await ipalKit({ access: { authCollection: 'users' }, i18n: config, twoFactor: false })(base())
expect(tabs(on)).toContain('Search & AI')
const off = await ipalKit({
access: { authCollection: 'users' },
i18n: config,
seo: { collections: [], searchSettings: false },
twoFactor: false,
})(base())
expect(tabs(off)).not.toContain('Search & AI')
const custom = await ipalKit({
access: { authCollection: 'users' },
i18n: config,
seo: { collections: [], searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name !== 'llmsIntro') },
twoFactor: false,
})(base())
const settings = custom.globals?.find((g) => g.slug === 'site-settings')
const tab = (settings?.fields[0] as { tabs: { fields: { name?: string }[]; label: string }[] }).tabs.find((t) => t.label === 'Search & AI')
expect(tab?.fields.map((f) => f.name)).toEqual(['searchVerification', 'aiCrawlers'])
})
})