Built-in statistics (cookieless, consent-gated visitor history); per-page meta descriptions, NoSnippet

Stats: ipalKit({ stats: true }) adds the stats-visits collection, POST /api/ipal/hit, the
/admin/stats view (30-day visits chart, top/entry pages, referrers, devices), a dashboard card
and a nav link. <PageStats> (or <SiteProviders stats>) sends one beacon per page view. Without
consent nothing is stored on the device and no IP is kept: page views are joined by a hash with
an in-memory salt replaced daily. With analytics consent an ipal_vid cookie links visits across
days (server re-checks the consent cookie and policy version; withdrawal deletes the cookie).
Bots, logged-in panel users and prefetches aren't counted. Retention 90 days.
@payloadcms/next added to peerDependencies (DefaultTemplate). Docs: stats.md with privacy text.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-21 15:10:55 +02:00
co-authored by Claude Opus 5.5
parent 305c564d13
commit 4ec27d9ef0
47 changed files with 1799 additions and 57 deletions
+1 -1
View File
@@ -13,7 +13,7 @@ export default async function LocaleLayout({ children, params }: Props) {
return (
<html lang={locale}>
<body>
<SiteProviders banner={<CookieBanner equalChoice />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)}>
<SiteProviders banner={<CookieBanner equalChoice />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)} stats={{ locale }}>
<main>{children}</main>
</SiteProviders>
</body>
+60 -6
View File
@@ -1,12 +1,39 @@
import { OverviewComponent as OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaTitleComponent as MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaDescriptionComponent as MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { MetaDescriptionCheck as MetaDescriptionCheck_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { MetaImageComponent as MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { PreviewComponent as PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860 } from '@payloadcms/plugin-seo/client'
import { IntegrationStatusBanner as IntegrationStatusBanner_630f031911beff97691b963f10a20a86 } from '@intecion/ipal-kit/client'
import { MaskedField as MaskedField_630f031911beff97691b963f10a20a86 } from '@intecion/ipal-kit/client'
import { TestEmailButton as TestEmailButton_630f031911beff97691b963f10a20a86 } from '@intecion/ipal-kit/client'
import { RscEntryLexicalCell as RscEntryLexicalCell_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { RscEntryLexicalField as RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { LexicalDiffComponent as LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { InlineToolbarFeatureClient as InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { HorizontalRuleFeatureClient as HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { UploadFeatureClient as UploadFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { BlockquoteFeatureClient as BlockquoteFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { RelationshipFeatureClient as RelationshipFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { LinkFeatureClient as LinkFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ChecklistFeatureClient as ChecklistFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { OrderedListFeatureClient as OrderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { UnorderedListFeatureClient as UnorderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { IndentFeatureClient as IndentFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { AlignFeatureClient as AlignFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { HeadingFeatureClient as HeadingFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ParagraphFeatureClient as ParagraphFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { InlineCodeFeatureClient as InlineCodeFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { SuperscriptFeatureClient as SuperscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { SubscriptFeatureClient as SubscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { StrikethroughFeatureClient as StrikethroughFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { TestEmailButton as TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsNavLink as StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsWidget as StatsWidget_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
/** @type import('payload').ImportMap */
@@ -14,11 +41,38 @@ export const importMap = {
"@payloadcms/plugin-seo/client#OverviewComponent": OverviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#MetaTitleComponent": MetaTitleComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#MetaDescriptionComponent": MetaDescriptionComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@intecion/ipal-kit/admin#MetaDescriptionCheck": MetaDescriptionCheck_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/plugin-seo/client#MetaImageComponent": MetaImageComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@payloadcms/plugin-seo/client#PreviewComponent": PreviewComponent_a8a977ebc872c5d5ea7ee689724c0860,
"@intecion/ipal-kit/client#IntegrationStatusBanner": IntegrationStatusBanner_630f031911beff97691b963f10a20a86,
"@intecion/ipal-kit/client#MaskedField": MaskedField_630f031911beff97691b963f10a20a86,
"@intecion/ipal-kit/client#TestEmailButton": TestEmailButton_630f031911beff97691b963f10a20a86,
"@payloadcms/richtext-lexical/rsc#RscEntryLexicalCell": RscEntryLexicalCell_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/rsc#RscEntryLexicalField": RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/rsc#LexicalDiffComponent": LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/client#InlineToolbarFeatureClient": InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#HorizontalRuleFeatureClient": HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#UploadFeatureClient": UploadFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#BlockquoteFeatureClient": BlockquoteFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#RelationshipFeatureClient": RelationshipFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#LinkFeatureClient": LinkFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ChecklistFeatureClient": ChecklistFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#OrderedListFeatureClient": OrderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#UnorderedListFeatureClient": UnorderedListFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#IndentFeatureClient": IndentFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#AlignFeatureClient": AlignFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#HeadingFeatureClient": HeadingFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ParagraphFeatureClient": ParagraphFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#InlineCodeFeatureClient": InlineCodeFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#SuperscriptFeatureClient": SuperscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#SubscriptFeatureClient": SubscriptFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#StrikethroughFeatureClient": StrikethroughFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#UnderlineFeatureClient": UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@intecion/ipal-kit/admin#IntegrationStatusBanner": IntegrationStatusBanner_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#TestEmailButton": TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsNavLink": StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsWidget": StatsWidget_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#IntegrationAlerts": IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23,
"@intecion/ipal-kit/admin#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23,
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
}
+1
View File
@@ -69,6 +69,7 @@ export default buildConfig({
consentLog: true,
forms: {},
seo: { collections: ['posts', 'pages'] },
stats: true,
// 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator.
twoFactor: false,
}),
+39
View File
@@ -8,6 +8,45 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
dopiero powyżej 20.
## 1.12.1
### Nowe
- **Opis każdej strony z jej treści** — auto-fill wypełnia puste `meta.description` z bloków strony (`layout` →
akapity bez nagłówków, całe zdania do ~155 znaków), gdy `autoFill.description` nic nie daje. Wcześniej strona bez
opisu dostawała `siteDescription` — ten sam na każdej stronie, więc Google go ignorował i cytował stopkę.
`autoFill: { content: 'blocks' | false, descriptionLength }`. Opis wpisany ręcznie nigdy nie jest nadpisywany.
- **`<NoSnippet>`** (`/rsc`, `/client`) — `data-nosnippet` na `div`/`section`/`span`. Dla stopki, paska kontaktowego,
powtarzanego CTA: Google przestaje pokazywać adres i godziny ze stopki jako opis podstron. `CookieBanner` i
`LanguageSwitcher` mają `data-nosnippet` same. Opis: seo.md → „Opisy w Google”.
- **Podpowiedź pod opisem w tabie SEO** (`MetaDescriptionCheck`) — opis pusty, taki sam jak `siteDescription` albo jak
w innym dokumencie kolekcji. Nie blokuje zapisu. `seo.descriptionCheck: { settingsSlug, siteDescriptionField }`
albo `false`.
- **ipal-seo-check** — ostrzeżenia: zduplikowane meta description, stopka bez `data-nosnippet`.
- **Statystyki w panelu** — `ipalKit({ stats: true })` + `<SiteProviders stats={{ locale }}>` (albo `<PageStats>`
z `/client`). Widok `/admin/stats`: wizyty dziennie z 30 dni, strony, wejścia, źródła, urządzenia; wykres na
dashboardzie. Bez cookies i bez zapisu IP — **nie wymaga zgody** (hash z solą wymienianą codziennie). Odwiedzający ze
zgodą *analytics* (ta sama co GA4) dostają cookie `ipal_vid` i historię przez wiele dni; serwer sam sprawdza cookie
zgody. Kolekcja `stats-visits`, retencja 90 dni. Opis + tekst do polityki prywatności: stats.md.
- `@payloadcms/next` w peerDependencies (widok `/admin/stats` używa jego `DefaultTemplate`; każdy projekt Payload+Next
już go ma).
### Poprawki
- **Auto-fill przy częściowym zapisie** — `payload.update` / REST PATCH bez grupy `meta` nie traktuje już zapisanego
tytułu jako pustego (czyta go z dokumentu).
### Wymaga zmian w projekcie
1. `pnpm payload generate:importmap` — nowy komponent panelu `@intecion/ipal-kit/admin#MetaDescriptionCheck`.
2. Stopka: treść w `<NoSnippet>` wewnątrz `<footer>` (nie na `<footer>` — tam Google atrybutu nie honoruje):
`import { NoSnippet } from '@intecion/ipal-kit/rsc'`. To samo dla powtarzanego paska kontaktowego / CTA.
3. Opcjonalnie: istniejące strony bez opisu dostaną go przy najbliższym zapisie. Żeby od razu — zapisz je w panelu.
Projekt bez pola `layout` (bloki pod inną nazwą): `autoFill: { content: '<nazwa pola>' }`.
4. Sprawdzenie: `ipal-seo-check` bez ostrzeżeń o stopce i zduplikowanych opisach; w Search Console → Sprawdź URL
→ poproś o ponowne zindeksowanie głównych stron.
5. Opcjonalnie, statystyki: `stats: true` w `ipalKit`, `stats={{ locale }}` w `<SiteProviders>`,
`pnpm payload generate:importmap`, migracja (Postgres). W panelu Cookie Settings → Cookies dopisz `ipal_vid`
(analytics) i uzupełnij politykę prywatności — gotowy tekst w stats.md.
## 1.12.0
### Nowe
+1
View File
@@ -31,6 +31,7 @@ Szczegóły API — jeden plik na moduł:
| Rich text, spis treści | [richtext.md](./richtext.md) |
| Nagłówki, CSP, 2FA | [security.md](./security.md) |
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](./seo.md) |
| Statystyki w panelu (bez cookies; historia odwiedzającego za zgodą) | [stats.md](./stats.md) |
| Auto-slug | [slug.md](./slug.md) |
| Motyw jasny / ciemny, przełącznik | [theme.md](./theme.md) |
| Media, R2 | [storage.md](./storage.md) |
+5
View File
@@ -138,6 +138,8 @@ panelu (seed, faza 6 w ipal-site), stosujesz poniższe — nie wymyślając fakt
### Meta w zakładce SEO
Tytuł ≤ 60 znaków, unikalny, fraza na początku; opis ≤ 155 znaków, z konkretem i zachętą;
obraz udostępniania (1200×630) na stronach z ofertą — reszta dziedziczy domyślny z Site Settings.
Opis **unikalny na każdej stronie** — pusty uzupełnia się z treści przy zapisie, ale napisany
ręcznie jest lepszy. Ten sam opis na wielu stronach Google ignoruje.
### noindex — kiedy TAK, kiedy NIE
| Strona | noindex? |
@@ -650,6 +652,9 @@ Skill: **ipal-nav**.
zbudowane z `buildLinkField` — model danych firmy zależy od kraju (NIP/ABN/EIN).
- Menu: jeden poziom podmenu, nie głębiej. CTA w nagłówku = `links`.
- Logo i nazwa z Site Settings — nie duplikuj pól w Header.
- **Treść stopki w `<NoSnippet>`** (`/rsc`, wewnątrz `<footer>`) — inaczej Google pokazuje adres
ze stopki jako opis każdej podstrony. To samo dla paska kontaktowego i CTA powtarzanego na
każdej stronie. Nigdy na `<main>`. Szczegóły: seo.md → „Opisy w Google”.
- **Linki prawne w stopce** z ról System Pages: `await getSystemLinks(locale)` (href + tytuł strony), nie ręcznie i bez etykiet w kodzie.
- Wyróżnienie pozycji menu / wariant przycisku = `appearance` z panelu (`buildLinkField({ appearances: [...] })`, dowolne nazwy), nigdy warunek na treści (`label === '…'`).
- Linki rozwiązuj **na serwerze**: `await resolveNav(header.navItems, locale)` z `lib/content`
@@ -153,3 +153,14 @@ export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: s
Header/Footer pobierasz w `[locale]/layout.tsx` (przez cached getter w
`lib/`) i podajesz jako props — layout to jedyne miejsce, które je składa.
Komponent `Footer` — treść w `NoSnippet` (inaczej Google pokazuje adres ze stopki jako
opis każdej podstrony; seo.md → „Opisy w Google”):
```tsx
import { NoSnippet } from '@intecion/ipal-kit/rsc'
<footer className="…">
<NoSnippet className="…">{/* dane firmy, linki, linki prawne */}</NoSnippet>
</footer>
```
@@ -98,7 +98,8 @@ for (let i = 0; sample.length < Math.min(MAX, urls.length); i++) {
const multiLocale = hasAlternates || byLocale.size > 1
const urlSet = new Set(urls.map(norm))
const titles = new Map()
const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [], jsonLd: [], mdAlt: [], h1: [], headingSkip: [], alt: [], imgSize: [], lcp: [], ogImage: [], thin: [], noLinks: [], xRobots: [] }
const descriptions = new Map()
const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [], jsonLd: [], mdAlt: [], h1: [], headingSkip: [], alt: [], imgSize: [], lcp: [], ogImage: [], thin: [], noLinks: [], xRobots: [], footerSnippet: [] }
const checkedPaths = []
for (const url of sample) {
@@ -120,7 +121,9 @@ for (const url of sample) {
if (title.length > 65) issues.longTitle.push(`${url} (${title.length} chars)`)
titles.set(title, [...(titles.get(title) ?? []), url])
}
if (!/<meta[^>]+name="description"[^>]+content="[^"]+"/i.test(head)) issues.desc.push(url)
const desc = tags(head, /<meta[^>]+name="description"[^>]*>/gi).map((t) => attr(t, 'content'))[0]?.trim()
if (!desc) issues.desc.push(url)
else descriptions.set(desc, [...(descriptions.get(desc) ?? []), url])
const canonTag = tags(head, /<link[^>]+rel="canonical"[^>]*>/gi)[0]
const canon = canonTag && attr(canonTag, 'href')
@@ -161,6 +164,9 @@ for (const url of sample) {
try { const u = new URL(href, url); return u.host === own && norm(u.pathname) !== norm(new URL(url).pathname) } catch { return false }
})
if (internal.length === 0) issues.noLinks.push(url)
// Repeated footer text (address, hours) is what Google quotes for brand searches
const footer = main.match(/<footer\b[\s\S]*<\/footer>/i)?.[0]
if (footer && !/data-nosnippet/i.test(footer)) issues.footerSnippet.push(url)
if (multiLocale) {
const alts = tags(head, /<link[^>]+hreflang="[^"]+"[^>]*>/gi).map((t) => ({ lang: attr(t, 'hreflang'), href: attr(t, 'href') }))
@@ -174,6 +180,7 @@ for (const url of sample) {
}
const dupTitles = [...titles.entries()].filter(([, us]) => us.length > 1).map(([t, us]) => `"${t}" × ${us.length}`)
const dupDescs = [...descriptions.entries()].filter(([, us]) => us.length > 1).map(([d, us]) => `"${d.slice(0, 60)}…" × ${us.length}`)
if (issues.status.length) report('ERROR', 'sitemap URLs not 200 (redirect / error)', 'sitemap must list final, live URLs', issues.status)
if (issues.noHead.length) report('ERROR', 'no </head> in HTML', 'broken document', issues.noHead)
if (issues.body.length) report('ERROR', 'metadata rendered in <body>', 'htmlLimitedBots, no explicit <head>, ISR + generateStaticParams (AGENT.md §4)', issues.body)
@@ -186,6 +193,8 @@ if (issues.xdefault.length) report('WARNING', 'no x-default hreflang', 'buildHre
if (issues.reciprocal.length) report('WARNING', 'hreflang alternates not in the sitemap', 'translation missing/unpublished or noindex in that locale', issues.reciprocal.slice(0, 15))
if (issues.desc.length) report('WARNING', 'missing meta description', 'fill SEO tab in the panel (or site description fallback)', issues.desc)
if (dupTitles.length) report('WARNING', 'duplicate titles', 'unique meta titles per page', dupTitles)
if (dupDescs.length) report('WARNING', 'duplicate meta descriptions (Google ignores them)', 'own description per page in the SEO tab — empty ones auto-fill from content on save', dupDescs)
if (issues.footerSnippet.length) report('WARNING', 'footer without data-nosnippet (Google quotes the address as the snippet)', 'wrap footer contents in <NoSnippet> (seo.md → Opisy w Google)', issues.footerSnippet.slice(0, 3))
if (issues.longTitle.length) report('WARNING', 'titles over 65 chars (truncated in results)', 'shorten in the SEO tab', issues.longTitle)
if (issues.favicon.length) report('WARNING', 'no favicon link in head', 'buildIconsMetadata(settings.favicon) in root generateMetadata', issues.favicon.slice(0, 3))
if (issues.xRobots.length) report('ERROR', 'X-Robots-Tag: noindex on pages', 'IPAL_NOINDEX is set in this environment — remove it in production', issues.xRobots.slice(0, 3))
+1
View File
@@ -233,6 +233,7 @@ Nie musisz nic konfigurować — działa out of the box:
```ts
const DEFAULT_COOKIE_MAP = {
functional: [LOCALE_COOKIE_NAME], // 'NEXT_LOCALE' — plugin zna własną cookie
analytics: [/* GA, Clarity, … */ 'ipal_vid'], // ipal_vid — statystyki w panelu (stats.md)
}
```
+4 -3
View File
@@ -120,13 +120,14 @@ const r2Url = process.env.R2_PUBLIC_URL || ''
const csp = [
"default-src 'self'",
// skrypty: self + Turnstile (Cloudflare) + analytics (GTM/GA jeśli używasz)
"script-src 'self' 'unsafe-inline' https://challenges.cloudflare.com https://www.googletagmanager.com",
"script-src 'self' 'unsafe-inline' https://challenges.cloudflare.com https://*.googletagmanager.com",
// style: self + inline (Tailwind) + Google Fonts
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
// obrazy: self + media R2 (z env!) + data:
`img-src 'self' data: ${r2Url}`.trim(),
`img-src 'self' data: https://*.google-analytics.com https://*.googletagmanager.com ${r2Url}`.trim(),
"font-src 'self' https://fonts.gstatic.com data:",
"connect-src 'self' https://www.google-analytics.com",
// GA4: wildcardy obowiązkowe — ruch z UE idzie na region1.google-analytics.com
"connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com",
// ramki: Turnstile (widget captcha)
"frame-src https://challenges.cloudflare.com",
"form-action 'self'",
+47 -4
View File
@@ -25,15 +25,26 @@ ipalKit({
// generateDescription: ({ doc }) => doc.excerpt ?? '',
// fields: [...], // extra pola w grupie SEO
// autoFill: { title: 'title', description: 'excerpt' }, // mapowanie auto-fill
// autoFill: { content: 'blocks', descriptionLength: 155 }, // opis z innego pola bloków
// autoFill: false, // wyłącz auto-fill
// descriptionCheck: { settingsSlug: 'site-settings', siteDescriptionField: 'siteDescription' },
// descriptionCheck: false, // bez podpowiedzi pod opisem
},
})
```
Dodaje tab **SEO** do wskazanych kolekcji: title, description, image,
titleOverride. Auto-fill: hook `beforeChange` wypełnia puste `meta.title` z pola
dokumentu (domyślnie `title`). Nigdy nie nadpisuje tego, co edytor wpisał
ręcznie.
dokumentu (domyślnie `title`), a puste `meta.description` — z pola
`autoFill.description` (jeśli podane), inaczej z treści strony (bloki `layout` →
pierwsze akapity bez nagłówków, całe zdania do ~155 znaków). Nigdy nie nadpisuje
tego, co edytor wpisał ręcznie; przy częściowym zapisie (REST PATCH,
`payload.update` z kilkoma polami) czyta zapisany opis z dokumentu.
Pod polem opisu w tabie SEO stoi podpowiedź (`MetaDescriptionCheck`, `/admin`):
opis pusty, taki sam jak `siteDescription` z Site Settings albo taki sam jak w innym
dokumencie kolekcji. Tylko informuje — zapisu nie blokuje. Długość pokazuje licznik
plugin-seo.
Tab budowany jest przez `injectSeoTabs`, nie przez `tabbedUI` plugin-seo —
tamten scala taby patrząc na pierwsze pole kolekcji i psuje się, gdy są tam już
@@ -654,7 +665,36 @@ Działa automatycznie przez createPageMetadata (canonical + hreflang + x-default
- Redirect roota na twardo 301 do jednego języka → tracisz negocjację i drugą
wersję. Zostaw negocjację + hreflang.
## Sitelinks i structured data (branding w wynikach Google)
## Opisy w Google — data-nosnippet (stopka, dane kontaktowe)
Objaw: pod wynikiem i sitelinkami Google pokazuje adres, godziny i e-mail ze
stopki zamiast meta description — ten sam tekst pod każdą podstroną.
Przyczyna: Google sam wybiera tekst snippetu, gdy uzna, że pasuje do zapytania
lepiej niż description. Przy wyszukiwaniu marki „pasuje” blok kontaktowy, a stopka
jest na każdej stronie. Dobre, unikalne description tego nie wyłączy.
Rozwiązanie: tekst powtarzany na każdej stronie w `data-nosnippet`. Strona dalej
jest indeksowana, Google tylko nie cytuje tego fragmentu. Adres i godziny nadal ma
z JSON-LD `LocalBusiness`.
```tsx
import { NoSnippet } from '@intecion/ipal-kit/rsc' // w komponencie klienckim: /client
<footer>
<NoSnippet>…adres, godziny, telefon, linki…</NoSnippet>
</footer>
```
- Google honoruje `data-nosnippet` tylko na `div`, `section`, `span` — na `footer`,
`nav`, `aside` NIE. Dlatego `NoSnippet` renderuje `div` (`as="section"` /
`as="span"`), a `<footer>` zostaje na zewnątrz.
- Owiń: stopkę, pasek kontaktowy, sekcję CTA powtarzaną na każdej stronie
(„Umów się na konsultację”). **Nigdy `<main>`** — z niego ma pochodzić snippet.
- Komponenty pluginu robią to same: `CookieBanner`, `LanguageSwitcher`.
- Efekt po ponownym crawlu (dni–tygodnie). `ipal-seo-check` ostrzega o stopce bez
`data-nosnippet` i o zduplikowanych opisach.
Cel: żeby wyszukanie marki („rcustomcars") pokazało stronę główną + podlinki
(sitelinks) z opisami. Ważne — **sitelinków NIE DA SIĘ wymusić.** Google
@@ -735,6 +775,7 @@ Plugin dostarcza helpery — projekt MUSI je wpiąć i podać dane z panelu:
- [ ] `app/robots.ts` i `app/sitemap.ts` wystawione (patrz niżej — bez tego
Google nie widzi stron!)
- [ ] Jasne, opisowe tytuły stron (nie generyczne)
- [ ] Stopka i powtarzane bloki kontaktowe w `<NoSnippet>` (wyżej: „Opisy w Google”)
- [ ] Logiczna hierarchia + linkowanie wewnętrzne z głównej
Dane WSZĘDZIE z panelu (siteName, nav, logo), nigdy zaszyte.
@@ -947,7 +988,9 @@ globalnego siteDescription gdy pusty) — patrz niżej.
## Fallback meta description (siteDescription)
Strona bez `meta.description` → plugin używa globalnego `siteDescription` z
SiteSettings. Lepsze niż brak description (Google losowo wyciąga tekst ze strony).
SiteSettings. Lepsze niż brak description, ale ten sam opis na wielu stronach
Google ignoruje — dlatego auto-fill (wyżej) daje każdej stronie opis z jej treści,
a fallback zostaje dla stron bez treści w blokach.
- Pole **siteDescription** w SiteSettings → General (localized, textarea)
- buildMetadata: `meta.description || siteDescription`
+120
View File
@@ -0,0 +1,120 @@
# stats
Wbudowane statystyki w panelu: **wizyty dziennie z ostatnich 30 dni**, najczęściej
oglądane strony, strony wejścia, źródła ruchu, urządzenia — oraz **historia
odwiedzającego**, ale tylko dla tych, którzy zgodzili się na cookies analityczne.
Dane zostają w bazie projektu; nic nie idzie do Google ani innych firm.
## Dwa poziomy — i dlaczego pierwszy nie wymaga zgody
| | Bez zgody (każdy odwiedzający) | Ze zgodą **analytics** (ta sama co GA4) |
|---|---|---|
| Co w przeglądarce | **nic** — żadnego cookie, localStorage, fingerprintu | cookie `ipal_vid` (losowe id, 180 dni) |
| Jak łączymy odsłony w wizytę | hash z losowej soli + IP + user agent; sól jest tylko w pamięci serwera i **wymieniana codziennie** — po północy nikt (także my) nie powiąże wizyty z IP ani z wizytą z innego dnia | jak obok + `visitorId` z cookie |
| Co widać w panelu | wykres dzienny, strony, wejścia, źródła, urządzenia, ścieżka w ramach jednej wizyty | dodatkowo **historia tej osoby przez wiele dni** |
| Zapisane IP / user agent | **nie** | **nie** |
- **Art. 399 Prawa komunikacji elektronicznej (ePrivacy 5(3))** wymaga zgody na zapis lub odczyt
informacji z urządzenia użytkownika. Poziom 1 niczego na urządzeniu nie zapisuje ani nie czyta,
więc baner go nie dotyczy.
- **RODO dalej obowiązuje** — IP jest przetwarzane przez chwilę przy liczeniu hasha. Podstawa: prawnie
uzasadniony interes (art. 6 ust. 1 lit. f). **Trzeba to opisać w polityce prywatności** (tekst niżej).
- **Poziom 2 bez zgody jest nielegalny** — `ipal_vid` tworzy `<PageStats>` dopiero po zgodzie na
analytics, a serwer i tak sprawdza cookie zgody (z aktualną *Policy version*) zanim zapisze
`visitorId`. Nie obchodź tego.
To nie jest porada prawna — przy nietypowym projekcie (dane wrażliwe, dzieci) skonsultuj z prawnikiem klienta.
## Config
```ts
ipalKit({
// …
stats: true,
// albo:
stats: {
retentionDays: 90, // ile dni trzymamy wizyty (domyślnie 90; wykres pokazuje 30)
timeZone: 'Europe/Warsaw', // gdzie zaczyna się „dzień” (domyślnie Europe/Warsaw)
dashboard: true, // wykres na dashboardzie panelu (domyślnie true)
},
})
```
Dodaje:
- kolekcję `stats-visits` (grupa *Statistics*, odczyt i usuwanie: admin; zapis tylko przez endpoint),
- `POST /api/ipal/hit`,
- widok **`/admin/stats`** + link w nawigacji (`StatsNavLink`),
- wykres 30 dni na dashboardzie (`StatsWidget`),
- `STATS_SLUG` (`'stats-visits'`) z `@intecion/ipal-kit` — do własnych zapytań.
Po włączeniu: `pnpm payload generate:importmap` (komponenty `@intecion/ipal-kit/admin#StatsView`,
`#StatsWidget`, `#StatsNavLink`) i migracja bazy (Postgres: `pnpm payload migrate:create`).
## Front
Z `SiteProviders`:
```tsx
<SiteProviders shell={shell} logEndpoint="/api/ipal/consent" stats={{ locale }}>
```
Albo ręcznie — **wewnątrz `ConsentProvider`**:
```tsx
import { PageStats } from '@intecion/ipal-kit/client'
<PageStats locale={locale} /> // endpoint domyślnie '/api/ipal/hit'
```
`<PageStats>` wysyła jeden beacon na odsłonę (także przy nawigacji klienckiej Next). Nic nie renderuje.
`VISITOR_COOKIE` (`'ipal_vid'`) z `/client` — nazwa cookie, np. do własnej tabeli cookies.
CSP: endpoint jest na tej samej domenie — `connect-src 'self'` wystarcza.
## Czego nie liczymy
- zalogowanych użytkowników panelu (redaktor oglądający stronę nie zawyża statystyk),
- botów (Googlebot, podglądy linków, Lighthouse, curl, headless),
- prefetchu Next (`sec-purpose: prefetch`),
- odświeżenia tej samej strony w ciągu 10 s.
Zapisujemy samą ścieżkę: query string i `#hash` są odcinane (mogą zawierać e-mail, token, frazę
wyszukiwania). Referrer — tylko nazwa domeny. Kraj — tylko z nagłówka Cloudflare `cf-ipcountry`, jeśli jest.
## Wizyta
Ciąg odsłon z przerwami poniżej 30 minut, w ramach jednego dnia. Restart serwera albo kilka instancji
(każda ma własną sól) mogą rozbić trwającą wizytę na dwie — dla statystyk bez znaczenia. **Nie**
zapisuj soli w bazie, żeby to „naprawić”: wtedy wczorajsze hashe dałoby się odwrócić do IP.
Wizyty starsze niż `retentionDays` są usuwane automatycznie (raz na dobę, przy pierwszej odsłonie).
## Prawa odwiedzającego (RODO)
- **Wycofanie zgody** — `useConsent` usuwa `ipal_vid` (jest w `DEFAULT_COOKIE_MAP.analytics`); kolejne
odsłony są już anonimowe.
- **Usunięcie danych** — odwiedzający podaje id z cookie `ipal_vid` (DevTools → Application →
Cookies). W panelu: *Statistics → Visits*, filtr `visitorId` = id → zaznacz wszystko → Delete.
Widok `/admin/stats?visitor=<id>` pokazuje to samo jako historię.
- Wizyt anonimowych nie da się przypisać osobie — nie ma czego wydać ani usunąć na żądanie.
## Do polityki prywatności i tabeli cookies
Dopisz w **Cookie Settings → Cookies** (panel) wiersz:
| Nazwa | Dostawca | Kategoria | Cel | Czas |
|---|---|---|---|---|
| `ipal_vid` | ta strona | analytics | Rozpoznanie powracającego odwiedzającego w statystykach strony | 180 dni |
Tekst do polityki prywatności (dopasuj nazwę administratora i okres):
> **Statystyki odwiedzin.** Liczymy odwiedziny strony własnym narzędziem, bez udziału podmiotów
> trzecich. Bez Twojej zgody nie zapisujemy niczego na Twoim urządzeniu: kolejne odsłony łączymy w
> wizytę za pomocą jednodniowego, nieodwracalnego skrótu adresu IP i typu przeglądarki; samego adresu
> IP nie przechowujemy, a skrót traci znaczenie po upływie doby. Zapisujemy odwiedzone podstrony,
> czas, domenę strony odsyłającej, rodzaj urządzenia (komputer / telefon / tablet) i język.
> Podstawą jest nasz prawnie uzasadniony interes (art. 6 ust. 1 lit. f RODO) — wiedza, jak
> korzystacie ze strony. Jeśli zgodzisz się na cookies analityczne, zapiszemy cookie `ipal_vid` z
> losowym identyfikatorem, dzięki któremu zobaczymy Twoje kolejne wizyty jako jedną historię
> (podstawa: zgoda, art. 6 ust. 1 lit. a RODO; możesz ją wycofać w ustawieniach cookies). Dane
> przechowujemy przez 90 dni.
+1
View File
@@ -90,6 +90,7 @@
},
"peerDependencies": {
"@clocklimited/payload-2fa": "^3.0.0-0",
"@payloadcms/next": "^3.90.2",
"@payloadcms/plugin-form-builder": "^3.90.2",
"@payloadcms/plugin-seo": "^3.90.2",
"@payloadcms/richtext-lexical": "^3.90.2",
+4
View File
@@ -11,3 +11,7 @@ export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { MetaDescriptionCheck } from '../modules/seo/MetaDescriptionCheck.js'
export { StatsNavLink } from '../modules/stats/admin/StatsNavLink.js'
export { StatsView } from '../modules/stats/admin/StatsView.js'
export { StatsWidget } from '../modules/stats/admin/StatsWidget.js'
+4
View File
@@ -79,6 +79,10 @@ export { LocaleView } from '../modules/pages/LocaleView.js'
export { NotFoundLoader } from '../modules/pages/NotFoundLoader.js'
export { TableOfContents } from '../modules/richtext/TableOfContents.js'
export type { TableOfContentsClassNames, TableOfContentsProps } from '../modules/richtext/TableOfContents.js'
export { NoSnippet } from '../modules/seo/NoSnippet.js'
export type { NoSnippetProps } from '../modules/seo/NoSnippet.js'
export { PageStats, VISITOR_COOKIE } from '../modules/stats/client.js'
export type { PageStatsProps } from '../modules/stats/client.js'
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
export { isTheme, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE } from '../modules/theme/theme.js'
export type { Theme, ThemeConfig, ThemeSetting } from '../modules/theme/theme.js'
+2
View File
@@ -26,6 +26,8 @@ export { extractHeadings } from '../modules/richtext/headings.js'
export { RenderRichText } from '../modules/richtext/index.js'
export type { RenderRichTextProps } from '../modules/richtext/index.js'
export { JsonLdGraph } from '../modules/seo/index.js'
export { NoSnippet } from '../modules/seo/NoSnippet.js'
export type { NoSnippetProps } from '../modules/seo/NoSnippet.js'
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'
export { ThemeScript } from '../modules/theme/ThemeScript.js'
export type { ThemeScriptProps } from '../modules/theme/ThemeScript.js'
+2
View File
@@ -227,6 +227,8 @@ export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/ind
export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { STATS_SLUG } from './modules/stats/index.js'
export type { StatsOptions, StatsPage, StatsVisit } from './modules/stats/index.js'
export { buildImagesConfig } from './modules/storage/buildImagesConfig.js'
export type { ImagesConfig } from './modules/storage/buildImagesConfig.js'
export { buildR2Storage } from './modules/storage/index.js'
+10 -6
View File
@@ -17,14 +17,18 @@ declare global {
const GTM_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtm.js?id=${id}`
const GA4_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtag/js?id=${id}`
/** Reads the current consent state from cookie, or defaults if none. */
function readConsent() {
/**
* Reads the current consent state from cookie, or defaults if none. `version`
* must be the panel's policy version — the same one useConsent checks — or a
* valid consent under any version other than 1 reads as "all denied".
*/
function readConsent(version: number | undefined) {
if (typeof document === 'undefined') {return DEFAULT_CONSENT}
const raw = document.cookie
.split('; ')
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
?.split('=')[1]
return parseConsent(raw) ?? DEFAULT_CONSENT
return parseConsent(raw, version) ?? DEFAULT_CONSENT
}
function injectScript(src: string) {
@@ -121,7 +125,7 @@ export function Analytics(props: AnalyticsProps) {
} = props
// Live consent state — drives the non-Google pixels.
const { state } = useConsentContext()
const { state, texts } = useConsentContext()
const ready = useDeferredReady(defer, deferTimeoutMs)
const defaultConsentSet = useRef(false)
@@ -131,9 +135,9 @@ export function Analytics(props: AnalyticsProps) {
useEffect(() => {
if (defaultConsentSet.current) {return}
if (!ga4MeasurementId && !gtmContainerId) {return}
setDefaultConsent(readConsent())
setDefaultConsent(readConsent(texts.version))
defaultConsentSet.current = true
}, [ga4MeasurementId, gtmContainerId])
}, [ga4MeasurementId, gtmContainerId, texts.version])
// --- Google: load once `ready`; Consent Mode handles gating ---
useEffect(() => {
+3 -1
View File
@@ -313,6 +313,8 @@ export function CookieBanner({
<div
className={cn('overlay')}
data-ipal="consent-overlay"
// banner text is not page content — keep it out of Google's snippets
data-nosnippet
onClick={(event) => {
if (event.target === event.currentTarget) {setShowSettings(false)}
}}
@@ -327,7 +329,7 @@ export function CookieBanner({
}
return (
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" role="dialog">
<div aria-label={texts.title || texts.settingsTitle} className={cn('root')} data-ipal="banner" data-nosnippet role="dialog">
<div className={cn('body')}>
{!showSettings ? (
<div className={cn('content')}>
+1 -1
View File
@@ -17,7 +17,7 @@ export type ConsentCookieMap = Partial<Record<ConsentCategory, string[]>>
* projects add theirs through <ConsentProvider cookieMap> (merged, not replaced).
*/
export const DEFAULT_COOKIE_MAP: ConsentCookieMap = {
analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*'],
analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*', 'ipal_vid'],
functional: [LOCALE_COOKIE_NAME],
marketing: ['_fbp', '_fbc', '_gcl_*', '_ttp', 'li_fat_id', '_uetsid', '_uetvid'],
}
+9
View File
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react'
import type { AnalyticsProps } from '../analytics/Analytics.js'
import type { ConsentCookieMap } from '../consent/useConsent.js'
import type { PageStatsProps } from '../stats/PageStats.js'
import type { SiteShell } from './createContentHelpers.js'
import { Analytics } from '../analytics/Analytics.js'
@@ -9,6 +10,7 @@ import { ConsentProvider } from '../consent/ConsentContext.js'
import { CookieBanner } from '../consent/CookieBanner.js'
import { CookieButton } from '../consent/CookieButton.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
import { PageStats } from '../stats/PageStats.js'
import { MediaPreconnect } from '../storage/MediaPreconnect.js'
import { ThemeScript } from '../theme/ThemeScript.js'
import { TurnstileProvider } from '../turnstile/TurnstileProvider.js'
@@ -31,6 +33,11 @@ export type SiteProvidersProps = {
preconnect?: boolean
/** getSiteShell(locale) from lib/content. */
shell: SiteShell
/**
* Built-in statistics (ipalKit stats: true): mounts <PageStats>. `true` or
* `{ locale, endpoint }`. Default off.
*/
stats?: boolean | PageStatsProps
/**
* Light / dark theme from Site Settings → Theme: renders <ThemeScript> first,
* so the theme is on <html> before the first paint. Put <SiteProviders> first in
@@ -65,6 +72,7 @@ export function SiteProviders({
logEndpoint,
preconnect = true,
shell,
stats = false,
theme = false,
}: SiteProvidersProps) {
return (
@@ -77,6 +85,7 @@ export function SiteProviders({
{banner === undefined ? <CookieBanner /> : banner || null}
{cookieButton === undefined ? <CookieButton /> : cookieButton || null}
{analytics === false ? null : <Analytics {...shell.analytics} {...analytics} />}
{stats ? <PageStats {...(stats === true ? {} : stats)} /> : null}
</ConsentProvider>
</>
)
+1 -1
View File
@@ -58,7 +58,7 @@ export function LanguageSwitcher({
const current = locales.find((l) => l.code === currentLocale)
return (
<div className={cn.root} data-ipal-langswitcher>
<div className={cn.root} data-ipal-langswitcher data-nosnippet>
<button
aria-expanded={open}
aria-haspopup="true"
+6 -3
View File
@@ -86,9 +86,12 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string
}
if (analytics) {
src['script-src'].push('https://www.googletagmanager.com')
src['connect-src'].push('https://www.google-analytics.com', 'https://www.googletagmanager.com')
src['img-src'].push('https://www.google-analytics.com', 'https://www.googletagmanager.com')
// Google's GA4/GTM CSP set. Wildcards are required: GA4 sends EU hits to
// region1.google-analytics.com and some to *.analytics.google.com — allowing
// only www.google-analytics.com blocks every hit ("data collection not active").
src['script-src'].push('https://*.googletagmanager.com')
src['connect-src'].push('https://*.google-analytics.com', 'https://*.analytics.google.com', 'https://*.googletagmanager.com')
src['img-src'].push('https://*.google-analytics.com', 'https://*.googletagmanager.com')
}
if (youtube) {
+122
View File
@@ -0,0 +1,122 @@
'use client'
import { useConfig, useDocumentInfo, useFormFields, useLocale } from '@payloadcms/ui'
import { useEffect, useState } from 'react'
export type MetaDescriptionCheckProps = {
/** An empty description is filled from the page content on save (autoFill). */
autoFill?: boolean
/** SiteSettings global slug. */
settingsSlug?: string
/** Field on SiteSettings holding the site-wide fallback description. */
siteDescriptionField?: string
/** Field shown as the name of the page that has the same description. */
titleField?: string
}
type Warning = { text: string; tone: 'info' | 'warn' }
const norm = (v: unknown) => (typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : '')
/**
* Hint under the meta description in the SEO tab. Google ignores a description
* it sees on many pages and quotes page text instead (usually the footer), so
* this flags a description that matches the site-wide fallback or another
* document in the collection. Advisory only — saving is never blocked. Length
* is already shown by plugin-seo's own counter.
*/
export function MetaDescriptionCheck({
autoFill = true,
settingsSlug = 'site-settings',
siteDescriptionField = 'siteDescription',
titleField = 'title',
}: MetaDescriptionCheckProps) {
const description = norm(useFormFields(([f]) => f['meta.description']?.value))
const { id, collectionSlug } = useDocumentInfo()
const { code: locale } = useLocale()
const {
config: {
routes: { api },
serverURL,
},
} = useConfig()
const [warning, setWarning] = useState<null | Warning>(null)
useEffect(() => {
if (!description) {
setWarning(
autoFill
? { text: 'Empty — on save it is filled from this page’s content. Writing your own is better.', tone: 'info' }
: { text: 'Empty — the page gets the site-wide description, the same as every other page.', tone: 'warn' },
)
return
}
if (!collectionSlug) {return}
const controller = new AbortController()
const base = `${serverURL ?? ''}${api}`
const get = async (url: string) => {
const res = await fetch(url, { credentials: 'include', signal: controller.signal })
return res.ok ? ((await res.json()) as Record<string, unknown>) : null
}
const timer = setTimeout(() => {
void (async () => {
try {
const settings = await get(`${base}/globals/${settingsSlug}?depth=0&locale=${locale}`)
if (settings && norm(settings[siteDescriptionField]) === description) {
setWarning({
text: 'Same as the site-wide description. Google ignores a description repeated across pages — write one about this page.',
tone: 'warn',
})
return
}
const query = new URLSearchParams({
depth: '0',
limit: '1',
locale,
'where[meta.description][equals]': description,
})
if (id !== undefined && id !== null) {query.set('where[id][not_equals]', String(id))}
const found = await get(`${base}/${collectionSlug}?${query}`)
const twin = (found?.docs as Record<string, unknown>[] | undefined)?.[0]
if (twin) {
const name = norm(twin[titleField]) || String(twin.id)
setWarning({
text: `Same description as “${name}”. Google ignores a description repeated across pages — make each one unique.`,
tone: 'warn',
})
return
}
setWarning(null)
} catch {
// aborted or offline — a hint is not worth an error
}
})()
}, 600)
return () => {
clearTimeout(timer)
controller.abort()
}
}, [api, autoFill, collectionSlug, description, id, locale, serverURL, settingsSlug, siteDescriptionField, titleField])
if (!warning) {return null}
return (
<div
role="status"
style={{
background:
warning.tone === 'warn' ? 'var(--theme-warning-50, rgba(255, 178, 36, 0.1))' : 'var(--theme-elevation-50)',
border: `1px solid ${warning.tone === 'warn' ? 'var(--theme-warning-400, #ffb224)' : 'var(--theme-elevation-150)'}`,
borderRadius: 4,
fontSize: '0.85rem',
marginBottom: '1.5rem',
padding: '0.6rem 0.9rem',
}}
>
{warning.text}
</div>
)
}
+37
View File
@@ -0,0 +1,37 @@
import type { HTMLAttributes, ReactNode } from 'react'
export type NoSnippetProps = {
/**
* Wrapper element. Only div, section and span — Google honours
* `data-nosnippet` on those and ignores it on footer, nav, aside and the rest.
* Default 'div'.
*/
as?: 'div' | 'section' | 'span'
children?: ReactNode
} & HTMLAttributes<HTMLElement>
/**
* Keeps its contents out of Google's search snippets (`data-nosnippet`). The
* text is still crawled and indexed — Google just won't quote it under a
* result.
*
* Use it for text that repeats on every page: the footer's address, hours and
* phone, a contact strip, a "book a visit" call to action. Google picks snippet
* text itself when it thinks it fits the query better than the meta
* description; for a brand search that is the contact block, so every sitelink
* ends up showing the same address. The address stays available to Google
* through the LocalBusiness JSON-LD.
*
* Never wrap <main> — that's the text the snippet should come from.
*
* <footer>
* <NoSnippet>…address, hours, phone, links…</NoSnippet>
* </footer>
*/
export function NoSnippet({ as: Tag = 'div', children, ...rest }: NoSnippetProps) {
return (
<Tag {...rest} data-nosnippet="">
{children}
</Tag>
)
}
+35 -8
View File
@@ -1,12 +1,22 @@
import type { CollectionBeforeChangeHook } from 'payload'
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
import { describeFromMarkdown } from './plainText.js'
/**
* Maps document fields to SEO meta fields for auto-fill.
* Defaults match the Payload website template (title → meta.title).
*/
export type AutoFillMapping = {
/** Document field used to fill meta.description when empty. */
/**
* Block layout field to derive meta.description from when it's empty and the
* `description` field gives nothing. Default 'layout'; false turns it off.
*/
content?: false | string
/** Document field used to fill meta.description when empty. Tried before `content`. */
description?: string
/** Target length of a description derived from `content`. Default 155. */
descriptionLength?: number
/** Document field used to fill meta.title when empty. Default: 'title'. */
title?: string
}
@@ -27,32 +37,49 @@ function readString(value: unknown): string | undefined {
* editor typed. This runs server-side on every create/update, so editors get
* sensible meta without clicking "auto-generate".
*
* Every page gets its own description: from the `description` field when one
* is mapped, otherwise from the page's own blocks. Without it, pages fall back
* to the one site-wide description, and Google — seeing the same text on every
* page — ignores it and quotes the footer instead.
*
* The plugin doesn't know the client's collection shape, so the field mapping
* is configurable; defaults follow the website template.
*/
export function buildAutoFillMetaHook(mapping: AutoFillMapping = {}): CollectionBeforeChangeHook {
const titleField = mapping.title ?? 'title'
const descriptionField = mapping.description
const contentField = mapping.content === undefined ? 'layout' : mapping.content
const descriptionLength = mapping.descriptionLength ?? 155
return ({ data }) => {
return ({ data, originalDoc }) => {
if (!data) {return data}
// plugin-seo stores meta as a group under `meta`
const meta = (data.meta as Record<string, unknown> | undefined) ?? {}
// A partial update (REST PATCH, payload.update with a few fields) carries
// only what changed — read the rest from the stored document, so a saved
// description isn't treated as empty and replaced.
const stored = (originalDoc?.meta as Record<string, unknown> | undefined) ?? {}
const current = (key: string) => (key in meta ? meta[key] : stored[key])
const source = (field: string) => (field in data ? data[field] : originalDoc?.[field])
// Fill meta.title from the document title when empty
if (!readString(meta.title)) {
const sourceTitle = readString(data[titleField])
if (!readString(current('title'))) {
const sourceTitle = readString(source(titleField))
if (sourceTitle) {meta.title = sourceTitle}
}
// Fill meta.description from a configured field when empty
if (descriptionField && !readString(meta.description)) {
const sourceDescription = readString(data[descriptionField])
// Fill meta.description from a configured field, else from the page content
if (!readString(current('description'))) {
const sourceDescription =
(descriptionField && readString(source(descriptionField))) ||
(contentField &&
describeFromMarkdown(blocksToMarkdown(source(contentField)), descriptionLength)) ||
undefined
if (sourceDescription) {meta.description = sourceDescription}
}
data.meta = meta
if (data.meta !== undefined || Object.keys(meta).length) {data.meta = meta}
return data
}
}
+1 -20
View File
@@ -1,6 +1,7 @@
import type { Field, FieldHook, TextareaField } from 'payload'
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
import { mdToPlain, truncate } from './plainText.js'
type BuildSummaryFieldArgs = {
/** Auto-fill from page content when the editor leaves it empty. Default true. */
@@ -19,26 +20,6 @@ type BuildSummaryFieldArgs = {
overrides?: Partial<TextareaField>
}
/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */
function mdToPlain(md: string): string {
return md
.replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text
.replace(/^#{1,6}\s+/gm, '') // heading markers
.replace(/^[>\-*]\s+/gm, '') // quote/list markers
.replace(/[*_~`]/g, '') // inline emphasis/code marks
.replace(/\s+/g, ' ')
.trim()
}
/** Truncate at a word boundary, adding an ellipsis when cut. */
function truncate(text: string, max: number): string {
if (text.length <= max) {return text}
const slice = text.slice(0, max)
const lastSpace = slice.lastIndexOf(' ')
return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`
}
/**
* A localized `aiSummary` textarea — a concise, human-written (or auto-derived)
* description of the page, richer than the SEO meta description. It's the
+51
View File
@@ -0,0 +1,51 @@
/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */
export function mdToPlain(md: string): string {
return md
.replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text
.replace(/^#{1,6}\s+/gm, '') // heading markers
.replace(/^[>\-*]\s+/gm, '') // quote/list markers
.replace(/[*_~`]/g, '') // inline emphasis/code marks
.replace(/\s+/g, ' ')
.trim()
}
/** Truncate at a word boundary, adding an ellipsis when cut. */
export function truncate(text: string, max: number): string {
if (text.length <= max) {return text}
const slice = text.slice(0, max)
const lastSpace = slice.lastIndexOf(' ')
return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`
}
/** Ensure a fragment ends like a sentence, so joined fragments don't run together. */
function terminate(text: string): string {
return /[.!?…:]$/.test(text) ? text : `${text}.`
}
/**
* A meta description from a page's Markdown (blocksToMarkdown output).
*
* Headings are skipped while there's body text — they usually repeat the page
* title, which Google already shows above the snippet. Whole sentences are
* kept up to `max`; a first sentence longer than that is cut at a word
* boundary. Returns '' when the content has no text.
*/
export function describeFromMarkdown(md: string, max = 155): string {
const parts = md.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean)
const body = parts.filter((p) => !/^#{1,6}\s/.test(p) && !/^!\[/.test(p))
const source = (body.length ? body : parts).map(mdToPlain).filter(Boolean).map(terminate)
const text = source.join(' ')
if (!text) {return ''}
if (text.length <= max) {return text}
// Longest run of whole sentences that fits.
const sentences = text.match(/[^.!?…]+[.!?…]+(?=\s|$)/g) ?? []
let out = ''
for (const s of sentences) {
const next = `${out} ${s.trim()}`.trim()
if (next.length > max) {break}
out = next
}
return out || truncate(text, max)
}
+38 -1
View File
@@ -25,6 +25,39 @@ const titleOverrideField: Field = {
localized: true,
}
/**
* Admin hint right under meta.description (MetaDescriptionCheck): empty,
* same as the site-wide description, or same as another document's.
*/
function descriptionCheckField(seo: SeoOption): Field | null {
if (seo.descriptionCheck === false) {return null}
const autoFill =
seo.autoFill !== false && (seo.autoFill?.content !== false || Boolean(seo.autoFill?.description))
return {
name: 'descriptionCheck',
type: 'ui',
admin: {
components: {
Field: {
clientProps: {
autoFill,
titleField: (seo.autoFill && seo.autoFill.title) || 'title',
...(seo.descriptionCheck ?? {}),
},
path: '@intecion/ipal-kit/admin#MetaDescriptionCheck',
},
},
},
}
}
/** Puts `extra` right after the description field (end of the group if it's missing). */
function afterDescription(fields: Field[], extra: Field | null): Field[] {
if (!extra) {return fields}
const at = fields.findIndex((f) => 'name' in f && f.name === 'description')
return at === -1 ? [...fields, extra] : [...fields.slice(0, at + 1), extra, ...fields.slice(at + 1)]
}
/**
* Configures @payloadcms/plugin-seo from IPAL's SeoOption.
*
@@ -37,7 +70,11 @@ const titleOverrideField: Field = {
export function buildSeoPlugin({ seo, uploadsCollection = 'media' }: BuildSeoPluginArgs): Plugin {
return seoPlugin({
collections: seo.collections,
fields: ({ defaultFields }) => [...defaultFields, titleOverrideField, ...(seo.fields ?? [])],
fields: ({ defaultFields }) => [
...afterDescription(defaultFields, descriptionCheckField(seo)),
titleOverrideField,
...(seo.fields ?? []),
],
uploadsCollection,
...(seo.generateTitle && { generateTitle: seo.generateTitle }),
...(seo.generateDescription && { generateDescription: seo.generateDescription }),
+13
View File
@@ -17,6 +17,19 @@ export type SeoOption = {
autoFill?: AutoFillMapping | false
/** Collection slugs that receive SEO meta fields, e.g. ['pages', 'posts']. */
collections: string[]
/**
* Hint under the meta description in the admin when it's empty, or the same
* as the site-wide description or another document's. Advisory, never blocks
* saving. Point it at your SiteSettings when the slugs differ; false hides it.
*/
descriptionCheck?:
| {
/** SiteSettings global slug. Default 'site-settings'. */
settingsSlug?: string
/** Field holding the site-wide description. Default 'siteDescription'. */
siteDescriptionField?: string
}
| false
/** Extra fields appended to the SEO group in the admin. */
fields?: Field[]
/** Optional: customize how meta descriptions are generated. */
+75
View File
@@ -0,0 +1,75 @@
'use client'
import { useEffect, useRef } from 'react'
// .js extension: Node's ESM resolution (this plugin's tsconfig) can't find
// 'next/navigation' without it.
import { usePathname } from 'next/navigation.js'
import { useConsentContext } from '../consent/ConsentContext.js'
import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent } from '../consent/storage.js'
/** Visitor id cookie — set ONLY with analytics consent, deleted on withdrawal (DEFAULT_COOKIE_MAP). */
export const VISITOR_COOKIE = 'ipal_vid'
function readCookie(name: string): string | undefined {
return document.cookie
.split('; ')
.find((c) => c.startsWith(`${name}=`))
?.split('=')[1]
}
function ensureVisitorId(): string {
const existing = readCookie(VISITOR_COOKIE)
if (existing && /^[0-9a-f]{32}$/.test(existing)) {return existing}
const bytes = new Uint8Array(16)
globalThis.crypto.getRandomValues(bytes)
const id = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
const secure = location.protocol === 'https:' ? ';secure' : ''
document.cookie = `${VISITOR_COOKIE}=${id};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`
return id
}
export type PageStatsProps = {
/** The hit endpoint. Default '/api/ipal/hit' (ipalKit({ stats: true })). */
endpoint?: string
/** Current locale code, stored with the visit. */
locale?: string
}
/**
* Built-in statistics: sends one beacon per page view to the hit endpoint.
*
* - **Everyone, no consent needed** — nothing is stored in the browser; the
* server joins page views into a visit with a daily-salted hash it can't
* reverse, and keeps no IP.
* - **With analytics consent** (the same category that turns on GA4) — sets the
* `ipal_vid` cookie with a random id, so the panel can show that visitor's
* history across days. Withdrawing consent deletes the cookie.
*
* Renders nothing. Mount once in the locale layout, INSIDE <ConsentProvider>.
*/
export function PageStats({ endpoint = '/api/ipal/hit', locale }: PageStatsProps) {
const pathname = usePathname()
const { texts } = useConsentContext()
const firstHit = useRef(true)
useEffect(() => {
if (!pathname) {return}
const body: Record<string, string> = { p: pathname }
// the external referrer belongs to the landing page only
if (firstHit.current && document.referrer) {body.r = document.referrer}
firstHit.current = false
if (locale) {body.l = locale}
// The cookie, not context state: on a full page load this effect runs before
// useConsent has read the cookie, so state would still say "no consent".
if (parseConsent(readCookie(CONSENT_COOKIE), texts.version)?.analytics) {body.v = ensureVisitorId()}
const json = JSON.stringify(body)
if (!navigator.sendBeacon?.(endpoint, new Blob([json], { type: 'application/json' }))) {
void fetch(endpoint, { body: json, headers: { 'content-type': 'application/json' }, keepalive: true, method: 'POST' }).catch(() => {})
}
// texts.version is read, not a trigger: a policy change isn't a page view
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pathname, endpoint, locale])
return null
}
+10
View File
@@ -0,0 +1,10 @@
/** Nav link to /admin/stats (admin.components.afterNavLinks). */
export function StatsNavLink({ adminRoute = '/admin' }: { adminRoute?: string }) {
return (
<a className="nav__link" href={`${adminRoute.replace(/\/$/, '')}/stats`} id="nav-ipal-stats">
<span className="nav__link-label">Statistics</span>
</a>
)
}
export default StatsNavLink
+172
View File
@@ -0,0 +1,172 @@
import type { AdminViewServerProps } from 'payload'
import { DefaultTemplate } from '@payloadcms/next/templates'
import { Gutter } from '@payloadcms/ui'
import type { StatsVisit } from '../collection.js'
import { isAdmin } from '../../access/predicates.js'
import { VISITOR_ID_PATTERN } from '../parse.js'
import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
type Props = { adminRoute?: string; timeZone?: string } & AdminViewServerProps
const fmt = (n: number) => n.toLocaleString('en-US')
const when = (iso: string, timeZone: string) =>
new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium', timeStyle: 'short', timeZone }).format(new Date(iso))
function TopList({ rows, title, unit }: { rows: [string, number][]; title: string; unit: string }) {
return (
<section>
<h3>{title}</h3>
{rows.length ? (
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">{title}</th>
<th scope="col">{unit}</th>
</tr>
</thead>
<tbody>
{rows.map(([key, count]) => (
<tr key={key}>
<td><code>{key}</code></td>
<td>{fmt(count)}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No data yet.</p>
)}
</section>
)
}
function VisitorHistory({ base, timeZone, visitorId, visits }: { base: string; timeZone: string; visitorId: string; visits: StatsVisit[] }) {
return (
<>
<p><a href={base}>← All statistics</a></p>
<h1>Visitor <code>{visitorId}</code></h1>
<p>
{visits.length} visit{visits.length === 1 ? '' : 's'} recorded with analytics consent. To erase this
visitor’s data, filter <em>Statistics → Visits</em> by this visitor id and delete the results.
</p>
{visits.map((v) => (
<section className="ipal-stats-tile" key={v.id} style={{ marginBottom: '1rem' }}>
<strong>{when(v.startedAt, timeZone)}</strong>
<span>
{' '}· {v.pageCount} page{v.pageCount === 1 ? '' : 's'} · {v.device ?? 'unknown device'}
{v.referrer ? ` · from ${v.referrer}` : ''}
</span>
<ol style={{ margin: '0.5rem 0 0', paddingLeft: '1.25rem' }}>
{(v.pages ?? []).map((p, i) => (
<li key={`${p.t}-${i}`}>
<code>{p.p}</code> <span>{when(p.t, timeZone).split(', ').pop()}</span>
</li>
))}
</ol>
</section>
))}
</>
)
}
/**
* Admin view at /admin/stats (ipalKit({ stats: true })): visits per day for the
* last 30 days, top pages, entry pages, referrers, devices, and — for visitors
* who accepted analytics cookies — a per-visitor history (?visitor=<id>).
* Admins only.
*/
export async function StatsView(props: Props) {
const { adminRoute = '/admin', initPageResult, searchParams, timeZone = 'Europe/Warsaw' } = props
const { req, visibleEntities } = initPageResult
const base = `${adminRoute.replace(/\/$/, '')}/stats`
const visitorParam = typeof searchParams?.visitor === 'string' ? searchParams.visitor : undefined
const visitorId = visitorParam && VISITOR_ID_PATTERN.test(visitorParam) ? visitorParam : undefined
let content: React.ReactNode
if (!isAdmin(req.user)) {
content = <p>Statistics are available to administrators only.</p>
} else if (visitorId) {
content = <VisitorHistory base={base} timeZone={timeZone} visitorId={visitorId} visits={await loadVisitor(req.payload, visitorId)} />
} else {
const [stats, recent] = await Promise.all([loadStats(req.payload, { timeZone }), loadRecentVisitors(req.payload, 50)])
const { totals } = stats
const visitors = [...new Map(recent.map((v) => [v.visitorId!, v])).values()].slice(0, 15)
content = (
<>
<h1>Statistics</h1>
<p>
Last 30 days. Counted without cookies, so no consent is needed; no IP addresses are stored. Visitors who accept
analytics cookies also get a history across days.
</p>
<div className="ipal-stats-tiles">
<div className="ipal-stats-tile"><b>{fmt(totals.visits)}</b><span>Visits</span></div>
<div className="ipal-stats-tile"><b>{fmt(totals.views)}</b><span>Page views</span></div>
<div className="ipal-stats-tile">
<b>{totals.visits ? (totals.views / totals.visits).toFixed(1) : '0'}</b><span>Pages per visit</span>
</div>
<div className="ipal-stats-tile"><b>{Math.round(totals.bounceRate * 100)}%</b><span>Single-page visits</span></div>
<div className="ipal-stats-tile"><b>{fmt(totals.consented)}</b><span>Visits with analytics consent</span></div>
</div>
<h2>Visits per day</h2>
<VisitsChart days={stats.days} />
<div className="ipal-stats-lists">
<TopList rows={stats.topPages} title="Page" unit="Views" />
<TopList rows={stats.entries} title="Entry page" unit="Visits" />
<TopList rows={stats.referrers} title="Referrer" unit="Visits" />
<TopList rows={stats.devices} title="Device" unit="Visits" />
</div>
<section style={{ marginTop: '2rem' }}>
<h3>Visitor history (analytics consent only)</h3>
{visitors.length ? (
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">Visitor</th>
<th scope="col">Last seen</th>
</tr>
</thead>
<tbody>
{visitors.map((v) => (
<tr key={v.visitorId}>
<td><a aria-label={`Visitor ${v.visitorId}`} href={`${base}?visitor=${v.visitorId}`}><code>{v.visitorId}</code></a></td>
<td>{when(v.lastAt, timeZone)}</td>
</tr>
))}
</tbody>
</table>
) : (
<p>No visitor has accepted analytics cookies yet.</p>
)}
</section>
</>
)
}
return (
<DefaultTemplate
i18n={req.i18n}
locale={initPageResult.locale}
params={props.params}
payload={req.payload}
permissions={initPageResult.permissions}
req={req}
searchParams={searchParams}
user={req.user ?? undefined}
visibleEntities={visibleEntities}
>
<Gutter>
<div className="ipal-stats" style={{ paddingBottom: '3rem' }}>
<style>{STATS_CSS}</style>
{content}
</div>
</Gutter>
</DefaultTemplate>
)
}
export default StatsView
+42
View File
@@ -0,0 +1,42 @@
import type { Payload, PayloadRequest } from 'payload'
import { isAdmin } from '../../access/predicates.js'
import { loadStats } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
type Props = {
adminRoute?: string
/** Injected by Payload into admin server components. */
payload?: Payload
req?: PayloadRequest
timeZone?: string
user?: unknown
}
/**
* Dashboard card (admin.components.beforeDashboard): visits per day for the
* last 30 days with a link to the full view. Admins only; renders nothing on
* any error (DB not ready, collection missing).
*/
export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZone = 'Europe/Warsaw', user }: Props) {
if (!payload || !isAdmin((req?.user ?? user) as never)) {return null}
let stats
try {
stats = await loadStats(payload, { timeZone })
} catch {
return null
}
return (
<section className="ipal-stats" style={{ marginBottom: '2rem' }}>
<style>{STATS_CSS}</style>
<h2 style={{ marginBottom: '0.25rem' }}>Visits per day</h2>
<p style={{ color: 'var(--theme-elevation-500)', margin: '0 0 0.75rem' }}>
Last 30 days: {stats.totals.visits.toLocaleString('en-US')} visits, {stats.totals.views.toLocaleString('en-US')} page views ·{' '}
<a href={`${adminRoute.replace(/\/$/, '')}/stats`}>All statistics →</a>
</p>
<VisitsChart days={stats.days} />
</section>
)
}
export default StatsWidget
+108
View File
@@ -0,0 +1,108 @@
import type { StatsDay } from '../summarize.js'
const W = 1000
const H = 220
const PAD = { bottom: 24, left: 36, right: 8, top: 12 }
const RADIUS = 4
/** Round up to 1 / 2 / 5 × 10^k, so the gridlines land on readable numbers. */
function niceMax(value: number): number {
if (value <= 4) {return 4}
const pow = 10 ** Math.floor(Math.log10(value))
return ([1, 2, 5, 10].map((s) => s * pow).find((s) => s >= value) ?? 10 * pow)
}
/** Column with a 4px rounded top and a square base on the baseline. */
function column(x: number, y: number, w: number, h: number): string {
const r = Math.min(RADIUS, w / 2, h)
return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`
}
const shortDate = (day: string) => `${day.slice(8, 10)}.${day.slice(5, 7)}`
/**
* Visits per day — server-rendered SVG, no client JS. One series, so no
* legend: the heading names it. Each day has a full-height hover target with
* a native tooltip, and the numbers are in a table below for screen readers.
*/
export function VisitsChart({ days }: { days: StatsDay[] }) {
const max = niceMax(Math.max(0, ...days.map((d) => d.visits)))
const plotW = W - PAD.left - PAD.right
const plotH = H - PAD.top - PAD.bottom
const band = plotW / Math.max(1, days.length)
const barW = Math.min(24, band - 2)
const y = (v: number) => PAD.top + plotH - (v / max) * plotH
const ticks = [0, max / 2, max]
return (
<figure className="ipal-stats-chart" style={{ margin: 0 }}>
<svg aria-hidden="true" style={{ display: 'block', height: 'auto', width: '100%' }} viewBox={`0 0 ${W} ${H}`}>
{ticks.map((t) => (
<g key={t}>
<line className="ipal-stats-grid" x1={PAD.left} x2={W - PAD.right} y1={y(t)} y2={y(t)} />
<text className="ipal-stats-axis" dominantBaseline="middle" textAnchor="end" x={PAD.left - 6} y={y(t)}>
{Number.isInteger(t) ? t : t.toFixed(1)}
</text>
</g>
))}
{days.map((d, i) => {
const x = PAD.left + i * band
const h = (d.visits / max) * plotH
const label = i % 7 === (days.length - 1) % 7
return (
<g className="ipal-stats-day" key={d.day}>
<title>{`${d.day}: ${d.visits} visits, ${d.views} page views`}</title>
<rect fill="transparent" height={plotH} width={band} x={x} y={PAD.top} />
{h > 0 ? <path className="ipal-stats-bar" d={column(x + (band - barW) / 2, y(d.visits), barW, h)} /> : null}
{label ? (
<text className="ipal-stats-axis" textAnchor="middle" x={x + band / 2} y={H - 6}>
{shortDate(d.day)}
</text>
) : null}
</g>
)
})}
</svg>
<details style={{ marginTop: '0.5rem' }}>
<summary>Table</summary>
<table className="ipal-stats-table">
<thead>
<tr>
<th scope="col">Day</th>
<th scope="col">Visits</th>
<th scope="col">Page views</th>
</tr>
</thead>
<tbody>
{[...days].reverse().map((d) => (
<tr key={d.day}>
<td>{d.day}</td>
<td>{d.visits}</td>
<td>{d.views}</td>
</tr>
))}
</tbody>
</table>
</details>
</figure>
)
}
/** Colors from the reference palette (series 1, light/dark) + Payload's theme tokens for ink. */
export const STATS_CSS = `
.ipal-stats { --ipal-series-1: #2a78d6; }
html[data-theme='dark'] .ipal-stats { --ipal-series-1: #3987e5; }
.ipal-stats-bar { fill: var(--ipal-series-1); }
.ipal-stats-day:hover .ipal-stats-bar { opacity: 0.8; }
.ipal-stats-grid { stroke: var(--theme-elevation-100); stroke-width: 1; }
.ipal-stats-axis { fill: var(--theme-elevation-500); font-size: 11px; }
.ipal-stats-tiles { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin: 1rem 0 1.5rem; }
.ipal-stats-tile { border: 1px solid var(--theme-elevation-150); border-radius: 4px; padding: 0.75rem 1rem; }
.ipal-stats-tile b { display: block; font-size: 1.75rem; line-height: 1.2; }
.ipal-stats-tile span { color: var(--theme-elevation-500); font-size: 0.85rem; }
.ipal-stats-lists { display: grid; gap: 1.5rem; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); margin-top: 2rem; }
.ipal-stats-table { border-collapse: collapse; width: 100%; }
.ipal-stats-table th, .ipal-stats-table td { border-bottom: 1px solid var(--theme-elevation-100); padding: 0.35rem 0.5rem; text-align: left; }
.ipal-stats-table td:not(:first-child), .ipal-stats-table th:not(:first-child) { font-variant-numeric: tabular-nums; text-align: right; }
.ipal-stats-table code { word-break: break-all; }
`
+63
View File
@@ -0,0 +1,63 @@
import type { Payload } from 'payload'
import type { StatsVisit } from '../collection.js'
import type { StatsSummary } from '../summarize.js'
import { STATS_SLUG } from '../collection.js'
import { lastDays, summarize } from '../summarize.js'
const VISIT_FIELDS = {
day: true,
device: true,
entry: true,
exit: true,
lastAt: true,
pageCount: true,
pages: true,
referrer: true,
startedAt: true,
visitorId: true,
} as const
/** Summary of the last `days` days. Callers check the user is an admin first. */
export async function loadStats(payload: Payload, { days = 30, timeZone = 'Europe/Warsaw' } = {}): Promise<StatsSummary> {
const range = lastDays(days, timeZone)
const { docs } = await payload.find({
collection: STATS_SLUG as never,
depth: 0,
overrideAccess: true,
pagination: false,
select: VISIT_FIELDS as never,
where: { day: { greater_than_equal: range[0] } },
})
return summarize(docs as unknown as StatsVisit[], range)
}
/** Every stored visit of one consenting visitor, newest first. */
export async function loadVisitor(payload: Payload, visitorId: string): Promise<StatsVisit[]> {
const { docs } = await payload.find({
collection: STATS_SLUG as never,
depth: 0,
limit: 500,
overrideAccess: true,
pagination: false,
select: VISIT_FIELDS as never,
sort: '-startedAt',
where: { visitorId: { equals: visitorId } },
})
return docs as unknown as StatsVisit[]
}
/** Latest visits that carry a visitor id — the entry points into visitor history. */
export async function loadRecentVisitors(payload: Payload, limit = 20): Promise<StatsVisit[]> {
const { docs } = await payload.find({
collection: STATS_SLUG as never,
depth: 0,
limit,
overrideAccess: true,
select: VISIT_FIELDS as never,
sort: '-lastAt',
where: { visitorId: { exists: true } },
})
return docs as unknown as StatsVisit[]
}
+3
View File
@@ -0,0 +1,3 @@
'use client'
export { PageStats, VISITOR_COOKIE } from './PageStats.js'
export type { PageStatsProps } from './PageStats.js'
+90
View File
@@ -0,0 +1,90 @@
import type { CollectionConfig } from 'payload'
import { isAdmin } from '../access/predicates.js'
/**
* One document per visit (a run of page views with gaps under 30 minutes).
*
* Without consent a visit is anonymous: `visitKey` is a daily-salted hash
* (visitKey.ts) that can't be traced back to an IP or linked across days.
* With analytics consent the visit also carries `visitorId` — the random id
* from the visitor's `ipal_vid` cookie — and the panel can show that visitor's
* history across days. No IP, no user agent, no query strings are stored.
*/
export const STATS_SLUG = 'stats-visits'
export type StatsOptions = {
/** Show the 30-day chart on the admin dashboard. Default true. */
dashboard?: boolean
/** Days a visit is kept. Default 90 (the dashboard shows 30). */
retentionDays?: number
/** Time zone that decides where a day starts. Default 'Europe/Warsaw'. */
timeZone?: string
}
export type StatsPage = { p: string; t: string }
export type StatsVisit = {
country?: null | string
day: string
device?: 'desktop' | 'mobile' | 'tablet' | null
entry: string
exit: string
id: number | string
lastAt: string
locale?: null | string
pageCount: number
pages?: null | StatsPage[]
referrer?: null | string
startedAt: string
visitorId?: null | string
}
export function buildStatsCollection(): CollectionConfig {
return {
slug: STATS_SLUG,
access: {
// Written only by the hit endpoint (Local API); read and deleted by admins
// (deleting is how a visitor's erasure request is handled).
create: () => false,
delete: ({ req: { user } }) => isAdmin(user),
read: ({ req: { user } }) => isAdmin(user),
update: () => false,
},
admin: {
defaultColumns: ['day', 'entry', 'pageCount', 'referrer', 'device', 'visitorId'],
description:
'Visits from the built-in statistics. Anonymous by default; a visitor id appears only for visitors who accepted analytics cookies. No IP addresses are stored.',
group: 'Statistics',
useAsTitle: 'entry',
},
fields: [
{ name: 'day', type: 'text', index: true, required: true },
{ name: 'startedAt', type: 'date', admin: { date: { pickerAppearance: 'dayAndTime' } }, required: true },
{ name: 'lastAt', type: 'date', admin: { date: { pickerAppearance: 'dayAndTime' } }, index: true, required: true },
{ name: 'entry', type: 'text', required: true },
{ name: 'exit', type: 'text', required: true },
{ name: 'pageCount', type: 'number', required: true },
{ name: 'pages', type: 'json' },
{ name: 'referrer', type: 'text' },
{
name: 'device',
type: 'select',
options: ['desktop', 'mobile', 'tablet'],
},
{ name: 'locale', type: 'text' },
{ name: 'country', type: 'text' },
{
name: 'visitorId',
type: 'text',
admin: { description: 'Only with analytics consent — the id from the visitor’s ipal_vid cookie.' },
index: true,
},
// Daily-salted, unlinkable after midnight; only used to join hits into a visit.
{ name: 'visitKey', type: 'text', admin: { hidden: true }, index: true },
],
labels: { plural: 'Visits', singular: 'Visit' },
timestamps: false,
}
}
+158
View File
@@ -0,0 +1,158 @@
import type { Endpoint, PayloadRequest } from 'payload'
import type { StatsOptions, StatsPage, StatsVisit } from './collection.js'
import { CONSENT_COOKIE, CONSENT_VERSION, parseConsent } from '../consent/storage.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { STATS_SLUG } from './collection.js'
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath, VISITOR_ID_PATTERN } from './parse.js'
import { visitKey } from './visitKey.js'
const VISIT_GAP_MS = 30 * 60 * 1000
const MAX_PAGES = 200
let lastPurge = 0
let policy: { at: number; version: number } | null = null
/** Cookie Settings → Policy version, cached for a minute (read on every hit). */
async function policyVersion(req: PayloadRequest): Promise<number> {
if (policy && Date.now() - policy.at < 60_000) {return policy.version}
let version = CONSENT_VERSION
try {
const g = (await req.payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0 })) as { policyVersion?: unknown }
if (typeof g.policyVersion === 'number' && g.policyVersion >= 1) {version = Math.trunc(g.policyVersion)}
} catch {
// global missing — the default version applies
}
policy = { at: Date.now(), version }
return version
}
function readCookie(header: null | string, name: string): string | undefined {
return header
?.split(/;\s*/)
.find((c) => c.startsWith(`${name}=`))
?.slice(name.length + 1)
}
/**
* POST /api/ipal/hit — one page view, sent by <PageStats>. Body:
* `{ p: path, r?: referrer, l?: locale, v?: visitor id }`.
*
* Always 204 (nothing for a script to learn). The visitor id is kept only when
* the request's own consent cookie grants analytics under the current policy
* version — the server checks, it doesn't take the browser's word for it.
* Logged-in panel users, bots and prefetches aren't counted.
*/
export function buildStatsEndpoint({ retentionDays = 90, timeZone = 'Europe/Warsaw' }: StatsOptions = {}): Endpoint {
return {
handler: async (req: PayloadRequest) => {
const done = new Response(null, { status: 204 })
const request = req as unknown as Request
const headers = request.headers
const ip = clientIp(request)
const limit = await consumeRateLimit({ key: ip, max: 60, scope: 'stats' })
if (!limit.ok) {return done}
const ua = headers.get('user-agent') ?? ''
if (isBot(ua) || req.user) {return done}
if (/prefetch|prerender/i.test(headers.get('sec-purpose') ?? headers.get('purpose') ?? '')) {return done}
let body: { l?: unknown; p?: unknown; r?: unknown; v?: unknown }
try {
body = (await request.json()) as typeof body
} catch {
return done
}
const path = sanitizePath(body?.p)
if (!path) {return done}
const host = headers.get('host') ?? ''
let visitorId: string | undefined
if (typeof body.v === 'string' && VISITOR_ID_PATTERN.test(body.v)) {
const consent = parseConsent(readCookie(headers.get('cookie'), CONSENT_COOKIE), await policyVersion(req))
if (consent?.analytics) {visitorId = body.v}
}
const now = new Date()
const day = dayOf(now, timeZone)
const key = visitKey(day, [ip, ua, host])
try {
const { docs } = await req.payload.find({
collection: STATS_SLUG as never,
depth: 0,
limit: 1,
overrideAccess: true,
pagination: false,
sort: '-lastAt',
where: {
and: [
{ visitKey: { equals: key } },
{ lastAt: { greater_than: new Date(now.getTime() - VISIT_GAP_MS).toISOString() } },
],
},
})
const visit = docs[0] as StatsVisit | undefined
if (visit) {
const pages: StatsPage[] = Array.isArray(visit.pages) ? visit.pages : []
const last = pages[pages.length - 1]
// a reload within 10 s isn't a new page view
const reload = last?.p === path && now.getTime() - Date.parse(last.t) < 10_000
if (!reload && pages.length < MAX_PAGES) {pages.push({ p: path, t: now.toISOString() })}
await req.payload.update({
id: visit.id,
collection: STATS_SLUG as never,
data: {
exit: path,
lastAt: now.toISOString(),
pageCount: pages.length,
pages,
...(visitorId && !visit.visitorId ? { visitorId } : {}),
} as never,
depth: 0,
overrideAccess: true,
})
} else {
const country = headers.get('cf-ipcountry')
await req.payload.create({
collection: STATS_SLUG as never,
data: {
day,
device: deviceFromUa(ua),
entry: path,
exit: path,
lastAt: now.toISOString(),
pageCount: 1,
pages: [{ p: path, t: now.toISOString() }],
referrer: referrerHost(body.r, host),
startedAt: now.toISOString(),
visitKey: key,
...(typeof body.l === 'string' && /^[a-z]{2}(?:-[A-Za-z]{2})?$/.test(body.l) ? { locale: body.l } : {}),
...(country && /^[A-Z]{2}$/.test(country) && country !== 'XX' ? { country } : {}),
...(visitorId ? { visitorId } : {}),
} as never,
depth: 0,
overrideAccess: true,
})
}
if (now.getTime() - lastPurge > 24 * 60 * 60 * 1000) {
lastPurge = now.getTime()
await req.payload.delete({
collection: STATS_SLUG as never,
overrideAccess: true,
where: { lastAt: { less_than: new Date(now.getTime() - retentionDays * 86_400_000).toISOString() } },
})
}
} catch (err) {
req.payload.logger.error(`[ipal] stats hit failed: ${err instanceof Error ? err.message : String(err)}`)
}
return done
},
method: 'post',
path: '/ipal/hit',
}
}
+5
View File
@@ -0,0 +1,5 @@
// Server-safe: collection + hit endpoint (wired by ipalKit({ stats })). <PageStats>
// is client-side (./client); the admin view and dashboard card are in /admin.
export { buildStatsCollection, STATS_SLUG } from './collection.js'
export type { StatsOptions, StatsPage, StatsVisit } from './collection.js'
export { buildStatsEndpoint } from './endpoint.js'
+50
View File
@@ -0,0 +1,50 @@
/**
* Request → clean, non-identifying fields for a stats hit. Pure functions, so
* they're testable and run the same on every runtime.
*/
export type Device = 'desktop' | 'mobile' | 'tablet'
/** Crawlers, link previews, headless browsers, uptime checks — not visitors. */
const BOT_UA =
/bot|crawl|spider|slurp|facebookexternalhit|embedly|preview|headless|lighthouse|pagespeed|pingdom|uptime|monitor|curl|wget|python|axios|node-fetch|go-http|java\//i
export function isBot(userAgent: string): boolean {
return !userAgent || BOT_UA.test(userAgent)
}
/** Coarse device class — never the model, OS version or browser build. */
export function deviceFromUa(userAgent: string): Device {
if (/ipad|tablet|android(?!.*mobile)/i.test(userAgent)) {return 'tablet'}
if (/mobi|iphone|ipod|android/i.test(userAgent)) {return 'mobile'}
return 'desktop'
}
/**
* Path only: query and hash dropped — they can carry e-mails, tokens, search
* terms. Null for anything that isn't a same-site path.
*/
export function sanitizePath(value: unknown): null | string {
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) {return null}
const path = value.split(/[?#]/)[0].slice(0, 300)
return /^[^\s<>"]*$/.test(path) ? path : null
}
/** Referrer reduced to its hostname; empty for internal navigation or garbage. */
export function referrerHost(value: unknown, ownHost: string): string {
if (typeof value !== 'string' || !value) {return ''}
try {
const host = new URL(value).hostname.replace(/^www\./, '')
return host && host !== ownHost.replace(/^www\./, '').split(':')[0] ? host.slice(0, 100) : ''
} catch {
return ''
}
}
/** Visitor id stored in the `ipal_vid` cookie — only ever set after analytics consent. */
export const VISITOR_ID_PATTERN = /^[0-9a-f]{32}$/
/** Calendar day in `timeZone`, 'YYYY-MM-DD' — the site's day, not the server's. */
export function dayOf(date: Date, timeZone = 'UTC'): string {
return new Intl.DateTimeFormat('en-CA', { day: '2-digit', month: '2-digit', timeZone, year: 'numeric' }).format(date)
}
+75
View File
@@ -0,0 +1,75 @@
import type { StatsVisit } from './collection.js'
import { dayOf } from './parse.js'
export type StatsDay = { day: string; views: number; visits: number }
export type StatsSummary = {
/** Oldest first, one entry per day — days without visits are zeros. */
days: StatsDay[]
devices: [string, number][]
entries: [string, number][]
referrers: [string, number][]
topPages: [string, number][]
totals: {
/** Share of visits with a single page view, 0–1. */
bounceRate: number
/** Visits that carry a visitor id (analytics consent given). */
consented: number
views: number
visits: number
}
}
/** The last `count` calendar days in `timeZone`, oldest first. */
export function lastDays(count: number, timeZone: string, now = new Date()): string[] {
// today in the site's zone, then plain calendar arithmetic — DST can't skip or repeat a day
const [y, m, d] = dayOf(now, timeZone).split('-').map(Number)
const today = Date.UTC(y, m - 1, d)
return Array.from({ length: count }, (_, i) => new Date(today - (count - 1 - i) * 86_400_000).toISOString().slice(0, 10))
}
function top(counts: Map<string, number>, limit: number): [string, number][] {
return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, limit)
}
function bump(map: Map<string, number>, key: string, by = 1) {
map.set(key, (map.get(key) ?? 0) + by)
}
/** Daily series and top lists from raw visits. */
export function summarize(visits: StatsVisit[], days: string[], limit = 10): StatsSummary {
const byDay = new Map(days.map((d) => [d, { day: d, views: 0, visits: 0 }]))
const pages = new Map<string, number>()
const entries = new Map<string, number>()
const referrers = new Map<string, number>()
const devices = new Map<string, number>()
let views = 0
let bounces = 0
let consented = 0
let counted = 0
for (const visit of visits) {
const bucket = byDay.get(visit.day)
if (!bucket) {continue}
counted++
bucket.visits++
bucket.views += visit.pageCount
views += visit.pageCount
if (visit.pageCount <= 1) {bounces++}
if (visit.visitorId) {consented++}
for (const page of visit.pages ?? []) {bump(pages, page.p)}
bump(entries, visit.entry)
bump(referrers, visit.referrer || '(direct)')
if (visit.device) {bump(devices, visit.device)}
}
return {
days: [...byDay.values()],
devices: top(devices, limit),
entries: top(entries, limit),
referrers: top(referrers, limit),
topPages: top(pages, limit),
totals: { bounceRate: counted ? bounces / counted : 0, consented, views, visits: counted },
}
}
+19
View File
@@ -0,0 +1,19 @@
import { createHash, randomBytes } from 'node:crypto'
/**
* Cookieless visit key: SHA-256 of a random salt + IP + user agent + host. The
* salt lives only in this process's memory and is replaced when the day
* changes — the old one is gone, so nobody (us included) can link a stored key
* back to an IP or to the same visitor on another day. Nothing is stored on
* the visitor's device, which is why this needs no consent.
*
* Trade-off: a restart or a second instance starts its own salt, so a visit in
* progress can split in two. Fine for statistics; never fixed by persisting the
* salt — that would make yesterday's keys reversible.
*/
let current: { day: string; salt: Buffer } | null = null
export function visitKey(day: string, parts: string[]): string {
if (!current || current.day !== day) {current = { day, salt: randomBytes(32) }}
return createHash('sha256').update(current.salt).update(parts.join('\n')).digest('hex').slice(0, 32)
}
+33
View File
@@ -17,6 +17,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 { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
/**
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
@@ -232,6 +233,38 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
}
// --- built-in statistics: cookieless visits + consented history (opt-in) ---
if (options.stats) {
const statsOptions = options.stats === true ? {} : options.stats
const adminRoute = options.adminRoute ?? '/admin'
const viewProps = { adminRoute, ...(statsOptions.timeZone ? { timeZone: statsOptions.timeZone } : {}) }
config.collections = [...(config.collections ?? []), buildStatsCollection()]
config.endpoints = [...(config.endpoints ?? []), buildStatsEndpoint(statsOptions)]
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
afterNavLinks: [
...(config.admin?.components?.afterNavLinks ?? []),
{ path: '@intecion/ipal-kit/admin#StatsNavLink', serverProps: { adminRoute } },
],
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
...(statsOptions.dashboard === false
? []
: [{ path: '@intecion/ipal-kit/admin#StatsWidget', serverProps: viewProps }]),
],
views: {
...(config.admin?.components?.views ?? {}),
ipalStats: {
Component: { path: '@intecion/ipal-kit/admin#StatsView', serverProps: viewProps },
path: '/stats',
},
},
},
}
}
// --- IndexNow: submit published URLs (opt-in) ---
if (options.indexNow) {
const pagesSlug = options.pages?.slug ?? 'pages'
+11
View File
@@ -18,6 +18,7 @@ import type { FormsOption } from './modules/forms/types.js'
import type { I18nConfig } from './modules/i18n/types.js'
import type { PagesOption } from './modules/pages/types.js'
import type { SeoOption } from './modules/seo/types.js'
import type { StatsOptions } from './modules/stats/collection.js'
/**
* Configuration options for the IPAL plugin.
@@ -96,6 +97,16 @@ export type IpalOptions = {
/** Additional fields injected into SiteSettings global */
siteSettingsFields?: Field[]
/**
* Built-in statistics (docs/stats.md): the `stats-visits` collection,
* POST /api/ipal/hit, the /admin/stats view and a 30-day chart on the
* dashboard. The site mounts <PageStats> inside <ConsentProvider>.
* Cookieless and IP-free for everyone; visitors who accept analytics cookies
* also get a history across days. `true` or `{ retentionDays, timeZone,
* dashboard }`. Default off.
*/
stats?: boolean | StatsOptions
/**
* Two-factor authentication (TOTP), ENFORCED for every user. Wires
* @clocklimited/payload-2fa with forceSetup — no per-project opt-out. Every
+44
View File
@@ -7,10 +7,12 @@ import { markdownHref, prefersMarkdown } from '../src/modules/content/markdownNe
import { lexicalToMarkdown } from '../src/modules/richtext/lexicalToMarkdown.js'
import { buildCsp } from '../src/modules/security/buildCsp.js'
import { buildSecurityHeaders } from '../src/modules/security/buildSecurityHeaders.js'
import { buildAutoFillMetaHook } from '../src/modules/seo/autoFillMeta.js'
import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js'
import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js'
import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js'
import { buildHreflangAlternates } from '../src/modules/seo/hreflang.js'
import { describeFromMarkdown } from '../src/modules/seo/plainText.js'
const config: I18nConfig = {
defaultLocale: 'pl',
@@ -301,3 +303,45 @@ describe('buildProductJsonLd', () => {
})
})
})
describe('meta description auto-fill', () => {
const layout = [
{ blockType: 'hero', heading: 'Car detailing in Opole', subheading: 'For drivers who expect more' },
{ blockType: 'content', body: 'We apply Gtechniq ceramic coatings and correct paint. Every car gets a written report.' },
{ blockType: 'content', body: 'Book a free consultation — we will advise on the scope. Opening hours are listed on the contact page.' },
]
// the hook ignores everything but data and originalDoc
const run = (data: Record<string, unknown>, originalDoc?: Record<string, unknown>, mapping = {}) =>
buildAutoFillMetaHook(mapping)({ data, operation: originalDoc ? 'update' : 'create', originalDoc } as never) as Record<string, unknown>
test('describeFromMarkdown skips headings and keeps whole sentences', () => {
const md = '## Title\n\nFirst sentence here. Second one.\n\n### Sub\n\nThird part without a stop'
expect(describeFromMarkdown(md)).toBe('First sentence here. Second one. Third part without a stop.')
const long = describeFromMarkdown('One short sentence. ' + 'word '.repeat(60), 155)
expect(long).toBe('One short sentence.')
expect(describeFromMarkdown('## Only a heading')).toBe('Only a heading.')
expect(describeFromMarkdown('')).toBe('')
})
test('fills an empty description from the page blocks', () => {
const out = run({ layout, title: 'Detailing' })
const meta = out.meta as Record<string, string>
expect(meta.title).toBe('Detailing')
expect(meta.description).toBe(
'We apply Gtechniq ceramic coatings and correct paint. Every car gets a written report. Book a free consultation — we will advise on the scope.',
)
expect(meta.description.length).toBeLessThanOrEqual(155)
})
test('never replaces a description — typed now or already stored', () => {
expect((run({ layout, meta: { description: 'Mine' } }).meta as Record<string, string>).description).toBe('Mine')
// partial update: data carries only the layout, the stored doc has a description
const out = run({ layout }, { meta: { description: 'Stored', title: 'T' } })
expect(out.meta).toBeUndefined()
})
test('mapped description field wins; content: false turns the fallback off', () => {
expect((run({ excerpt: 'Excerpt text', layout }, undefined, { description: 'excerpt' }).meta as Record<string, string>).description).toBe('Excerpt text')
expect((run({ layout, title: 'T' }, undefined, { content: false }).meta as Record<string, string>).description).toBeUndefined()
})
})
+200
View File
@@ -0,0 +1,200 @@
import type { Config, PayloadRequest } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import type { StatsVisit } from '../src/modules/stats/collection.js'
import { serializeConsent } from '../src/modules/consent/storage.js'
import { buildStatsEndpoint } from '../src/modules/stats/endpoint.js'
import { dayOf, deviceFromUa, isBot, referrerHost, sanitizePath } from '../src/modules/stats/parse.js'
import { lastDays, summarize } from '../src/modules/stats/summarize.js'
import { ipalKit } from '../src/plugin.js'
const CHROME = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36'
const VID = 'a'.repeat(32)
describe('stats — request parsing', () => {
test('drops query strings and hashes, rejects non-paths', () => {
expect(sanitizePath('/pl/[email protected]#form')).toBe('/pl/kontakt')
expect(sanitizePath('https://evil.com/')).toBeNull()
expect(sanitizePath('//evil.com')).toBeNull()
expect(sanitizePath('/<script>')).toBeNull()
expect(sanitizePath(42)).toBeNull()
})
test('referrer is reduced to an external hostname', () => {
expect(referrerHost('https://www.google.com/search?q=secret', 'acme.pl')).toBe('google.com')
expect(referrerHost('https://acme.pl/pl/oferta', 'www.acme.pl')).toBe('')
expect(referrerHost('not a url', 'acme.pl')).toBe('')
})
test('bots and devices', () => {
expect(isBot('Googlebot/2.1')).toBe(true)
expect(isBot('')).toBe(true)
expect(isBot(CHROME)).toBe(false)
expect(deviceFromUa('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148')).toBe('mobile')
expect(deviceFromUa('Mozilla/5.0 (iPad; CPU OS 17_0)')).toBe('tablet')
expect(deviceFromUa(CHROME)).toBe('desktop')
})
test('day follows the site time zone, not UTC', () => {
const lateEvening = new Date('2026-10-20T22:30:00Z') // 00:30 on the 21st in Warsaw (CEST)
expect(dayOf(lateEvening, 'UTC')).toBe('2026-10-20')
expect(dayOf(lateEvening, 'Europe/Warsaw')).toBe('2026-10-21')
})
})
describe('stats — summary', () => {
test('lastDays is contiguous across a DST change', () => {
const days = lastDays(30, 'Europe/Warsaw', new Date('2026-11-05T12:00:00Z'))
expect(days).toHaveLength(30)
expect(days[0]).toBe('2026-10-07')
expect(days.at(-1)).toBe('2026-11-05')
expect(new Set(days).size).toBe(30)
})
test('daily series, totals and top lists', () => {
const visit = (day: string, pages: string[], extra: Partial<StatsVisit> = {}): StatsVisit => ({
id: Math.random(),
day,
entry: pages[0],
exit: pages.at(-1)!,
lastAt: `${day}T10:00:00Z`,
pageCount: pages.length,
pages: pages.map((p) => ({ p, t: `${day}T10:00:00Z` })),
startedAt: `${day}T10:00:00Z`,
...extra,
})
const s = summarize(
[
visit('2026-10-20', ['/pl', '/pl/oferta'], { referrer: 'google.com', visitorId: VID }),
visit('2026-10-21', ['/pl']),
visit('2026-10-21', ['/pl/oferta', '/pl/kontakt', '/pl']),
visit('2026-09-01', ['/old']), // outside the range — ignored
],
['2026-10-20', '2026-10-21'],
)
expect(s.days).toEqual([
{ day: '2026-10-20', views: 2, visits: 1 },
{ day: '2026-10-21', views: 4, visits: 2 },
])
expect(s.totals).toEqual({ bounceRate: 1 / 3, consented: 1, views: 6, visits: 3 })
expect(s.topPages[0]).toEqual(['/pl', 3])
expect(s.referrers).toEqual([['(direct)', 2], ['google.com', 1]])
})
})
/** Endpoint against an in-memory stats-visits collection. */
function harness(policyVersion = 1) {
const docs: Record<string, unknown>[] = []
const payload = {
create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
const doc = { id: docs.length + 1, ...data }
docs.push(doc)
return doc
}),
delete: vi.fn(async () => ({ docs: [] })),
find: vi.fn(async ({ where }: { where: { and: [{ visitKey: { equals: string } }, { lastAt: { greater_than: string } }] } }) => {
const [key, since] = [where.and[0].visitKey.equals, where.and[1].lastAt.greater_than]
return { docs: docs.filter((d) => d.visitKey === key && (d.lastAt as string) > since).reverse() }
}),
findGlobal: vi.fn(async () => ({ policyVersion })),
logger: { error: vi.fn() },
update: vi.fn(async ({ id, data }: { data: Record<string, unknown>; id: number }) => Object.assign(docs.find((d) => d.id === id)!, data)),
}
const endpoint = buildStatsEndpoint({ timeZone: 'UTC' })
const hit = (body: Record<string, unknown>, headers: Record<string, string> = {}, user: unknown = null) => {
const request = new Request('http://acme.pl/api/ipal/hit', {
body: JSON.stringify(body),
headers: { 'content-type': 'application/json', host: 'acme.pl', 'user-agent': CHROME, 'x-real-ip': '203.0.113.7', ...headers },
method: 'POST',
})
return endpoint.handler(Object.assign(request, { payload, user }) as unknown as PayloadRequest)
}
return { docs, hit }
}
describe('stats — hit endpoint', () => {
test('joins page views into one visit and stores no IP or user agent', async () => {
const { docs, hit } = harness()
expect((await hit({ l: 'pl', p: '/pl', r: 'https://www.google.com/' })).status).toBe(204)
await hit({ p: '/pl/oferta?utm_source=x' })
expect(docs).toHaveLength(1)
expect(docs[0]).toMatchObject({ entry: '/pl', exit: '/pl/oferta', locale: 'pl', pageCount: 2, referrer: 'google.com' })
const stored = JSON.stringify(docs[0])
expect(stored).not.toContain('203.0.113.7')
expect(stored).not.toContain('Chrome')
expect(docs[0].visitorId).toBeUndefined()
})
test('a different IP is a different visit', async () => {
const { docs, hit } = harness()
await hit({ p: '/pl' })
await hit({ p: '/pl' }, { 'x-real-ip': '198.51.100.1' })
expect(docs).toHaveLength(2)
})
test('visitor id is kept only when the consent cookie grants analytics', async () => {
const granted = serializeConsent({ analytics: true, functional: false, marketing: false, necessary: true }, 1)
const denied = serializeConsent({ analytics: false, functional: false, marketing: false, necessary: true }, 1)
const a = harness()
await a.hit({ p: '/pl', v: VID })
expect(a.docs[0].visitorId).toBeUndefined() // no cookie at all
const b = harness()
await b.hit({ p: '/pl', v: VID }, { cookie: `cookie-consent=${denied}` })
expect(b.docs[0].visitorId).toBeUndefined()
const d = harness()
await d.hit({ p: '/pl', v: VID }, { cookie: `other=1; cookie-consent=${granted}` })
expect(d.docs[0].visitorId).toBe(VID)
// consent given under policy v1, panel now at v2 → no longer valid (once the
// endpoint's one-minute policy cache has expired)
vi.useFakeTimers({ now: Date.now() + 61_000, toFake: ['Date'] })
try {
const c = harness(2)
await c.hit({ p: '/pl', v: VID }, { cookie: `cookie-consent=${granted}` })
expect(c.docs[0].visitorId).toBeUndefined()
} finally {
vi.useRealTimers()
}
})
test('bots, logged-in panel users and prefetches are not counted', async () => {
const { docs, hit } = harness()
await hit({ p: '/pl' }, { 'user-agent': 'Googlebot/2.1' })
await hit({ p: '/pl' }, {}, { id: 1 })
await hit({ p: '/pl' }, { 'sec-purpose': 'prefetch' })
await hit({ p: 'https://evil.com' })
expect(docs).toHaveLength(0)
})
})
describe('stats — plugin wiring', () => {
const base = () => ({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config
const i18n: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
test('off by default', async () => {
const config = await ipalKit({ i18n, twoFactor: false })(base())
expect(config.collections?.some((c) => c.slug === 'stats-visits')).toBe(false)
expect(config.endpoints?.some((e) => e.path === '/ipal/hit')).toBe(false)
})
test('stats: true adds the collection, endpoint, view, nav link and dashboard card', async () => {
const config = await ipalKit({ adminRoute: '/its', i18n, stats: true, twoFactor: false })(base())
expect(config.collections?.some((c) => c.slug === 'stats-visits')).toBe(true)
expect(config.endpoints?.some((e) => e.path === '/ipal/hit' && e.method === 'post')).toBe(true)
const components = config.admin?.components
expect(components?.views?.ipalStats).toMatchObject({ path: '/stats' })
expect(JSON.stringify(components?.afterNavLinks)).toContain('StatsNavLink')
expect(JSON.stringify(components?.beforeDashboard)).toContain('"adminRoute":"/its"')
})
test('dashboard: false leaves the dashboard alone', async () => {
const config = await ipalKit({ i18n, stats: { dashboard: false }, twoFactor: false })(base())
expect(JSON.stringify(config.admin?.components?.beforeDashboard)).not.toContain('StatsWidget')
})
})