Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ccc7e5064 | ||
|
|
3d467d7350 | ||
|
|
db05fe814b | ||
|
|
42df05af28 | ||
|
|
089b3a29ba | ||
|
|
ab16d459ed | ||
|
|
786dd346a9 | ||
|
|
86c873e4e7 | ||
|
|
efe8253f64 | ||
|
|
c0d9911d90 | ||
|
|
103c796e9d | ||
|
|
c6f177a37d | ||
|
|
1a9c51a1fd | ||
|
|
7f5ed75f9e | ||
|
|
4eb2b627f0 | ||
|
|
a92fc02cdf | ||
|
|
7aebe24236 |
@@ -71,7 +71,7 @@ pnpm add @payloadcms/[email protected] @payloadcms/[email protected] \
|
||||
> If your project pulls a different major (e.g. `1.x`), you end up with two copies
|
||||
> and confusing type errors. Pin your project to the same range.
|
||||
|
||||
From here, the guide takes over: **[docs/getting-started.md](./docs/getting-started.md)** —
|
||||
From here, the guide takes over: **[docs/dev/PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** —
|
||||
from an empty project to a working site.
|
||||
|
||||
---
|
||||
@@ -104,7 +104,7 @@ npm version patch # 1.0.0 → 1.0.1
|
||||
npm publish
|
||||
```
|
||||
|
||||
Full checklist and troubleshooting: **[docs/publishing.md](./docs/publishing.md)**.
|
||||
Full checklist and troubleshooting: **[docs/dev/PROGRAMISTA.md §8](./docs/dev/PROGRAMISTA.md)**.
|
||||
|
||||
---
|
||||
|
||||
@@ -112,8 +112,8 @@ Full checklist and troubleshooting: **[docs/publishing.md](./docs/publishing.md)
|
||||
|
||||
Everything lives in the **[docs/](./docs)** directory. To get started:
|
||||
|
||||
- **[getting-started.md](./docs/getting-started.md)** — project setup, step by step
|
||||
- **[publishing.md](./docs/publishing.md)** — releasing new plugin versions
|
||||
- **[AGENT.md](./docs/agent/AGENT.md)** — rules for AI agents (Polish)
|
||||
- **[PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** — setup, deployment, upgrades, releasing (Polish)
|
||||
- **[README.md](./docs/README.md)** — index of the plugin's modules
|
||||
|
||||
---
|
||||
@@ -127,5 +127,5 @@ Everything lives in the **[docs/](./docs)** directory. To get started:
|
||||
| two versions of `lucide-react` | your project pins a different major than the plugin's `^0.400.0` — align them |
|
||||
| `missing secret key … to secure Payload` | `PAYLOAD_SECRET` isn't set in the runtime environment (not a plugin issue) |
|
||||
|
||||
If you get stuck, see **[docs/publishing.md](./docs/publishing.md)** or message the
|
||||
If you get stuck, see **[docs/dev/PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** or message the
|
||||
team that maintains the plugin.
|
||||
@@ -1,260 +0,0 @@
|
||||
# Zasady i Standardy Projektowe — Payload CMS 3 + Next 16 + @intecion/ipal-kit
|
||||
|
||||
Niniejszy dokument stanowi bezwzględnie obowiązujące reguły pracy dla agenta (Antigravity) w niniejszym projekcie. Został sporządzony na podstawie dokumentacji w `/docs`. Każda zasada musi być ściśle przestrzegana, bez wyjątków i bez stosowania obejść/prowizorek.
|
||||
|
||||
---
|
||||
|
||||
## 1. ZASADA NADRZĘDNA: ipal-kit JEST OBOWIĄZKOWY
|
||||
|
||||
1. **Obowiązkowe użycie pluginu:**
|
||||
- Każda funkcja dostarczana przez `@intecion/ipal-kit` (i18n, SEO, formularze, consent, email, slug, bezpieczeństwo, strony systemowe, storage R2, breadcrumbs, JSON-LD) **MUSI** być realizowana przez plugin.
|
||||
- **NIGDY** nie twórz własnego kodu w projekcie dublującego możliwości pluginu.
|
||||
2. **Sprawdzaj przed pisaniem:**
|
||||
- Zanim napiszesz jakąkolwiek funkcję, helper czy komponent — sprawdź dokumentację w `node_modules/@intecion/ipal-kit/docs/` oraz definicje typów `.d.ts`. Jeśli funkcja istnieje w pluginie, **musisz** jej użyć.
|
||||
3. **Gdy w pluginie czegoś brakuje:**
|
||||
- **NIE** obchodź braku prowizorką ani własnym kodem w projekcie (to tworzy dług technologiczny i rozbieżności).
|
||||
- **Zgłoś brak funkcji do rozbudowy pluginu**, zamiast łatać to lokalnie.
|
||||
- Logika uniwersalna (przydatna w innych projektach) trafia do pluginu. W projekcie znajduje się **wyłącznie** specyfika danego klienta (jego bloki, wygląd, struktura danych).
|
||||
4. **Gdy coś w pluginie nie działa:**
|
||||
- **Zgłoś problem i błąd**, zamiast tworzyć ciche obejścia, prowizoryczne hooki czy hardkodowane patche.
|
||||
|
||||
---
|
||||
|
||||
## 2. KROK 0: INSTALACJA I DOSTĘP DO DOKUMENTACJI PLUGINU
|
||||
|
||||
1. **Utwórz `.npmrc` w katalogu projektu:**
|
||||
```ini
|
||||
legacy-peer-deps=true
|
||||
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
|
||||
```
|
||||
*(Scoped override: tylko `@intecion/*` z Gitea, rejestr publiczny bez tokena).*
|
||||
2. **Instalacja pluginu:**
|
||||
```bash
|
||||
pnpm add @intecion/ipal-kit
|
||||
```
|
||||
*(NIGDY nie instaluj z gita `git+https://...` — psuje React Client Manifest w Next).*
|
||||
3. **Lokalizacja dokumentacji źródłowej:**
|
||||
```bash
|
||||
ls node_modules/@intecion/ipal-kit/docs/
|
||||
```
|
||||
Zawsze korzystaj z plików w `docs/` pluginu (`getting-started.md`, `seo.md`, `forms.md`, `email.md`, `storage.md`, `i18n.md`, `blocks.md`, `turnstile.md` itd.).
|
||||
|
||||
---
|
||||
|
||||
## 3. ABSOLUTNY ZAKAZ HARDKODOWANIA
|
||||
|
||||
### A. Treść i teksty:
|
||||
- **ZAKAZ:** Tekst widoczny dla użytkownika wpisany w JSX, etykiety i komunikaty w kodzie, instrukcje `if (locale === 'pl')`, tablice z tekstami w kodzie.
|
||||
- **WYMAGANE:** Każdy tekst pochodzi z pola `localized: true`, pobierany z panelu CMS.
|
||||
- **Częsty błąd (ukryty hardkod w fallbacku):** `siteName || 'Nazwa Klienta'` lub `catch { return { name: 'Firma...' } }` to **niedopuszczalny hardkod**! Gdy brak danych z panelu/env: **pomiń pole** (np. `...(val ? { name: val } : {})`), nie wstawiaj danych klienta w fallbacku `||` ani w bloku `catch`.
|
||||
|
||||
### B. Obrazy i multimedia:
|
||||
- **ZAKAZ:** `import logo from '@/assets/...'`, ścieżki `src="/images/..."`.
|
||||
- **WYMAGANE:** Pole `type: 'upload', relationTo: 'media'`, renderowane z `media.url`. Do kolekcji `Media` obowiązkowo wepnij `normalizeFilenameHook`.
|
||||
- **Preconnect:** Użyj `<MediaPreconnect />` z pluginu (czyta `R2_PUBLIC_URL` z env), nigdy sztywnego tagu `<link>` z domeną.
|
||||
- **Favicon:** Użyj `buildIconsMetadata(settings.favicon)` z panelu (format PNG, nie ręczny SVG).
|
||||
|
||||
### C. Linki i routing:
|
||||
- **ZAKAZ:** `href="/pl/kontakt"`, menu jako statyczna tablica w kodzie, oraz **sztywna mapa zlokalizowanych ścieżek** (`const localizedRoutes = {...}` — kardynalny antywzorzec).
|
||||
- **WYMAGANE:** `getLocalizedSlugs` / `switchLocalePath` z bazy danych, `getSystemPagePath`, relacje `relationship -> pages` w panelu CMS.
|
||||
|
||||
### D. Konfiguracja i dane firmy:
|
||||
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
|
||||
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
|
||||
|
||||
### E. Renderer bloków, kolekcje, formularze (częste błędy):
|
||||
- **Renderer rich text:** ZAWSZE `RenderRichText` z pluginu (`@intecion/ipal-kit/rsc`, wrapper nad oficjalnym konwerterem Lexical). NIGDY własny parser Lexical (switch po node.type, flagi node.format, dangerouslySetInnerHTML, hardkod `.pl`). Styl przez `converters`. Patrz richtext.md.
|
||||
- **Renderer bloków:** ZAWSZE `RenderBlocks` z pluginu + mapa `registry`. NIGDY własny `switch (block.blockType)` — to gadatliwe, bez enhanceProps, rośnie liniowo. Mapa deklaratywna, silnik z pluginu.
|
||||
- **MINIMUM kolekcji, nie maksimum:** Domyślnie tylko rdzeń (pages, media, settings, navigation, footer + globale). Kolekcję treści (blog/produkty) TYLKO gdy klient JAWNIE wymaga. NIGDY nie twórz: `users` (WBUDOWANE w Payload — nie duplikuj!), `daneFirmy`/`settings` jako kolekcje (to GLOBALE), FAQ/hero/features jako kolekcje (to BLOKI). Test przed stworzeniem: lista rekordów + własny URL + jawna potrzeba + Payload nie ma wbudowanego. Patrz `kolekcje-katalog.md`.
|
||||
- **Formularze z buildera:** ZAWSZE pola/etykiety/komunikaty z buildera w panelu (kolekcja Forms) + `submitForm`. NIGDY nie hardkoduj pól ani tekstów w JSX. Turnstile: `TurnstileProvider` (siteKey raz w layoutcie) + `useTurnstile()`.
|
||||
- **Logika formularza z pluginu:** stan/walidacja/Turnstile/submit przez `useForm` (dowolne pola) lub `useContactForm` (preset) z `@intecion/ipal-kit/client` — hooki NIE renderują markupu, wygląd zostaje w projekcie. NIGDY nie kopiuj ręcznej hydrauliki (useState na pola, regex e-maila, obsługa tokenu, try/catch submitu) do projektu — to antywzorzec, który hook eliminuje. Walidacja przez `buildValidator` + reguły (`required`, `email`, `minLength`, `pattern`…). Patrz `forms.md`.
|
||||
- **Wartości lokalizowane:** ZAWSZE `resolveLocalized(value, locale)` z pluginu. NIGDY własny `getSafeString`/`(v as any)[locale]` kopiowany do JSON-LD, rich text czy topiców formularza.
|
||||
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
|
||||
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
|
||||
|
||||
---
|
||||
|
||||
## 4. ARCHITEKTURA I STRUKTURA PROJEKTU
|
||||
|
||||
### A. Next 16 + Payload 3:
|
||||
- **NIGDY nie twórz `middleware.ts`.** W Next 16 stosuje się **WYŁĄCZNIE `proxy.ts`** (funkcja `proxy`). Jeśli plik `middleware.ts` istnieje — usuń go natychmiast.
|
||||
- **Struktura katalogów:**
|
||||
```
|
||||
src/
|
||||
app/
|
||||
(frontend)/
|
||||
styles.css # Tailwind + @source na plugin
|
||||
[locale]/
|
||||
layout.tsx # root layout bez sztywnego <head>
|
||||
not-found.tsx # 404 (treść z panelu)
|
||||
[[...slug]]/
|
||||
page.tsx # render stron z bloków (podwójne nawiasy!)
|
||||
(payload)/ # panel admina
|
||||
manifest.ts # PWA z panelu — WYMAGANE export const dynamic = 'force-dynamic'
|
||||
sitemap.ts # z lib/content + export const dynamic = 'force-dynamic'
|
||||
robots.ts # z lib/content
|
||||
instrumentation.ts # assertEnv(ipalEnvRules(...)) — walidacja ENV na starcie
|
||||
blocks/
|
||||
<NazwaBloku>/
|
||||
config.ts # schemat pól bloku
|
||||
Component.tsx # render komponentu
|
||||
registry.ts # mapa blockType -> komponent
|
||||
collections/
|
||||
Pages.ts # layout typu blocks
|
||||
Media.ts # upload + normalizeFilenameHook
|
||||
globals/ # siteSettings, siteIntegrations, navigation, footer
|
||||
lib/
|
||||
content.ts # createContentHelpers — JEDNO źródło
|
||||
payload.ts # helpery projektu (getSettings...)
|
||||
i18n.config.ts # locale — jedno źródło
|
||||
payload.config.ts
|
||||
proxy.ts # routing locale (NIE middleware.ts)
|
||||
```
|
||||
|
||||
### B. Przepływ danych i zależności:
|
||||
- **Brak cykli importów:** Warstwa niższa (bloki) **NIE** może importować warstwy wyższej (`lib/*`). Dane zewnętrzne (np. klucze Turnstile) przekazuj przez `enhanceProps` w `page.tsx`.
|
||||
- **Dostęp do Payloada:** Jedno źródło `getCachedPayload` w `lib/content.ts`.
|
||||
- **Server Components (RSC) domyślnie:** Pobieranie danych po stronie serwera; `'use client'` stosuj wyłącznie dla komponentów z lokalnym stanem/interakcją. Chroń wrażliwe moduły przez `import 'server-only'`.
|
||||
|
||||
### C. Kluczowe wymagania SEO i Renderingu:
|
||||
1. **Brak jawnego `<head>` w layoutcie:** Sztywny `<head>` wypycha metatagi Next.js do `<body>`. Pozwól Next.js zarządzać nagłówkiem. `<MediaPreconnect />` umieszczaj w `<body>` (React 19 automatycznie hoistuje tag link do head).
|
||||
2. **Wymagane ISR:** `export const revalidate = 3600` w `page.tsx` stron (zapobiega race condition streamingu metadanych i zapewnia TTFB ~20ms).
|
||||
3. **Wymagane `generateStaticParams`:** W `[[...slug]]/page.tsx` eksportuj `generateStaticParams` z `lib/content` (`export { generateStaticParams } from '@/lib/content'`). Gwarantuje synchroniczne generowanie metadanych w `<head>` dla robotów.
|
||||
4. **`htmlLimitedBots`:** Skonfiguruj w `next.config.ts` zgodnie z `seo.md`.
|
||||
5. **`export const dynamic = 'force-dynamic'` na route'ach odpytujących bazę:** `manifest.ts`, `llms.txt/route.ts`, `sitemap.xml/route.ts`. Bez tego Next próbuje prerenderować je podczas `docker build` (baza offline → crash). Handlery pluginu mają try/catch jako drugą warstwę, ale `dynamic` to eksport modułowy — MUSI być w pliku route'a, handler nie ustawi go za Ciebie.
|
||||
6. **Walidacja ENV na starcie:** `instrumentation.ts` z `assertEnv(ipalEnvRules({ ... }))` — fail fast przy brakującej konfiguracji, zamiast kryptograficznego crashu w buildzie. Patrz `env.md`.
|
||||
|
||||
---
|
||||
|
||||
## 5. STANDARDY KODU I TYPOWANIA (POZIOM SENIOR)
|
||||
|
||||
1. **Zero `any` i zero `@ts-ignore`:**
|
||||
- Zawsze typuj precyzyjnie. Jeśli kształt danych z zewnątrz jest nieznany, użyj `unknown` + zawężenie (type guard).
|
||||
- Wyjątek: wąskie rzutowanie `as unknown as Record<string, unknown>` przy udokumentowanych rozbieżnościach generatora Payload (np. pole zlokalizowane przy `locale: 'all'`).
|
||||
2. **Typy generowane:** Importuj typy z `@/payload-types` (`pnpm generate:types`), nie twórz ręcznych duplikatów interfejsów.
|
||||
3. **Generyki przy wywołaniu:** Stosuj np. `getSiteSettings<SiteSetting>(payload)`, a nie rzutowanie `as SiteSetting` na wyniku.
|
||||
4. **`satisfies` dla konfiguracji:** Używaj `as const satisfies I18nConfig`.
|
||||
5. **Obsługa błędów:** Nigdy nie połykaj błędów (`catch {}`). Loguj konkretny komunikat i zwracaj kontrolowany błąd. Stosuj guard clauses (płaski kod).
|
||||
6. **Transakcje i hooki:** W hookach Payload zawsze przekazuj `req` do kolejnych operacji bazodanowych. Chroń hooki przed nieskończonymi pętlami za pomocą flagi w `context` (np. `context.skip`). Przy `payload.find` pamiętaj o `overrideAccess: false`, jeśli operacja ma respektować uprawnienia usera.
|
||||
|
||||
---
|
||||
|
||||
## 6. NAZEWNICTWO I KONWENCJE
|
||||
|
||||
- **Foldery bloków i pliki kolekcji:** PascalCase (`blocks/HeroSection/`, `collections/Pages.ts`).
|
||||
- **Pliki bloku:** `config.ts` + `Component.tsx` w jednym folderze.
|
||||
- **Slugi kolekcji:** camelCase, liczba mnoga (`pages`, `blogPosts`, `products`).
|
||||
- **Slugi bloków:** camelCase (`hero`, `textSection`). Klucz w `registry.ts` musi być identyczny ze slugiem bloku.
|
||||
- **Wspólne nazwy pól (obowiązkowe w każdym projekcie):**
|
||||
- Nagłówek: `heading`
|
||||
- Podtytuł: `subheading`
|
||||
- Treść: `body` (textarea) lub `content` (richText)
|
||||
- Obraz: `image` (upload -> media)
|
||||
- Przycisk CTA: `ctaLabel` (text, localized)
|
||||
- Cel CTA: `ctaTarget` (relationship -> pages)
|
||||
- Link zewn.: `url` (text)
|
||||
- Zgoda prawna: `consent` (checkbox)
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Globale Company/Header/Footer → PROJEKT, nie plugin.** Model danych firmy różni się per kraj (NIP/PL, ABN/AU, EIN/US) i branżę. NIE szukaj buildCompanyGlobal w pluginie — zdefiniuj własny src/globals/Company.ts. Schema.org: klocki pluginu (buildOrganizationJsonLd...) + JsonLdGraph, zmapuj SWOJE dane na @type (LegalService/PL, HVACBusiness/AU). Patrz seo.md.
|
||||
|
||||
## 6b. WYMAGANIA PRAWNE (COMPLIANCE)
|
||||
|
||||
Każda strona (PL/EU) MUSI mieć: polityka prywatności, polityka cookies, baner
|
||||
zgody cookies, zgoda RODO w formularzach. Plugin dostarcza MECHANIZM:
|
||||
- **Strony polityk** → System Pages (role: privacyPolicy, cookiePolicy, termsOfService), linkowane przez `getSystemPagePath`.
|
||||
- **Baner cookies** → CookieBanner + CookieButton + ConsentProvider (analytics/marketing gated — NIE ładują się przed zgodą).
|
||||
- **Zgoda RODO** → checkbox `consent` w formularzu (enforcement server-side w submitForm).
|
||||
- **Strony noindex** → polityki/regulamin zaznacz `noindex` w panelu SEO (kanibalizacja fraz).
|
||||
- **Ochrona:** hook `buildPreventDeleteSystemPage` blokuje usunięcie strony systemowej.
|
||||
|
||||
Granica: MY dostarczamy mechanizm, TREŚĆ prawną (tekst polityk) tworzy klient/prawnik.
|
||||
|
||||
**Widget dostępności (a11y)** — OPCJONALNY, NIE dodawaj domyślnie. Wymagany tylko
|
||||
dla podmiotów publicznych / części e-commerce (European Accessibility Act). Dla
|
||||
zwykłych stron komercyjnych to opcja — dodawaj GDY klient wymaga (AccessibilityProvider
|
||||
+ AccessibilityWidget + CSS projektu). Patrz `accessibility.md`.
|
||||
Patrz `wymagania-prawne.md`.
|
||||
|
||||
## 6c. HOOKI PLUGINU (automatyzacja)
|
||||
|
||||
Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`):
|
||||
- **buildRevalidateHook** (afterChange/afterDelete) — ISR odświeżany po zapisie (redaktor od razu widzi zmianę). `revalidatePath` wstrzykiwany z projektu.
|
||||
- **trackSlugHistoryHook** (beforeChange) — zmiana slug → zapis starego slug. Odczyt robi **resolveRedirect** (patrz niżej) — NIE pisz własnego lookupu.
|
||||
- **resolveRedirect** (moduł content) — w catch-all, gdy `resolveRoute` nic nie znajdzie: czyta slugHistory i zwraca cel 301/308; projekt woła `permanentRedirect` (plugin nie importuje `next/navigation`). Domyka trackSlugHistoryHook.
|
||||
- **buildCrossLocaleFieldSync** (afterChange) — kopiuje pola wspólne dla języków (obrazki) wewnątrz lokalizowanego `blocks` między locale. Lista języków z `config` (NIGDY hardkod `['pl','en',…]`). Zastępuje ręczny hook z zahardkodowaną listą.
|
||||
- **buildNoindexField** (pole, nie hook) — sidebarowy checkbox `noindex` zgrany z `meta.noindex`, bez `any`. Zamiast ręcznego checkboxa + hooka glue.
|
||||
- **setPublishedAtHook** — auto-data publikacji (blog).
|
||||
- **normalizeFilenameHook** — czyste nazwy plików (Media, obowiązkowo).
|
||||
- **buildPreventDeleteSystemPage** / **buildValidateUniqueRole** — ochrona stron systemowych.
|
||||
|
||||
## 6d. BEZPIECZEŃSTWO (nagłówki)
|
||||
|
||||
- **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne).
|
||||
- **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`.
|
||||
- **2FA WYMUSZONE** — `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`, potem WSTRZYKNIJ: `import { payloadTotp } from '@clocklimited/payload-2fa'` + `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', plugin: payloadTotp } })`. Wstrzyknięcie obowiązkowe — bez niego plugin robi dynamiczny import, którego Next nie wbundluje → „Cannot find module" na froncie. (Ewentualnie zamiast wstrzyknięcia: `serverExternalPackages: ['@clocklimited/payload-2fa']` w next.config.) Wymuszone dla WSZYSTKICH (forceSetup), bez opcji per user. NIE `twoFactor: false` (chyba że klient wprost odmawia). Patrz security.md.
|
||||
- **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona).
|
||||
- CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA).
|
||||
|
||||
## 7. PODZIAŁ PRACY I RÓL
|
||||
|
||||
- **Antigravity (Agent):** Buduje architekturę, logikę, kolekcje, bloki, routing, edytowalność przez panel, integracje oraz dba o brak hardkodów.
|
||||
- **Impeccable (osobne narzędzie):** Dopracowuje wygląd, system wizualny na bazie `PRODUCT.md` i `DESIGN.md`. Antigravity nie „dopieszcza" styli ad-hoc kosztem logiki i edytowalności.
|
||||
- **Klient / Redaktor:** Samodzielnie zarządza każdą treścią z poziomu panelu CMS.
|
||||
|
||||
---
|
||||
|
||||
## 8. PROCEDURA RAPORTOWANIA DO PLUGINU
|
||||
|
||||
Jeśli w trakcie pracy:
|
||||
1. Funkcja okaże się brakująca w `@intecion/ipal-kit`,
|
||||
2. Wystąpi błąd wewnętrzny w bibliotece pluginu,
|
||||
3. Pojawi się powtarzalna potrzeba biznesowa przydatna w wielu projektach,
|
||||
|
||||
**Należy natychmiast przygotować raport proponowanej zmiany/rozbudowy pluginu:**
|
||||
- Dokładny opis problemu / brakującej funkcjonalności,
|
||||
- Proponowany interfejs API / sygnatura funkcji lub konfiguracji,
|
||||
- Uzasadnienie uniwersalności dla innych projektów.
|
||||
**Nie wolno tworzyć cichej łaty w kodzie projektu.**
|
||||
|
||||
---
|
||||
|
||||
## 9. MAPA DOKUMENTACJI — gdzie szukać szczegółów
|
||||
|
||||
Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-kit/docs/`:
|
||||
|
||||
| Chcę... | Plik |
|
||||
|---|---|
|
||||
| Zbudować projekt od zera | `getting-started.md` |
|
||||
| Strukturę, nazewnictwo, konwencje | `fundamenty-projektu.md` |
|
||||
| Jakie kolekcje budować (minimum!) | `kolekcje-katalog.md` |
|
||||
| SEO, metadane, sitemap, favicon, structured data, llms.txt | `seo.md` |
|
||||
| Hooki (revalidate, slug history, cross-locale sync, ochrona) | `hooks.md` |
|
||||
| Redirecty 301/308 (resolveRedirect) | `content.md` |
|
||||
| Walidacja ENV na starcie (assertEnv) | `env.md` |
|
||||
| Czytelność dla AI: Markdown per strona, llms-full, boty AI w robots | `content.md`, `seo.md` |
|
||||
| Serwer MCP strony (Claude podłącza się do treści) | `mcp.md` |
|
||||
| GTM + Meta Pixel — konfiguracja krok po kroku | `gtm-meta-pixel.md` |
|
||||
| White-label panelu admina (logo/nazwa z SiteSettings) | `white-label.md` |
|
||||
| Bezpieczeństwo, CSP, COOP | `security.md` |
|
||||
| Formularze, Turnstile, submitForm, useForm/useContactForm | `forms.md`, `turnstile.md` |
|
||||
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
|
||||
| Strony systemowe, routing | `pages.md` |
|
||||
| Bloki, RenderBlocks | `blocks.md` |
|
||||
| Media, R2, MediaPreconnect | `storage.md` |
|
||||
| Email (SMTP/Graph) | `email.md` |
|
||||
| Consent, cookies | `consent.md` |
|
||||
| Deployment, ISR/SSG, Coolify | `deployment.md` |
|
||||
| Wymagania prawne, compliance | `wymagania-prawne.md` |
|
||||
| Filozofia CMS, edytowalność, Impeccable | `architektura-tresci.md` |
|
||||
| Standardy kodu, antywzorce | `standardy-kodu.md` |
|
||||
|
||||
---
|
||||
|
||||
## 10. ZAPISZ REGUŁY PROJEKTU
|
||||
|
||||
Kluczowe ustalenia projektu (stack, decyzje, tryby stron) zapisz we własnym pliku
|
||||
kontekstu (`agents.md` / `.agents/context/`), żeby nie gubić ich między sesjami.
|
||||
Nie polegaj tylko na pamięci sesji.
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env node
|
||||
// ipal-skills — copies the ipal-kit agent skills into the project.
|
||||
// pnpm ipal-skills → ./.agents/skills/ipal-*
|
||||
// pnpm ipal-skills --dry-run → show what would change
|
||||
// pnpm ipal-skills --dest .claude/skills
|
||||
// Only folders named ipal-* are touched; the project's own skills stay as they are.
|
||||
// ipal-* folders that no longer exist in the package are removed (renamed/retired skills).
|
||||
|
||||
import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
if (args.includes('--help') || args.includes('-h')) {
|
||||
console.log('Usage: ipal-skills [--dest <dir>] [--dry-run]\nDefault dest: .agents/skills')
|
||||
process.exit(0)
|
||||
}
|
||||
const dryRun = args.includes('--dry-run')
|
||||
const destArg = args.indexOf('--dest')
|
||||
const dest = resolve(process.cwd(), destArg >= 0 ? args[destArg + 1] ?? '' : '.agents/skills')
|
||||
|
||||
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const src = join(pkgRoot, 'docs', 'agent', 'skills')
|
||||
if (!existsSync(src)) {
|
||||
console.error(`ipal-skills: no skills found in ${src} — is @intecion/ipal-kit installed with docs?`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const isSkillDir = (base, name) => name.startsWith('ipal-') && statSync(join(base, name)).isDirectory()
|
||||
const shipped = readdirSync(src).filter((n) => isSkillDir(src, n))
|
||||
const existing = existsSync(dest) ? readdirSync(dest).filter((n) => isSkillDir(dest, n)) : []
|
||||
const retired = existing.filter((n) => !shipped.includes(n))
|
||||
|
||||
if (!dryRun) mkdirSync(dest, { recursive: true })
|
||||
for (const name of shipped) {
|
||||
const action = existing.includes(name) ? 'update' : 'add '
|
||||
console.log(`${action} ${name}`)
|
||||
if (!dryRun) {
|
||||
rmSync(join(dest, name), { recursive: true, force: true }) // drop files removed upstream
|
||||
cpSync(join(src, name), join(dest, name), { recursive: true })
|
||||
}
|
||||
}
|
||||
for (const name of retired) {
|
||||
console.log(`remove ${name} (no longer in ipal-kit)`)
|
||||
if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true })
|
||||
}
|
||||
console.log(`${dryRun ? '[dry-run] ' : ''}${shipped.length} skill(s) → ${dest}`)
|
||||
Vendored
+5
-2
@@ -1,9 +1,11 @@
|
||||
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
|
||||
export { AccessibilityProvider, AccessibilityWidget, useAccessibility, } from '../modules/accessibility/client.js';
|
||||
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
|
||||
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js';
|
||||
export { Analytics } from '../modules/analytics/client.js';
|
||||
export type { AnalyticsProps } from '../modules/analytics/client.js';
|
||||
export { pushDataLayer } from '../modules/analytics/client.js';
|
||||
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js';
|
||||
/**
|
||||
* Entry point: ipal-kit/client
|
||||
*
|
||||
@@ -17,7 +19,7 @@ export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js';
|
||||
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js';
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||
export type { ContactFormErrors, ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js';
|
||||
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js';
|
||||
export { useForm } from '../modules/forms/useForm.js';
|
||||
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js';
|
||||
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from '../modules/forms/validators.js';
|
||||
@@ -26,6 +28,7 @@ export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath
|
||||
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js';
|
||||
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks, } from '../modules/i18n/index.js';
|
||||
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js';
|
||||
export { LocaleView } from '../modules/pages/LocaleView.js';
|
||||
export { Turnstile } from '../modules/turnstile/client.js';
|
||||
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
|
||||
export type { TurnstileProps } from '../modules/turnstile/client.js';
|
||||
|
||||
Vendored
+2
@@ -4,6 +4,7 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
|
||||
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
|
||||
export { Analytics } from '../modules/analytics/client.js';
|
||||
export { pushDataLayer } from '../modules/analytics/client.js';
|
||||
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js';
|
||||
/**
|
||||
* Entry point: ipal-kit/client
|
||||
*
|
||||
@@ -20,6 +21,7 @@ export { buildValidator, checked, custom, email, isEmail, maxLength, minLength,
|
||||
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
|
||||
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js';
|
||||
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks } from '../modules/i18n/index.js';
|
||||
export { LocaleView } from '../modules/pages/LocaleView.js';
|
||||
export { Turnstile } from '../modules/turnstile/client.js';
|
||||
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
|
||||
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport { pushDataLayer } from '../modules/analytics/client.js'\n\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","pushDataLayer","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","formAnalyticsOnSuccess","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,aAAa,QAAQ,iCAAgC;AAE9D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,sBAAsB,QAAQ,oCAAmC;AAE1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
|
||||
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport type { AnalyticsProps } from '../modules/analytics/client.js'\n\nexport { pushDataLayer } from '../modules/analytics/client.js'\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { LocaleView } from '../modules/pages/LocaleView.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","pushDataLayer","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","formAnalyticsOnSuccess","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","LocaleView","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SAASC,qBAAqB,EAAEC,mBAAmB,EAAEC,gBAAgB,QAAQ,qCAAoC;AAEjH,SAASC,SAAS,QAAQ,iCAAgC;AAG1D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,iCAAgC;AACrG;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,sBAAsB,QAAQ,oCAAmC;AAE1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAEnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
|
||||
+3
-2
@@ -1,7 +1,8 @@
|
||||
import type { Field } from 'payload';
|
||||
/**
|
||||
* Fields for the CookieSettings global — GDPR consent banner copy, editable
|
||||
* per locale. The privacy-policy link is NOT stored here: it comes from the
|
||||
* pages module (system page role 'privacyPolicy'), keeping one source of truth.
|
||||
* per locale. The privacy-policy link TARGET is NOT stored here: it comes from
|
||||
* the pages module (system page role 'privacyPolicy'), keeping one source of
|
||||
* truth. Only the link's visible text lives here (privacyLinkLabel).
|
||||
*/
|
||||
export declare const cookieSettingsFields: Field[];
|
||||
|
||||
+12
-3
@@ -1,8 +1,9 @@
|
||||
import { CONSENT_CATEGORIES } from '../../modules/consent/index.js';
|
||||
import { CONSENT_CATEGORIES } from '../../modules/consent/categories.js';
|
||||
/**
|
||||
* Fields for the CookieSettings global — GDPR consent banner copy, editable
|
||||
* per locale. The privacy-policy link is NOT stored here: it comes from the
|
||||
* pages module (system page role 'privacyPolicy'), keeping one source of truth.
|
||||
* per locale. The privacy-policy link TARGET is NOT stored here: it comes from
|
||||
* the pages module (system page role 'privacyPolicy'), keeping one source of
|
||||
* truth. Only the link's visible text lives here (privacyLinkLabel).
|
||||
*/ export const cookieSettingsFields = [
|
||||
{
|
||||
name: 'message',
|
||||
@@ -20,6 +21,14 @@ import { CONSENT_CATEGORIES } from '../../modules/consent/index.js';
|
||||
},
|
||||
localized: true
|
||||
},
|
||||
{
|
||||
name: 'privacyLinkLabel',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description: 'Text of the privacy-policy link in the banner, e.g. "Privacy policy". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used.'
|
||||
},
|
||||
localized: true
|
||||
},
|
||||
{
|
||||
name: 'buttons',
|
||||
type: 'group',
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/globals/CookieSettings/fields.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport { CONSENT_CATEGORIES } from '../../modules/consent/index.js'\n\n/**\n * Fields for the CookieSettings global — GDPR consent banner copy, editable\n * per locale. The privacy-policy link is NOT stored here: it comes from the\n * pages module (system page role 'privacyPolicy'), keeping one source of truth.\n */\nexport const cookieSettingsFields: Field[] = [\n {\n name: 'message',\n type: 'textarea',\n admin: {\n description: 'Main consent message shown in the banner.',\n },\n localized: true,\n },\n {\n name: 'settingsTitle',\n type: 'text',\n admin: {\n description: 'Heading for the detailed settings panel.',\n },\n localized: true,\n },\n {\n name: 'buttons',\n type: 'group',\n admin: {\n description: 'Button labels.',\n },\n fields: [\n { name: 'acceptAll', type: 'text', localized: true },\n { name: 'reject', type: 'text', localized: true },\n { name: 'settings', type: 'text', localized: true },\n { name: 'save', type: 'text', localized: true },\n { name: 'back', type: 'text', localized: true },\n ],\n },\n {\n name: 'categories',\n type: 'array',\n admin: {\n description: 'Per-category titles and descriptions.',\n },\n fields: [\n {\n name: 'key',\n type: 'select',\n options: CONSENT_CATEGORIES.map((c) => ({ label: c, value: c })),\n required: true,\n },\n { name: 'title', type: 'text', localized: true },\n { name: 'description', type: 'textarea', localized: true },\n ],\n },\n]\n"],"names":["CONSENT_CATEGORIES","cookieSettingsFields","name","type","admin","description","localized","fields","options","map","c","label","value","required"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,iCAAgC;AAEnE;;;;CAIC,GACD,OAAO,MAAMC,uBAAgC;IAC3C;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAE,QAAQ;YACN;gBAAEL,MAAM;gBAAaC,MAAM;gBAAQG,WAAW;YAAK;YACnD;gBAAEJ,MAAM;gBAAUC,MAAM;gBAAQG,WAAW;YAAK;YAChD;gBAAEJ,MAAM;gBAAYC,MAAM;gBAAQG,WAAW;YAAK;YAClD;gBAAEJ,MAAM;gBAAQC,MAAM;gBAAQG,WAAW;YAAK;YAC9C;gBAAEJ,MAAM;gBAAQC,MAAM;gBAAQG,WAAW;YAAK;SAC/C;IACH;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAE,QAAQ;YACN;gBACEL,MAAM;gBACNC,MAAM;gBACNK,SAASR,mBAAmBS,GAAG,CAAC,CAACC,IAAO,CAAA;wBAAEC,OAAOD;wBAAGE,OAAOF;oBAAE,CAAA;gBAC7DG,UAAU;YACZ;YACA;gBAAEX,MAAM;gBAASC,MAAM;gBAAQG,WAAW;YAAK;YAC/C;gBAAEJ,MAAM;gBAAeC,MAAM;gBAAYG,WAAW;YAAK;SAC1D;IACH;CACD,CAAA"}
|
||||
{"version":3,"sources":["../../../src/globals/CookieSettings/fields.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport { CONSENT_CATEGORIES } from '../../modules/consent/categories.js'\n\n/**\n * Fields for the CookieSettings global — GDPR consent banner copy, editable\n * per locale. The privacy-policy link TARGET is NOT stored here: it comes from\n * the pages module (system page role 'privacyPolicy'), keeping one source of\n * truth. Only the link's visible text lives here (privacyLinkLabel).\n */\nexport const cookieSettingsFields: Field[] = [\n {\n name: 'message',\n type: 'textarea',\n admin: {\n description: 'Main consent message shown in the banner.',\n },\n localized: true,\n },\n {\n name: 'settingsTitle',\n type: 'text',\n admin: {\n description: 'Heading for the detailed settings panel.',\n },\n localized: true,\n },\n {\n name: 'privacyLinkLabel',\n type: 'text',\n admin: {\n description:\n 'Text of the privacy-policy link in the banner, e.g. \"Privacy policy\". The link target is the page assigned as Privacy Policy in Site Settings → System Pages. Empty → the page title is used.',\n },\n localized: true,\n },\n {\n name: 'buttons',\n type: 'group',\n admin: {\n description: 'Button labels.',\n },\n fields: [\n { name: 'acceptAll', type: 'text', localized: true },\n { name: 'reject', type: 'text', localized: true },\n { name: 'settings', type: 'text', localized: true },\n { name: 'save', type: 'text', localized: true },\n { name: 'back', type: 'text', localized: true },\n ],\n },\n {\n name: 'categories',\n type: 'array',\n admin: {\n description: 'Per-category titles and descriptions.',\n },\n fields: [\n {\n name: 'key',\n type: 'select',\n options: CONSENT_CATEGORIES.map((c) => ({ label: c, value: c })),\n required: true,\n },\n { name: 'title', type: 'text', localized: true },\n { name: 'description', type: 'textarea', localized: true },\n ],\n },\n]\n"],"names":["CONSENT_CATEGORIES","cookieSettingsFields","name","type","admin","description","localized","fields","options","map","c","label","value","required"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,sCAAqC;AAExE;;;;;CAKC,GACD,OAAO,MAAMC,uBAAgC;IAC3C;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aACE;QACJ;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAE,QAAQ;YACN;gBAAEL,MAAM;gBAAaC,MAAM;gBAAQG,WAAW;YAAK;YACnD;gBAAEJ,MAAM;gBAAUC,MAAM;gBAAQG,WAAW;YAAK;YAChD;gBAAEJ,MAAM;gBAAYC,MAAM;gBAAQG,WAAW;YAAK;YAClD;gBAAEJ,MAAM;gBAAQC,MAAM;gBAAQG,WAAW;YAAK;YAC9C;gBAAEJ,MAAM;gBAAQC,MAAM;gBAAQG,WAAW;YAAK;SAC/C;IACH;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAE,QAAQ;YACN;gBACEL,MAAM;gBACNC,MAAM;gBACNK,SAASR,mBAAmBS,GAAG,CAAC,CAACC,IAAO,CAAA;wBAAEC,OAAOD;wBAAGE,OAAOF;oBAAE,CAAA;gBAC7DG,UAAU;YACZ;YACA;gBAAEX,MAAM;gBAASC,MAAM;gBAAQG,WAAW;YAAK;YAC/C;gBAAEJ,MAAM;gBAAeC,MAAM;gBAAYG,WAAW;YAAK;SAC1D;IACH;CACD,CAAA"}
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
import type { Field } from 'payload';
|
||||
/**
|
||||
* Analytics configuration — GA4 measurement ID and GTM container ID.
|
||||
* IDs are public (exposed client-side), so no read restriction needed.
|
||||
* Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no
|
||||
* read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only
|
||||
* after the matching consent category is granted (see modules/analytics).
|
||||
*/
|
||||
export declare const analyticsFields: Field[];
|
||||
|
||||
+37
-4
@@ -1,12 +1,13 @@
|
||||
/**
|
||||
* Analytics configuration — GA4 measurement ID and GTM container ID.
|
||||
* IDs are public (exposed client-side), so no read restriction needed.
|
||||
* Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no
|
||||
* read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only
|
||||
* after the matching consent category is granted (see modules/analytics).
|
||||
*/ export const analyticsFields = [
|
||||
{
|
||||
name: 'ga4MeasurementId',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description: 'Google Analytics 4 Measurement ID.',
|
||||
description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',
|
||||
placeholder: 'G-XXXXXXXXXX'
|
||||
}
|
||||
},
|
||||
@@ -14,9 +15,41 @@
|
||||
name: 'gtmContainerId',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description: 'Google Tag Manager container ID.',
|
||||
description: 'Google Tag Manager container ID. (Google — Consent Mode)',
|
||||
placeholder: 'GTM-XXXXXXX'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'metaPixelId',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',
|
||||
placeholder: '1234567890123456'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'clarityProjectId',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',
|
||||
placeholder: 'abcdefghij'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'linkedInPartnerId',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',
|
||||
placeholder: '1234567'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'tiktokPixelId',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description: 'TikTok Pixel ID. Loads only after MARKETING consent.',
|
||||
placeholder: 'CXXXXXXXXXXXXXXXXXXX'
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/analytics.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Analytics configuration — GA4 measurement ID and GTM container ID.\n * IDs are public (exposed client-side), so no read restriction needed.\n */\nexport const analyticsFields: Field[] = [\n {\n name: 'ga4MeasurementId',\n type: 'text',\n admin: {\n description: 'Google Analytics 4 Measurement ID.',\n placeholder: 'G-XXXXXXXXXX',\n },\n },\n {\n name: 'gtmContainerId',\n type: 'text',\n admin: {\n description: 'Google Tag Manager container ID.',\n placeholder: 'GTM-XXXXXXX',\n },\n },\n]\n"],"names":["analyticsFields","name","type","admin","description","placeholder"],"mappings":"AAEA;;;CAGC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;CACD,CAAA"}
|
||||
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/analytics.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no\n * read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only\n * after the matching consent category is granted (see modules/analytics).\n */\nexport const analyticsFields: Field[] = [\n {\n name: 'ga4MeasurementId',\n type: 'text',\n admin: {\n description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',\n placeholder: 'G-XXXXXXXXXX',\n },\n },\n {\n name: 'gtmContainerId',\n type: 'text',\n admin: {\n description: 'Google Tag Manager container ID. (Google — Consent Mode)',\n placeholder: 'GTM-XXXXXXX',\n },\n },\n {\n name: 'metaPixelId',\n type: 'text',\n admin: {\n description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',\n placeholder: '1234567890123456',\n },\n },\n {\n name: 'clarityProjectId',\n type: 'text',\n admin: {\n description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',\n placeholder: 'abcdefghij',\n },\n },\n {\n name: 'linkedInPartnerId',\n type: 'text',\n admin: {\n description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',\n placeholder: '1234567',\n },\n },\n {\n name: 'tiktokPixelId',\n type: 'text',\n admin: {\n description: 'TikTok Pixel ID. Loads only after MARKETING consent.',\n placeholder: 'CXXXXXXXXXXXXXXXXXXX',\n },\n },\n]\n"],"names":["analyticsFields","name","type","admin","description","placeholder"],"mappings":"AAEA;;;;CAIC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;CACD,CAAA"}
|
||||
Vendored
+6
-3
@@ -7,7 +7,7 @@ export { getAnalyticsConfig } from './modules/analytics/index.js';
|
||||
export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent, } from './modules/consent/index.js';
|
||||
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js';
|
||||
export type { ContentCollectionOption, ContentOption, ResolvedRoute, } from './modules/content/index.js';
|
||||
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js';
|
||||
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js';
|
||||
export type { ArchiveEntries } from './modules/content/index.js';
|
||||
export type { SearchResult } from './modules/content/index.js';
|
||||
export { graphAdapter } from './modules/email/graphAdapter.js';
|
||||
@@ -34,6 +34,8 @@ export type { LocaleMiddlewareResult } from './modules/i18n/index.js';
|
||||
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
|
||||
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
|
||||
export { resolveLocalized } from './modules/i18n/index.js';
|
||||
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js';
|
||||
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance, LinkValue, ResolveLinkHrefOptions, } from './modules/links/index.js';
|
||||
export { createMcpRoute } from './modules/mcp/index.js';
|
||||
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
|
||||
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage, } from './modules/notifications/index.js';
|
||||
@@ -48,8 +50,9 @@ export { buildCsp } from './modules/security/index.js';
|
||||
export type { BuildCspArgs } from './modules/security/index.js';
|
||||
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js';
|
||||
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js';
|
||||
export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js';
|
||||
export type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js';
|
||||
export { buildHreflangAlternates, buildMetadata, composeTitle, readSiteMetaConfig, slugsAcrossLocales, } from './modules/seo/index.js';
|
||||
export type { SiteMetaConfig } from './modules/seo/index.js';
|
||||
export type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry, } from './modules/seo/index.js';
|
||||
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta, } from './modules/seo/index.js';
|
||||
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler, } from './modules/seo/index.js';
|
||||
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField, } from './modules/seo/index.js';
|
||||
|
||||
Vendored
+3
-2
@@ -2,7 +2,7 @@ export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSe
|
||||
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js';
|
||||
export { getAnalyticsConfig } from './modules/analytics/index.js';
|
||||
export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent } from './modules/consent/index.js';
|
||||
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js';
|
||||
export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js';
|
||||
export { graphAdapter } from './modules/email/graphAdapter.js';
|
||||
export { mailAdapter } from './modules/email/mailAdapter.js';
|
||||
// Imported straight from the file, NOT from ./modules/email/index.js — that
|
||||
@@ -27,6 +27,7 @@ export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefiniti
|
||||
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
|
||||
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
|
||||
export { resolveLocalized } from './modules/i18n/index.js';
|
||||
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js';
|
||||
// Read-only MCP server (Claude/agents connect to the site and query it).
|
||||
export { createMcpRoute } from './modules/mcp/index.js';
|
||||
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
|
||||
@@ -37,7 +38,7 @@ export { getGlobal, getSiteIntegrations, getSiteSettings, SITE_INTEGRATIONS_SLUG
|
||||
export { lexicalToMarkdown } from './modules/richtext/index.js';
|
||||
export { buildSecurityHeaders } from './modules/security/index.js';
|
||||
export { buildCsp } from './modules/security/index.js';
|
||||
export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js';
|
||||
export { buildHreflangAlternates, buildMetadata, composeTitle, readSiteMetaConfig, slugsAcrossLocales } from './modules/seo/index.js';
|
||||
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta } from './modules/seo/index.js';
|
||||
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js';
|
||||
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js';
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+32
-9
@@ -4,16 +4,39 @@ declare global {
|
||||
dataLayer?: unknown[];
|
||||
}
|
||||
}
|
||||
export type AnalyticsProps = {
|
||||
/**
|
||||
* Core Web Vitals mode: hold back every tag's NETWORK load until the first
|
||||
* user interaction (scroll, pointer, touch, key) or `deferTimeoutMs` after the
|
||||
* window `load` event — whichever comes first. Keeps ~100+ KiB of third-party
|
||||
* JS out of the FCP/LCP window.
|
||||
*
|
||||
* Consent is unaffected: the Consent Mode default is still pushed immediately
|
||||
* (a synchronous dataLayer push, no network), and non-Google pixels still
|
||||
* require their consent category. Defer changes WHEN a tag loads, never WHETHER.
|
||||
*
|
||||
* Trade-off: visitors who leave before interacting and before the timeout are
|
||||
* not counted (slightly fewer sessions in GA). Default false.
|
||||
*/
|
||||
defer?: boolean;
|
||||
/** Fallback delay after window `load`, in ms. Default 3500. */
|
||||
deferTimeoutMs?: number;
|
||||
} & AnalyticsConfig;
|
||||
/**
|
||||
* Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.
|
||||
* Loads every configured analytics / marketing tag, each respecting consent:
|
||||
*
|
||||
* Consent Mode is initialised to the visitor's stored consent BEFORE the tag
|
||||
* loads (via setDefaultConsent from the consent module), so tags respect the
|
||||
* choice from the first hit; useConsent sends an update the moment the visitor
|
||||
* decides. IDs are public and come from SiteIntegrations, passed in as props
|
||||
* (the client project reads them server-side).
|
||||
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
|
||||
* the default BEFORE the tag loads (always immediately, even with `defer`),
|
||||
* and useConsent pushes an update the moment they decide. GTM wins if both
|
||||
* IDs are set.
|
||||
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
|
||||
* each loads ONLY after its category is granted (marketing for
|
||||
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
|
||||
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
|
||||
* after load, for better LCP/INP. See AnalyticsProps.defer.
|
||||
*
|
||||
* Renders nothing — it only injects the scripts. Mount once, high in the tree
|
||||
* (e.g. root layout), inside ConsentProvider.
|
||||
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
|
||||
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
|
||||
* <ConsentProvider> (required — it reads live consent state).
|
||||
*/
|
||||
export declare function Analytics({ ga4MeasurementId, gtmContainerId }: AnalyticsConfig): null;
|
||||
export declare function Analytics(props: AnalyticsProps): null;
|
||||
|
||||
Vendored
+129
-17
@@ -1,7 +1,9 @@
|
||||
'use client';
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useConsentContext } from '../consent/client.js';
|
||||
import { gtag } from '../consent/googleConsent.js';
|
||||
import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js';
|
||||
import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
|
||||
const GTM_SCRIPT = (id)=>`https://www.googletagmanager.com/gtm.js?id=${id}`;
|
||||
const GA4_SCRIPT = (id)=>`https://www.googletagmanager.com/gtag/js?id=${id}`;
|
||||
/** Reads the current consent state from cookie, or defaults if none. */ function readConsent() {
|
||||
@@ -20,25 +22,106 @@ function injectScript(src) {
|
||||
s.async = true;
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
/**
|
||||
* Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.
|
||||
*
|
||||
* Consent Mode is initialised to the visitor's stored consent BEFORE the tag
|
||||
* loads (via setDefaultConsent from the consent module), so tags respect the
|
||||
* choice from the first hit; useConsent sends an update the moment the visitor
|
||||
* decides. IDs are public and come from SiteIntegrations, passed in as props
|
||||
* (the client project reads them server-side).
|
||||
*
|
||||
* Renders nothing — it only injects the scripts. Mount once, high in the tree
|
||||
* (e.g. root layout), inside ConsentProvider.
|
||||
*/ export function Analytics({ ga4MeasurementId, gtmContainerId }) {
|
||||
const INTERACTION_EVENTS = [
|
||||
'scroll',
|
||||
'pointerdown',
|
||||
'touchstart',
|
||||
'keydown'
|
||||
];
|
||||
/** True once third-party tags may load (immediately, or per `defer` rules). */ function useDeferredReady(defer, timeoutMs) {
|
||||
const [ready, setReady] = useState(!defer);
|
||||
useEffect(()=>{
|
||||
if (!defer || ready) {
|
||||
return;
|
||||
}
|
||||
let timer;
|
||||
const fire = ()=>setReady(true);
|
||||
const onLoad = ()=>{
|
||||
timer = setTimeout(()=>{
|
||||
if ('requestIdleCallback' in window) {
|
||||
window.requestIdleCallback(fire, {
|
||||
timeout: 1000
|
||||
});
|
||||
} else {
|
||||
fire();
|
||||
}
|
||||
}, timeoutMs);
|
||||
};
|
||||
for (const e of INTERACTION_EVENTS){
|
||||
window.addEventListener(e, fire, {
|
||||
once: true,
|
||||
passive: true
|
||||
});
|
||||
}
|
||||
if (document.readyState === 'complete') {
|
||||
onLoad();
|
||||
} else {
|
||||
window.addEventListener('load', onLoad, {
|
||||
once: true
|
||||
});
|
||||
}
|
||||
return ()=>{
|
||||
for (const e of INTERACTION_EVENTS){
|
||||
window.removeEventListener(e, fire);
|
||||
}
|
||||
window.removeEventListener('load', onLoad);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
}, [
|
||||
defer,
|
||||
ready,
|
||||
timeoutMs
|
||||
]);
|
||||
return ready;
|
||||
}
|
||||
/**
|
||||
* Loads every configured analytics / marketing tag, each respecting consent:
|
||||
*
|
||||
* - **Google (GA4 / GTM)** — Consent Mode: the visitor's stored choice is set as
|
||||
* the default BEFORE the tag loads (always immediately, even with `defer`),
|
||||
* and useConsent pushes an update the moment they decide. GTM wins if both
|
||||
* IDs are set.
|
||||
* - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — no Consent Mode, so
|
||||
* each loads ONLY after its category is granted (marketing for
|
||||
* Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to the banner.
|
||||
* - **`defer`** (opt-in) — additionally waits for first interaction / idle
|
||||
* after load, for better LCP/INP. See AnalyticsProps.defer.
|
||||
*
|
||||
* All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed
|
||||
* in as props. Renders nothing. Mount once, high in the tree, INSIDE
|
||||
* <ConsentProvider> (required — it reads live consent state).
|
||||
*/ export function Analytics(props) {
|
||||
const { clarityProjectId, defer = false, deferTimeoutMs = 3500, ga4MeasurementId, gtmContainerId, linkedInPartnerId, metaPixelId, tiktokPixelId } = props;
|
||||
// Live consent state — drives the non-Google pixels.
|
||||
const { state } = useConsentContext();
|
||||
const ready = useDeferredReady(defer, deferTimeoutMs);
|
||||
const defaultConsentSet = useRef(false);
|
||||
// --- Consent Mode default: immediately, once — never deferred ---
|
||||
// No network cost, and it must precede any gtag('config') / GTM start, or
|
||||
// Google assumes "granted".
|
||||
useEffect(()=>{
|
||||
if (defaultConsentSet.current) {
|
||||
return;
|
||||
}
|
||||
if (!ga4MeasurementId && !gtmContainerId) {
|
||||
return;
|
||||
}
|
||||
// 1. Consent Mode default = the visitor's stored choice, before tags load.
|
||||
setDefaultConsent(readConsent());
|
||||
// 2. Load the tag.
|
||||
defaultConsentSet.current = true;
|
||||
}, [
|
||||
ga4MeasurementId,
|
||||
gtmContainerId
|
||||
]);
|
||||
// --- Google: load once `ready`; Consent Mode handles gating ---
|
||||
useEffect(()=>{
|
||||
if (!ready) {
|
||||
return;
|
||||
}
|
||||
if (!ga4MeasurementId && !gtmContainerId) {
|
||||
return;
|
||||
}
|
||||
if (gtmContainerId) {
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
window.dataLayer.push({
|
||||
@@ -48,15 +131,44 @@ function injectScript(src) {
|
||||
injectScript(GTM_SCRIPT(gtmContainerId));
|
||||
} else if (ga4MeasurementId) {
|
||||
injectScript(GA4_SCRIPT(ga4MeasurementId));
|
||||
// Uses the shared gtag (pushes `arguments`, as Google's tags expect);
|
||||
// real gtag.js wires itself up once the script loads.
|
||||
gtag('js', new Date());
|
||||
gtag('config', ga4MeasurementId);
|
||||
}
|
||||
}, [
|
||||
ready,
|
||||
ga4MeasurementId,
|
||||
gtmContainerId
|
||||
]);
|
||||
// --- Non-Google: each when `ready` AND its consent category is granted ---
|
||||
// Loaders are idempotent, so re-running on state changes is safe; a tag loads
|
||||
// the first time both conditions hold and never doubles up.
|
||||
useEffect(()=>{
|
||||
if (!ready) {
|
||||
return;
|
||||
}
|
||||
if (state.marketing) {
|
||||
if (metaPixelId) {
|
||||
loadMetaPixel(metaPixelId);
|
||||
}
|
||||
if (linkedInPartnerId) {
|
||||
loadLinkedIn(linkedInPartnerId);
|
||||
}
|
||||
if (tiktokPixelId) {
|
||||
loadTikTok(tiktokPixelId);
|
||||
}
|
||||
}
|
||||
if (state.analytics && clarityProjectId) {
|
||||
loadClarity(clarityProjectId);
|
||||
}
|
||||
}, [
|
||||
ready,
|
||||
state.marketing,
|
||||
state.analytics,
|
||||
metaPixelId,
|
||||
linkedInPartnerId,
|
||||
tiktokPixelId,
|
||||
clarityProjectId
|
||||
]);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+2
@@ -1,2 +1,4 @@
|
||||
export { Analytics } from './Analytics.js';
|
||||
export type { AnalyticsProps } from './Analytics.js';
|
||||
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
|
||||
export { pushDataLayer } from './pushDataLayer.js';
|
||||
|
||||
Vendored
+3
@@ -1,5 +1,8 @@
|
||||
'use client';
|
||||
export { Analytics } from './Analytics.js';
|
||||
// Low-level pixel loaders — exported for manual conversion events if a project
|
||||
// needs them (Analytics loads them automatically, consent-gated).
|
||||
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js';
|
||||
export { pushDataLayer } from './pushDataLayer.js';
|
||||
|
||||
//# sourceMappingURL=client.js.map
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,aAAa,QAAQ,qBAAoB"}
|
||||
{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\nexport type { AnalyticsProps } from './Analytics.js'\n// Low-level pixel loaders — exported for manual conversion events if a project\n// needs them (Analytics loads them automatically, consent-gated).\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAE1C,+EAA+E;AAC/E,kEAAkE;AAClE,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,cAAa;AAClF,SAASC,aAAa,QAAQ,qBAAoB"}
|
||||
+2
-3
@@ -1,9 +1,8 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { AnalyticsConfig } from './types.js';
|
||||
/**
|
||||
* Reads the public analytics IDs from SiteIntegrations, server-side.
|
||||
*
|
||||
* Returns only the two public IDs (GA4 / GTM) — safe to pass to the client
|
||||
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
|
||||
* server-side. All are public (exposed client-side), so safe to pass to the
|
||||
* <Analytics> component. Does NOT expose any secret from SiteIntegrations.
|
||||
*/
|
||||
export declare function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig>;
|
||||
|
||||
+7
-4
@@ -1,14 +1,17 @@
|
||||
import { getSiteIntegrations } from '../payload/index.js';
|
||||
/**
|
||||
* Reads the public analytics IDs from SiteIntegrations, server-side.
|
||||
*
|
||||
* Returns only the two public IDs (GA4 / GTM) — safe to pass to the client
|
||||
* Reads the public analytics / marketing tag IDs from SiteIntegrations,
|
||||
* server-side. All are public (exposed client-side), so safe to pass to the
|
||||
* <Analytics> component. Does NOT expose any secret from SiteIntegrations.
|
||||
*/ export async function getAnalyticsConfig(payload) {
|
||||
const integrations = await getSiteIntegrations(payload);
|
||||
return {
|
||||
clarityProjectId: integrations.clarityProjectId ?? null,
|
||||
ga4MeasurementId: integrations.ga4MeasurementId ?? null,
|
||||
gtmContainerId: integrations.gtmContainerId ?? null
|
||||
gtmContainerId: integrations.gtmContainerId ?? null,
|
||||
linkedInPartnerId: integrations.linkedInPartnerId ?? null,
|
||||
metaPixelId: integrations.metaPixelId ?? null,
|
||||
tiktokPixelId: integrations.tiktokPixelId ?? null
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/analytics/getAnalyticsConfig.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { getSiteIntegrations } from '../payload/index.js'\n\n/**\n * Reads the public analytics IDs from SiteIntegrations, server-side.\n *\n * Returns only the two public IDs (GA4 / GTM) — safe to pass to the client\n * <Analytics> component. Does NOT expose any secret from SiteIntegrations.\n */\nexport async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {\n const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)\n return {\n ga4MeasurementId: integrations.ga4MeasurementId ?? null,\n gtmContainerId: integrations.gtmContainerId ?? null,\n }\n}\n"],"names":["getSiteIntegrations","getAnalyticsConfig","payload","integrations","ga4MeasurementId","gtmContainerId"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,sBAAqB;AAEzD;;;;;CAKC,GACD,OAAO,eAAeC,mBAAmBC,OAAoB;IAC3D,MAAMC,eAAe,MAAMH,oBAAqCE;IAChE,OAAO;QACLE,kBAAkBD,aAAaC,gBAAgB,IAAI;QACnDC,gBAAgBF,aAAaE,cAAc,IAAI;IACjD;AACF"}
|
||||
{"version":3,"sources":["../../../src/modules/analytics/getAnalyticsConfig.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { getSiteIntegrations } from '../payload/index.js'\n\n/**\n * Reads the public analytics / marketing tag IDs from SiteIntegrations,\n * server-side. All are public (exposed client-side), so safe to pass to the\n * <Analytics> component. Does NOT expose any secret from SiteIntegrations.\n */\nexport async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {\n const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)\n return {\n clarityProjectId: integrations.clarityProjectId ?? null,\n ga4MeasurementId: integrations.ga4MeasurementId ?? null,\n gtmContainerId: integrations.gtmContainerId ?? null,\n linkedInPartnerId: integrations.linkedInPartnerId ?? null,\n metaPixelId: integrations.metaPixelId ?? null,\n tiktokPixelId: integrations.tiktokPixelId ?? null,\n }\n}\n"],"names":["getSiteIntegrations","getAnalyticsConfig","payload","integrations","clarityProjectId","ga4MeasurementId","gtmContainerId","linkedInPartnerId","metaPixelId","tiktokPixelId"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,sBAAqB;AAEzD;;;;CAIC,GACD,OAAO,eAAeC,mBAAmBC,OAAoB;IAC3D,MAAMC,eAAe,MAAMH,oBAAqCE;IAChE,OAAO;QACLE,kBAAkBD,aAAaC,gBAAgB,IAAI;QACnDC,kBAAkBF,aAAaE,gBAAgB,IAAI;QACnDC,gBAAgBH,aAAaG,cAAc,IAAI;QAC/CC,mBAAmBJ,aAAaI,iBAAiB,IAAI;QACrDC,aAAaL,aAAaK,WAAW,IAAI;QACzCC,eAAeN,aAAaM,aAAa,IAAI;IAC/C;AACF"}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards
|
||||
* against double-init) and loads the vendor's own script + bootstrap.
|
||||
*
|
||||
* These are the one place `any` is unavoidable: vendor SDK bootstraps attach
|
||||
* untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained
|
||||
* here; nothing else in the kit uses `any`.
|
||||
*
|
||||
* CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)
|
||||
* loads each ONLY after the matching consent category is granted:
|
||||
* Meta Pixel / LinkedIn / TikTok → marketing
|
||||
* Microsoft Clarity → analytics
|
||||
*/
|
||||
/** Meta (Facebook) Pixel — fires PageView on load. */
|
||||
export declare function loadMetaPixel(id: string): void;
|
||||
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */
|
||||
export declare function loadClarity(id: string): void;
|
||||
/** LinkedIn Insight Tag (marketing). */
|
||||
export declare function loadLinkedIn(partnerId: string): void;
|
||||
/** TikTok Pixel (marketing) — fires page view on load. */
|
||||
export declare function loadTikTok(id: string): void;
|
||||
Vendored
+134
@@ -0,0 +1,134 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */ /**
|
||||
* Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards
|
||||
* against double-init) and loads the vendor's own script + bootstrap.
|
||||
*
|
||||
* These are the one place `any` is unavoidable: vendor SDK bootstraps attach
|
||||
* untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained
|
||||
* here; nothing else in the kit uses `any`.
|
||||
*
|
||||
* CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)
|
||||
* loads each ONLY after the matching consent category is granted:
|
||||
* Meta Pixel / LinkedIn / TikTok → marketing
|
||||
* Microsoft Clarity → analytics
|
||||
*/ /** Meta (Facebook) Pixel — fires PageView on load. */ export function loadMetaPixel(id) {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const w = window;
|
||||
if (w.fbq) {
|
||||
return;
|
||||
}
|
||||
const n = w.fbq = function(...args) {
|
||||
if (n.callMethod) {
|
||||
n.callMethod.apply(n, args);
|
||||
} else {
|
||||
n.queue.push(args);
|
||||
}
|
||||
};
|
||||
if (!w._fbq) {
|
||||
w._fbq = n;
|
||||
}
|
||||
n.push = n;
|
||||
n.loaded = true;
|
||||
n.version = '2.0';
|
||||
n.queue = [];
|
||||
const s = document.createElement('script');
|
||||
s.async = true;
|
||||
s.src = 'https://connect.facebook.net/en_US/fbevents.js';
|
||||
document.head.appendChild(s);
|
||||
w.fbq('init', id);
|
||||
w.fbq('track', 'PageView');
|
||||
}
|
||||
/** Microsoft Clarity — heatmaps / session recordings (analytics category). */ export function loadClarity(id) {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const w = window;
|
||||
if (w.clarity) {
|
||||
return;
|
||||
}
|
||||
w.clarity = function(...a) {
|
||||
;
|
||||
(w.clarity.q = w.clarity.q || []).push(a);
|
||||
};
|
||||
const s = document.createElement('script');
|
||||
s.async = true;
|
||||
s.src = `https://www.clarity.ms/tag/${id}`;
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
/** LinkedIn Insight Tag (marketing). */ export function loadLinkedIn(partnerId) {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const w = window;
|
||||
w._linkedin_partner_id = partnerId;
|
||||
w._linkedin_data_partner_ids = w._linkedin_data_partner_ids || [];
|
||||
if (w._linkedin_data_partner_ids.includes(partnerId)) {
|
||||
if (document.getElementById('ipal-linkedin-insight')) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
w._linkedin_data_partner_ids.push(partnerId);
|
||||
}
|
||||
if (document.getElementById('ipal-linkedin-insight')) {
|
||||
return;
|
||||
}
|
||||
const s = document.createElement('script');
|
||||
s.async = true;
|
||||
s.id = 'ipal-linkedin-insight';
|
||||
s.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js';
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
/** TikTok Pixel (marketing) — fires page view on load. */ export function loadTikTok(id) {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
const w = window;
|
||||
if (w.ttq) {
|
||||
return;
|
||||
}
|
||||
w.TiktokAnalyticsObject = 'ttq';
|
||||
const ttq = w.ttq = [];
|
||||
ttq.methods = [
|
||||
'page',
|
||||
'track',
|
||||
'identify',
|
||||
'instances',
|
||||
'debug',
|
||||
'on',
|
||||
'off',
|
||||
'once',
|
||||
'ready',
|
||||
'alias',
|
||||
'group',
|
||||
'enableCookie',
|
||||
'disableCookie'
|
||||
];
|
||||
ttq.setAndDefer = function(t, e) {
|
||||
t[e] = function(...args) {
|
||||
t.push([
|
||||
e,
|
||||
...args
|
||||
]);
|
||||
};
|
||||
};
|
||||
for (const m of ttq.methods){
|
||||
ttq.setAndDefer(ttq, m);
|
||||
}
|
||||
ttq.load = function(e) {
|
||||
const url = 'https://analytics.tiktok.com/i18n/pixel/events.js';
|
||||
ttq._i = ttq._i || {};
|
||||
ttq._i[e] = [];
|
||||
ttq._i[e]._u = url;
|
||||
ttq._t = ttq._t || {};
|
||||
ttq._t[e] = Number(new Date());
|
||||
const s = document.createElement('script');
|
||||
s.async = true;
|
||||
s.src = `${url}?sdkid=${e}&lib=ttq`;
|
||||
document.head.appendChild(s);
|
||||
};
|
||||
ttq.load(id);
|
||||
ttq.page();
|
||||
}
|
||||
|
||||
//# sourceMappingURL=pixels.js.map
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+13
-3
@@ -1,9 +1,19 @@
|
||||
/**
|
||||
* Analytics IDs, read from SiteIntegrations (public — safe on the client).
|
||||
* Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe
|
||||
* on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only
|
||||
* after the matching consent category is granted (see Analytics).
|
||||
*/
|
||||
export type AnalyticsConfig = {
|
||||
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */
|
||||
/** Microsoft Clarity project ID. (analytics consent) */
|
||||
clarityProjectId?: null | string;
|
||||
/** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */
|
||||
ga4MeasurementId?: null | string;
|
||||
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. */
|
||||
/** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */
|
||||
gtmContainerId?: null | string;
|
||||
/** LinkedIn Insight Tag partner ID. (marketing consent) */
|
||||
linkedInPartnerId?: null | string;
|
||||
/** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */
|
||||
metaPixelId?: null | string;
|
||||
/** TikTok Pixel ID. (marketing consent) */
|
||||
tiktokPixelId?: null | string;
|
||||
};
|
||||
|
||||
Vendored
+3
-1
@@ -1,5 +1,7 @@
|
||||
/**
|
||||
* Analytics IDs, read from SiteIntegrations (public — safe on the client).
|
||||
* Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe
|
||||
* on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only
|
||||
* after the matching consent category is granted (see Analytics).
|
||||
*/ export { };
|
||||
|
||||
//# sourceMappingURL=types.js.map
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/analytics/types.ts"],"sourcesContent":["/**\n * Analytics IDs, read from SiteIntegrations (public — safe on the client).\n */\nexport type AnalyticsConfig = {\n /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */\n ga4MeasurementId?: null | string\n /** GTM Container ID, e.g. 'GTM-XXXXXXX'. */\n gtmContainerId?: null | string\n}\n"],"names":[],"mappings":"AAAA;;CAEC,GACD,WAKC"}
|
||||
{"version":3,"sources":["../../../src/modules/analytics/types.ts"],"sourcesContent":["/**\n * Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe\n * on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only\n * after the matching consent category is granted (see Analytics).\n */\nexport type AnalyticsConfig = {\n /** Microsoft Clarity project ID. (analytics consent) */\n clarityProjectId?: null | string\n /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */\n ga4MeasurementId?: null | string\n /** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */\n gtmContainerId?: null | string\n /** LinkedIn Insight Tag partner ID. (marketing consent) */\n linkedInPartnerId?: null | string\n /** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */\n metaPixelId?: null | string\n /** TikTok Pixel ID. (marketing consent) */\n tiktokPixelId?: null | string\n}\n"],"names":[],"mappings":"AAAA;;;;CAIC,GACD,WAaC"}
|
||||
+14
-7
@@ -1,3 +1,4 @@
|
||||
import type { Payload } from 'payload';
|
||||
/**
|
||||
* White-label admin branding: the Payload admin panel's logo (login + nav) and
|
||||
* icon, pulled from the project's SiteSettings so each client sees THEIR brand,
|
||||
@@ -5,13 +6,13 @@
|
||||
* automatically by `ipalKit({ whiteLabel: true })` (it injects
|
||||
* admin.components.graphics.Logo/Icon pointing here).
|
||||
*
|
||||
* Server Components — they read the SiteSettings global at render. Data access
|
||||
* uses the project's `@payload-config` alias (universal in Payload 3 Next apps),
|
||||
* loaded via a variable specifier so the PLUGIN's own typecheck doesn't try to
|
||||
* resolve it (same pattern as the optional 2FA import). Everything is wrapped in
|
||||
* try/catch: on the login screen before the DB is ready, or a build with no DB,
|
||||
* the component falls back to the site name text, then to null (Payload's own
|
||||
* default) — never throws, never blocks the panel.
|
||||
* Server Components — they read the SiteSettings global at render, using the
|
||||
* `payload` instance Payload itself passes to admin server components. NO
|
||||
* `import('@payload-config')`: a variable-specifier import isn't traced by the
|
||||
* Next bundler ("Cannot find module '@payload-config'") — same bug class as the
|
||||
* old 2FA import. Everything is wrapped in try/catch: no payload prop, DB not
|
||||
* ready, etc. → site name text, then null (Payload's own default) — never
|
||||
* throws, never blocks the panel.
|
||||
*
|
||||
* A0: no client brand in code. The logo/name come from the panel; if nothing is
|
||||
* set, nothing is forced.
|
||||
@@ -19,8 +20,14 @@
|
||||
type BrandingProps = {
|
||||
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
|
||||
imageField?: string;
|
||||
/** Injected by Payload — current admin locale (object or code). */
|
||||
locale?: {
|
||||
code?: string;
|
||||
} | string;
|
||||
/** Field holding the site name. Default 'siteName'. */
|
||||
nameField?: string;
|
||||
/** Injected by Payload into admin server components. */
|
||||
payload?: Payload;
|
||||
/** SiteSettings global slug. Default 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
};
|
||||
|
||||
+33
-13
@@ -1,25 +1,45 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import { getPayload } from 'payload';
|
||||
async function loadBranding(settingsSlug, nameField, imageField) {
|
||||
/** A localized text field may arrive as a string or a { locale: value } map. */ function pickText(value, locale) {
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
const map = value;
|
||||
const preferred = locale ? map[locale] : undefined;
|
||||
if (typeof preferred === 'string') {
|
||||
return preferred;
|
||||
}
|
||||
const first = Object.values(map).find((v)=>typeof v === 'string');
|
||||
return first ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async function loadBranding(props, settingsSlug, nameField, imageField) {
|
||||
const { payload } = props;
|
||||
if (!payload) {
|
||||
return {
|
||||
name: null,
|
||||
url: null
|
||||
};
|
||||
}
|
||||
try {
|
||||
// Consumer alias — resolved in the project's build, hidden from plugin tsc.
|
||||
const spec = '@payload-config';
|
||||
const mod = await import(spec);
|
||||
const payload = await getPayload({
|
||||
config: mod.default
|
||||
});
|
||||
const locale = typeof props.locale === 'string' ? props.locale : props.locale?.code;
|
||||
const settings = await payload.findGlobal({
|
||||
slug: settingsSlug,
|
||||
depth: 1
|
||||
depth: 1,
|
||||
...locale ? {
|
||||
locale: locale
|
||||
} : {}
|
||||
});
|
||||
const name = typeof settings[nameField] === 'string' ? settings[nameField] : null;
|
||||
const name = pickText(settings[nameField], locale);
|
||||
const image = settings[imageField];
|
||||
const url = image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null;
|
||||
return {
|
||||
name,
|
||||
url
|
||||
};
|
||||
} catch {
|
||||
} catch (error) {
|
||||
console.warn('[ipal] admin branding: falling back to Payload default:', error);
|
||||
return {
|
||||
name: null,
|
||||
url: null
|
||||
@@ -32,7 +52,7 @@ async function loadBranding(settingsSlug, nameField, imageField) {
|
||||
* falls back to `siteName` text. Sized generously for the login screen.
|
||||
*/ export async function AdminLogo(props = {}) {
|
||||
const { imageField = 'logo', nameField = 'siteName', settingsSlug = 'site-settings' } = props;
|
||||
const { name, url } = await loadBranding(settingsSlug, nameField, imageField);
|
||||
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField);
|
||||
if (url) {
|
||||
return /*#__PURE__*/ _jsx("img", {
|
||||
alt: name ?? '',
|
||||
@@ -59,7 +79,7 @@ async function loadBranding(settingsSlug, nameField, imageField) {
|
||||
}
|
||||
/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */ export async function AdminIcon(props = {}) {
|
||||
const { imageField = 'favicon', nameField = 'siteName', settingsSlug = 'site-settings' } = props;
|
||||
const { name, url } = await loadBranding(settingsSlug, nameField, imageField);
|
||||
const { name, url } = await loadBranding(props, settingsSlug, nameField, imageField);
|
||||
if (url) {
|
||||
return /*#__PURE__*/ _jsx("img", {
|
||||
alt: name ?? '',
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+21
-10
@@ -1,25 +1,36 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
import type { ConsentTexts } from './texts.js';
|
||||
type PrivacyPage = {
|
||||
slug?: null | Record<string, unknown>;
|
||||
title?: unknown;
|
||||
} | null;
|
||||
type GetConsentTextsArgs = {
|
||||
config: I18nConfig;
|
||||
locale?: string;
|
||||
payload: BasePayload;
|
||||
/**
|
||||
* Privacy-policy label + the system page (from SiteSettings.privacyPolicy,
|
||||
* read with locale:'all') to link to. Optional — omit for no link.
|
||||
* Privacy-policy link. Omit it — the page is read automatically from
|
||||
* SiteSettings → System Pages → Privacy Policy, and the link text from
|
||||
* CookieSettings → privacyLinkLabel (per locale, editable in the panel).
|
||||
*
|
||||
* - `false` → no link.
|
||||
* - `{ page }` → use this page (SiteSettings.privacyPolicy read with locale:'all').
|
||||
* - `label` → DEPRECATED (hardcoded text); used only when the panel field is empty.
|
||||
*/
|
||||
privacyPolicy?: {
|
||||
label: string;
|
||||
page: {
|
||||
slug?: null | Record<string, unknown>;
|
||||
} | null;
|
||||
};
|
||||
/** @deprecated Set CookieSettings → privacyLinkLabel in the panel instead. */
|
||||
label?: string;
|
||||
page?: PrivacyPage;
|
||||
} | false;
|
||||
/** SiteSettings global slug for the automatic privacy page lookup. Default 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
};
|
||||
/**
|
||||
* Resolves consent banner texts from the CookieSettings global, falling back to
|
||||
* English defaults per field. The privacy-policy link is built from the pages
|
||||
* module (system page role), not stored in CookieSettings — one source of truth.
|
||||
* English defaults per field. The privacy-policy link target comes from the
|
||||
* pages module (system page role, read automatically); its text from
|
||||
* CookieSettings.privacyLinkLabel — both editable in the panel, per locale.
|
||||
*/
|
||||
export declare function getConsentTexts({ config, locale, payload, privacyPolicy, }: GetConsentTextsArgs): Promise<ConsentTexts>;
|
||||
export declare function getConsentTexts({ config, locale, payload, privacyPolicy, settingsSlug, }: GetConsentTextsArgs): Promise<ConsentTexts>;
|
||||
export {};
|
||||
|
||||
+30
-9
@@ -1,3 +1,4 @@
|
||||
import { resolveLocalized } from '../i18n/resolveLocalized.js';
|
||||
import { getSystemPagePath } from '../pages/index.js';
|
||||
import { getGlobal } from '../payload/index.js';
|
||||
import { CONSENT_CATEGORIES } from './categories.js';
|
||||
@@ -31,11 +32,28 @@ import { CONSENT_CATEGORIES } from './categories.js';
|
||||
privacyLink: null,
|
||||
settingsTitle: 'Cookie settings'
|
||||
};
|
||||
/** Last-resort link text — only when neither the panel nor the page has one. */ const FALLBACK_PRIVACY_LABEL = 'Privacy policy';
|
||||
/** Reads SiteSettings.privacyPolicy with all locales (slug + title as maps). */ async function readPrivacyPage(payload, settingsSlug) {
|
||||
try {
|
||||
const settings = await payload.findGlobal({
|
||||
slug: settingsSlug,
|
||||
depth: 1,
|
||||
locale: 'all'
|
||||
});
|
||||
const page = settings.privacyPolicy;
|
||||
return page && typeof page === 'object' ? page : null;
|
||||
} catch (error) {
|
||||
// No pages option / no privacyPolicy field / DB unreachable at build → no link.
|
||||
console.warn('[ipal] getConsentTexts: privacy page lookup failed, banner without link:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Resolves consent banner texts from the CookieSettings global, falling back to
|
||||
* English defaults per field. The privacy-policy link is built from the pages
|
||||
* module (system page role), not stored in CookieSettings — one source of truth.
|
||||
*/ export async function getConsentTexts({ config, locale, payload, privacyPolicy }) {
|
||||
* English defaults per field. The privacy-policy link target comes from the
|
||||
* pages module (system page role, read automatically); its text from
|
||||
* CookieSettings.privacyLinkLabel — both editable in the panel, per locale.
|
||||
*/ export async function getConsentTexts({ config, locale, payload, privacyPolicy, settingsSlug = 'site-settings' }) {
|
||||
const g = await getGlobal(payload, 'cookie-settings', {
|
||||
locale
|
||||
});
|
||||
@@ -48,16 +66,19 @@ import { CONSENT_CATEGORIES } from './categories.js';
|
||||
};
|
||||
}
|
||||
let privacyLink = null;
|
||||
if (privacyPolicy?.page && locale) {
|
||||
const href = getSystemPagePath({
|
||||
if (privacyPolicy !== false && locale) {
|
||||
const page = privacyPolicy?.page !== undefined ? privacyPolicy.page : await readPrivacyPage(payload, settingsSlug);
|
||||
const href = page ? getSystemPagePath({
|
||||
config,
|
||||
locale,
|
||||
page: privacyPolicy.page
|
||||
});
|
||||
if (href) {
|
||||
page
|
||||
}) : undefined;
|
||||
if (page && href) {
|
||||
// Panel first, then the deprecated code label, then the page's own title.
|
||||
const label = g.privacyLinkLabel?.trim() || privacyPolicy?.label?.trim() || resolveLocalized(page.title, locale).trim() || FALLBACK_PRIVACY_LABEL;
|
||||
privacyLink = {
|
||||
href,
|
||||
label: privacyPolicy.label
|
||||
label
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -6,6 +6,7 @@ export { getArchiveEntries } from './getArchiveEntries.js';
|
||||
export type { ArchiveEntries } from './getArchiveEntries.js';
|
||||
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js';
|
||||
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
|
||||
export { resolveNotFoundPage } from './resolveNotFoundPage.js';
|
||||
export { resolveRedirect } from './resolveRedirect.js';
|
||||
export { resolveRoute } from './resolveRoute.js';
|
||||
export type { ResolvedRoute } from './resolveRoute.js';
|
||||
|
||||
Vendored
+1
@@ -5,6 +5,7 @@ export { createSearchRoute } from './createSearchRoute.js';
|
||||
export { getArchiveEntries } from './getArchiveEntries.js';
|
||||
export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js';
|
||||
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
|
||||
export { resolveNotFoundPage } from './resolveNotFoundPage.js';
|
||||
export { resolveRedirect } from './resolveRedirect.js';
|
||||
export { resolveRoute } from './resolveRoute.js';
|
||||
export { searchContent } from './searchContent.js';
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"}
|
||||
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveNotFoundPage } from './resolveNotFoundPage.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveNotFoundPage","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
type ResolveNotFoundPageArgs = {
|
||||
locale: string;
|
||||
/** Client's Pages collection slug. Defaults to 'pages'. */
|
||||
pagesSlug?: string;
|
||||
payload: BasePayload;
|
||||
/** SiteSettings global slug. Defaults to 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
};
|
||||
/**
|
||||
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
|
||||
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
|
||||
* the role is unassigned.
|
||||
*
|
||||
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
|
||||
* like: a dedicated "Not found" page, or simply the homepage. Null means
|
||||
* "render the project's built-in fallback view".
|
||||
*
|
||||
* Never throws — a missing DB (container build prerendering not-found) or a
|
||||
* deleted page just yields null, so the 404 view can't crash the build.
|
||||
*/
|
||||
export declare function resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug, }: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>>;
|
||||
export {};
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
|
||||
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
|
||||
* the role is unassigned.
|
||||
*
|
||||
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
|
||||
* like: a dedicated "Not found" page, or simply the homepage. Null means
|
||||
* "render the project's built-in fallback view".
|
||||
*
|
||||
* Never throws — a missing DB (container build prerendering not-found) or a
|
||||
* deleted page just yields null, so the 404 view can't crash the build.
|
||||
*/ export async function resolveNotFoundPage({ locale, pagesSlug = 'pages', payload, settingsSlug = 'site-settings' }) {
|
||||
try {
|
||||
const settings = await payload.findGlobal({
|
||||
slug: settingsSlug,
|
||||
depth: 0,
|
||||
locale: locale
|
||||
});
|
||||
const rel = settings.notFound;
|
||||
const id = typeof rel === 'string' || typeof rel === 'number' ? rel : rel && typeof rel === 'object' ? rel.id : undefined;
|
||||
if (id === undefined) {
|
||||
return null;
|
||||
}
|
||||
const doc = await payload.findByID({
|
||||
id,
|
||||
collection: pagesSlug,
|
||||
depth: 2,
|
||||
locale: locale
|
||||
});
|
||||
return doc ?? null;
|
||||
} catch (error) {
|
||||
console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=resolveNotFoundPage.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/content/resolveNotFoundPage.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\ntype ResolveNotFoundPageArgs = {\n locale: string\n /** Client's Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Returns the page the editor assigned as **404 (Not Found)** in System Pages,\n * fully populated (depth 2, same shape as resolveRoute's pages), or null when\n * the role is unassigned.\n *\n * Used by the project's `not-found.tsx`. The editor decides what a 404 looks\n * like: a dedicated \"Not found\" page, or simply the homepage. Null means\n * \"render the project's built-in fallback view\".\n *\n * Never throws — a missing DB (container build prerendering not-found) or a\n * deleted page just yields null, so the 404 view can't crash the build.\n */\nexport async function resolveNotFoundPage({\n locale,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n}: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>> {\n try {\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 0,\n locale: locale as never,\n })) as Record<string, unknown>\n\n const rel = settings.notFound\n const id =\n typeof rel === 'string' || typeof rel === 'number'\n ? rel\n : rel && typeof rel === 'object'\n ? (rel as { id?: number | string }).id\n : undefined\n if (id === undefined) {return null}\n\n const doc = await payload.findByID({\n id,\n collection: pagesSlug as never,\n depth: 2,\n locale: locale as never,\n })\n return (doc as null | Record<string, unknown>) ?? null\n } catch (error) {\n console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error)\n return null\n }\n}\n"],"names":["resolveNotFoundPage","locale","pagesSlug","payload","settingsSlug","settings","findGlobal","slug","depth","rel","notFound","id","undefined","doc","findByID","collection","error","console","warn"],"mappings":"AAWA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeA,oBAAoB,EACxCC,MAAM,EACNC,YAAY,OAAO,EACnBC,OAAO,EACPC,eAAe,eAAe,EACN;IACxB,IAAI;QACF,MAAMC,WAAY,MAAMF,QAAQG,UAAU,CAAC;YACzCC,MAAMH;YACNI,OAAO;YACPP,QAAQA;QACV;QAEA,MAAMQ,MAAMJ,SAASK,QAAQ;QAC7B,MAAMC,KACJ,OAAOF,QAAQ,YAAY,OAAOA,QAAQ,WACtCA,MACAA,OAAO,OAAOA,QAAQ,WACpB,AAACA,IAAiCE,EAAE,GACpCC;QACR,IAAID,OAAOC,WAAW;YAAC,OAAO;QAAI;QAElC,MAAMC,MAAM,MAAMV,QAAQW,QAAQ,CAAC;YACjCH;YACAI,YAAYb;YACZM,OAAO;YACPP,QAAQA;QACV;QACA,OAAO,AAACY,OAA0C;IACpD,EAAE,OAAOG,OAAO;QACdC,QAAQC,IAAI,CAAC,kEAAkEF;QAC/E,OAAO;IACT;AACF"}
|
||||
+7
-1
@@ -38,6 +38,12 @@ type ResolveRouteArgs = {
|
||||
payload: BasePayload;
|
||||
/** Route segments after the locale, e.g. ['artykuly', 'moj-post']. */
|
||||
segments?: string[];
|
||||
/**
|
||||
* SiteSettings already read for this locale (depth ≥ 1). Pass it to skip the
|
||||
* read — createContentHelpers does, so layout, metadata and page share ONE
|
||||
* settings query per request.
|
||||
*/
|
||||
settings?: null | Record<string, unknown>;
|
||||
/** SiteSettings global slug. Defaults to 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
};
|
||||
@@ -64,5 +70,5 @@ type ResolveRouteArgs = {
|
||||
* make canonical and hreflang ambiguous (the same entry reachable under several
|
||||
* URLs).
|
||||
*/
|
||||
export declare function resolveRoute({ content, locale, page, pagesSlug, payload, segments, settingsSlug, }: ResolveRouteArgs): Promise<null | ResolvedRoute>;
|
||||
export declare function resolveRoute({ content, locale, page, pagesSlug, payload, segments, settings: preloaded, settingsSlug, }: ResolveRouteArgs): Promise<null | ResolvedRoute>;
|
||||
export {};
|
||||
|
||||
Vendored
+16
-2
@@ -21,8 +21,8 @@ import { archiveFieldName } from './types.js';
|
||||
* Depth beyond {archive}/{entry} isn't supported — categories in the path would
|
||||
* make canonical and hreflang ambiguous (the same entry reachable under several
|
||||
* URLs).
|
||||
*/ export async function resolveRoute({ content, locale, page = 1, pagesSlug = 'pages', payload, segments, settingsSlug = 'site-settings' }) {
|
||||
const settings = await payload.findGlobal({
|
||||
*/ export async function resolveRoute({ content, locale, page = 1, pagesSlug = 'pages', payload, segments, settings: preloaded, settingsSlug = 'site-settings' }) {
|
||||
const settings = preloaded ?? await payload.findGlobal({
|
||||
slug: settingsSlug,
|
||||
depth: 1,
|
||||
locale: locale
|
||||
@@ -114,6 +114,20 @@ import { archiveFieldName } from './types.js';
|
||||
if (!doc) {
|
||||
return null;
|
||||
}
|
||||
// The page assigned as 404 in System Pages must not be reachable as a normal
|
||||
// 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat
|
||||
// it as not found, so the route calls notFound() and not-found.tsx renders
|
||||
// that same page with a real 404 status. (If 404 = homepage, the homepage is
|
||||
// served from the root branch above and never reaches here by its own slug
|
||||
// in a way that matters — but guard anyway so we never hide the homepage.)
|
||||
const notFound = settings.notFound;
|
||||
const homepage = settings.homepage;
|
||||
const notFoundId = notFound && typeof notFound === 'object' ? notFound.id : notFound;
|
||||
const homepageId = homepage && typeof homepage === 'object' ? homepage.id : homepage;
|
||||
const docId = doc.id;
|
||||
if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
type: 'page',
|
||||
doc: doc
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+10
-2
@@ -1,7 +1,7 @@
|
||||
import type { BasePayload, SanitizedConfig } from 'payload';
|
||||
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
import type { RobotsRules, SitemapEntry } from '../seo/index.js';
|
||||
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry } from '../seo/index.js';
|
||||
type CreateContentHelpersArgs = {
|
||||
/**
|
||||
* Absolute site origin for sitemap/robots URLs. Falls back to
|
||||
@@ -23,6 +23,12 @@ type CreateContentHelpersArgs = {
|
||||
i18n?: I18nConfig;
|
||||
/** Pages collection slug. Defaults to 'pages'. */
|
||||
pagesSlug?: string;
|
||||
/**
|
||||
* Options for the ready-made `robots` handler, e.g.
|
||||
* `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or
|
||||
* `{ adminRoute: false }` when the admin path is hidden (ipalKit adminRoute).
|
||||
*/
|
||||
robots?: RobotsOptions;
|
||||
/** SiteSettings global slug. Defaults to 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
};
|
||||
@@ -52,7 +58,8 @@ type CreateContentHelpersArgs = {
|
||||
* a URL is, fetching gets the listing. Metadata generation needs the first and
|
||||
* not the second, and a page component composes them in two obvious lines.
|
||||
*/
|
||||
export declare function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug, settingsSlug, }: CreateContentHelpersArgs): {
|
||||
export declare function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug, robots: robotsOptions, settingsSlug, }: CreateContentHelpersArgs): {
|
||||
generatePageMetadata: (locale: string, segments: string[] | undefined, page?: number) => Promise<PageMetadata>;
|
||||
generateStaticParams: () => Promise<Array<{
|
||||
locale: string;
|
||||
slug: string[];
|
||||
@@ -62,6 +69,7 @@ export declare function createContentHelpers({ baseUrl, config, content, i18n, p
|
||||
getCachedPayload: () => Promise<BasePayload>;
|
||||
getConfiguredLocales: () => Promise<string[]>;
|
||||
getEntries: (collection: string, locale: string, page: number, perPage: number) => Promise<ArchiveEntries>;
|
||||
getNotFoundPage: (locale: string) => Promise<Record<string, unknown> | null>;
|
||||
getSettings: (locale: string) => Promise<import("payload").JsonObject>;
|
||||
resolveRoute: (locale: string, segments: string[] | undefined, page: number) => Promise<null | ResolvedRoute>;
|
||||
robots: () => RobotsRules;
|
||||
|
||||
+91
-3
@@ -1,7 +1,7 @@
|
||||
import { getPayload } from 'payload';
|
||||
import { cache } from 'react';
|
||||
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js';
|
||||
import { buildRobots, buildSitemapEntries } from '../seo/index.js';
|
||||
import { buildRobots, buildSitemapEntries, createPageMetadata } from '../seo/index.js';
|
||||
/**
|
||||
* Bundles the per-request data helpers a frontend needs — the same cached
|
||||
* wrappers every project was writing by hand (getPayload, settings, locale
|
||||
@@ -27,7 +27,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
|
||||
* `resolveRoute` and `getEntries` are separate on purpose: routing decides what
|
||||
* a URL is, fetching gets the listing. Metadata generation needs the first and
|
||||
* not the second, and a page component composes them in two obvious lines.
|
||||
*/ export function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug = 'pages', settingsSlug = 'site-settings' }) {
|
||||
*/ export function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug = 'pages', robots: robotsOptions, settingsSlug = 'site-settings' }) {
|
||||
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '';
|
||||
const getCachedPayload = cache(async ()=>getPayload({
|
||||
config: await config
|
||||
@@ -36,7 +36,10 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
|
||||
const c = await config;
|
||||
return c.localization ? c.localization.locales.map((l)=>l.code) : [];
|
||||
});
|
||||
const getSettings = cache(async (locale)=>{
|
||||
/**
|
||||
* SiteSettings for a locale — ONE query per locale per request, shared by the
|
||||
* layout, generatePageMetadata, resolveRoute and anything else that asks.
|
||||
*/ const getSettings = cache(async (locale)=>{
|
||||
const payload = await getCachedPayload();
|
||||
return payload.findGlobal({
|
||||
slug: settingsSlug,
|
||||
@@ -46,6 +49,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
|
||||
});
|
||||
/** What does this URL point at? Routing only — no listing data. */ const resolveRoute = cache(async (locale, segments, page)=>{
|
||||
const payload = await getCachedPayload();
|
||||
const settings = await getSettings(locale);
|
||||
return resolveRouteRaw({
|
||||
content,
|
||||
locale,
|
||||
@@ -53,9 +57,85 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
|
||||
pagesSlug,
|
||||
payload,
|
||||
segments,
|
||||
settings,
|
||||
settingsSlug
|
||||
});
|
||||
});
|
||||
/**
|
||||
* generateMetadata for the catch-all page, sharing the request cache with
|
||||
* the page component: the same settings read and the same resolveRoute call
|
||||
* (React cache spans generateMetadata and the page within one request), so
|
||||
* metadata costs no extra route/settings queries.
|
||||
*
|
||||
* export async function generateMetadata({ params }) {
|
||||
* const { locale, slug } = await params
|
||||
* return generatePageMetadata(locale, slug)
|
||||
* }
|
||||
*/ let pageMetadata;
|
||||
const generatePageMetadata = async (locale, segments, page = 1)=>{
|
||||
if (!i18n) {
|
||||
throw new Error('[ipal] createContentHelpers: pass `i18n` to use generatePageMetadata.');
|
||||
}
|
||||
pageMetadata ??= createPageMetadata({
|
||||
baseUrl: origin || undefined,
|
||||
collection: pagesSlug,
|
||||
config: i18n,
|
||||
content,
|
||||
loaders: {
|
||||
getSettings: async (l)=>await getSettings(l),
|
||||
resolveRoute
|
||||
},
|
||||
settingsSlug
|
||||
});
|
||||
return pageMetadata({
|
||||
slug: segments,
|
||||
locale,
|
||||
page,
|
||||
payload: await getCachedPayload()
|
||||
});
|
||||
};
|
||||
/** ID of the page assigned as 404 — the relation isn't localized, so one read serves every locale. */ const getNotFoundPageId = cache(async ()=>{
|
||||
const payload = await getCachedPayload();
|
||||
const settings = await payload.findGlobal({
|
||||
slug: settingsSlug,
|
||||
depth: 0
|
||||
});
|
||||
const rel = settings.notFound;
|
||||
if (typeof rel === 'string' || typeof rel === 'number') {
|
||||
return rel;
|
||||
}
|
||||
if (rel && typeof rel === 'object') {
|
||||
const id = rel.id;
|
||||
if (typeof id === 'string' || typeof id === 'number') {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
/**
|
||||
* The page assigned as 404 in System Pages (or null → built-in fallback).
|
||||
* For app/not-found.tsx; never throws. not-found.tsx receives no params and
|
||||
* must NOT read headers() (breaks SSG/ISR) — call this for every configured
|
||||
* locale and let <LocaleView> (client) pick the one from the URL. See pages.md.
|
||||
*/ const getNotFoundPage = cache(async (locale)=>{
|
||||
try {
|
||||
const id = await getNotFoundPageId();
|
||||
if (id === null) {
|
||||
return null;
|
||||
}
|
||||
const payload = await getCachedPayload();
|
||||
const doc = await payload.findByID({
|
||||
id,
|
||||
collection: pagesSlug,
|
||||
depth: 2,
|
||||
locale: locale
|
||||
});
|
||||
return doc ?? null;
|
||||
} catch {
|
||||
return null // DB unreachable (container build) or page deleted — fallback view
|
||||
;
|
||||
}
|
||||
});
|
||||
/** One page of a collection's entries, for an archive listing. */ const getEntries = cache(async (collection, locale, page, perPage)=>{
|
||||
const payload = await getCachedPayload();
|
||||
return getArchiveEntries({
|
||||
@@ -115,6 +195,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
|
||||
* export { robots as default } from '@/lib/content'
|
||||
* ```
|
||||
*/ const robots = ()=>buildRobots({
|
||||
...robotsOptions,
|
||||
baseUrl: origin
|
||||
});
|
||||
/**
|
||||
@@ -154,6 +235,8 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
|
||||
locale: 'all'
|
||||
}).catch(()=>null);
|
||||
const homeId = settings?.homepage?.id;
|
||||
// The assigned 404 page renders via not-found.tsx, never as its own URL.
|
||||
const notFoundId = settings?.notFound?.id !== undefined && settings.notFound.id !== homeId ? settings.notFound.id : undefined;
|
||||
const EXCLUDED = new Set([
|
||||
'404',
|
||||
'500',
|
||||
@@ -177,6 +260,9 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
|
||||
if (raw._status && raw._status !== 'published') {
|
||||
continue;
|
||||
}
|
||||
if (notFoundId !== undefined && raw.id === notFoundId) {
|
||||
continue;
|
||||
}
|
||||
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
|
||||
// page (privacy, cookies, terms) still needs to render — users reach it
|
||||
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
|
||||
@@ -226,10 +312,12 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
|
||||
}
|
||||
};
|
||||
return {
|
||||
generatePageMetadata,
|
||||
generateStaticParams,
|
||||
getCachedPayload,
|
||||
getConfiguredLocales,
|
||||
getEntries,
|
||||
getNotFoundPage,
|
||||
getSettings,
|
||||
resolveRoute,
|
||||
robots,
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+39
@@ -0,0 +1,39 @@
|
||||
import type { ArrayField, GroupField } from 'payload';
|
||||
export type LinkAppearance = 'link' | 'primary' | 'secondary';
|
||||
export type BuildLinkFieldOptions = {
|
||||
/** Visual styles the editor may pick. `false` → no appearance select. Default all three. */
|
||||
appearances?: false | LinkAppearance[];
|
||||
/** Hide the label — for links that wrap something (a whole card, an image). */
|
||||
disableLabel?: boolean;
|
||||
/** Field name. Default 'link'. */
|
||||
name?: string;
|
||||
/** Collection the "Page" option points at. Default 'pages'. */
|
||||
relationTo?: string;
|
||||
required?: boolean;
|
||||
/** Upload collection for "File" links (PDF, documents). Default 'media'. */
|
||||
uploadTo?: string;
|
||||
};
|
||||
/**
|
||||
* The ONE link shape for a project: a page, an external URL (also mailto:,
|
||||
* tel:, #anchor) or an uploaded file — plus label, new-tab flag and visual
|
||||
* style. Every CTA, card link and download in every block uses this field, so
|
||||
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
|
||||
* (resolveLinkHref + the project's CMSLink) handles them all.
|
||||
*
|
||||
* Generates a named TypeScript type `CmsLink` in payload-types.ts.
|
||||
*
|
||||
* fields: [buildLinkField()] // single link
|
||||
* fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card
|
||||
*/
|
||||
export declare function buildLinkField({ name, appearances, disableLabel, relationTo, required, uploadTo, }?: BuildLinkFieldOptions): GroupField;
|
||||
export type BuildLinksFieldOptions = {
|
||||
/** Max number of buttons. Default 2. */
|
||||
maxRows?: number;
|
||||
/** Field name. Default 'links'. */
|
||||
name?: string;
|
||||
} & Omit<BuildLinkFieldOptions, 'disableLabel' | 'name'>;
|
||||
/**
|
||||
* 0..N buttons — use for every "CTA(s)" of a section. Each row holds one
|
||||
* `link` (buildLinkField). Render: `links.map(({ id, link }) => <CMSLink … />)`.
|
||||
*/
|
||||
export declare function buildLinksField({ name, maxRows, ...linkOptions }?: BuildLinksFieldOptions): ArrayField;
|
||||
Vendored
+134
@@ -0,0 +1,134 @@
|
||||
const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/;
|
||||
/**
|
||||
* The ONE link shape for a project: a page, an external URL (also mailto:,
|
||||
* tel:, #anchor) or an uploaded file — plus label, new-tab flag and visual
|
||||
* style. Every CTA, card link and download in every block uses this field, so
|
||||
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
|
||||
* (resolveLinkHref + the project's CMSLink) handles them all.
|
||||
*
|
||||
* Generates a named TypeScript type `CmsLink` in payload-types.ts.
|
||||
*
|
||||
* fields: [buildLinkField()] // single link
|
||||
* fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card
|
||||
*/ export function buildLinkField({ name = 'link', appearances = [
|
||||
'primary',
|
||||
'secondary',
|
||||
'link'
|
||||
], disableLabel = false, relationTo = 'pages', required = false, uploadTo = 'media' } = {}) {
|
||||
const fields = [
|
||||
{
|
||||
type: 'row',
|
||||
fields: [
|
||||
{
|
||||
name: 'type',
|
||||
type: 'radio',
|
||||
admin: {
|
||||
layout: 'horizontal',
|
||||
width: '50%'
|
||||
},
|
||||
defaultValue: 'internal',
|
||||
options: [
|
||||
{
|
||||
label: 'Page',
|
||||
value: 'internal'
|
||||
},
|
||||
{
|
||||
label: 'URL',
|
||||
value: 'external'
|
||||
},
|
||||
{
|
||||
label: 'File',
|
||||
value: 'file'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'newTab',
|
||||
type: 'checkbox',
|
||||
admin: {
|
||||
style: {
|
||||
alignSelf: 'flex-end'
|
||||
},
|
||||
width: '50%'
|
||||
},
|
||||
label: 'Open in new tab'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'page',
|
||||
type: 'relationship',
|
||||
admin: {
|
||||
condition: (_, s)=>s?.type === 'internal'
|
||||
},
|
||||
relationTo,
|
||||
required
|
||||
},
|
||||
{
|
||||
name: 'url',
|
||||
type: 'text',
|
||||
admin: {
|
||||
condition: (_, s)=>s?.type === 'external',
|
||||
description: 'Full URL (https://…), mailto:, tel: or #section-anchor.'
|
||||
},
|
||||
required,
|
||||
validate: (v)=>!v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor'
|
||||
},
|
||||
{
|
||||
name: 'file',
|
||||
type: 'upload',
|
||||
admin: {
|
||||
condition: (_, s)=>s?.type === 'file',
|
||||
description: 'Upload a PDF / document / image. Never paste a file URL.'
|
||||
},
|
||||
relationTo: uploadTo,
|
||||
required
|
||||
}
|
||||
];
|
||||
if (!disableLabel) {
|
||||
fields.push({
|
||||
name: 'label',
|
||||
type: 'text',
|
||||
localized: true,
|
||||
required
|
||||
});
|
||||
}
|
||||
if (appearances && appearances.length) {
|
||||
fields.push({
|
||||
name: 'appearance',
|
||||
type: 'select',
|
||||
defaultValue: appearances[0],
|
||||
options: appearances.map((a)=>({
|
||||
label: a,
|
||||
value: a
|
||||
}))
|
||||
});
|
||||
}
|
||||
return {
|
||||
name,
|
||||
type: 'group',
|
||||
admin: {
|
||||
hideGutter: true
|
||||
},
|
||||
fields,
|
||||
interfaceName: 'CmsLink'
|
||||
};
|
||||
}
|
||||
/**
|
||||
* 0..N buttons — use for every "CTA(s)" of a section. Each row holds one
|
||||
* `link` (buildLinkField). Render: `links.map(({ id, link }) => <CMSLink … />)`.
|
||||
*/ export function buildLinksField({ name = 'links', maxRows = 2, ...linkOptions } = {}) {
|
||||
return {
|
||||
name,
|
||||
type: 'array',
|
||||
admin: {
|
||||
initCollapsed: true
|
||||
},
|
||||
fields: [
|
||||
buildLinkField(linkOptions)
|
||||
],
|
||||
maxRows
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=buildLinkField.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
export { buildLinkField, buildLinksField } from './buildLinkField.js';
|
||||
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js';
|
||||
export { resolveLinkHref } from './resolveLinkHref.js';
|
||||
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js';
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
export { buildLinkField, buildLinksField } from './buildLinkField.js';
|
||||
export { resolveLinkHref } from './resolveLinkHref.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/links/index.ts"],"sourcesContent":["export { buildLinkField, buildLinksField } from './buildLinkField.js'\nexport type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'\nexport { resolveLinkHref } from './resolveLinkHref.js'\nexport type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'\n"],"names":["buildLinkField","buildLinksField","resolveLinkHref"],"mappings":"AAAA,SAASA,cAAc,EAAEC,eAAe,QAAQ,sBAAqB;AAErE,SAASC,eAAe,QAAQ,uBAAsB"}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
/**
|
||||
* Minimal shape of a link value (the project's generated `CmsLink` fits it).
|
||||
* The plugin doesn't know the project's types — only this contract.
|
||||
*/
|
||||
export type LinkValue = {
|
||||
appearance?: null | string;
|
||||
file?: unknown;
|
||||
label?: null | string;
|
||||
newTab?: boolean | null;
|
||||
page?: unknown;
|
||||
type?: 'external' | 'file' | 'internal' | null;
|
||||
url?: null | string;
|
||||
};
|
||||
export type ResolveLinkHrefOptions = {
|
||||
config: I18nConfig;
|
||||
/**
|
||||
* Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a
|
||||
* string. Usually from SiteSettings.homepage.
|
||||
*/
|
||||
homeSlug?: Record<string, string> | string;
|
||||
locale: string;
|
||||
};
|
||||
/**
|
||||
* Turns a link value (buildLinkField) into an href — the single place that
|
||||
* knows the link types. Returns null when the link is empty or its target is
|
||||
* missing in this locale (deleted page, page not populated, no file).
|
||||
*
|
||||
* Internal links need the related page POPULATED (block depth ≥ 2) — a bare ID
|
||||
* resolves to null.
|
||||
*
|
||||
* resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
|
||||
* // internal → '/en/about' · external → 'https://…' · file → media URL
|
||||
*/
|
||||
export declare function resolveLinkHref(link: LinkValue | null | undefined, { config, homeSlug, locale }: ResolveLinkHrefOptions): null | string;
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { buildLocalizedPath } from '../i18n/index.js';
|
||||
/**
|
||||
* Turns a link value (buildLinkField) into an href — the single place that
|
||||
* knows the link types. Returns null when the link is empty or its target is
|
||||
* missing in this locale (deleted page, page not populated, no file).
|
||||
*
|
||||
* Internal links need the related page POPULATED (block depth ≥ 2) — a bare ID
|
||||
* resolves to null.
|
||||
*
|
||||
* resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
|
||||
* // internal → '/en/about' · external → 'https://…' · file → media URL
|
||||
*/ export function resolveLinkHref(link, { config, homeSlug, locale }) {
|
||||
if (!link) {
|
||||
return null;
|
||||
}
|
||||
if (link.type === 'external') {
|
||||
return link.url?.trim() || null;
|
||||
}
|
||||
if (link.type === 'file') {
|
||||
const file = link.file;
|
||||
if (file && typeof file === 'object' && 'url' in file) {
|
||||
const url = file.url;
|
||||
return typeof url === 'string' && url ? url : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// internal (default)
|
||||
const page = link.page;
|
||||
if (!page || typeof page !== 'object') {
|
||||
return null;
|
||||
}
|
||||
const slug = page.slug;
|
||||
if (typeof slug !== 'string' || !slug) {
|
||||
return null;
|
||||
}
|
||||
return buildLocalizedPath({
|
||||
config,
|
||||
locale,
|
||||
slugs: {
|
||||
[locale]: slug
|
||||
},
|
||||
...homeSlug ? {
|
||||
homeSlug
|
||||
} : {}
|
||||
}) ?? null;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=resolveLinkHref.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/links/resolveLinkHref.ts"],"sourcesContent":["import type { I18nConfig } from '../i18n/index.js'\n\nimport { buildLocalizedPath } from '../i18n/index.js'\n\n/**\n * Minimal shape of a link value (the project's generated `CmsLink` fits it).\n * The plugin doesn't know the project's types — only this contract.\n */\nexport type LinkValue = {\n appearance?: null | string\n file?: unknown\n label?: null | string\n newTab?: boolean | null\n page?: unknown\n type?: 'external' | 'file' | 'internal' | null\n url?: null | string\n}\n\nexport type ResolveLinkHrefOptions = {\n config: I18nConfig\n /**\n * Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a\n * string. Usually from SiteSettings.homepage.\n */\n homeSlug?: Record<string, string> | string\n locale: string\n}\n\n/**\n * Turns a link value (buildLinkField) into an href — the single place that\n * knows the link types. Returns null when the link is empty or its target is\n * missing in this locale (deleted page, page not populated, no file).\n *\n * Internal links need the related page POPULATED (block depth ≥ 2) — a bare ID\n * resolves to null.\n *\n * resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })\n * // internal → '/en/about' · external → 'https://…' · file → media URL\n */\nexport function resolveLinkHref(\n link: LinkValue | null | undefined,\n { config, homeSlug, locale }: ResolveLinkHrefOptions,\n): null | string {\n if (!link) {return null}\n\n if (link.type === 'external') {return link.url?.trim() || null}\n\n if (link.type === 'file') {\n const file = link.file\n if (file && typeof file === 'object' && 'url' in file) {\n const url = (file as { url?: unknown }).url\n return typeof url === 'string' && url ? url : null\n }\n return null\n }\n\n // internal (default)\n const page = link.page\n if (!page || typeof page !== 'object') {return null}\n const slug = (page as { slug?: unknown }).slug\n if (typeof slug !== 'string' || !slug) {return null}\n\n return (\n buildLocalizedPath({\n config,\n locale,\n slugs: { [locale]: slug },\n ...(homeSlug ? { homeSlug } : {}),\n }) ?? null\n )\n}\n"],"names":["buildLocalizedPath","resolveLinkHref","link","config","homeSlug","locale","type","url","trim","file","page","slug","slugs"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,mBAAkB;AA0BrD;;;;;;;;;;CAUC,GACD,OAAO,SAASC,gBACdC,IAAkC,EAClC,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,EAA0B;IAEpD,IAAI,CAACH,MAAM;QAAC,OAAO;IAAI;IAEvB,IAAIA,KAAKI,IAAI,KAAK,YAAY;QAAC,OAAOJ,KAAKK,GAAG,EAAEC,UAAU;IAAI;IAE9D,IAAIN,KAAKI,IAAI,KAAK,QAAQ;QACxB,MAAMG,OAAOP,KAAKO,IAAI;QACtB,IAAIA,QAAQ,OAAOA,SAAS,YAAY,SAASA,MAAM;YACrD,MAAMF,MAAM,AAACE,KAA2BF,GAAG;YAC3C,OAAO,OAAOA,QAAQ,YAAYA,MAAMA,MAAM;QAChD;QACA,OAAO;IACT;IAEA,qBAAqB;IACrB,MAAMG,OAAOR,KAAKQ,IAAI;IACtB,IAAI,CAACA,QAAQ,OAAOA,SAAS,UAAU;QAAC,OAAO;IAAI;IACnD,MAAMC,OAAO,AAACD,KAA4BC,IAAI;IAC9C,IAAI,OAAOA,SAAS,YAAY,CAACA,MAAM;QAAC,OAAO;IAAI;IAEnD,OACEX,mBAAmB;QACjBG;QACAE;QACAO,OAAO;YAAE,CAACP,OAAO,EAAEM;QAAK;QACxB,GAAIP,WAAW;YAAEA;QAAS,IAAI,CAAC,CAAC;IAClC,MAAM;AAEV"}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
import type { ReactNode } from 'react';
|
||||
type LocaleViewProps = {
|
||||
/** Used when the URL has no locale segment (single-locale site) or an unknown one. */
|
||||
defaultLocale: string;
|
||||
/**
|
||||
* One pre-rendered view per locale, e.g. { pl: <RenderBlocks …/>, en: … }.
|
||||
* Rendered on the SERVER (RSC) and passed in as props — this component only
|
||||
* picks one, so the content can come from the panel and the route stays static.
|
||||
*/
|
||||
views: Record<string, ReactNode>;
|
||||
};
|
||||
/**
|
||||
* Shows the view matching the locale in the current URL (`/en/...` → `en`).
|
||||
*
|
||||
* Made for `not-found.tsx`, which receives no `params`: reading the locale with
|
||||
* `headers()` there turns an SSG/ISR route dynamic ("Page changed from static
|
||||
* to dynamic at runtime"). `usePathname()` is client-side and static-safe, and
|
||||
* it also runs during SSR, so the HTML already contains the right language.
|
||||
*/
|
||||
export declare function LocaleView({ defaultLocale, views }: LocaleViewProps): import("react/jsx-runtime").JSX.Element;
|
||||
export {};
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
'use client';
|
||||
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
|
||||
// '.js' is required: `next` has no package.json "exports", so NodeNext resolution
|
||||
// (this plugin's tsconfig) can't find 'next/navigation' without the extension.
|
||||
// Bundlers in the project resolve the same file either way.
|
||||
import { usePathname } from 'next/navigation.js';
|
||||
/**
|
||||
* Shows the view matching the locale in the current URL (`/en/...` → `en`).
|
||||
*
|
||||
* Made for `not-found.tsx`, which receives no `params`: reading the locale with
|
||||
* `headers()` there turns an SSG/ISR route dynamic ("Page changed from static
|
||||
* to dynamic at runtime"). `usePathname()` is client-side and static-safe, and
|
||||
* it also runs during SSR, so the HTML already contains the right language.
|
||||
*/ export function LocaleView({ defaultLocale, views }) {
|
||||
const pathname = usePathname() ?? '';
|
||||
const segment = pathname.split('/').filter(Boolean)[0] ?? '';
|
||||
const locale = segment in views ? segment : defaultLocale;
|
||||
return /*#__PURE__*/ _jsx(_Fragment, {
|
||||
children: views[locale] ?? views[defaultLocale] ?? null
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=LocaleView.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/pages/LocaleView.tsx"],"sourcesContent":["'use client'\nimport type { ReactNode } from 'react'\n// '.js' is required: `next` has no package.json \"exports\", so NodeNext resolution\n// (this plugin's tsconfig) can't find 'next/navigation' without the extension.\n// Bundlers in the project resolve the same file either way.\nimport { usePathname } from 'next/navigation.js'\n\ntype LocaleViewProps = {\n /** Used when the URL has no locale segment (single-locale site) or an unknown one. */\n defaultLocale: string\n /**\n * One pre-rendered view per locale, e.g. { pl: <RenderBlocks …/>, en: … }.\n * Rendered on the SERVER (RSC) and passed in as props — this component only\n * picks one, so the content can come from the panel and the route stays static.\n */\n views: Record<string, ReactNode>\n}\n\n/**\n * Shows the view matching the locale in the current URL (`/en/...` → `en`).\n *\n * Made for `not-found.tsx`, which receives no `params`: reading the locale with\n * `headers()` there turns an SSG/ISR route dynamic (\"Page changed from static\n * to dynamic at runtime\"). `usePathname()` is client-side and static-safe, and\n * it also runs during SSR, so the HTML already contains the right language.\n */\nexport function LocaleView({ defaultLocale, views }: LocaleViewProps) {\n const pathname = usePathname() ?? ''\n const segment = pathname.split('/').filter(Boolean)[0] ?? ''\n const locale = segment in views ? segment : defaultLocale\n return <>{views[locale] ?? views[defaultLocale] ?? null}</>\n}\n"],"names":["usePathname","LocaleView","defaultLocale","views","pathname","segment","split","filter","Boolean","locale"],"mappings":"AAAA;;AAEA,kFAAkF;AAClF,+EAA+E;AAC/E,4DAA4D;AAC5D,SAASA,WAAW,QAAQ,qBAAoB;AAahD;;;;;;;CAOC,GACD,OAAO,SAASC,WAAW,EAAEC,aAAa,EAAEC,KAAK,EAAmB;IAClE,MAAMC,WAAWJ,iBAAiB;IAClC,MAAMK,UAAUD,SAASE,KAAK,CAAC,KAAKC,MAAM,CAACC,QAAQ,CAAC,EAAE,IAAI;IAC1D,MAAMC,SAASJ,WAAWF,QAAQE,UAAUH;IAC5C,qBAAO;kBAAGC,KAAK,CAACM,OAAO,IAAIN,KAAK,CAACD,cAAc,IAAI;;AACrD"}
|
||||
+2
@@ -2,12 +2,14 @@ import { ALL_SYSTEM_PAGE_ROLES } from './types.js';
|
||||
/** Admin-facing labels per role. */ const ROLE_LABELS = {
|
||||
cookiePolicy: 'Cookie Policy',
|
||||
homepage: 'Homepage',
|
||||
notFound: '404 (Not Found)',
|
||||
privacyPolicy: 'Privacy Policy',
|
||||
termsOfService: 'Terms of Service'
|
||||
};
|
||||
/** Admin descriptions per role. */ const ROLE_DESCRIPTIONS = {
|
||||
cookiePolicy: 'Page linked from the cookie consent banner.',
|
||||
homepage: 'Page served at the locale root (e.g. /pl, /en).',
|
||||
notFound: 'Page shown for unknown URLs (404). Pick a dedicated "Not found" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',
|
||||
privacyPolicy: 'Page linked as the privacy policy.',
|
||||
termsOfService: 'Page linked as the terms of service / site regulations.'
|
||||
};
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/pages/systemPagesFields.ts"],"sourcesContent":["import type { Field, RelationshipField } from 'payload'\n\nimport type { PagesOption, SystemPageRole } from './types.js'\n\nimport { ALL_SYSTEM_PAGE_ROLES } from './types.js'\n\n/** Admin-facing labels per role. */\nconst ROLE_LABELS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Cookie Policy',\n homepage: 'Homepage',\n privacyPolicy: 'Privacy Policy',\n termsOfService: 'Terms of Service',\n}\n\n/** Admin descriptions per role. */\nconst ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Page linked from the cookie consent banner.',\n homepage: 'Page served at the locale root (e.g. /pl, /en).',\n privacyPolicy: 'Page linked as the privacy policy.',\n termsOfService: 'Page linked as the terms of service / site regulations.',\n}\n\n/**\n * Builds one relationship field per configured system-page role.\n *\n * Each field points at the client's Pages collection (via the provided slug)\n * and holds a single document reference. The referenced document's slug is\n * localized, so the same assignment resolves to /pl/strona-glowna and\n * /en/home at runtime — role assignment is locale-agnostic, path resolution\n * is locale-aware (see getSystemPagePath).\n */\nexport function buildSystemPagesFields(pages: PagesOption): Field[] {\n const roles = pages.roles?.length ? pages.roles : [...ALL_SYSTEM_PAGE_ROLES]\n\n return roles.map((role): RelationshipField => ({\n name: role,\n type: 'relationship',\n admin: {\n description: ROLE_DESCRIPTIONS[role],\n },\n label: ROLE_LABELS[role],\n maxDepth: 1,\n relationTo: pages.slug,\n }))\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES","ROLE_LABELS","cookiePolicy","homepage","privacyPolicy","termsOfService","ROLE_DESCRIPTIONS","buildSystemPagesFields","pages","roles","length","map","role","name","type","admin","description","label","maxDepth","relationTo","slug"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,aAAY;AAElD,kCAAkC,GAClC,MAAMC,cAA8C;IAClDC,cAAc;IACdC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA,iCAAiC,GACjC,MAAMC,oBAAoD;IACxDJ,cAAc;IACdC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,uBAAuBC,KAAkB;IACvD,MAAMC,QAAQD,MAAMC,KAAK,EAAEC,SAASF,MAAMC,KAAK,GAAG;WAAIT;KAAsB;IAE5E,OAAOS,MAAME,GAAG,CAAC,CAACC,OAA6B,CAAA;YAC7CC,MAAMD;YACNE,MAAM;YACNC,OAAO;gBACLC,aAAaV,iBAAiB,CAACM,KAAK;YACtC;YACAK,OAAOhB,WAAW,CAACW,KAAK;YACxBM,UAAU;YACVC,YAAYX,MAAMY,IAAI;QACxB,CAAA;AACF"}
|
||||
{"version":3,"sources":["../../../src/modules/pages/systemPagesFields.ts"],"sourcesContent":["import type { Field, RelationshipField } from 'payload'\n\nimport type { PagesOption, SystemPageRole } from './types.js'\n\nimport { ALL_SYSTEM_PAGE_ROLES } from './types.js'\n\n/** Admin-facing labels per role. */\nconst ROLE_LABELS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Cookie Policy',\n homepage: 'Homepage',\n notFound: '404 (Not Found)',\n privacyPolicy: 'Privacy Policy',\n termsOfService: 'Terms of Service',\n}\n\n/** Admin descriptions per role. */\nconst ROLE_DESCRIPTIONS: Record<SystemPageRole, string> = {\n cookiePolicy: 'Page linked from the cookie consent banner.',\n homepage: 'Page served at the locale root (e.g. /pl, /en).',\n notFound:\n 'Page shown for unknown URLs (404). Pick a dedicated \"Not found\" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',\n privacyPolicy: 'Page linked as the privacy policy.',\n termsOfService: 'Page linked as the terms of service / site regulations.',\n}\n\n/**\n * Builds one relationship field per configured system-page role.\n *\n * Each field points at the client's Pages collection (via the provided slug)\n * and holds a single document reference. The referenced document's slug is\n * localized, so the same assignment resolves to /pl/strona-glowna and\n * /en/home at runtime — role assignment is locale-agnostic, path resolution\n * is locale-aware (see getSystemPagePath).\n */\nexport function buildSystemPagesFields(pages: PagesOption): Field[] {\n const roles = pages.roles?.length ? pages.roles : [...ALL_SYSTEM_PAGE_ROLES]\n\n return roles.map((role): RelationshipField => ({\n name: role,\n type: 'relationship',\n admin: {\n description: ROLE_DESCRIPTIONS[role],\n },\n label: ROLE_LABELS[role],\n maxDepth: 1,\n relationTo: pages.slug,\n }))\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES","ROLE_LABELS","cookiePolicy","homepage","notFound","privacyPolicy","termsOfService","ROLE_DESCRIPTIONS","buildSystemPagesFields","pages","roles","length","map","role","name","type","admin","description","label","maxDepth","relationTo","slug"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,aAAY;AAElD,kCAAkC,GAClC,MAAMC,cAA8C;IAClDC,cAAc;IACdC,UAAU;IACVC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA,iCAAiC,GACjC,MAAMC,oBAAoD;IACxDL,cAAc;IACdC,UAAU;IACVC,UACE;IACFC,eAAe;IACfC,gBAAgB;AAClB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,uBAAuBC,KAAkB;IACvD,MAAMC,QAAQD,MAAMC,KAAK,EAAEC,SAASF,MAAMC,KAAK,GAAG;WAAIV;KAAsB;IAE5E,OAAOU,MAAME,GAAG,CAAC,CAACC,OAA6B,CAAA;YAC7CC,MAAMD;YACNE,MAAM;YACNC,OAAO;gBACLC,aAAaV,iBAAiB,CAACM,KAAK;YACtC;YACAK,OAAOjB,WAAW,CAACY,KAAK;YACxBM,UAAU;YACVC,YAAYX,MAAMY,IAAI;QACxB,CAAA;AACF"}
|
||||
Vendored
+1
-1
@@ -2,7 +2,7 @@
|
||||
* Built-in "system page" roles — documents from the client's Pages
|
||||
* collection that the site references by function rather than by slug.
|
||||
*/
|
||||
export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService';
|
||||
export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService';
|
||||
/**
|
||||
* All system roles in a stable order (used when no subset is configured).
|
||||
*/
|
||||
|
||||
Vendored
+1
@@ -5,6 +5,7 @@
|
||||
* All system roles in a stable order (used when no subset is configured).
|
||||
*/ export const ALL_SYSTEM_PAGE_ROLES = [
|
||||
'homepage',
|
||||
'notFound',
|
||||
'privacyPolicy',
|
||||
'cookiePolicy',
|
||||
'termsOfService'
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/pages/types.ts"],"sourcesContent":["/**\n * Built-in \"system page\" roles — documents from the client's Pages\n * collection that the site references by function rather than by slug.\n */\nexport type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService'\n\n/**\n * All system roles in a stable order (used when no subset is configured).\n */\nexport const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [\n 'homepage',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n]\n\n/**\n * Plugin option enabling system-page assignments in SiteSettings.\n *\n * The plugin doesn't own the Pages collection — the client creates it in\n * their own project. This option hands the plugin the collection's slug so\n * it can build relationship fields pointing at it. No hardcoding: the slug\n * always comes from the client.\n */\nexport type PagesOption = {\n /**\n * Which system roles to expose as assignable fields.\n * Defaults to all roles when omitted.\n */\n roles?: SystemPageRole[]\n /** Slug of the client's Pages collection, e.g. 'pages'. */\n slug: string\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES"],"mappings":"AAAA;;;CAGC,GAGD;;CAEC,GACD,OAAO,MAAMA,wBAAmD;IAC9D;IACA;IACA;IACA;CACD,CAAA"}
|
||||
{"version":3,"sources":["../../../src/modules/pages/types.ts"],"sourcesContent":["/**\n * Built-in \"system page\" roles — documents from the client's Pages\n * collection that the site references by function rather than by slug.\n */\nexport type SystemPageRole =\n 'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService'\n\n/**\n * All system roles in a stable order (used when no subset is configured).\n */\nexport const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [\n 'homepage',\n 'notFound',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n]\n\n/**\n * Plugin option enabling system-page assignments in SiteSettings.\n *\n * The plugin doesn't own the Pages collection — the client creates it in\n * their own project. This option hands the plugin the collection's slug so\n * it can build relationship fields pointing at it. No hardcoding: the slug\n * always comes from the client.\n */\nexport type PagesOption = {\n /**\n * Which system roles to expose as assignable fields.\n * Defaults to all roles when omitted.\n */\n roles?: SystemPageRole[]\n /** Slug of the client's Pages collection, e.g. 'pages'. */\n slug: string\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES"],"mappings":"AAAA;;;CAGC,GAID;;CAEC,GACD,OAAO,MAAMA,wBAAmD;IAC9D;IACA;IACA;IACA;IACA;CACD,CAAA"}
|
||||
Vendored
+28
-7
@@ -14,7 +14,13 @@ type RobotRule = {
|
||||
export declare const AI_ASSISTANT_BOTS: readonly ["ClaudeBot", "Claude-Web", "Claude-SearchBot", "ChatGPT-User", "OAI-SearchBot", "PerplexityBot", "Perplexity-User"];
|
||||
export declare const AI_TRAINING_BOTS: readonly ["GPTBot", "Google-Extended", "CCBot", "anthropic-ai", "Applebot-Extended", "Bytespider", "Meta-ExternalAgent"];
|
||||
type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false;
|
||||
type BuildRobotsArgs = {
|
||||
export type RobotsOptions = {
|
||||
/**
|
||||
* Admin path to disallow. Default '/admin'. With a hidden panel
|
||||
* (ipalKit adminRoute) pass `false`: robots.txt is public, so listing the
|
||||
* path would reveal it — the admin is noindex anyway.
|
||||
*/
|
||||
adminRoute?: false | string;
|
||||
/** Override the assistant/search bot list. */
|
||||
aiAssistantAgents?: readonly string[];
|
||||
/**
|
||||
@@ -31,13 +37,27 @@ type BuildRobotsArgs = {
|
||||
aiBots?: AiBotsPolicy;
|
||||
/** Override the training crawler list. */
|
||||
aiTrainingAgents?: readonly string[];
|
||||
/** Absolute origin, e.g. 'https://example.com'. */
|
||||
baseUrl: string;
|
||||
/** Paths to disallow. Defaults to Payload's admin and API. */
|
||||
/**
|
||||
* Full disallow list — REPLACES the defaults ([adminRoute, '/api']). Prefer
|
||||
* `extraDisallow` / `disallowParams`, which add to the defaults instead.
|
||||
*/
|
||||
disallow?: string[];
|
||||
/**
|
||||
* Query parameters whose URLs crawlers should skip (thin/duplicate pages that
|
||||
* waste crawl budget), e.g. ['s', 'meter', 'utm_source']. Each becomes
|
||||
* `/*?name=` and `/*&name=` (the parameter may not be first).
|
||||
* Don't list `page` — paginated archives are real, canonical-to-self pages.
|
||||
*/
|
||||
disallowParams?: string[];
|
||||
/** Paths added to the default disallow list, e.g. ['/koszyk']. */
|
||||
extraDisallow?: string[];
|
||||
/** Whether to advertise the sitemap. Defaults to true. */
|
||||
sitemap?: boolean;
|
||||
};
|
||||
type BuildRobotsArgs = {
|
||||
/** Absolute origin, e.g. 'https://example.com'. */
|
||||
baseUrl: string;
|
||||
} & RobotsOptions;
|
||||
/**
|
||||
* Shape for Next's `app/robots.ts`. `rules` may be a single rule or an array
|
||||
* (Next accepts both) — it becomes an array when AI-bot rules are added.
|
||||
@@ -68,10 +88,11 @@ export type RobotsRules = {
|
||||
* PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of
|
||||
* model training, use `aiBots: 'block-training'`. To block them all, 'disallow'.
|
||||
*
|
||||
* Pass custom disallow to block parametrized/thin URLs that waste crawl budget:
|
||||
* Block parametrized/thin URLs that waste crawl budget — added to the defaults:
|
||||
* ```ts
|
||||
* buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] })
|
||||
* buildRobots({ baseUrl, disallowParams: ['s', 'meter'] })
|
||||
* // Disallow: /admin, /api, /*?s=, /*&s=, /*?meter=, /*&meter=
|
||||
* ```
|
||||
*/
|
||||
export declare function buildRobots({ aiAssistantAgents, aiBots, aiTrainingAgents, baseUrl, disallow, sitemap, }: BuildRobotsArgs): RobotsRules;
|
||||
export declare function buildRobots({ adminRoute, aiAssistantAgents, aiBots, aiTrainingAgents, baseUrl, disallow: disallowOverride, disallowParams, extraDisallow, sitemap, }: BuildRobotsArgs): RobotsRules;
|
||||
export {};
|
||||
|
||||
Vendored
+21
-6
@@ -44,15 +44,30 @@ export const AI_TRAINING_BOTS = [
|
||||
* PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of
|
||||
* model training, use `aiBots: 'block-training'`. To block them all, 'disallow'.
|
||||
*
|
||||
* Pass custom disallow to block parametrized/thin URLs that waste crawl budget:
|
||||
* Block parametrized/thin URLs that waste crawl budget — added to the defaults:
|
||||
* ```ts
|
||||
* buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] })
|
||||
* buildRobots({ baseUrl, disallowParams: ['s', 'meter'] })
|
||||
* // Disallow: /admin, /api, /*?s=, /*&s=, /*?meter=, /*&meter=
|
||||
* ```
|
||||
*/ export function buildRobots({ aiAssistantAgents = AI_ASSISTANT_BOTS, aiBots = 'allow', aiTrainingAgents = AI_TRAINING_BOTS, baseUrl, disallow = [
|
||||
'/admin',
|
||||
'/api'
|
||||
], sitemap = true }) {
|
||||
*/ export function buildRobots({ adminRoute = '/admin', aiAssistantAgents = AI_ASSISTANT_BOTS, aiBots = 'allow', aiTrainingAgents = AI_TRAINING_BOTS, baseUrl, disallow: disallowOverride, disallowParams = [], extraDisallow = [], sitemap = true }) {
|
||||
const origin = baseUrl.replace(/\/$/, '');
|
||||
const defaults = [
|
||||
...adminRoute ? [
|
||||
adminRoute
|
||||
] : [],
|
||||
'/api'
|
||||
];
|
||||
const paramRules = disallowParams.map((p)=>p.trim()).filter(Boolean).flatMap((p)=>[
|
||||
`/*?${p}=`,
|
||||
`/*&${p}=`
|
||||
]);
|
||||
const disallow = [
|
||||
...new Set([
|
||||
...disallowOverride ?? defaults,
|
||||
...extraDisallow,
|
||||
...paramRules
|
||||
])
|
||||
];
|
||||
const baseRule = {
|
||||
allow: '/',
|
||||
disallow,
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+10
-1
@@ -1,5 +1,5 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { ContentOption } from '../content/index.js';
|
||||
import type { ContentOption, ResolvedRoute } from '../content/index.js';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
import type { PageMetadata } from './buildMetadata.js';
|
||||
type CreatePageMetadataArgs = {
|
||||
@@ -14,6 +14,15 @@ type CreatePageMetadataArgs = {
|
||||
* omit it and only pages are handled.
|
||||
*/
|
||||
content?: ContentOption;
|
||||
/**
|
||||
* Request-cached loaders (createContentHelpers passes its own), so metadata
|
||||
* reuses the SAME settings read and route resolution as the layout and the
|
||||
* page component instead of querying again. Omit → plain queries.
|
||||
*/
|
||||
loaders?: {
|
||||
getSettings?: (locale: string) => Promise<null | Record<string, unknown>>;
|
||||
resolveRoute?: (locale: string, segments: string[] | undefined, page: number) => Promise<null | ResolvedRoute>;
|
||||
};
|
||||
/** SiteSettings global slug. Defaults to 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
/** Field on SiteSettings holding the site name. Defaults to 'siteName'. */
|
||||
|
||||
+6
-2
@@ -34,11 +34,14 @@ import { slugsAcrossLocales } from './slugsAcrossLocales.js';
|
||||
* }
|
||||
* ```
|
||||
*/ export function createPageMetadata(args) {
|
||||
const { baseUrl, collection = 'pages', config, content, settingsSlug = 'site-settings', siteNameField = 'siteName' } = args;
|
||||
const { baseUrl, collection = 'pages', config, content, loaders, settingsSlug = 'site-settings', siteNameField = 'siteName' } = args;
|
||||
return async function pageMetadata({ slug, locale, page, payload }) {
|
||||
const settings = loaders?.getSettings ? await loaders.getSettings(locale) : undefined;
|
||||
const site = await readSiteMetaConfig({
|
||||
locale,
|
||||
pagesSlug: collection,
|
||||
payload,
|
||||
settings,
|
||||
settingsSlug,
|
||||
siteNameField
|
||||
});
|
||||
@@ -51,13 +54,14 @@ import { slugsAcrossLocales } from './slugsAcrossLocales.js';
|
||||
separator: site.separator,
|
||||
siteName: site.siteName
|
||||
};
|
||||
const route = await resolveRoute({
|
||||
const route = loaders?.resolveRoute ? await loaders.resolveRoute(locale, slug, page ?? 1) : await resolveRoute({
|
||||
content,
|
||||
locale,
|
||||
page,
|
||||
pagesSlug: collection,
|
||||
payload,
|
||||
segments: slug,
|
||||
settings,
|
||||
settingsSlug
|
||||
});
|
||||
// Unknown route (the page component will 404) — still return something
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+1
-1
@@ -12,7 +12,7 @@ export type { PageMetadata } from './buildMetadata.js';
|
||||
export { buildNoindexField } from './buildNoindexField.js';
|
||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
|
||||
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js';
|
||||
export type { RobotsRules } from './buildRobots.js';
|
||||
export type { RobotsOptions, RobotsRules } from './buildRobots.js';
|
||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
|
||||
export { buildSitemapEntries } from './buildSitemapEntries.js';
|
||||
export type { SitemapEntry } from './buildSitemapEntries.js';
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'\nexport { buildSummaryField } from './buildSummaryField.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,WAAW,QAAQ,mBAAkB;AAEnF,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
|
||||
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'\nexport type { RobotsOptions, RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'\nexport { buildSummaryField } from './buildSummaryField.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,WAAW,QAAQ,mBAAkB;AAEnF,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
|
||||
+5
-1
@@ -23,9 +23,13 @@ export type SiteMetaConfig = {
|
||||
* that the separator arrives unpadded, or that the home slug hides inside a
|
||||
* relationship — it should receive a resolved config.
|
||||
*/
|
||||
export declare function readSiteMetaConfig({ locale, payload, settingsSlug, siteNameField, }: {
|
||||
export declare function readSiteMetaConfig({ locale, pagesSlug, payload, settings: preloaded, settingsSlug, siteNameField, }: {
|
||||
locale: string;
|
||||
/** Collection holding the homepage. Default 'pages'. */
|
||||
pagesSlug?: string;
|
||||
payload: BasePayload;
|
||||
/** SiteSettings already read for this locale (depth ≥ 1) — skips the read. */
|
||||
settings?: null | Record<string, unknown>;
|
||||
settingsSlug?: string;
|
||||
siteNameField?: string;
|
||||
}): Promise<SiteMetaConfig>;
|
||||
|
||||
+3
-3
@@ -5,10 +5,10 @@
|
||||
* whatever an editor set in the panel. Metadata generation shouldn't also know
|
||||
* that the separator arrives unpadded, or that the home slug hides inside a
|
||||
* relationship — it should receive a resolved config.
|
||||
*/ export async function readSiteMetaConfig({ locale, payload, settingsSlug = 'site-settings', siteNameField = 'siteName' }) {
|
||||
*/ export async function readSiteMetaConfig({ locale, pagesSlug = 'pages', payload, settings: preloaded, settingsSlug = 'site-settings', siteNameField = 'siteName' }) {
|
||||
// depth 1 populates the homepage relationship, so its slug is available
|
||||
// without a second query.
|
||||
const settings = await payload.findGlobal({
|
||||
const settings = preloaded ?? await payload.findGlobal({
|
||||
slug: settingsSlug,
|
||||
depth: 1,
|
||||
locale: locale
|
||||
@@ -23,7 +23,7 @@
|
||||
try {
|
||||
const homeDoc = await payload.findByID({
|
||||
id: homepage.id,
|
||||
collection: 'pages',
|
||||
collection: pagesSlug,
|
||||
depth: 0,
|
||||
locale: 'all'
|
||||
});
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+40
-1
@@ -1,4 +1,32 @@
|
||||
import type { Plugin } from 'payload';
|
||||
type GenerateFileURL = (args: {
|
||||
filename: string;
|
||||
prefix?: string;
|
||||
}) => string;
|
||||
/**
|
||||
* Minimal shape of `s3Storage` from @payloadcms/storage-s3 — the plugin never
|
||||
* imports that package (it's optional: projects on local disk don't install it).
|
||||
* The project injects the real function; TypeScript checks it fits this shape.
|
||||
*/
|
||||
export type S3StorageFactory = (options: {
|
||||
bucket: string;
|
||||
collections: Record<string, {
|
||||
generateFileURL: GenerateFileURL;
|
||||
} | true>;
|
||||
config: {
|
||||
credentials: {
|
||||
accessKeyId: string;
|
||||
secretAccessKey: string;
|
||||
};
|
||||
endpoint: string;
|
||||
forcePathStyle: boolean;
|
||||
region: string;
|
||||
};
|
||||
}) => Plugin;
|
||||
export type BuildR2StorageDeps = {
|
||||
/** `import { s3Storage } from '@payloadcms/storage-s3'` — required when R2 env is set. */
|
||||
s3Storage?: S3StorageFactory;
|
||||
};
|
||||
/**
|
||||
* Cloudflare R2 media storage — configured from environment variables (agency
|
||||
* infrastructure, not per-project panel data). R2 is S3-compatible, so we use
|
||||
@@ -13,6 +41,17 @@ import type { Plugin } from 'payload';
|
||||
* storage (useful in dev without R2). This mirrors how mailAdapter degrades
|
||||
* gracefully when a transport isn't configured.
|
||||
*
|
||||
* The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse):
|
||||
*
|
||||
* import { s3Storage } from '@payloadcms/storage-s3'
|
||||
* plugins: [buildR2Storage(['media'], { s3Storage })]
|
||||
*
|
||||
* A static import here would make @payloadcms/storage-s3 mandatory for every
|
||||
* project — including ones on local disk — because this module is exported
|
||||
* from the package's main entry.
|
||||
*
|
||||
* @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])
|
||||
* @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set)
|
||||
*/
|
||||
export declare const buildR2Storage: (collections?: string[]) => Plugin;
|
||||
export declare const buildR2Storage: (collections?: string[], deps?: BuildR2StorageDeps) => Plugin;
|
||||
export {};
|
||||
|
||||
+17
-2
@@ -1,4 +1,3 @@
|
||||
import { s3Storage } from '@payloadcms/storage-s3';
|
||||
/**
|
||||
* Cloudflare R2 media storage — configured from environment variables (agency
|
||||
* infrastructure, not per-project panel data). R2 is S3-compatible, so we use
|
||||
@@ -13,10 +12,20 @@ import { s3Storage } from '@payloadcms/storage-s3';
|
||||
* storage (useful in dev without R2). This mirrors how mailAdapter degrades
|
||||
* gracefully when a transport isn't configured.
|
||||
*
|
||||
* The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse):
|
||||
*
|
||||
* import { s3Storage } from '@payloadcms/storage-s3'
|
||||
* plugins: [buildR2Storage(['media'], { s3Storage })]
|
||||
*
|
||||
* A static import here would make @payloadcms/storage-s3 mandatory for every
|
||||
* project — including ones on local disk — because this module is exported
|
||||
* from the package's main entry.
|
||||
*
|
||||
* @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])
|
||||
* @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set)
|
||||
*/ export const buildR2Storage = (collections = [
|
||||
'media'
|
||||
])=>{
|
||||
], deps = {})=>{
|
||||
const bucket = process.env.R2_BUCKET;
|
||||
const endpoint = process.env.R2_ENDPOINT;
|
||||
const accessKeyId = process.env.R2_ACCESS_KEY_ID;
|
||||
@@ -47,6 +56,12 @@ import { s3Storage } from '@payloadcms/storage-s3';
|
||||
prefix,
|
||||
filename
|
||||
].filter(Boolean).join('/') : undefined;
|
||||
// R2 env is complete → the adapter is required. Fail loudly at boot rather
|
||||
// than silently storing media on the container disk (lost on redeploy).
|
||||
const { s3Storage } = deps;
|
||||
if (!s3Storage) {
|
||||
throw new Error('[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' + "Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) " + "with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md.");
|
||||
}
|
||||
const collectionsConfig = {};
|
||||
for (const slug of collections){
|
||||
collectionsConfig[slug] = generateFileURL ? {
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -1 +1,2 @@
|
||||
export { buildR2Storage } from './buildR2Storage.js';
|
||||
export type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js';
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/storage/index.ts"],"sourcesContent":["export { buildR2Storage } from './buildR2Storage.js'\n"],"names":["buildR2Storage"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"}
|
||||
{"version":3,"sources":["../../../src/modules/storage/index.ts"],"sourcesContent":["export { buildR2Storage } from './buildR2Storage.js'\nexport type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js'\n"],"names":["buildR2Storage"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"}
|
||||
@@ -1,264 +0,0 @@
|
||||
# Playbook wdrożenia — ipal-kit
|
||||
|
||||
Sztywna procedura dla pracownika albo AI (Antigravity). Mówi CO robić, W JAKIEJ
|
||||
KOLEJNOŚCI, i CZYM SIĘ KIEROWAĆ. Zasady są twarde, przykłady realne — wzięte z
|
||||
faktycznych błędów, które się zdarzyły. Odstępstwa tylko za świadomą decyzją.
|
||||
|
||||
Powiązane: [standardy-kodu.md](./standardy-kodu.md) (dobre praktyki senior),
|
||||
[publishing.md](./publishing.md) (cykl publikacji), [getting-started.md](./getting-started.md)
|
||||
(nowy projekt), ../antigravity_zasady_agent.md (zasady dla AI).
|
||||
|
||||
---
|
||||
|
||||
## ZŁOTE ZASADY (łam tylko świadomie)
|
||||
|
||||
1. **Nic na sztywno.** Tekst, obraz, link, dane firmy → panel/baza, nie kod.
|
||||
2. **Logika w pluginie, projekt podłącza.** Jeśli piszesz w projekcie coś, co
|
||||
robi już plugin — zatrzymaj się, użyj pluginu.
|
||||
3. **Next 16 = proxy.ts.** NIGDY middleware.ts. Jeśli istnieje — usuń.
|
||||
4. **Weryfikuj każdy etap grepem.** Nie zakładaj, że zadziałało. Sprawdź.
|
||||
5. **Napraw u źródła, nie łataj.** Bez `as any`, `@ts-ignore`, kopii logiki.
|
||||
6. **Zmiana w pluginie nie działa, dopóki nie: build → publish → wciągnięcie.**
|
||||
7. **Zmieniłeś API → zaktualizuj docs w tym samym commicie.** Docs jadą w
|
||||
pakiecie; rozjazd kod↔docs = agent dostaje złą mapę.
|
||||
|
||||
---
|
||||
|
||||
## CZĘŚĆ A — ŁAŃCUCH ZMIANY W PLUGINIE (najważniejsze)
|
||||
|
||||
Najczęstsze źródło frustracji tej sesji: „zmieniłem kod, a nie działa". Prawie
|
||||
zawsze przyczyna: **przerwany łańcuch**. Zmiana w pluginie przechodzi przez
|
||||
PIĘĆ etapów. Pominięcie któregokolwiek = stara wersja w projekcie.
|
||||
|
||||
```
|
||||
źródła (src) → build (dist) → publish (rejestr) → wciągnięcie (node_modules) → restart
|
||||
```
|
||||
|
||||
### Sztywna procedura zmiany w pluginie
|
||||
|
||||
```bash
|
||||
cd ~/payload-cms/ipal-kit
|
||||
|
||||
# 1. ŹRÓDŁA — nanieś zmianę, ZWERYFIKUJ że jest
|
||||
grep -c "<symbol-zmiany>" src/<ścieżka> # MUSI być >0
|
||||
|
||||
# 1b. DOCS — jeśli zmiana dotyka API/zachowania, ZAKTUALIZUJ docs/
|
||||
# (nowa funkcja, zmiana sygnatury, nowe pole panelu, nowy adapter...).
|
||||
# Docs jadą w pakiecie (files: dist, docs) — nieaktualne docs = agent
|
||||
# dostaje złą mapę. Kod i docs publikuj RAZEM.
|
||||
|
||||
# 2. BUILD — zbuduj, ZWERYFIKUJ że dist ma zmianę
|
||||
pnpm build
|
||||
grep -c "<symbol-zmiany>" dist/<ścieżka> # MUSI być >0
|
||||
|
||||
# 3. COMMIT (PRZED version — inaczej "working directory not clean")
|
||||
git add -A && git commit -m "opis"
|
||||
|
||||
# 4. VERSION + PUBLISH
|
||||
npm version patch # czyste repo wymagane
|
||||
npm publish
|
||||
|
||||
# 5. PUSH
|
||||
git push && git push --tags
|
||||
|
||||
# 6. PROJEKT — wciągnij, ZWERYFIKUJ że node_modules ma zmianę
|
||||
cd ~/<projekt>
|
||||
pnpm add @intecion/ipal-kit@<nowa-wersja>
|
||||
grep -c "<symbol-zmiany>" node_modules/@intecion/ipal-kit/dist/<ścieżka> # MUSI być >0
|
||||
|
||||
# 7. RESTART dev (Payload buduje adaptery/config przy starcie!)
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
### TRZY punkty kontrolne grep (nie pomijaj żadnego)
|
||||
|
||||
| Etap | Grep | Jeśli 0 |
|
||||
|---|---|---|
|
||||
| po edycji | `src/...` | zmiana nie zapisana / zły plik |
|
||||
| po build | `dist/...` | build nie złapał / błąd typów |
|
||||
| po pnpm add | `node_modules/...` | projekt ma starą wersję |
|
||||
|
||||
**Realny przykład (z tej sesji):** `buildSecurityHeaders is not a function`.
|
||||
Przyczyna: moduł istniał w `src`, ale NIE był wyeksportowany w `src/index.ts`
|
||||
→ `dist` go nie miał → import w projekcie = undefined. Grep `dist/index.js`
|
||||
pokazał 0. Naprawa: dodać eksport, przejść łańcuch od nowa.
|
||||
|
||||
### Pułapki kolejności (realne błędy sesji)
|
||||
|
||||
- **`npm version` przed commitem** → "Git working directory not clean". ZAWSZE
|
||||
commit przed version.
|
||||
- **`npm publish` bez `pnpm build`** → publikujesz STARY dist. ZAWSZE build przed
|
||||
publish, grep dist po buildzie.
|
||||
- **`pnpm add` przy działającym dev** → proces ma stary adapter w pamięci.
|
||||
Payload czyta email/config przy starcie. ZAWSZE restart po wciągnięciu.
|
||||
- **Publikacja bez aktualizacji docs** → agent (Antigravity) po `pnpm add`
|
||||
czyta `node_modules/@intecion/ipal-kit/docs/` z NIEAKTUALNĄ mapą. Jeśli
|
||||
zmieniłeś API — docs w tym samym commicie.
|
||||
|
||||
---
|
||||
|
||||
## CZĘŚĆ B — GREP JAKO NARZĘDZIE (jak weryfikować dobrze)
|
||||
|
||||
Grep był w tej sesji głównym narzędziem diagnozy. Ale trzeba go używać mądrze.
|
||||
|
||||
### Reguła: grepuj TOKENY, nie całe frazy z kolejnością
|
||||
|
||||
**Realny błąd:** grep `"env.sender, name: senderName"` dał 0, choć kod był OK —
|
||||
bo plik miał odwróconą kolejność kluczy (`name: senderName, address: env.sender`).
|
||||
Obiekt JS ignoruje kolejność, ale grep nie.
|
||||
|
||||
```bash
|
||||
# ŹLE — zależny od kolejności/formatowania:
|
||||
grep -c "env.sender, name: senderName" plik.ts # 0 mimo poprawnego kodu
|
||||
|
||||
# DOBRZE — pojedynczy token, odporny:
|
||||
grep -c "senderName" plik.ts # 3 ✓
|
||||
```
|
||||
|
||||
Grepuj **nazwę symbolu** (funkcja, zmienna, eksport), nie całą linię z interpunkcją.
|
||||
|
||||
---
|
||||
|
||||
## CZĘŚĆ C — DIAGNOSTYKA „KOD DOBRY, ZACHOWANIE ZŁE"
|
||||
|
||||
Gdy grep potwierdza kod, wersja nowa, a zachowanie stare — przejdź listę:
|
||||
|
||||
1. **Dev nie zrestartowany?** Payload buduje adaptery/config przy starcie.
|
||||
Ctrl+C + `pnpm dev`. (Najczęstsza przyczyna.)
|
||||
2. **Zmiana zapisana w panelu?** Endpointy czytają z BAZY, nie z pola na ekranie.
|
||||
Kliknij Save.
|
||||
3. **Zdublowana zależność?** `@payloadcms/ui` w node_modules pluginu = dwie
|
||||
instancje = hooki bez kontekstu. Sprawdź:
|
||||
`ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms/ui`
|
||||
Jest? → peerDependency problem (patrz Część D).
|
||||
4. **Cache klienta?** Np. klient pocztowy pokazuje zapamiętaną nazwę nadawcy
|
||||
mimo poprawnych nagłówków. Sprawdź surowe źródło (View Source), wyślij na
|
||||
inny adres.
|
||||
5. **Import map nieaktualny?** Custom komponenty Payload:
|
||||
`npx payload generate:importmap`.
|
||||
|
||||
**Realny przykład:** MaskedField rzucał "Cannot destructure property 'config'".
|
||||
Kod OK. Przyczyna: dublet `@payloadcms/ui` (plugin miał własną kopię) →
|
||||
`useField` z jednej instancji nie widział kontekstu z drugiej. Naprawa w Część D.
|
||||
|
||||
---
|
||||
|
||||
## CZĘŚĆ D — peerDependencies (dublety zależności)
|
||||
|
||||
**Zasada:** wszystko, co dostarcza PROJEKT, jest `peerDependency` w pluginie,
|
||||
NIE `dependency`. Inaczej menedżer instaluje własną kopię dla pluginu → dublet
|
||||
→ React/Payload context się rozjeżdża (dwie instancje nie widzą się nawzajem).
|
||||
|
||||
Peer (projekt dostarcza): `payload`, `@payloadcms/ui`, `@payloadcms/next`,
|
||||
`@payloadcms/plugin-*`, `react`, `react-dom`, `next`.
|
||||
|
||||
**Realny błąd:** `@payloadcms/ui` był tylko w devDependencies (brak w peer) →
|
||||
pnpm dołożył kopię pluginowi → MaskedField/TestEmailButton/CookieBanner
|
||||
wszystkie się psuły (hooki bez kontekstu). Naprawa: dodać do peerDependencies,
|
||||
opublikować, w projekcie `rm -rf node_modules/@intecion/ipal-kit && pnpm add`.
|
||||
|
||||
Weryfikacja braku dubletu:
|
||||
```bash
|
||||
ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms/ui 2>/dev/null \
|
||||
&& echo "DUBLET ✗" || echo "OK ✓"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CZĘŚĆ E — NOWY PROJEKT KLIENCKI (kolejność)
|
||||
|
||||
Pełne szczegóły: [getting-started.md](./getting-started.md). Tu skrót kolejności.
|
||||
|
||||
1. **Szkielet** Payload 3 + Next 16, pnpm, Node 22
|
||||
2. **`.npmrc`** — `legacy-peer-deps=true` + rejestr `@intecion`
|
||||
3. **`pnpm add @intecion/ipal-kit`** + zależności peer
|
||||
4. **build script z `--webpack`** (Next 16 + Payload; Turbopack konfliktuje)
|
||||
5. **i18n.config.ts** — jedno źródło locale
|
||||
6. **payload.config.ts** — ipalKit({...}), `email: mailAdapter()`
|
||||
7. **Kolekcje/globale** — wszystko localized/upload (nic na sztywno)
|
||||
8. **lib/content.ts + lib/payload.ts** — helpery, jedno źródło getCachedPayload
|
||||
9. **proxy.ts** (NIE middleware.ts) — routing locale, obsługa roota
|
||||
10. **Bloki** — dane przez enhanceProps, nie import lib (cykl)
|
||||
11. **buildSlugField** zamiast ręcznego slug; **buildNoindexField** na pole noindex
|
||||
12. **getLocalizedSlugs** zamiast zaszytej mapy ścieżek
|
||||
13. **buildSecurityHeaders** w next.config
|
||||
14. **instrumentation.ts** — `assertEnv(ipalEnvRules({...}))` (walidacja ENV na starcie)
|
||||
15. **Route'y z bazą** (`manifest.ts`, `llms.txt/route.ts`, `sitemap.xml/route.ts`) — `export const dynamic = 'force-dynamic'`
|
||||
16. **resolveRedirect** w catch-all (+ `trackSlugHistoryHook` i pole `slugHistory` w kolekcjach)
|
||||
17. **Formularz** — `useContactForm`/`useForm` (logika z pluginu, markup w projekcie)
|
||||
18. **Test:** root `/` przekierowuje, formularz wysyła, panel działa, zmiana slug → 308 na nowy URL
|
||||
|
||||
---
|
||||
|
||||
## CZĘŚĆ F — EMAIL (SMTP vs Graph)
|
||||
|
||||
Pełne szczegóły: [email.md](./email.md). Decyzja transportu:
|
||||
|
||||
- **Klient na M365/Exchange** → Graph (SMTP AUTH na M365 często wyłączony)
|
||||
- **Klient z własnym SMTP / Gmail** → SMTP
|
||||
- **Przełącznik:** panel → Site Integrations → SMTP → Email Transport
|
||||
- **Dyspozytor:** `email: mailAdapter()` czyta wybór przy każdej wysyłce
|
||||
|
||||
### Graph — checklist wdrożenia (Wasza strona, jednorazowo)
|
||||
|
||||
1. Azure: App registration → tenantId, clientId, clientSecret
|
||||
2. Azure: Mail.Send APPLICATION permission + **Grant admin consent**
|
||||
3. `.env` projektu: GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER
|
||||
4. Panel: From Name (nazwa nadawcy), From Address (→ reply-to)
|
||||
|
||||
### Realne pułapki Graph (wszystkie zdarzyły się w sesji)
|
||||
|
||||
| Błąd | Przyczyna | Naprawa |
|
||||
|---|---|---|
|
||||
| `ErrorSendAsDenied` | `from` ≠ sender | from.address = GRAPH_SENDER, klient w replyTo |
|
||||
| nazwa „Noreply" mimo panelu | Exchange nadpisuje / cache klienta | display name skrzynki / sprawdź nagłówki |
|
||||
| `Insufficient privileges` | brak admin consent | Grant admin consent w Azure |
|
||||
| `AADSTS1002012` | zły scope | scope = `.../.default`, nie Mail.Send |
|
||||
|
||||
**Zasada from/replyTo:** `from.address` ZAWSZE = GRAPH_SENDER (wspólna skrzynka,
|
||||
zero Send-As). Nazwa (`from.name`) z panelu — różna per projekt. Adres klienta
|
||||
→ replyTo (odpowiedzi trafiają do klienta).
|
||||
|
||||
---
|
||||
|
||||
## CZĘŚĆ G — CO NALEŻY DO PLUGINU, A CO DO PROJEKTU
|
||||
|
||||
Powtarzalne pytanie. Reguła: **jeśli zależy od danych/domen konkretnego projektu
|
||||
→ projekt. Jeśli identyczne wszędzie → plugin.**
|
||||
|
||||
| Rzecz | Gdzie | Dlaczego |
|
||||
|---|---|---|
|
||||
| i18n, SEO meta, forms, consent, blog | plugin | uniwersalne |
|
||||
| Powiadomienia (teksty wyników) | plugin | uniwersalne, per język z panelu |
|
||||
| Zgoda RODO (enforcement) | plugin | uniwersalne, server-side |
|
||||
| Nagłówki bezpieczeństwa (HSTS...) | plugin | identyczne wszędzie |
|
||||
| Email (SMTP + Graph) | plugin | uniwersalne, konfiguracja z panelu/env |
|
||||
| **CSP** | **projekt** | zależy od domen projektu |
|
||||
| **schema.org / JSON-LD** | **projekt** | zależy od danych firmy |
|
||||
| **Breadcrumbs** | **projekt** | render z danych routingu projektu |
|
||||
| **Dane rejestrowe firmy** | **projekt** | różne per typ firmy |
|
||||
|
||||
---
|
||||
|
||||
## CZĘŚĆ H — CHECKLIST PRZED „GOTOWE"
|
||||
|
||||
Nie mów „działa", dopóki:
|
||||
|
||||
- [ ] `pnpm build --webpack` przechodzi lokalnie (nie tylko dev)
|
||||
- [ ] root `/` przekierowuje na locale (bez middleware.ts)
|
||||
- [ ] formularz wysyła (test przez panel: Send test)
|
||||
- [ ] panel: wszystkie teksty/obrazy edytowalne (nic na sztywno)
|
||||
- [ ] brak dubletu @payloadcms/ui (Część D)
|
||||
- [ ] grep potwierdza wersję pluginu w node_modules
|
||||
- [ ] sekrety w .env (nie w repo), maskowane w panelu
|
||||
- [ ] brak plików middleware.ts, brak zaszytej mapy slugów
|
||||
- [ ] strona 404 (not-found.tsx) — edytowalna, per język, link powrotu
|
||||
- [ ] app/robots.ts + app/sitemap.ts wystawione (Google widzi strony)
|
||||
- [ ] `export const dynamic = 'force-dynamic'` na manifest.ts, llms.txt, sitemap.xml (build bez bazy nie wywala)
|
||||
- [ ] `instrumentation.ts` z `assertEnv(ipalEnvRules({...}))` — build/boot łapie brak ENV
|
||||
- [ ] zmiana slug → stary URL robi 308 na nowy (resolveRedirect + slugHistory)
|
||||
- [ ] obrazki w blokach: po zapisie w jednym języku są też w pozostałych (buildCrossLocaleFieldSync)
|
||||
- [ ] favicon PNG (nie SVG) w buildIconsMetadata; structured data (Organization, WebSite)
|
||||
- [ ] formularz: logika z useForm/useContactForm (NIE skopiowana hydraulika), pola/teksty z buildera
|
||||
- [ ] compliance: polityki, baner cookies, zgoda RODO w formularzach
|
||||
(patrz [wymagania-prawne.md](./wymagania-prawne.md))
|
||||
+36
-148
@@ -1,152 +1,40 @@
|
||||
# IPAL — Dokumentacja modułów
|
||||
# Dokumentacja @intecion/ipal-kit
|
||||
|
||||
> **Zaczynasz wdrożenie?** Przeczytaj najpierw [WDROZENIE-PLAYBOOK.md](./WDROZENIE-PLAYBOOK.md) — sztywna procedura, kolejność, realne przykłady błędów.
|
||||
| Kim jesteś | Czytaj |
|
||||
|---|---|
|
||||
| **Agent AI** pracujący w projekcie | [AGENT.md](./agent/AGENT.md) — reguły, struktura, budowa sekcji, kontrole przed „gotowe” |
|
||||
| **Agent AI — skille** | [agent/skills/](./agent/skills) — 7 skilli `ipal-*` dla Antigravity/Claude Code (kopiowane do projektu: `pnpm ipal:skills`, AGENT.md §14) |
|
||||
| **Programista** | [PROGRAMISTA.md](./dev/PROGRAMISTA.md) — instalacja, nowy projekt, env, wdrożenie, aktualizacja, publikacja pluginu, Gitea |
|
||||
| **Osoba prowadząca agenta AI** | [vibe.md](./dev/vibe.md) — gotowe polecenia do wklejenia, krok po kroku, moduł po module |
|
||||
|
||||
**Instalacja pakietu** (token Gitea, rejestr vs repozytorium) → główny
|
||||
[README](../README.md).
|
||||
**Nowy projekt krok po kroku** → [getting-started.md](./getting-started.md).
|
||||
Szczegóły API — jeden plik na moduł:
|
||||
|
||||
Ta dokumentacja opisuje **konfigurację i moduły** pluginu — zakłada, że
|
||||
`@intecion/ipal-kit` jest już zainstalowany.
|
||||
| Moduł | Plik |
|
||||
|---|---|
|
||||
| Role i dostęp do panelu | [access.md](./access.md) |
|
||||
| Widget dostępności (opcjonalny) | [accessibility.md](./accessibility.md) |
|
||||
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
|
||||
| Bloki, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
|
||||
| Zgoda cookies, baner | [consent.md](./consent.md) |
|
||||
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](./content.md) |
|
||||
| Email SMTP / Graph | [email.md](./email.md) |
|
||||
| Walidacja env | [env.md](./env.md) |
|
||||
| Formularze, useForm, honeypot | [forms.md](./forms.md) |
|
||||
| Hooki | [hooks.md](./hooks.md) |
|
||||
| i18n, proxy, przełącznik języka | [i18n.md](./i18n.md) |
|
||||
| Linki / CTA: buildLinkField, buildLinksField, resolveLinkHref | [links.md](./links.md) |
|
||||
| Serwer MCP strony | [mcp.md](./mcp.md) |
|
||||
| Komunikaty formularzy | [notifications.md](./notifications.md) |
|
||||
| Strony systemowe, 404, generateStaticParams | [pages.md](./pages.md) |
|
||||
| Helpery Payload | [payload-helpers.md](./payload-helpers.md) |
|
||||
| Rich text | [richtext.md](./richtext.md) |
|
||||
| Nagłówki, CSP, 2FA | [security.md](./security.md) |
|
||||
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](./seo.md) |
|
||||
| Auto-slug | [slug.md](./slug.md) |
|
||||
| Media, R2 | [storage.md](./storage.md) |
|
||||
| Turnstile | [turnstile.md](./turnstile.md) |
|
||||
| White-label panelu | [white-label.md](./white-label.md) |
|
||||
|
||||
IPAL (Intecion Payload Advanced Library) to plugin do Payload CMS 3, który
|
||||
dostarcza logikę i konfigurację; projekt klienta zawiera tylko komponenty
|
||||
wizualne i podłączenia do Next.js.
|
||||
|
||||
## Zasada
|
||||
|
||||
- **Plugin** = logika, helpery, konfiguracja, globale.
|
||||
- **Klient (projekt)** = komponenty (wygląd), pliki-podłączenia Next.js
|
||||
(jednolinijkowe re-eksporty), konfiguracja front.
|
||||
|
||||
## Konfiguracja i wpięcie
|
||||
|
||||
### Wymagane zależności
|
||||
|
||||
Projekt klienta musi mieć (poza payloadem):
|
||||
|
||||
```json
|
||||
"dependencies": {
|
||||
"@payloadcms/plugin-seo": "3.84.1",
|
||||
"@payloadcms/plugin-form-builder": "3.84.1",
|
||||
"nodemailer": "^8.0.1",
|
||||
"lucide-react": "^0.400.0",
|
||||
"slugify": "^1.6.6",
|
||||
"server-only": "^0.0.1"
|
||||
}
|
||||
```
|
||||
|
||||
Wersje `@payloadcms/*` **muszą** być identyczne z wersją `payload`. Wymuś
|
||||
spójność przez `pnpm.overrides` (patrz niżej), inaczej Payload odrzuci wpięcie
|
||||
pluginów (pusty tab SEO, brak kolekcji Forms) albo crashuje.
|
||||
|
||||
```json
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"payload": "3.84.1",
|
||||
"@payloadcms/ui": "3.84.1",
|
||||
"@payloadcms/next": "3.84.1",
|
||||
"@payloadcms/db-sqlite": "3.84.1",
|
||||
"@payloadcms/richtext-lexical": "3.84.1",
|
||||
"@payloadcms/plugin-seo": "3.84.1",
|
||||
"@payloadcms/plugin-form-builder": "3.84.1"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Po wpięciu — wygeneruj importMap
|
||||
|
||||
Plugin dostarcza komponenty admina (pola SEO). Po dodaniu uruchom:
|
||||
|
||||
```bash
|
||||
pnpm payload generate:importmap
|
||||
```
|
||||
|
||||
Bez tego pola SEO nie wyrenderują się (błąd `PayloadComponent not found in
|
||||
importMap`).
|
||||
|
||||
```ts
|
||||
// payload.config.ts
|
||||
import { ipalKit } from '@intecion/ipal-kit'
|
||||
|
||||
export default buildConfig({
|
||||
// ...
|
||||
plugins: [
|
||||
ipalKit({
|
||||
i18n: {
|
||||
defaultLocale: 'pl',
|
||||
locales: [
|
||||
{ code: 'pl', label: 'Polski' },
|
||||
{ code: 'en', label: 'English' },
|
||||
],
|
||||
},
|
||||
access: { authCollection: 'users' },
|
||||
pages: { slug: 'pages' },
|
||||
seo: { collections: ['pages', 'posts'] },
|
||||
forms: { redirectRelationships: ['pages'] },
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Entry pointy pakietu
|
||||
|
||||
| Import | Zawiera | Kontekst |
|
||||
|---|---|---|
|
||||
| `@intecion/ipal-kit` | logika server-safe, plugin, helpery | server / config |
|
||||
| `@intecion/ipal-kit/server` | runtime server-only (sendEmail, verifyTurnstile, submitForm) | Server Actions / route handlers |
|
||||
| `@intecion/ipal-kit/client` | komponenty client (consent, Turnstile, Analytics) | `'use client'` |
|
||||
| `@intecion/ipal-kit/rsc` | RenderBlocks (RSC) | server component |
|
||||
| `@intecion/ipal-kit/next/middleware` | locale middleware (import bez zmian) | `proxy.ts` (Next 16; dawniej `middleware.ts`) |
|
||||
|
||||
## Moduły
|
||||
|
||||
| Moduł | Opis | Dok |
|
||||
|---|---|---|
|
||||
| i18n | Lokalizacja, negocjacja locale, ścieżki URL, strona jednojęzyczna | [i18n.md](./i18n.md) |
|
||||
| hooks | Hooki: revalidate ISR, slug history, cross-locale sync, noindex, ochrona | [hooks.md](./hooks.md) |
|
||||
| env | Walidacja zmiennych środowiskowych na starcie (assertEnv, fail fast) | [env.md](./env.md) |
|
||||
| mcp | Read-only serwer MCP strony — Claude/agent podłącza się i odpytuje treść | [mcp.md](./mcp.md) |
|
||||
| kolekcje-katalog | Jakie kolekcje budować, kiedy, jak wpiąć (minimum nie maksimum) | [kolekcje-katalog.md](./kolekcje-katalog.md) |
|
||||
| fundamenty-projektu | Struktura katalogów, nazewnictwo, konwencje | [fundamenty-projektu.md](./fundamenty-projektu.md) |
|
||||
| deployment | Zmienne .env, ISR/SSG, force-dynamic, Coolify/Docker | [deployment.md](./deployment.md) |
|
||||
| pages | System pages (homepage/privacy/cookies) → ścieżki | [pages.md](./pages.md) |
|
||||
| access | Role admin > editor > user, kontrola dostępu | [access.md](./access.md) |
|
||||
| payload-helpers | getSiteSettings / getSiteIntegrations | [payload-helpers.md](./payload-helpers.md) |
|
||||
| seo | Metadata, hreflang, auto-fill, plugin-seo | [seo.md](./seo.md) |
|
||||
| migration | Migracja projektu na nową wersję | [migration.md](./migration.md) |
|
||||
| AGENTS-TEMPLATE | Szablon agents.md do roota nowego projektu | [AGENTS-TEMPLATE.md](./AGENTS-TEMPLATE.md) |
|
||||
| wymagania-prawne | **Polityki, regulaminy, baner cookies, RODO (compliance)** | [wymagania-prawne.md](./wymagania-prawne.md) |
|
||||
| standardy-kodu | **Dobre praktyki senior: typy, architektura, antywzorce** | [standardy-kodu.md](./standardy-kodu.md) |
|
||||
| architektura-tresci | **Jak budować, żeby klient wszystko edytował** (filozofia CMS) | [architektura-tresci.md](./architektura-tresci.md) |
|
||||
| blocks | RenderBlocks — silnik renderowania bloków | [blocks.md](./blocks.md) |
|
||||
| accessibility | Widget dostępności (WCAG): tekst, kontrast, szarość, animacje | [accessibility.md](./accessibility.md) |
|
||||
| consent | Banner cookies GDPR, Google Consent Mode | [consent.md](./consent.md) |
|
||||
| turnstile | Cloudflare Turnstile (widget + verify) | [turnstile.md](./turnstile.md) |
|
||||
| email | Wysyłka: SMTP z panelu lub Microsoft Graph (M365) | [email.md](./email.md) |
|
||||
| forms | Form-builder + submitForm + useForm/useContactForm (logika klienta) | [forms.md](./forms.md) |
|
||||
| analytics | GA4 / GTM spięte z Consent Mode, pushDataLayer | [analytics.md](./analytics.md) |
|
||||
| gtm-meta-pixel | Konfiguracja GTM + Meta Pixel krok po kroku (pod ten stack) | [gtm-meta-pixel.md](./gtm-meta-pixel.md) |
|
||||
| slug | Auto-slug z tytułu, per locale | [slug.md](./slug.md) |
|
||||
| notifications | Teksty wyników akcji (formularz) per język | [notifications.md](./notifications.md) |
|
||||
| storage | Media na Cloudflare R2 (offload z .env) | [storage.md](./storage.md) |
|
||||
| security | Nagłówki bezpieczeństwa HTTP (HSTS, X-Frame...) | [security.md](./security.md) |
|
||||
| white-label | Branding panelu admina (logo + nazwa z SiteSettings) | [white-label.md](./white-label.md) |
|
||||
| content | Blog/archiwa: kolekcje pod stroną-archiwum, listing, paginacja, redirecty (resolveRedirect) | [content.md](./content.md) |
|
||||
|
||||
Nowy projekt krok po kroku: [getting-started.md](./getting-started.md)
|
||||
Referencja wdrożenia frontu: [getting-started.md](./getting-started.md)
|
||||
Wydawanie nowych wersji wtyczki: [publishing.md](./publishing.md)
|
||||
Jak komendy łączą się z Gitea (dla instalujących): [gitea-commands.md](./gitea-commands.md)
|
||||
Working with a project repo on Gitea (clone/pull/push): [gitea-workflow.md](./gitea-workflow.md) · [🇵🇱 PL](./gitea-workflow.pl.md)
|
||||
|
||||
## Zasady dla wszystkich modułów
|
||||
|
||||
1. **Helpery przyjmują `payload` jako argument** — plugin nigdy nie woła
|
||||
`getPayload` sam.
|
||||
2. **Sekrety w panelu** — SMTP, Turnstile secret, R2 w SiteIntegrations
|
||||
(admin-only). Odczyt server-side przez Local API.
|
||||
3. **Client/server split** — kod z sekretami ma `server-only`; komponenty
|
||||
client w `@intecion/ipal-kit/client`.
|
||||
4. **Generyki na typy klienta** — helpery przyjmują `<T>` (np. wygenerowany
|
||||
`SiteSetting`), bo plugin nie zna typów projektu.
|
||||
Zasada utrzymania: zmiana API modułu → aktualizacja jego pliku w tym samym
|
||||
commicie. Nowe reguły pracy → AGENT.md. Nowy krok procesu → PROGRAMISTA.md. Nowy etap budowy → vibe.md.
|
||||
Nie dodawaj kolejnych plików ogólnych.
|
||||
|
||||
+1
-1
@@ -76,4 +76,4 @@ import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/
|
||||
```ts
|
||||
import { ROLE_HIERARCHY } from '@intecion/ipal-kit'
|
||||
// ['user', 'editor', 'admin'] — wyższa rola spełnia wymóg niższej
|
||||
```
|
||||
```
|
||||
|
||||
@@ -190,4 +190,4 @@ to **opcja, nie obowiązek** — dodawaj gdy klient wymaga, nie z automatu.
|
||||
Gdy dodajesz: widget sam w sobie NIE czyni strony w pełni dostępną — to pomoc dla
|
||||
użytkownika. Pełna dostępność to też semantyczny HTML, alt teksty, nawigacja
|
||||
klawiaturą, kontrast bazowy. Widget uzupełnia, nie zastępuje. Nie sprzedawaj
|
||||
klientowi „mamy widget = jesteśmy zgodni z WCAG". Patrz wymagania-prawne.md.
|
||||
klientowi „mamy widget = jesteśmy zgodni z WCAG". Patrz PROGRAMISTA.md §5.
|
||||
|
||||
@@ -0,0 +1,670 @@
|
||||
# AGENT.md — reguły dla AI (Payload 3 + Next 16 + @intecion/ipal-kit)
|
||||
|
||||
> **Dla kogo:** agent AI (Antigravity, Claude Code, Cursor) pracujący w projekcie
|
||||
> klienta na ipal-kit. **Przeczytaj w całości przed pierwszą zmianą.** Reguły są
|
||||
> twarde, bez obejść. Szczegóły API każdego modułu: `docs/<moduł>.md` (mapa w
|
||||
> §12). Instalacja, wdrożenie, migracja i Gitea to dokument dla ludzi:
|
||||
> [PROGRAMISTA.md](../dev/PROGRAMISTA.md).
|
||||
>
|
||||
> **W projekcie:**
|
||||
> - w roocie krótki `AGENTS.md` (szablon w §13), który wskazuje na ten plik w
|
||||
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` — nie kopiuj reguł, kopia się zestarzeje;
|
||||
> - skille w `.agents/skills/` (§14) — kopiowane z pakietu jedną komendą, odświeżane
|
||||
> po każdej aktualizacji ipal-kit.
|
||||
|
||||
---
|
||||
|
||||
## 0. KOMPAS (jeśli zapamiętasz tylko to)
|
||||
|
||||
1. **ipal-kit jest obowiązkowy.** Funkcja, którą plugin ma, idzie przez plugin.
|
||||
Brakuje czegoś → zgłoś (§1.3), nie łataj w projekcie.
|
||||
2. **Nic na sztywno.** Tekst, obraz, link, plik, dane firmy → panel. Domeny,
|
||||
klucze → `.env`. Także w fallbacku `||` i w `catch`.
|
||||
3. **Next 16 = `proxy.ts`.** NIGDY `middleware.ts`.
|
||||
4. **Bez jawnego `<head>`, z ISR i `generateStaticParams`** — inaczej metadata
|
||||
ląduje w `<body>` i SEO pada.
|
||||
5. **Minimum kolekcji.** Users są wbudowane, dane firmy/nawigacja to globale,
|
||||
FAQ/hero to bloki.
|
||||
6. **Sekcja = kompozycja prymitywów.** `buildLinksField()` + `<CMSLink>`, upload +
|
||||
`<Media>`, `<Section>` + `<SectionHeader>`. Zero pól `ctaLabel`/`pdfUrl`.
|
||||
7. **Renderery z pluginu:** `RenderBlocks` (nie `switch`), `RenderRichText` (nie
|
||||
własny parser Lexical), `useForm` (nie ręczna hydraulika formularza).
|
||||
8. **Zero `any` i `@ts-ignore`.** Typy z `@/payload-types`, `unknown` + guard.
|
||||
9. **Jedno źródło prawdy** — `i18n.config.ts`, `lib/content.ts`, nigdy kopie.
|
||||
10. **„Gotowe” dopiero po** lokalnym `pnpm build` + kontrolach z §11.
|
||||
|
||||
---
|
||||
|
||||
## 1. ipal-kit JEST OBOWIĄZKOWY
|
||||
|
||||
### 1.1 Zanim napiszesz cokolwiek
|
||||
Sprawdź, czy plugin to ma: docs modułu (§12) i typy
|
||||
`node_modules/@intecion/ipal-kit/dist/**/*.d.ts`. Nie zgaduj sygnatur. Jeśli
|
||||
plugin to ma — użyj go. Własna wersja istniejącej funkcji pluginu to błąd.
|
||||
|
||||
### 1.2 Co należy do pluginu, a co do projektu
|
||||
Reguła: **identyczne w każdym projekcie → plugin. Zależy od klienta → projekt.**
|
||||
|
||||
| Plugin (używasz) | Projekt (piszesz) |
|
||||
|---|---|
|
||||
| i18n, routing, slug, SEO meta, sitemap, hreflang | bloki: schemat + wygląd |
|
||||
| formularze, zgoda RODO, Turnstile, email | globale Company/Header/Footer (model danych zależy od kraju: NIP/ABN/EIN) |
|
||||
| consent, analytics/pixele | CSP (domeny projektu) |
|
||||
| nagłówki bezpieczeństwa, 2FA, white-label | schema.org: mapowanie SWOICH danych na `@type` |
|
||||
| hooki (revalidate, slugHistory, cross-locale), strony systemowe, storage R2 | wygląd (Tailwind, DESIGN.md) |
|
||||
|
||||
### 1.3 Gdy w pluginie czegoś brakuje albo nie działa
|
||||
**Zatrzymaj się. Nie łataj w projekcie** (hook z zaszytą wartością, własny
|
||||
helper, `as any`). To prawie zawsze znak, że plugin już to ma (sprawdź docs) albo
|
||||
pluginowi tego brakuje. Przygotuj raport:
|
||||
- opis problemu / brakującej funkcji,
|
||||
- proponowane API (sygnatura funkcji / opcji),
|
||||
- dlaczego to uniwersalne (przyda się w innych projektach).
|
||||
|
||||
Realne błędy: hook `afterRead` w Media z `https://media.klient.pl` (plugin generuje
|
||||
URL z `R2_PUBLIC_URL`), `<link rel="preconnect">` z zaszytą domeną (plugin ma
|
||||
`<MediaPreconnect/>`), skopiowany komponent `Analytics` w projekcie z usuniętym
|
||||
gatingiem zgody (plugin ma opcję `defer`).
|
||||
|
||||
---
|
||||
|
||||
## 2. ZAKAZ HARDKODOWANIA
|
||||
|
||||
| Co | ZAKAZ | WYMAGANE |
|
||||
|---|---|---|
|
||||
| Tekst | tekst w JSX, `if (locale === 'pl')`, tablice tekstów w kodzie | pole `localized: true` z panelu |
|
||||
| Obraz / plik | `import x from '@/assets/…'`, `src="/images/…"`, URL pliku w polu `text` | `upload → media` + `<Media>` / link typu `file` |
|
||||
| Link | `href="/pl/kontakt"`, menu jako tablica, mapa `localizedRoutes` | `buildLinkField()` + `<CMSLink>`, `getLocalizedSlugs`, `getSystemPagePath`, nawigacja jako relationship → pages |
|
||||
| Konfiguracja | `locale as 'pl' \| 'en'`, zaszyty slug kolekcji, lista języków `['pl','en']` | `i18n.config.ts`, `locale as never`, lista z configu |
|
||||
| Dane firmy | NIP, adres, telefon, nazwa w kodzie | global (`siteSettings` / `company`) |
|
||||
| Infrastruktura | domena, klucz, bucket w kodzie | `.env` |
|
||||
|
||||
**Ukryty hardkod w fallbacku (częsty):** `siteName || 'Kancelaria X'`,
|
||||
`catch { return { name: 'Firma…' } }`, `theme_color: '#0e1e24'`. Gdy panel nie
|
||||
zwróci danych → **pomiń pole** (`...(name ? { name } : {})`), nie wstawiaj
|
||||
wartości klienta. Inny projekt skopiuje kod i pokaże cudze dane.
|
||||
|
||||
Favicon: `buildIconsMetadata(settings.favicon)` (PNG, nie ręczny SVG).
|
||||
Preconnect CDN: `<MediaPreconnect />` (z env). Media: `normalizeFilenameHook`.
|
||||
|
||||
---
|
||||
|
||||
## 3. STRUKTURA PROJEKTU I NAZEWNICTWO
|
||||
|
||||
```
|
||||
src/
|
||||
app/
|
||||
(frontend)/
|
||||
styles.css # Tailwind + @source na node_modules/@intecion/ipal-kit/dist
|
||||
[locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md)
|
||||
layout.tsx # bez <head>; ConsentProvider + Analytics
|
||||
not-found.tsx # 404 z panelu (getNotFoundPage)
|
||||
[[...slug]]/page.tsx # PODWÓJNE nawiasy; RenderBlocks
|
||||
(payload)/ # panel (generowany)
|
||||
manifest.ts # createManifestHandler + force-dynamic
|
||||
sitemap.ts, robots.ts # z lib/content (+ force-dynamic na sitemap)
|
||||
api/health/route.ts # createHealthRoute
|
||||
instrumentation.ts # assertEnv(ipalEnvRules({...}))
|
||||
fields/ # sectionHeader.ts, sectionSettings.ts (linki: z pluginu)
|
||||
components/
|
||||
ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader
|
||||
layout/ # Header, Footer, MobileNav (§6.8)
|
||||
icons/ # names.ts + Icon.tsx (§6.10)
|
||||
blocks/<NazwaBloku>/ # config.ts + Component.tsx (+ XxxCard.tsx, klienckie obok)
|
||||
blocks/registry.ts # blockType → komponent
|
||||
collections/ # Pages.ts, Media.ts (+ treść tylko gdy wymagana)
|
||||
globals/ # Header.ts, Footer.ts, Company.ts
|
||||
lib/content.ts # createContentHelpers — JEDYNY dostęp do Payloada
|
||||
lib/navigation.ts # resolveNav → dane dla menu
|
||||
i18n.config.ts # locale — jedno źródło
|
||||
payload.config.ts
|
||||
proxy.ts # NIE middleware.ts
|
||||
```
|
||||
|
||||
| Element | Konwencja | Przykład |
|
||||
|---|---|---|
|
||||
| Folder bloku, kolekcja, global | PascalCase | `blocks/FeatureGrid/`, `collections/Pages.ts` |
|
||||
| Helper, plik lib | camelCase | `lib/content.ts` |
|
||||
| Slug kolekcji | camelCase, l.mn. | `pages`, `blogPosts` |
|
||||
| Slug bloku = klucz w registry | camelCase | `hero`, `featureGrid` |
|
||||
| Nazwa pola | camelCase, słownictwo z §6.5 | `header`, `links`, `media` |
|
||||
| Komponent | nazwana funkcja, typy z `@/payload-types` | `export function Hero(...)` |
|
||||
|
||||
Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`,
|
||||
`lib/locales.ts` — plugin ma `resolveRoute`, `getConfiguredLocales`.
|
||||
|
||||
---
|
||||
|
||||
## 4. NEXT 16 — RENDERING, SEO, BUILD
|
||||
|
||||
1. **`proxy.ts`, nigdy `middleware.ts`.** Istnieje middleware.ts → usuń. Proxy:
|
||||
`export const proxy = createProxy(i18nConfig, { NextResponse })`, matcher
|
||||
jako **literał inline** (`['/((?!api|admin|_next|.*\\..*).*)']`), nie import.
|
||||
2. **Bez jawnego `<head>` w layoutcie.** Wypycha metadata do `<body>`.
|
||||
`<MediaPreconnect/>` w `<body>` (React 19 hoistuje).
|
||||
3. **ISR:** `export const revalidate = 3600` w `page.tsx`. Odświeżanie po zapisie:
|
||||
`buildRevalidateHook` (hooks.md).
|
||||
4. **`generateStaticParams`** w `[[...slug]]/page.tsx`:
|
||||
`export { generateStaticParams } from '@/lib/content'`. Trasa bez niego jest
|
||||
dynamiczna → metadata w body.
|
||||
5. **`htmlLimitedBots`** w `next.config.ts` (seo.md).
|
||||
6. **Nie czytaj `searchParams`** w stronie bez paginacji — deoptymalizuje
|
||||
ISR/SSG. **Nie czytaj `headers()` / `cookies()`** nigdzie w drzewie stron
|
||||
statycznych — w blokach, komponentach, layoucie `[locale]` ani w
|
||||
`not-found.tsx` (Next 16: `Page changed from static to dynamic at runtime`).
|
||||
Locale do bloków → `enhanceProps`; w `not-found.tsx` (brak `params`) →
|
||||
wersja na każdy język + `<LocaleView>` (pages.md).
|
||||
7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę:
|
||||
`manifest.ts`, `sitemap.ts`/`sitemap.xml`, `llms.txt`, `api/health`. Handlery
|
||||
pluginu mają try/catch, ale `dynamic` musi być w pliku trasy.
|
||||
8. **`instrumentation.ts`** z `assertEnv(ipalEnvRules({...}))` (env.md).
|
||||
9. **RSC domyślnie.** `'use client'` tylko dla stanu/interakcji, w osobnym pliku;
|
||||
sekcja zostaje serwerowa i podaje mu dane. Sekrety: `import 'server-only'`.
|
||||
10. **Bloki nie importują `lib/*`** (cykl). Dane server-side → `enhanceProps`.
|
||||
|
||||
---
|
||||
|
||||
## 5. MODEL TREŚCI — CO JEST CZYM
|
||||
|
||||
### 5.1 Zasada nadrzędna
|
||||
**Wszystko, co widać na stronie, redaktor zmienia w panelu** — nagłówki,
|
||||
akapity, przyciski (tekst i cel), obrazy, pliki, kolejność sekcji, SEO, teksty
|
||||
formularza i banera, dane kontaktowe. Deweloper dostarcza klocki (bloki),
|
||||
redaktor składa z nich strony. Nowa strona = zero kodu.
|
||||
|
||||
### 5.2 Kolekcja, global czy blok?
|
||||
- **Blok** — część strony (hero, FAQ, galeria, CTA, opinie w sekcji).
|
||||
- **Global** — jeden zestaw na serwis (nawigacja, stopka, dane firmy, ustawienia).
|
||||
- **Kolekcja** — lista rekordów, każdy z **własnym URL** (post, produkt, realizacja).
|
||||
|
||||
### 5.3 MINIMUM kolekcji
|
||||
Domyślnie: `pages`, `media` + globale pluginu (`site-settings`,
|
||||
`site-integrations`, Notifications, Cookie Settings) + globale projektu
|
||||
(nawigacja, stopka, firma). Nic więcej, dopóki klient jawnie nie wymaga.
|
||||
|
||||
**NIGDY:** `users` (wbudowane w Payload), druga `media`, `daneFirmy`/`settings`/
|
||||
`navigation`/`footer` jako kolekcje (to globale), FAQ/hero/features jako kolekcje
|
||||
(to bloki), kolekcja dla jednej rzeczy (to strona albo global).
|
||||
|
||||
**Test przed nową kolekcją — wszystkie muszą być TAK:** lista wielu rekordów?
|
||||
każdy ma własny URL? klient jawnie wymaga? Payload tego nie ma wbudowanego?
|
||||
|
||||
Typowe kolekcje treści (gdy wymagane): `posts`/`blogPosts` (+ `authors`,
|
||||
`categories`), `products`, `projects` (portfolio). Opinie (`testimonials`) bez
|
||||
własnych URL-i → nie dodawaj do `content`.
|
||||
|
||||
### 5.4 Wpięcie kolekcji z URL-ami
|
||||
```ts
|
||||
// ipalKit({ content: contentConfig }) i createContentHelpers({ content: contentConfig })
|
||||
export const contentConfig = {
|
||||
collections: [{ slug: 'posts', perPage: 10 }],
|
||||
} satisfies ContentOption
|
||||
```
|
||||
Prefiks URL **nie jest w kodzie** — redaktor przypisuje stronę-archiwum w Site
|
||||
Settings (`postsArchive`). Zmiana jej sluga przenosi całą sekcję, per język.
|
||||
Plugin robi routing (`resolveRoute`), sitemap, `generateStaticParams`, hreflang.
|
||||
Każda kolekcja treści: `title`, `buildSlugField`, tab SEO, `buildNoindexField`,
|
||||
`trackSlugHistoryHook`, structured data jeśli dotyczy (seo.md). Szczegóły: content.md.
|
||||
|
||||
### 5.5 Strony systemowe
|
||||
Site Settings → System Pages: `homepage`, `notFound` (404), `privacyPolicy`,
|
||||
`cookiePolicy`, `termsOfService`. Linkuj przez rolę (`getSystemPagePath`),
|
||||
nigdy po slugu. pages.md.
|
||||
|
||||
---
|
||||
|
||||
## 6. BUDOWA SEKCJI (bloki `.tsx`)
|
||||
|
||||
Trzy problemy, których nie wolno powtarzać: **zoo pól CTA** (`ctaLabel`,
|
||||
`cta2Text`, `buttonUrl`…), **pliki jako tekst** (`pdfUrl: '/files/x.pdf'`),
|
||||
**sekcja-monolit** (200–400 linii z kartami, ikonami SVG i stylami przycisków).
|
||||
|
||||
### 6.1 Trzy warstwy
|
||||
```
|
||||
WARSTWA 1 — wspólne pola: linki z pluginu (buildLinkField, buildLinksField)
|
||||
+ src/fields/ projektu (sectionHeader, sectionSettings)
|
||||
src/components/ui/ WARSTWA 2 — prymitywy UI (CMSLink, Button, Media, Section, SectionHeader)
|
||||
src/blocks/X/ WARSTWA 3 — sekcja = kompozycja warstw 1 i 2
|
||||
```
|
||||
Zmiana wyglądu przycisku w całym serwisie = jedna zmiana w `Button.tsx`. Jeśli
|
||||
musisz zmieniać 12 bloków, architektura jest zła.
|
||||
|
||||
### 6.2 Warstwa 1 — wspólne pola
|
||||
|
||||
**Link / CTA — z pluginu** ([links.md](../links.md)), nigdy kopia w projekcie:
|
||||
|
||||
```ts
|
||||
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
|
||||
|
||||
buildLinksField() // pole `links`: 0–2 przyciski sekcji
|
||||
buildLinkField() // pole `link`: pojedynczy link
|
||||
buildLinkField({ disableLabel: true, appearances: false }) // klikalna cała karta
|
||||
```
|
||||
Typ linku: strona / URL (też mailto, tel, #anchor) / **plik** (upload). Plik do
|
||||
pobrania = link typu `file`, nigdy pole `pdfUrl`. W `payload-types.ts`: `CmsLink`.
|
||||
|
||||
**Obraz / wideo:** `{ name: 'media', type: 'upload', relationTo: 'media' }`. Kolekcja
|
||||
`media` dopuszcza PDF, ma `alt` (required, localized) i `normalizeFilenameHook`.
|
||||
|
||||
**W projekcie (`src/fields/`)** — dwa małe helpery, kod w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md):
|
||||
- `sectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized),
|
||||
- `sectionSettingsField()` → grupa `settings` (sidebar): `anchor`, `background`.
|
||||
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `sectionId` per blok.
|
||||
Etykiety pól po angielsku (panel jest EN).
|
||||
|
||||
### 6.3 Warstwa 2 — prymitywy UI
|
||||
|
||||
Kod 1:1: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). Każdy ma jedno zadanie:
|
||||
|
||||
| Prymityw | Robi | Zamiast |
|
||||
|---|---|---|
|
||||
| `CMSLink` (async, serwer) | każdy link z panelu: `resolveLinkHref` z pluginu + styl z `Button` + `newTab`/plik | `<a href>`, `<Link href>` w sekcjach |
|
||||
| `Button.tsx` | `Record<LinkAppearance, string>` z klasami wariantów | łańcuchy ternary, style przycisków w sekcjach |
|
||||
| `Media` | każdy obraz/wideo z panelu (`next/image`, alt z dokumentu) | `<img src={x.url}>` |
|
||||
| `Section` | `id` z anchora, tło z mapy, kontener | ręczne `<section className=…>` |
|
||||
| `SectionHeader` | eyebrow + nagłówek (`h1`/`h2`) + intro | luźne nagłówki w każdej sekcji |
|
||||
|
||||
**`locale` dla bloków — raz, w trasie strony** (nigdy `headers()` w komponentach):
|
||||
```tsx
|
||||
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
|
||||
locale,
|
||||
...(block.blockType === 'formBlock' ? { turnstileSiteKey } : {}),
|
||||
})
|
||||
```
|
||||
|
||||
### 6.4 Warstwa 3 — sekcja = kompozycja
|
||||
|
||||
Wzorcowy kształt sekcji (cały komponent; schemat `config.ts` i przykład z
|
||||
powtarzalnymi elementami — `FeatureGrid` + `FeatureCard` — w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md)):
|
||||
|
||||
```tsx
|
||||
// src/blocks/Hero/Component.tsx — cały komponent
|
||||
import type { HeroBlock } from '@/payload-types'
|
||||
import { Section } from '@/components/ui/Section'
|
||||
import { SectionHeader } from '@/components/ui/SectionHeader'
|
||||
import { Media } from '@/components/ui/Media'
|
||||
import { CMSLink } from '@/components/ui/CMSLink'
|
||||
|
||||
export function Hero({ header, media, links, settings, locale }: HeroBlock & { locale: string }) {
|
||||
return (
|
||||
<Section settings={settings}>
|
||||
<div className="grid items-center gap-10 md:grid-cols-2">
|
||||
<div>
|
||||
<SectionHeader header={header} as="h1" />
|
||||
{links?.length ? (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{links.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<Media resource={media} priority sizes="(min-width: 768px) 50vw, 100vw" />
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Wydziel podkomponent, gdy którekolwiek jest prawdą:** ten sam JSX 2+ razy;
|
||||
element `items[]` ma >5 linii markupu (→ `<Nazwa>Card.tsx`); `Component.tsx` >80
|
||||
linii JSX; jest stan/interakcja (→ osobny plik `'use client'`, §6.9).
|
||||
Podkomponent jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/components/ui/`.
|
||||
|
||||
### 6.5 Stałe słownictwo pól
|
||||
|
||||
| Rzecz | Nazwa pola | ZAKAZANE |
|
||||
|---|---|---|
|
||||
| Przyciski / CTA sekcji | `links` (`buildLinksField()`) | `cta`, `ctaLabel`, `ctaHref`, `ctaTarget`, `cta2…`, `buttons`, `buttonText`, `buttonUrl`, `primaryCta` |
|
||||
| Pojedynczy link (karta, element) | `link` (`buildLinkField()`) | `href`, `url`, `target`, `linkTo`, `readMoreUrl` |
|
||||
| Obraz / wideo | `media` | `image`, `img`, `imageUrl`, `photo`, `bgImage`, `heroImage` |
|
||||
| Plik do pobrania | `link` typu `file` | osobne `pdf`, `pdfUrl`, `file`, `download`, `attachment` |
|
||||
| Nagłówek sekcji | `header` (`sectionHeaderField()`) | luźne `title`, `headline`, `sectionTitle`, `subheading`, `subtitle` |
|
||||
| Tekst elementu | `heading` + `text` | `title`/`desc`/`description` naprzemiennie |
|
||||
| Tekst sformatowany | `content` (richText) | `body`, `html`, `richText` |
|
||||
| Lista elementów | `items` | `cards`, `features`, `list`, `boxes` |
|
||||
| Anchor / tło | `settings` (`sectionSettingsField()`) | `sectionId`, `bgColor`, `dark`, `theme` per blok |
|
||||
| Zgoda RODO w formularzu | `consent` (checkbox) | — |
|
||||
|
||||
Wyjątek tylko przy dwóch rzeczach tego samego rodzaju o różnej roli
|
||||
(`media` + `backgroundMedia`); rdzeń nazwy zostaje.
|
||||
|
||||
### 6.6 Antywzorce → poprawka
|
||||
|
||||
```ts
|
||||
// ŹLE
|
||||
{ name: 'ctaLabel', type: 'text' }, { name: 'ctaHref', type: 'text' },
|
||||
{ name: 'secondaryCtaTarget', type: 'relationship', relationTo: 'pages' },
|
||||
{ name: 'pdfUrl', type: 'text' },
|
||||
// DOBRZE
|
||||
buildLinksField({ maxRows: 3 })
|
||||
```
|
||||
```tsx
|
||||
// ŹLE — sekcja sama składa href i stylizuje przycisk
|
||||
<a href={`/${locale}/${cta.slug}`} className="rounded-full bg-orange-500 px-6 py-3">{ctaLabel}</a>
|
||||
<a href="/files/katalog.pdf" download>Pobierz katalog</a>
|
||||
<img src={image.url} alt="" />
|
||||
// DOBRZE
|
||||
{links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
|
||||
<Media resource={media} />
|
||||
```
|
||||
```tsx
|
||||
// ŹLE — łańcuch ternary
|
||||
className={v === 'a' ? 'x' : v === 'b' ? 'y' : 'z'}
|
||||
// DOBRZE — Record<Variant, string> (Button.tsx, Section.tsx)
|
||||
```
|
||||
|
||||
### 6.7 Refaktor sekcji-monolitu
|
||||
1. Spisz, co sekcja wyświetla (nagłówek, obrazy, przyciski, powtórzenia).
|
||||
2. Schemat wg §6.5; CTA → `buildLinksField()`.
|
||||
3. **Zmiana nazw pól gubi treść w bazie.** Projekt z treścią → najpierw migracja
|
||||
(stare pole → nowe), potem usunięcie starych. Pusty projekt → sama zmiana.
|
||||
4. Komponent: `<Section>`, `<SectionHeader>`, `<Media>`, `<CMSLink>`,
|
||||
powtórzenia → `items.map` + `XxxCard`.
|
||||
5. `pnpm generate:types`, typy z `@/payload-types`, kontrole z §11.
|
||||
|
||||
### 6.8 Header i Footer (globale nawigacji)
|
||||
|
||||
Kod (globale, `resolveNav`, `Header`, `Footer`, `MobileNav`): [kod-nawigacji.md](./skills/ipal-nav/resources/kod-nawigacji.md).
|
||||
Skill: **ipal-nav**.
|
||||
|
||||
- Nawigacja, stopka, dane firmy = **globale projektu** (`header`, `footer`, `company`),
|
||||
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.
|
||||
- **Linki prawne w stopce** z ról System Pages (`getSystemPagePath`), nie ręcznie.
|
||||
- Linki rozwiązuj **na serwerze** (`resolveNav` → `{ href, label, newTab }`); do
|
||||
komponentu klienckiego idą tylko proste dane — `CMSLink` jest serwerowy.
|
||||
- Etykiety a11y (przycisk menu) — pola w panelu.
|
||||
- Global zmieniany na każdej stronie → `afterChange` z `revalidatePath('/', 'layout')`.
|
||||
- Globale pobiera tylko `[locale]/layout.tsx` i podaje jako props.
|
||||
|
||||
### 6.9 Komponenty klienckie (`'use client'`)
|
||||
|
||||
1. **Najpierw natywny HTML.** Rozwijane FAQ → `<details>`/`<summary>`, modal →
|
||||
`<dialog>`. Zero JS, działa bez hydracji. `useState` dopiero gdy HTML nie wystarczy.
|
||||
2. **Osobny plik**, pierwsza linia `'use client'`, nazwa mówi o zachowaniu
|
||||
(`MobileNav.tsx`, `Slider.tsx`, `Tabs.tsx`). Sekcja zostaje serwerowa.
|
||||
3. **Props tylko serializowalne** — stringi, liczby, tablice prostych obiektów.
|
||||
Bez funkcji, bez całych dokumentów Payload (przytnij do potrzebnych pól).
|
||||
4. **Treść renderuj na serwerze, przekaż jako `children`** — rich text, `Media`,
|
||||
`CMSLink` nie wchodzą do komponentu klienckiego:
|
||||
```tsx
|
||||
// serwer (blok)
|
||||
<Tabs labels={items.map((i) => i.heading)}>
|
||||
{items.map((i) => <RenderRichText key={i.id} data={i.content} />)}
|
||||
</Tabs>
|
||||
// klient: Tabs pokazuje children[active]
|
||||
```
|
||||
5. **Zakazane w kliencie:** import `payload`, `@/lib/content`, `@/payload.config`,
|
||||
`server-only`, sekretów. Typy wolno (`import type`).
|
||||
6. Hooki pluginu z `@intecion/ipal-kit/client` (`useForm`, `useConsentContext`…).
|
||||
7. Etykiety a11y (`aria-label`, „Zamknij”, „Następny slajd”) — z panelu, przez props.
|
||||
|
||||
### 6.10 Ikony
|
||||
|
||||
Dwa źródła, nic pomiędzy: **grafika od klienta** (także logo, ikony marki) →
|
||||
upload + `<Media>`; **stały zestaw ikon UI** → pole `select` z nazwami +
|
||||
mapa `lucide-react` w `src/components/icons/` (nazwy w osobnym pliku, żeby config
|
||||
bloku nie importował Reacta). Kod: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). **Nigdy** SVG wklejone w JSX sekcji.
|
||||
|
||||
### 6.11 Style
|
||||
|
||||
- Tailwind w komponentach; kolory i fonty jako **tokeny** w `styles.css` (`@theme`)
|
||||
ze źródła `DESIGN.md`. W komponentach tylko tokeny (`bg-primary`), **nigdy**
|
||||
`bg-[#ff6600]` ani hex.
|
||||
- Tokeny pluginu mapuj na projekt: `--ipal-primary: var(--color-primary)`.
|
||||
- Fonty przez `next/font`, podpięte zmienną CSS do `@theme`.
|
||||
- Bez CSS Modules i `style={{…}}` — wyjątek: wartość dynamiczna z danych.
|
||||
- Warianty → `Record<Variant, string>`, nie łańcuchy ternary.
|
||||
Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md).
|
||||
|
||||
### 6.12 Eksporty i importy
|
||||
|
||||
- **Eksporty nazwane** (`export function Hero`). `export default` tylko tam,
|
||||
gdzie wymaga go Next/Payload: `page`, `layout`, `not-found`, `route`,
|
||||
`sitemap`, `robots`, `manifest`, `payload.config`.
|
||||
- **Bez barreli `index.ts`** w `blocks/` i `components/` — mieszają moduły
|
||||
serwerowe z `'use client'` i psują tree-shaking. Importuj plik wprost:
|
||||
`@/components/ui/CMSLink`.
|
||||
- **Zawsze alias `@/`**, nigdy `../../../`. Wyjątek: plik obok w tym samym
|
||||
folderze (`./FeatureCard`).
|
||||
- **`import type`** dla samych typów.
|
||||
- **Kolejność importów:** zewnętrzne → `@intecion/ipal-kit` → `@/` → względne.
|
||||
- `payload.config` i kolekcje importują tylko `config.ts` bloków, nigdy
|
||||
`Component.tsx`. Komponenty spina wyłącznie `blocks/registry.ts`.
|
||||
|
||||
---
|
||||
|
||||
## 7. WZORCE PLUGINU — UŻYWAJ, NIE PISZ OD NOWA
|
||||
|
||||
| Potrzeba | Użyj | Doc |
|
||||
|---|---|---|
|
||||
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField`, `resolveLinkHref` | links.md |
|
||||
| Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md |
|
||||
| Rich text | `RenderRichText` (`/rsc`), styl przez `converters` | richtext.md |
|
||||
| Wartość zlokalizowana | `resolveLocalized(value, locale)` (nie `getSafeString`) | forms.md |
|
||||
| Formularz | builder w panelu + `submitForm`; logika `useForm`/`useContactForm` | forms.md |
|
||||
| Turnstile | `TurnstileProvider` w layoutcie + `useTurnstile()` | turnstile.md |
|
||||
| Slug | `buildSlugField({ from: 'title' })` | slug.md |
|
||||
| noindex | `buildNoindexField()` | seo.md |
|
||||
| Ścieżki językowe | `getLocalizedSlugs`, `switchLocalePath`, `LanguageSwitcher` | i18n.md |
|
||||
| Strony systemowe, 404 | `getSystemPagePath`, `getNotFoundPage` | pages.md |
|
||||
| Routing, archiwa | `resolveRoute`, `getEntries`, `resolveRedirect` | content.md |
|
||||
| ISR po zapisie | `buildRevalidateHook` (wstrzyknięty `revalidatePath`) | hooks.md |
|
||||
| Stary slug → 308 | `trackSlugHistoryHook` + `resolveRedirect` | hooks.md |
|
||||
| Obrazy między językami | `buildCrossLocaleFieldSync` (języki z configu) | hooks.md |
|
||||
| Ochrona stron systemowych | `buildPreventDeleteSystemPage`, `buildValidateUniqueRole` | hooks.md |
|
||||
| Metadata, sitemap, JSON-LD, llms.txt | `generatePageMetadata` (z `createContentHelpers`), `sitemap`, `build*JsonLd`, `createLlmsTxtRoute` | seo.md |
|
||||
| Consent, analytics, pixele | `ConsentProvider`, `CookieBanner`, `Analytics` (wewnątrz providera) | consent.md, analytics.md |
|
||||
| Nagłówki, CSP, 2FA | `buildSecurityHeaders`, `buildCsp`, `twoFactor` (wstrzyknięty `payloadTotp`) | security.md |
|
||||
| Media, R2 | `buildR2Storage(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `MediaPreconnect` | storage.md |
|
||||
| Email | `email: mailAdapter()` | email.md |
|
||||
| Walidacja env | `assertEnv(ipalEnvRules({...}))` | env.md |
|
||||
|
||||
**Compliance (PL/EU) — mechanizm z pluginu, treść od klienta:** strony polityk
|
||||
jako System Pages, `CookieBanner` + `CookieButton`, checkbox `consent` w
|
||||
formularzach (enforcement server-side), dane administratora w globalu, polityki z
|
||||
`noindex`. Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
|
||||
wymaga (accessibility.md).
|
||||
|
||||
**Bezpieczeństwo:** 2FA wymuszone (`ipalKit({ twoFactor: { issuer, plugin:
|
||||
payloadTotp } })`, nigdy `twoFactor: false` bez decyzji klienta). CSP: najpierw
|
||||
`report-only`, potem `enforce`; bez Trusted Types (psują Turnstile/GA).
|
||||
|
||||
---
|
||||
|
||||
## 8. STANDARDY KODU
|
||||
|
||||
**Typy**
|
||||
- Zero `any` / `@ts-ignore`. Nieznany kształt → `unknown` + type guard.
|
||||
- Typy z `@/payload-types` (`pnpm generate:types`), nie ręczne kopie.
|
||||
`interfaceName` na wspólnych polach/blokach daje nazwane typy.
|
||||
- Generyk przy wywołaniu: `getSiteSettings<SiteSetting>(payload)`, nie `as` na wyniku.
|
||||
- Konfiguracja: `as const satisfies I18nConfig`.
|
||||
- Dopuszczalne wąskie rzutowanie: `doc.slug as unknown as Record<string, unknown>`
|
||||
przy `locale: 'all'` (generator nie modeluje tego trybu), `locale as never`.
|
||||
|
||||
**Payload**
|
||||
- W hookach przekazuj `req` do kolejnych operacji (jedna transakcja).
|
||||
- Hook aktualizujący dokument → flaga w `context` (`context.skip`) przeciw pętli.
|
||||
- Local API omija access control — `overrideAccess: false`, gdy ma respektować usera.
|
||||
- `blocks: []` crashuje — zawsze ≥1 blok.
|
||||
|
||||
**Błędy**
|
||||
- Nigdy `catch {}`. Loguj konkret (`payload.logger.error`), zwracaj kontrolowany wynik.
|
||||
- Błąd użytkownika (400, czytelny komunikat) ≠ błąd systemu (log + ogólny komunikat).
|
||||
- Waliduj input w endpointach i server actions.
|
||||
- Guard clauses zamiast piramidy `if`.
|
||||
|
||||
**Czytelność**
|
||||
- Nazwy mówią CO (`publishedPosts`, nie `arr`); funkcje = czasownik + rzeczownik.
|
||||
- Komentarz mówi DLACZEGO, nie CO.
|
||||
- Magic numbers/strings → nazwane stałe.
|
||||
- Najmniejsza zmiana, która rozwiązuje problem. Nie przepisuj przy okazji.
|
||||
|
||||
---
|
||||
|
||||
## 9. ANTYWZORCE, KTÓRE NAPRAWDĘ SIĘ ZDARZYŁY
|
||||
|
||||
| Antywzorzec | Skutek | Reguła |
|
||||
|---|---|---|
|
||||
| `middleware.ts` w Next 16 | routing nie działa | tylko `proxy.ts` |
|
||||
| matcher proxy jako import | `/admin`, `/_next` → 500 | literał inline |
|
||||
| `[slug]` zamiast `[[...slug]]` | `slug.join is not a function`, `/pl` nie łapie | podwójne nawiasy |
|
||||
| jawny `<head>` w layoutcie | metadata w body, crawlery jej nie widzą | bez `<head>` |
|
||||
| brak ISR / `generateStaticParams` | trasa dynamiczna, metadata w body | oba obowiązkowe |
|
||||
| `await searchParams` bez paginacji | utrata SSG/ISR | nie czytaj |
|
||||
| zaszyta mapa slugów | drugie źródło prawdy | `getLocalizedSlugs` |
|
||||
| `lib/pages.ts`, własny `resolvePage` | rozjazd z pluginem | `resolveRoute` |
|
||||
| własny `switch (blockType)` | rośnie liniowo, bez enhanceProps | `RenderBlocks` |
|
||||
| własny parser Lexical | błędy formatowania, XSS | `RenderRichText` |
|
||||
| ręczna hydraulika formularza | duplikat logiki, dziury | `useForm` |
|
||||
| zaszyta domena w hooku Media | inny projekt = cudza domena | R2 z env przez plugin |
|
||||
| `siteName \|\| 'Firma X'` | cudze dane w innym projekcie | pomiń pole |
|
||||
| favicon renderowany ręcznie | Google go nie pokazuje | `buildIconsMetadata` |
|
||||
| skopiowany `Analytics` w projekcie | pixele bez zgody (RODO) | opcje pluginu (`defer`) |
|
||||
| `import('@payload-config')` przez zmienną | `Cannot find module` w buildzie | wstrzyknięcie / props |
|
||||
| `ctaLabel`, `buttonUrl`, `pdfUrl` w blokach | zoo pól, brak spójności | `buildLinksField()` |
|
||||
| brak `@source` na plugin w CSS | komponenty pluginu bez stylów | `@source` |
|
||||
| kolekcja `users`/`settings`/`faq` | duplikat Payloada / zły byt | §5.3 |
|
||||
|
||||
Wspólny mianownik: **duplikacja** (dwa źródła prawdy) albo **przerwany łańcuch**
|
||||
(zmiana nie dotarła tam, gdzie trzeba). Jedno źródło + weryfikacja grepem
|
||||
eliminują większość.
|
||||
|
||||
---
|
||||
|
||||
## 10. PODZIAŁ PRACY
|
||||
|
||||
- **Agent (Antigravity / Claude):** architektura, kolekcje, bloki, routing,
|
||||
edytowalność przez panel, integracje, brak hardkodów. Funkcjonalność najpierw.
|
||||
- **Impeccable:** wygląd (kolory, typografia, spacing, animacje) na podstawie
|
||||
`PRODUCT.md` + `DESIGN.md` w roocie projektu (`/impeccable init`,
|
||||
`/impeccable document`). Agent nie „dopieszcza” stylów ad hoc. Impeccable nie
|
||||
rusza treści — design tokeny w kodzie to system wizualny, nie hardkod treści.
|
||||
- **Redaktor:** każda treść w panelu.
|
||||
|
||||
Kluczowe ustalenia projektu (stack, decyzje, tryby stron) zapisuj w `AGENTS.md`
|
||||
projektu (§13), nie polegaj na pamięci sesji.
|
||||
|
||||
---
|
||||
|
||||
## 11. ZANIM POWIESZ „GOTOWE”
|
||||
|
||||
**Uruchom, nie zgaduj:**
|
||||
```bash
|
||||
pnpm generate:types && pnpm tsc --noEmit
|
||||
pnpm build # --webpack w skrypcie; lokalnie, nie tylko dev
|
||||
# hardkody i zoo pól w blokach
|
||||
grep -rnE "name: '[a-zA-Z]*([cC]ta|[bB]utton|Url|Href|[pP]df)[a-zA-Z]*'" src/blocks
|
||||
grep -rnE 'href=\{?["`]/|<img |/files/|/images/|\.pdf' src/blocks
|
||||
grep -rnE '<(a|Link) ' src/blocks # w sekcjach tylko CMSLink
|
||||
find src/blocks -name 'Component.tsx' -exec wc -l {} + | awk '$1 > 120'
|
||||
grep -rnE "(bg|text|border)-\[#" src/blocks src/components # hex zamiast tokenów
|
||||
grep -rln "^'use client'" src | xargs grep -lnE "@/lib/content|from 'payload'|server-only" # serwer w kliencie
|
||||
find src/blocks src/components -name 'index.ts' # barrel — usuń (wyjątków brak)
|
||||
# architektura
|
||||
ls src/middleware.ts 2>/dev/null && echo "USUŃ middleware.ts"
|
||||
grep -rn "localizedRoutes\|as any\|@ts-ignore" src
|
||||
grep -rn "<head" src/app
|
||||
```
|
||||
Każde trafienie to błąd albo świadomy, skomentowany wyjątek. Po buildzie trasy
|
||||
stron mają być `●` (SSG), nie `ƒ`.
|
||||
|
||||
**Test redaktora — przez sam panel, bez kodu, w każdym języku:**
|
||||
- [ ] zmienia każdy nagłówek, tekst, etykietę
|
||||
- [ ] podmienia każdy obraz i plik do pobrania
|
||||
- [ ] zmienia tekst i cel każdego przycisku
|
||||
- [ ] dodaje, usuwa, przestawia sekcje; tworzy nową stronę z bloków
|
||||
- [ ] zmienia menu, stopkę, dane firmy
|
||||
- [ ] zmienia SEO strony, teksty formularza i banera cookies
|
||||
- [ ] przypisuje strony systemowe (w tym 404)
|
||||
|
||||
Cokolwiek wymaga dewelopera → przenieś do panelu.
|
||||
|
||||
---
|
||||
|
||||
## 12. MAPA MODUŁÓW (szczegóły API)
|
||||
|
||||
| Moduł | Plik |
|
||||
|---|---|
|
||||
| Role i dostęp do panelu | [access.md](../access.md) |
|
||||
| Widget dostępności (opcjonalny) | [accessibility.md](../accessibility.md) |
|
||||
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok | [analytics.md](../analytics.md) |
|
||||
| Bloki, RenderBlocks, enhanceProps | [blocks.md](../blocks.md) |
|
||||
| Zgoda cookies, baner | [consent.md](../consent.md) |
|
||||
| Routing, archiwa, redirecty, Markdown, wyszukiwarka | [content.md](../content.md) |
|
||||
| Email SMTP / Graph | [email.md](../email.md) |
|
||||
| Walidacja env | [env.md](../env.md) |
|
||||
| Formularze, useForm, honeypot | [forms.md](../forms.md) |
|
||||
| Hooki | [hooks.md](../hooks.md) |
|
||||
| i18n, proxy, przełącznik języka | [i18n.md](../i18n.md) |
|
||||
| Linki / CTA (pola + href) | [links.md](../links.md) |
|
||||
| Serwer MCP strony | [mcp.md](../mcp.md) |
|
||||
| Komunikaty formularzy | [notifications.md](../notifications.md) |
|
||||
| Strony systemowe, 404, generateStaticParams | [pages.md](../pages.md) |
|
||||
| Helpery Payload (getSiteSettings…) | [payload-helpers.md](../payload-helpers.md) |
|
||||
| Rich text | [richtext.md](../richtext.md) |
|
||||
| Nagłówki, CSP, 2FA, ścieżka panelu | [security.md](../security.md) |
|
||||
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](../seo.md) |
|
||||
| Auto-slug | [slug.md](../slug.md) |
|
||||
| Media, R2 | [storage.md](../storage.md) |
|
||||
| Turnstile | [turnstile.md](../turnstile.md) |
|
||||
| White-label panelu | [white-label.md](../white-label.md) |
|
||||
|
||||
---
|
||||
|
||||
## 13. SZABLON `AGENTS.md` DLA PROJEKTU
|
||||
|
||||
Skopiuj do roota projektu jako `AGENTS.md` i uzupełnij. Reguł nie kopiuj — ten
|
||||
plik wskazuje na nie.
|
||||
|
||||
```markdown
|
||||
# AGENTS.md
|
||||
|
||||
**Projekt:** <klient> · <domena> · rynek <PL/AU/US> · branża <…>
|
||||
**Języki:** <pl, en, de> · **Media:** <R2 / lokalne> · **Email:** <SMTP / Graph>
|
||||
|
||||
## Reguły
|
||||
Przed pierwszą zmianą przeczytaj w całości:
|
||||
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`
|
||||
Szczegóły modułów: `node_modules/@intecion/ipal-kit/docs/<moduł>.md`.
|
||||
Skille: `.agents/skills/ipal-*` (odśwież: `pnpm ipal:skills`). Przed „gotowe” zawsze `ipal-audit`.
|
||||
Reguły z AGENT.md mają pierwszeństwo przed Twoją ogólną wiedzą o Next/Payload.
|
||||
|
||||
## Ustalenia projektu
|
||||
- <decyzje specyficzne dla klienta, np. „blog bez autorów”, „404 = strona główna”>
|
||||
- <wyjątki od reguł — z uzasadnieniem>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. SKILLE (Antigravity, Claude Code, Cursor)
|
||||
|
||||
Skille są w pakiecie: `node_modules/@intecion/ipal-kit/docs/agent/skills/`.
|
||||
Agent widzi na starcie tylko ich nazwy i opisy, a pełną instrukcję czyta, gdy
|
||||
zadanie pasuje — ręcznie: `/<nazwa>`.
|
||||
|
||||
| Skill | Kiedy |
|
||||
|---|---|
|
||||
| `ipal-setup` | nowy projekt od zera |
|
||||
| `ipal-block` | nowa albo poprawiana sekcja (blok) |
|
||||
| `ipal-collection` | „potrzebny blog / produkty / …” — zanim powstanie plik w `src/collections` |
|
||||
| `ipal-nav` | nagłówek, menu, stopka, dane firmy |
|
||||
| `ipal-upgrade` | aktualizacja ipal-kit w istniejącym projekcie |
|
||||
| `ipal-audit` | przed każdym „gotowe” — skrypt z kontrolami §11 + tsc + build |
|
||||
| `ipal-plugin-gap` | pluginowi czegoś brakuje albo nie działa — raport zamiast łatki |
|
||||
|
||||
**Instalacja w projekcie** (raz i po każdej aktualizacji ipal-kit) — skrypt w
|
||||
`package.json` projektu:
|
||||
```json
|
||||
"scripts": {
|
||||
"ipal:skills": "ipal-skills"
|
||||
}
|
||||
```
|
||||
```bash
|
||||
pnpm ipal:skills
|
||||
```
|
||||
`ipal-skills` (komenda z pakietu) kopiuje tylko foldery `ipal-*`: dodaje nowe,
|
||||
nadpisuje zmienione, usuwa wycofane. Własne skille projektu nazywaj **bez**
|
||||
prefiksu `ipal-` — zostaną nietknięte. Opcje: `--dry-run`, `--dest .claude/skills`
|
||||
(Claude Code). Commituj `.agents/skills/ipal-*` do repo projektu.
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: ipal-audit
|
||||
description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project.
|
||||
---
|
||||
|
||||
# ipal-audit
|
||||
|
||||
Kontrole z AGENT.md §11 jako skrypt — zawsze te same, bez interpretacji.
|
||||
|
||||
## Kroki
|
||||
|
||||
1. Z roota projektu uruchom:
|
||||
```bash
|
||||
bash .agents/skills/ipal-audit/scripts/audit.sh --quick # w trakcie pracy
|
||||
bash .agents/skills/ipal-audit/scripts/audit.sh # przed „gotowe” (+ tsc + build)
|
||||
```
|
||||
Opcje: `--help`. Nie czytaj źródła skryptu — wynik wystarczy.
|
||||
2. Pokaż użytkownikowi **pełny wynik** (podsumowanie + listę naruszeń).
|
||||
3. Każde `[ERROR]` napraw albo — jeśli to świadomy wyjątek — dodaj w kodzie
|
||||
komentarz z uzasadnieniem i wymień go w odpowiedzi.
|
||||
Reguła przy każdym naruszeniu wskazuje sekcję w
|
||||
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` — przeczytaj ją przed poprawką.
|
||||
4. `[WARNING]` — oceń i powiedz użytkownikowi, co z nim zrobić; nie poprawiaj
|
||||
na ślepo (np. `searchParams` jest OK w trasie archiwum z paginacją).
|
||||
5. Uruchom ponownie, aż wynik to `0 error(s)`.
|
||||
|
||||
## Czego skrypt nie sprawdzi (zrób ręcznie)
|
||||
|
||||
- **Test redaktora** (AGENT.md §11): czy każdy tekst, obraz, przycisk, sekcja,
|
||||
menu, stopka i SEO zmienia się w panelu, w każdym języku.
|
||||
- **Zgoda cookies:** w Network przed akceptacją brak żądań do
|
||||
google-analytics / googletagmanager (poza Consent Mode), facebook.net,
|
||||
clarity.ms, licdn, tiktok.
|
||||
- **Treść**: czy fallbacki nie zawierają danych klienta (`|| 'Firma X'`).
|
||||
|
||||
Nie mów „gotowe”, dopóki pełny audyt (bez `--quick`) nie ma błędów.
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env bash
|
||||
# ipal-audit — deterministic checks of an ipal-kit project against AGENT.md.
|
||||
# Run from the project root:
|
||||
# bash .agents/skills/ipal-audit/scripts/audit.sh # all checks + tsc + build
|
||||
# bash .agents/skills/ipal-audit/scripts/audit.sh --quick # static checks only
|
||||
# bash .agents/skills/ipal-audit/scripts/audit.sh --help
|
||||
# Exit code: 0 = no errors (warnings allowed), 1 = at least one error.
|
||||
|
||||
set -u
|
||||
|
||||
QUICK=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--quick) QUICK=1 ;;
|
||||
--help|-h)
|
||||
sed -n '2,7p' "$0" | sed 's/^# \{0,1\}//'
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ ! -d src ]; then
|
||||
echo "ipal-audit: run from the project root (no ./src found)." >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
ERRORS=0
|
||||
WARNINGS=0
|
||||
|
||||
# report LEVEL "title" "rule" <<< "$matches"
|
||||
report() {
|
||||
local level="$1" title="$2" rule="$3" matches="$4"
|
||||
[ -z "$matches" ] && return 0
|
||||
local count
|
||||
count=$(printf '%s\n' "$matches" | grep -c .)
|
||||
if [ "$level" = ERROR ]; then ERRORS=$((ERRORS + count)); else WARNINGS=$((WARNINGS + count)); fi
|
||||
printf '\n[%s] %s (%s) — %s\n' "$level" "$title" "$count" "$rule"
|
||||
printf '%s\n' "$matches" | head -20 | sed 's/^/ /'
|
||||
[ "$count" -gt 20 ] && printf ' … and %s more\n' "$((count - 20))"
|
||||
}
|
||||
|
||||
g() { grep -rnE "$@" 2>/dev/null || true; }
|
||||
# drop matches that sit inside a // or /* comment (keeps http:// URLs)
|
||||
nc() { grep -vE "(^|[^:])//.*$1|/\*.*$1" || true; }
|
||||
dirs() { for d in "$@"; do [ -d "$d" ] && printf '%s ' "$d"; done; }
|
||||
|
||||
BLOCKS=$(dirs src/blocks)
|
||||
UI=$(dirs src/blocks src/components)
|
||||
|
||||
echo "ipal-audit — $(pwd)"
|
||||
|
||||
# --- Architecture (AGENT.md §4) ---
|
||||
report ERROR "middleware.ts exists" "§4.1 Next 16 uses proxy.ts only" \
|
||||
"$(ls src/middleware.ts middleware.ts 2>/dev/null)"
|
||||
|
||||
report ERROR "<head> in app" "§4.2 no explicit <head> — metadata ends up in <body>" \
|
||||
"$(g '<head[ >]' src/app --include=*.tsx | nc '<head')"
|
||||
|
||||
PAGES=$(find src/app -path '*\[\[...slug\]\]*' -name 'page.tsx' 2>/dev/null)
|
||||
for p in $PAGES; do
|
||||
grep -q 'revalidate' "$p" || report ERROR "no ISR" "§4.3 export const revalidate" "$p"
|
||||
grep -q 'generateStaticParams' "$p" || report ERROR "no generateStaticParams" "§4.4 without it the route is dynamic and metadata lands in <body>" "$p"
|
||||
report WARNING "searchParams in catch-all page" "§4.6 deoptimizes SSG/ISR — only for paginated archives" \
|
||||
"$(grep -n 'searchParams' "$p" | nc 'searchParams' | sed "s|^|$p:|")"
|
||||
done
|
||||
|
||||
for r in src/app/sitemap.ts src/app/manifest.ts src/app/llms.txt/route.ts src/app/sitemap.xml/route.ts src/app/api/health/route.ts; do
|
||||
[ -f "$r" ] && ! grep -q "dynamic = 'force-dynamic'" "$r" && \
|
||||
report ERROR "DB route without force-dynamic" "§4.7 build without DB will crash" "$r"
|
||||
done
|
||||
|
||||
report ERROR "headers()/cookies() in blocks/components" "§4.6 forces dynamic rendering — pass locale via enhanceProps" \
|
||||
"$( [ -n "$UI" ] && g "from 'next/headers'" $UI)"
|
||||
|
||||
report ERROR "headers()/cookies() in static page tree" "§4.6 SSG/ISR → 'Page changed from static to dynamic' — not-found: LocaleView (pages.md)" \
|
||||
"$(g "from 'next/headers'" src/app --include=page.tsx --include=layout.tsx --include=not-found.tsx --include=template.tsx | grep -v '/api/\|(payload)')"
|
||||
|
||||
# --- Hardcoding & types (§2, §8) ---
|
||||
report ERROR "hardcoded locale map / any / ts-ignore" "§2, §8" \
|
||||
"$(g 'localizedRoutes|as any\b|@ts-ignore|: any\b' src --include=*.ts --include=*.tsx | grep -v '/payload-types.ts:')"
|
||||
|
||||
report ERROR "hardcoded locale list" "§2 languages come from i18n.config.ts" \
|
||||
"$(g "\[ *'(pl|en|de|fr|es|it)' *, *'(pl|en|de|fr|es|it)'" src --include=*.ts --include=*.tsx | grep -v 'i18n.config.ts')"
|
||||
|
||||
# --- Sections (§6) ---
|
||||
if [ -n "$BLOCKS" ]; then
|
||||
report ERROR "forbidden field names" "§6.5 use links/link/media (linksField, linkField, upload)" \
|
||||
"$(g "name: *'[a-zA-Z]*([cC]ta|[bB]utton|Url|Href|[pP]df|[iI]mage)[a-zA-Z]*'" $BLOCKS --include=config.ts)"
|
||||
|
||||
report ERROR "hardcoded href/src/file paths in blocks" "§2, §6 use CMSLink / Media" \
|
||||
"$(g 'href=\{?["`]/|<img |/files/|/images/|\.pdf' $BLOCKS --include=*.tsx | nc '(href|<img|/files/|/images/|\.pdf)')"
|
||||
|
||||
report ERROR "raw <a>/<Link> in blocks" "§6.3 links from the panel render via CMSLink" \
|
||||
"$(g '<(a|Link)[ >]' $BLOCKS --include=*.tsx)"
|
||||
|
||||
report WARNING "inline <svg> in blocks" "§6.10 icons via media upload or Icon map" \
|
||||
"$(g '<svg[ >]' $BLOCKS --include=*.tsx)"
|
||||
|
||||
report WARNING "large section component (>120 lines)" "§6.4 split into subcomponents" \
|
||||
"$(find $BLOCKS -name '*.tsx' -exec wc -l {} + 2>/dev/null | awk '$2 != "total" && $1 > 120 {print $2": "$1" lines"}')"
|
||||
|
||||
report ERROR "Component imported into block config" "§6.12 payload.config must not pull React components" \
|
||||
"$(g "from '\./Component'|/Component'" $BLOCKS --include=config.ts)"
|
||||
fi
|
||||
|
||||
if [ -n "$UI" ]; then
|
||||
report ERROR "hex colors in classes" "§6.11 use design tokens (bg-primary…)" \
|
||||
"$(g '(bg|text|border|from|to|via|fill|stroke)-\[#' $UI --include=*.tsx)"
|
||||
|
||||
report ERROR "barrel index.ts" "§6.12 import files directly" \
|
||||
"$(find $UI -name 'index.ts' 2>/dev/null)"
|
||||
|
||||
CLIENT=$(grep -rlE "^['\"]use client['\"]" $UI 2>/dev/null)
|
||||
for c in $CLIENT; do
|
||||
report ERROR "server import in client component" "§6.9 no payload / lib/content / server-only in 'use client'" \
|
||||
"$(grep -nE "from '(payload|server-only|@/lib/content|@/payload\.config)'" "$c" | grep -v 'import type' | sed "s|^|$c:|")"
|
||||
done
|
||||
fi
|
||||
|
||||
# --- Collections (§5.3) ---
|
||||
if [ -d src/collections ]; then
|
||||
report ERROR "forbidden collection" "§5.3 users are built in; settings/nav/footer are globals; FAQ/hero are blocks" \
|
||||
"$(ls src/collections | grep -iE '^(users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
|
||||
report WARNING "collections present — confirm each passed the §5.3 test" "minimum: Pages, Media" \
|
||||
"$(ls src/collections | grep -viE '^(pages|media|users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
|
||||
fi
|
||||
|
||||
# --- Plugin duplicates (§1, §7) ---
|
||||
report ERROR "own block renderer switch" "§7 use RenderBlocks + registry" \
|
||||
"$(g 'switch *\(.*blockType' src --include=*.tsx --include=*.ts)"
|
||||
report WARNING "files that usually duplicate the plugin" "§3 plugin has resolveRoute / getConfiguredLocales" \
|
||||
"$(ls src/lib/pages.ts src/lib/locales.ts 2>/dev/null)"
|
||||
report ERROR "project copy of link fields" "links.md — use buildLinkField / buildLinksField / resolveLinkHref from the plugin" \
|
||||
"$(ls src/fields/link.ts src/lib/links.ts 2>/dev/null; g "from '@/fields/link'|from '@/lib/links'" src --include=*.ts --include=*.tsx)"
|
||||
report ERROR "manual Lexical rendering" "§7 use RenderRichText" \
|
||||
"$(g 'node\.type *===|dangerouslySetInnerHTML' src --include=*.tsx)"
|
||||
|
||||
# --- Compile & build ---
|
||||
if [ "$QUICK" -eq 0 ]; then
|
||||
echo
|
||||
echo "== pnpm generate:types && tsc --noEmit =="
|
||||
if ! (pnpm -s generate:types >/dev/null && pnpm -s exec tsc --noEmit); then
|
||||
ERRORS=$((ERRORS + 1)); echo "[ERROR] type check failed"
|
||||
fi
|
||||
echo
|
||||
echo "== pnpm build =="
|
||||
BUILD_LOG=$(mktemp)
|
||||
if pnpm -s build >"$BUILD_LOG" 2>&1; then
|
||||
DYN=$(grep -E '^[│├└ ]*ƒ .*\[locale\]' "$BUILD_LOG" || true)
|
||||
report WARNING "page routes rendered dynamically (ƒ)" "§4 expected ● SSG — does the build see the DB?" "$DYN"
|
||||
else
|
||||
ERRORS=$((ERRORS + 1)); echo "[ERROR] build failed — last lines:"; tail -30 "$BUILD_LOG" | sed 's/^/ /'
|
||||
fi
|
||||
rm -f "$BUILD_LOG"
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "ipal-audit: $ERRORS error(s), $WARNINGS warning(s)$( [ "$QUICK" -eq 1 ] && echo ' (quick: no tsc/build)')"
|
||||
[ "$ERRORS" -eq 0 ]
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
name: ipal-block
|
||||
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — shared fields (sectionHeaderField, buildLinksField, buildLinkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
|
||||
---
|
||||
|
||||
# ipal-block
|
||||
|
||||
Jedna sekcja na jedno użycie skilla. Szczegóły i gotowy kod:
|
||||
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.
|
||||
|
||||
## 0. Warunki wstępne
|
||||
Sprawdź, czy istnieją: `src/fields/sectionHeader.ts`,
|
||||
`sectionSettings.ts`, `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
|
||||
Linki (`buildLinkField`, `buildLinksField`, `resolveLinkHref`) są w pluginie — nie twórz ich w projekcie.
|
||||
Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
|
||||
(i powiedz o tym użytkownikowi). Nie pisz własnych wersji.
|
||||
|
||||
## 1. Plan (pokaż i czekaj na OK)
|
||||
- slug bloku (camelCase), nazwa folderu (PascalCase),
|
||||
- lista pól **tylko** ze słownika AGENT.md §6.5:
|
||||
`header`, `media`, `links`, `link`, `items` (+ `heading`, `text`, `content`), `settings`,
|
||||
- czy elementy `items` dostają podkomponent `<Nazwa>Card.tsx`,
|
||||
- czy potrzebna interakcja → osobny plik `'use client'` (najpierw `<details>`/`<dialog>`),
|
||||
- czy sekcja to wariant istniejącego bloku (wtedy pole `variant: select`, nie nowy blok).
|
||||
|
||||
## 2. Kod
|
||||
Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`.
|
||||
|
||||
1. `src/blocks/<Nazwa>/config.ts` — `interfaceName: '<Nazwa>Block'`, pola z planu,
|
||||
zawsze `sectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`.
|
||||
Plik do pobrania = link typu `file`. Etykiety i opisy pól po angielsku.
|
||||
2. `src/blocks/<Nazwa>/Component.tsx` — nazwany eksport, typ z `@/payload-types`
|
||||
(`<Nazwa>Block & { locale: string }`), struktura:
|
||||
`<Section settings>` → `<SectionHeader header>` → treść z `<Media>`, `<CMSLink>`,
|
||||
`items.map(<Card/>)`. Zero tekstu, `href`, `<img>`, hexów, inline SVG.
|
||||
3. Podkomponenty w tym samym folderze; wspólne dla 2+ sekcji → `src/components/ui/`.
|
||||
4. Dodaj `config.ts` do `layout` w `src/collections/Pages.ts`,
|
||||
komponent do `src/blocks/registry.ts` (klucz = slug).
|
||||
5. `pnpm generate:types`.
|
||||
|
||||
## 3. Weryfikacja
|
||||
- `Component.tsx` ≤ ~80 linii JSX.
|
||||
- Uruchom skill **ipal-audit** (`--quick`), napraw wszystkie `[ERROR]`.
|
||||
- Refaktor istniejącego bloku ze zmianą nazw pól: **najpierw migracja danych**
|
||||
(stare pole → nowe), dopiero potem usunięcie starych pól (AGENT.md §6.7).
|
||||
@@ -0,0 +1,378 @@
|
||||
# Kod sekcji — gotowe pliki dla projektu
|
||||
|
||||
> Zasoby skilla **ipal-block**. Reguły (dlaczego tak, czego nie robić) są w
|
||||
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6 — ten plik to tylko kod
|
||||
> do utworzenia w projekcie **1:1**. Linki (`buildLinkField`, `buildLinksField`,
|
||||
> `resolveLinkHref`) są w pluginie — nie twórz ich kopii.
|
||||
|
||||
## Warstwa 1 — wspólne pola
|
||||
|
||||
**Link / CTA — z pluginu, nie kopiuj kodu** (`docs/links.md`):
|
||||
|
||||
```ts
|
||||
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
|
||||
|
||||
buildLinksField() // 0–2 przyciski sekcji → pole `links`
|
||||
buildLinksField({ maxRows: 3, appearances: ['primary', 'secondary'] })
|
||||
buildLinkField() // pojedynczy link → pole `link`
|
||||
buildLinkField({ disableLabel: true, appearances: false }) // klikalna cała karta
|
||||
```
|
||||
|
||||
Jeden kształt linku: typ (`internal` strona / `external` URL, mailto, tel, #anchor /
|
||||
`file` upload), `label` (localized), `newTab`, `appearance`. W `payload-types.ts`
|
||||
powstaje typ `CmsLink`. Opcje: `relationTo` (domyślnie `'pages'`), `uploadTo`
|
||||
(domyślnie `'media'`), `required`.
|
||||
|
||||
|
||||
**Pliki i obrazy:** `{ name: 'media', type: 'upload', relationTo: 'media' }`.
|
||||
Kolekcja `media` dopuszcza PDF (`upload.mimeTypes: ['image/*', 'application/pdf',
|
||||
'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`.
|
||||
„Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`.
|
||||
|
||||
`src/fields/sectionHeader.ts` i `src/fields/sectionSettings.ts`:
|
||||
|
||||
```ts
|
||||
import type { GroupField } from 'payload'
|
||||
|
||||
export function sectionHeaderField(name = 'header'): GroupField {
|
||||
return {
|
||||
name,
|
||||
type: 'group',
|
||||
interfaceName: 'SectionHeaderData',
|
||||
fields: [
|
||||
{ name: 'eyebrow', type: 'text', localized: true },
|
||||
{ name: 'heading', type: 'text', localized: true },
|
||||
{ name: 'intro', type: 'textarea', localized: true },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
export function sectionSettingsField(): GroupField {
|
||||
return {
|
||||
name: 'settings',
|
||||
type: 'group',
|
||||
interfaceName: 'SectionSettings',
|
||||
admin: { position: 'sidebar' },
|
||||
fields: [
|
||||
{
|
||||
name: 'anchor',
|
||||
type: 'text',
|
||||
admin: { description: 'Section id for #links and section nav, e.g. "pricing".' },
|
||||
},
|
||||
{
|
||||
name: 'background',
|
||||
type: 'select',
|
||||
defaultValue: 'default',
|
||||
options: ['default', 'muted', 'inverted'].map((v) => ({ label: v, value: v })),
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
|
||||
`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN).
|
||||
|
||||
## Warstwa 2 — prymitywy UI
|
||||
|
||||
`src/components/ui/CMSLink.tsx` — **każdy** link/przycisk z panelu:
|
||||
|
||||
```tsx
|
||||
import Link from 'next/link'
|
||||
import type { ReactNode } from 'react'
|
||||
import { resolveLinkHref } from '@intecion/ipal-kit'
|
||||
import type { CmsLink } from '@/payload-types'
|
||||
import { i18nConfig } from '@/i18n.config'
|
||||
import { getSettings } from '@/lib/content'
|
||||
import { buttonClass } from './Button'
|
||||
|
||||
type Props = {
|
||||
link: CmsLink | null | undefined
|
||||
locale: string
|
||||
className?: string
|
||||
/** For wrapping links (cards): content instead of link.label. */
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
export async function CMSLink({ link, locale, className, children }: Props) {
|
||||
const settings = await getSettings(locale) // react cache → one query per request
|
||||
const home = settings?.homepage
|
||||
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
|
||||
|
||||
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
|
||||
const content = children ?? link?.label
|
||||
if (!link || !href || !content) return null
|
||||
|
||||
const cls = [link.appearance ? buttonClass(link.appearance) : '', className]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
const newTab = link.newTab || link.type === 'file'
|
||||
const targetProps = newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {}
|
||||
|
||||
if (link.type === 'internal') {
|
||||
return <Link href={href} className={cls} {...targetProps}>{content}</Link>
|
||||
}
|
||||
return <a href={href} className={cls} {...targetProps}>{content}</a>
|
||||
}
|
||||
```
|
||||
|
||||
`src/components/ui/Button.tsx` — warianty jako mapa, nie ternary:
|
||||
|
||||
```ts
|
||||
import type { LinkAppearance } from '@intecion/ipal-kit'
|
||||
|
||||
const VARIANTS: Record<LinkAppearance, string> = {
|
||||
primary: 'btn btn-primary',
|
||||
secondary: 'btn btn-secondary',
|
||||
link: 'link-arrow',
|
||||
}
|
||||
|
||||
export function buttonClass(appearance: LinkAppearance): string {
|
||||
return VARIANTS[appearance]
|
||||
}
|
||||
```
|
||||
|
||||
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu:
|
||||
|
||||
```tsx
|
||||
import Image from 'next/image'
|
||||
import type { Media as MediaDoc } from '@/payload-types'
|
||||
|
||||
type Props = {
|
||||
resource: MediaDoc | string | number | null | undefined
|
||||
sizes?: string
|
||||
priority?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function Media({ resource, sizes = '100vw', priority = false, className }: Props) {
|
||||
if (!resource || typeof resource !== 'object' || !resource.url) return null
|
||||
const { url, alt, width, height, mimeType } = resource
|
||||
|
||||
if (mimeType?.startsWith('video/')) {
|
||||
return <video src={url} className={className} autoPlay muted loop playsInline />
|
||||
}
|
||||
if (!width || !height) return null // non-image file (PDF) — use CMSLink type 'file'
|
||||
|
||||
return (
|
||||
<Image src={url} alt={alt ?? ''} width={width} height={height}
|
||||
sizes={sizes} priority={priority} className={className} />
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
`Section.tsx` i `SectionHeader.tsx`:
|
||||
|
||||
```tsx
|
||||
// src/components/ui/Section.tsx
|
||||
import type { ReactNode } from 'react'
|
||||
import type { SectionSettings } from '@/payload-types'
|
||||
|
||||
const BACKGROUNDS: Record<NonNullable<SectionSettings['background']>, string> = {
|
||||
default: 'bg-background',
|
||||
muted: 'bg-muted',
|
||||
inverted: 'bg-foreground text-background',
|
||||
}
|
||||
|
||||
export function Section({ settings, children }: { settings?: SectionSettings | null; children: ReactNode }) {
|
||||
return (
|
||||
<section
|
||||
id={settings?.anchor || undefined}
|
||||
className={`py-16 md:py-24 ${BACKGROUNDS[settings?.background ?? 'default']}`}
|
||||
>
|
||||
<div className="container">{children}</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// src/components/ui/SectionHeader.tsx
|
||||
import type { SectionHeaderData } from '@/payload-types'
|
||||
|
||||
export function SectionHeader({ header, as: H = 'h2' }: { header?: SectionHeaderData | null; as?: 'h1' | 'h2' }) {
|
||||
if (!header?.heading && !header?.eyebrow && !header?.intro) return null
|
||||
return (
|
||||
<header className="mb-10 max-w-2xl">
|
||||
{header.eyebrow && <p className="eyebrow">{header.eyebrow}</p>}
|
||||
{header.heading && <H className="heading">{header.heading}</H>}
|
||||
{header.intro && <p className="lead">{header.intro}</p>}
|
||||
</header>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**`locale` dla każdego bloku — raz, w trasie strony:**
|
||||
|
||||
```tsx
|
||||
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
|
||||
locale,
|
||||
...(block.blockType === 'formBlock' ? { turnstileSiteKey } : {}),
|
||||
})
|
||||
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
|
||||
```
|
||||
|
||||
## Warstwa 3 — sekcja = kompozycja
|
||||
|
||||
```ts
|
||||
// src/blocks/Hero/config.ts
|
||||
import type { Block } from 'payload'
|
||||
import { buildLinksField } from '@intecion/ipal-kit'
|
||||
import { sectionHeaderField } from '@/fields/sectionHeader'
|
||||
import { sectionSettingsField } from '@/fields/sectionSettings'
|
||||
|
||||
export const HeroBlock: Block = {
|
||||
slug: 'hero',
|
||||
interfaceName: 'HeroBlock',
|
||||
labels: { singular: 'Hero', plural: 'Heroes' },
|
||||
fields: [
|
||||
sectionHeaderField(),
|
||||
{ name: 'media', type: 'upload', relationTo: 'media' },
|
||||
buildLinksField(),
|
||||
sectionSettingsField(),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// src/blocks/Hero/Component.tsx — cały komponent
|
||||
import type { HeroBlock } from '@/payload-types'
|
||||
import { Section } from '@/components/ui/Section'
|
||||
import { SectionHeader } from '@/components/ui/SectionHeader'
|
||||
import { Media } from '@/components/ui/Media'
|
||||
import { CMSLink } from '@/components/ui/CMSLink'
|
||||
|
||||
export function Hero({ header, media, links, settings, locale }: HeroBlock & { locale: string }) {
|
||||
return (
|
||||
<Section settings={settings}>
|
||||
<div className="grid items-center gap-10 md:grid-cols-2">
|
||||
<div>
|
||||
<SectionHeader header={header} as="h1" />
|
||||
{links?.length ? (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{links.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<Media resource={media} priority sizes="(min-width: 768px) 50vw, 100vw" />
|
||||
</div>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
|
||||
|
||||
```ts
|
||||
// src/blocks/FeatureGrid/config.ts (fields)
|
||||
sectionHeaderField(),
|
||||
{
|
||||
name: 'items',
|
||||
type: 'array',
|
||||
interfaceName: 'FeatureItem',
|
||||
fields: [
|
||||
{ name: 'media', type: 'upload', relationTo: 'media' },
|
||||
{ name: 'heading', type: 'text', localized: true, required: true },
|
||||
{ name: 'text', type: 'textarea', localized: true },
|
||||
buildLinkField({ appearances: ['link'] }),
|
||||
],
|
||||
},
|
||||
buildLinksField({ maxRows: 1 }),
|
||||
sectionSettingsField(),
|
||||
```
|
||||
|
||||
```tsx
|
||||
// src/blocks/FeatureGrid/FeatureCard.tsx
|
||||
export function FeatureCard({ item, locale }: { item: FeatureItem; locale: string }) {
|
||||
return (
|
||||
<article className="card">
|
||||
<Media resource={item.media} sizes="(min-width: 1024px) 33vw, 100vw" />
|
||||
<h3>{item.heading}</h3>
|
||||
{item.text && <p>{item.text}</p>}
|
||||
<CMSLink link={item.link} locale={locale} />
|
||||
</article>
|
||||
)
|
||||
}
|
||||
|
||||
// src/blocks/FeatureGrid/Component.tsx
|
||||
export function FeatureGrid({ header, items, links, settings, locale }: FeatureGridBlock & { locale: string }) {
|
||||
return (
|
||||
<Section settings={settings}>
|
||||
<SectionHeader header={header} />
|
||||
<div className="grid gap-6 md:grid-cols-3">
|
||||
{items?.map((item) => <FeatureCard key={item.id} item={item} locale={locale} />)}
|
||||
</div>
|
||||
{links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} className="mt-10" />)}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Wydziel podkomponent, gdy którekolwiek jest prawdą:** ten sam JSX 2+ razy;
|
||||
element `items[]` ma >5 linii markupu; `Component.tsx` >80 linii JSX; jest stan/
|
||||
interakcja (accordion, slider, tabs → osobny `'use client'`). Podkomponent
|
||||
jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/components/ui/`.
|
||||
Ikony: upload albo `select` z mapą w `src/components/icons` — nigdy SVG wklejone
|
||||
w sekcję.
|
||||
|
||||
## Ikony
|
||||
|
||||
Dwa źródła, nic pomiędzy:
|
||||
- **Dowolna grafika od klienta** → upload do `media` + `<Media>` (także logo, ikony SVG marki).
|
||||
- **Stały zestaw ikon UI** → pole `select` + mapa `lucide-react`:
|
||||
|
||||
```ts
|
||||
// src/components/icons/names.ts — same nazwy, importowane przez config bloku
|
||||
export const ICON_NAMES = ['phone', 'mail', 'mapPin', 'clock', 'check'] as const
|
||||
export type IconName = (typeof ICON_NAMES)[number]
|
||||
export const iconField = {
|
||||
name: 'icon',
|
||||
type: 'select',
|
||||
options: ICON_NAMES.map((value) => ({ label: value, value })),
|
||||
} as const
|
||||
```
|
||||
```tsx
|
||||
// src/components/icons/Icon.tsx — mapa, importowana tylko przez komponenty
|
||||
import { Check, Clock, Mail, MapPin, Phone, type LucideIcon } from 'lucide-react'
|
||||
import type { IconName } from './names'
|
||||
|
||||
const ICONS: Record<IconName, LucideIcon> = { phone: Phone, mail: Mail, mapPin: MapPin, clock: Clock, check: Check }
|
||||
|
||||
export function Icon({ name, className }: { name?: IconName | null; className?: string }) {
|
||||
if (!name) return null
|
||||
const Component = ICONS[name]
|
||||
return <Component className={className} aria-hidden />
|
||||
}
|
||||
```
|
||||
Nazwy są osobno, żeby config bloku (`payload.config`) nie importował komponentów
|
||||
React. **Nigdy** SVG wklejone w JSX sekcji.
|
||||
|
||||
## Style
|
||||
|
||||
- **Tailwind w komponentach**, kolory i fonty jako **tokeny** w `styles.css`
|
||||
(`@theme`) — źródłem jest `DESIGN.md` (Impeccable). W komponentach tylko nazwy
|
||||
tokenów (`bg-primary`, `text-foreground`), **nigdy** `bg-[#ff6600]` ani hex.
|
||||
- Tokeny pluginu mapuj na tokeny projektu — jeden kolor marki w jednym miejscu.
|
||||
- Fonty przez `next/font` w layoucie, podpięte zmienną CSS do `@theme`.
|
||||
- Bez CSS Modules i `style={{…}}` — wyjątek: wartość dynamiczna z danych.
|
||||
- Warianty wizualne → `Record<Variant, string>` (§6.3), nie łańcuchy ternary.
|
||||
|
||||
```css
|
||||
/* src/app/(frontend)/styles.css */
|
||||
@import "tailwindcss";
|
||||
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
|
||||
|
||||
@theme {
|
||||
--color-primary: oklch(0.62 0.19 45);
|
||||
--color-background: oklch(0.99 0 0);
|
||||
--color-foreground: oklch(0.2 0 0);
|
||||
--color-muted: oklch(0.96 0 0);
|
||||
--font-sans: var(--font-body); /* next/font: variable '--font-body' */
|
||||
}
|
||||
|
||||
:root {
|
||||
--ipal-primary: var(--color-primary); /* baner cookies, Turnstile = kolor marki */
|
||||
--ipal-radius: 0.75rem;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
name: ipal-collection
|
||||
description: Decides whether something should be a Payload collection, a global, or a block, and builds a content collection the ipal-kit way (title, buildSlugField, SEO tab, buildNoindexField, trackSlugHistoryHook, revalidate hook, archive page from System Pages, sitemap and routing via content option). Use when the user asks for a blog, news, products, portfolio, testimonials, authors, categories, or any new collection — and whenever you are about to create a file in src/collections.
|
||||
---
|
||||
|
||||
# ipal-collection
|
||||
|
||||
Źródła: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §5,
|
||||
`docs/content.md`, `docs/hooks.md`, `docs/seo.md`.
|
||||
|
||||
## 1. Test (zawsze, przed jakimkolwiek kodem)
|
||||
Odpowiedz użytkownikowi na 4 pytania — wszystkie muszą być TAK:
|
||||
1. Lista wielu rekordów tego samego typu?
|
||||
2. Każdy rekord ma **własny URL**?
|
||||
3. Klient **jawnie** tego wymaga?
|
||||
4. Payload nie ma tego wbudowanego?
|
||||
|
||||
Którekolwiek NIE → to nie kolekcja:
|
||||
- jeden zestaw danych (firma, menu, stopka, ustawienia) → **global**,
|
||||
- część strony (FAQ, hero, opinie w sekcji) → **blok** (skill ipal-block),
|
||||
- `users` → wbudowane w Payload, nie twórz.
|
||||
|
||||
Wyjątek: lista bez własnych URL-i zarządzana osobno (np. opinie używane w wielu
|
||||
blokach) — kolekcja **bez** wpięcia w `content`. Uzasadnij to w planie.
|
||||
|
||||
## 2. Plan (pokaż i czekaj na OK)
|
||||
slug (camelCase, l.mn.), pola, relacje, czy ma URL-e (archiwum), JSON-LD.
|
||||
|
||||
## 3. Kod
|
||||
1. `src/collections/<Nazwa>.ts`: `title` (localized), `buildSlugField({ from: 'title' })`,
|
||||
tab SEO (plugin-seo), `buildNoindexField()`, `trackSlugHistoryHook`,
|
||||
`buildRevalidateHook`, `setPublishedAtHook` (wpisy z datą), upload przez
|
||||
`media`, linki przez `buildLinkField()`. Nazwy pól wg AGENT.md §6.5.
|
||||
2. Z URL-ami: dopisz do `content.config.ts` → `{ slug, perPage }`.
|
||||
**Prefiks URL nie w kodzie** — redaktor przypisuje stronę-archiwum w
|
||||
Site Settings (`<slug>Archive`). Plugin robi routing, sitemap,
|
||||
generateStaticParams, hreflang.
|
||||
3. Lista wpisów = blok (EntriesList) z `getEntries`; strona wpisu z
|
||||
`resolveRoute` (typ `entry`); JSON-LD wg seo.md (np. Article).
|
||||
4. `pnpm generate:types`, `pnpm payload generate:importmap`.
|
||||
5. Postgres z migracjami → `pnpm payload migrate:create`.
|
||||
|
||||
## 4. Weryfikacja
|
||||
Skill **ipal-audit**. Ręcznie: wpis w panelu → widoczny pod `/<locale>/<archiwum>/<slug>`,
|
||||
w sitemapie, zmiana sluga → 308 ze starego adresu.
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
name: ipal-nav
|
||||
description: Builds the site header, footer, mobile menu and company data in an ipal-kit project — Header/Footer/Company globals with buildLinkField from the plugin, server-side link resolution (resolveNav), a small client MobileNav, legal links from System Pages, revalidation on change. Use when creating or changing navigation, menu, header, footer, contact details, social links or the company global.
|
||||
---
|
||||
|
||||
# ipal-nav
|
||||
|
||||
Gotowy kod: `resources/kod-nawigacji.md` (ten skill). Reguły: AGENT.md §6.8.
|
||||
Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (jak skill ipal-block, krok 0).
|
||||
|
||||
## Plan (pokaż i czekaj na OK)
|
||||
- pozycje menu (jeden poziom podmenu, nie głębiej), CTA w nagłówku (`links`),
|
||||
- kolumny stopki, notka,
|
||||
- model `Company` dla rynku z AGENTS.md (PL: NIP/REGON, AU: ABN, US: EIN…),
|
||||
- etykiety a11y (przycisk menu itp.) — pola w panelu.
|
||||
|
||||
## Kod
|
||||
1. `src/globals/Header.ts`, `Footer.ts` — z §6.8; `Company.ts` — dane firmy
|
||||
(teksty localized), `access.read: () => true`.
|
||||
2. Hook `afterChange` na każdym globalu: `revalidatePath('/', 'layout')`
|
||||
(wstrzyknięty z `next/cache`, hooks.md).
|
||||
3. `src/lib/navigation.ts` (`resolveNav`) — linki rozwiązane na serwerze do
|
||||
`{ href, label, newTab, subItems }`.
|
||||
4. `src/components/layout/Header.tsx`, `Footer.tsx` (serwer), `MobileNav.tsx`
|
||||
(`'use client'`, tylko stan otwarcia, dane przez props, `import type` z lib).
|
||||
5. **Linki prawne w stopce** z ról System Pages (`getSystemPagePath` + tytuł
|
||||
strony) — nie jako ręczne pozycje. Rok w copyright z kodu, nazwa z `Company`.
|
||||
6. Logo z Site Settings przez `<Media>` — nie duplikuj pola w Header.
|
||||
7. Podepnij w `src/app/(frontend)/[locale]/layout.tsx` (pobranie globali przez
|
||||
cached gettery w `lib/`, przekazanie jako props).
|
||||
|
||||
## Weryfikacja
|
||||
Skill **ipal-audit**. Ręcznie: dodanie pozycji menu w panelu widać od razu po
|
||||
zapisie; menu mobilne działa z klawiatury (Tab, Enter, Esc).
|
||||
@@ -0,0 +1,176 @@
|
||||
# Kod nawigacji — Header, Footer, menu mobilne
|
||||
|
||||
> Zasoby skilla **ipal-nav**. Reguły: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.8.
|
||||
> Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (CMSLink, Media).
|
||||
|
||||
## Header i Footer (globale nawigacji)
|
||||
|
||||
Nawigacja, stopka i dane firmy to **globale projektu** (model zależy od klienta
|
||||
i kraju), budowane z tych samych wspólnych pól co sekcje. Logo i nazwa są w
|
||||
Site Settings — nie duplikuj ich w Header.
|
||||
|
||||
```ts
|
||||
// src/globals/Header.ts
|
||||
import type { GlobalConfig } from 'payload'
|
||||
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
|
||||
|
||||
export const Header: GlobalConfig = {
|
||||
slug: 'header',
|
||||
access: { read: () => true },
|
||||
fields: [
|
||||
{
|
||||
name: 'navItems',
|
||||
type: 'array',
|
||||
maxRows: 8,
|
||||
fields: [
|
||||
buildLinkField({ appearances: false }),
|
||||
{
|
||||
name: 'subItems', // jeden poziom podmenu — głębiej nie budujemy
|
||||
type: 'array',
|
||||
maxRows: 10,
|
||||
fields: [buildLinkField({ appearances: false })],
|
||||
},
|
||||
],
|
||||
},
|
||||
buildLinksField({ maxRows: 1 }), // przycisk CTA w nagłówku
|
||||
{
|
||||
name: 'menuLabel',
|
||||
type: 'text',
|
||||
localized: true,
|
||||
admin: { description: 'Accessible label of the mobile menu button, e.g. "Menu".' },
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
```ts
|
||||
// src/globals/Footer.ts
|
||||
import type { GlobalConfig } from 'payload'
|
||||
import { buildLinkField } from '@intecion/ipal-kit'
|
||||
|
||||
export const Footer: GlobalConfig = {
|
||||
slug: 'footer',
|
||||
access: { read: () => true },
|
||||
fields: [
|
||||
{
|
||||
name: 'columns',
|
||||
type: 'array',
|
||||
maxRows: 4,
|
||||
fields: [
|
||||
{ name: 'heading', type: 'text', localized: true },
|
||||
{ name: 'items', type: 'array', fields: [buildLinkField({ appearances: false })] },
|
||||
],
|
||||
},
|
||||
{ name: 'note', type: 'textarea', localized: true }, // np. „Wszelkie prawa zastrzeżone”
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
- **Linki prawne w stopce** (polityka, cookies, regulamin) renderuj z ról System
|
||||
Pages (`getSystemPagePath` + tytuł strony) — nie dodawaj ich ręcznie do `columns`.
|
||||
- **Dane firmy** (nazwa, adres, NIP/ABN, telefon) — global `company` projektu;
|
||||
stopka i JSON-LD czytają z niego. Rok w copyright licz w kodzie
|
||||
(`new Date().getFullYear()`), nazwę bierz z globala.
|
||||
- **Odświeżanie:** global zmienia się na każdej stronie → hook `afterChange`
|
||||
z `revalidatePath('/', 'layout')` (hooks.md).
|
||||
|
||||
Linki rozwiązuj **na serwerze** do zwykłych danych, a do klienta (menu mobilne)
|
||||
przekazuj tylko `{ href, label, newTab }` — komponent kliencki nie może wołać
|
||||
`CMSLink` (to async server component).
|
||||
|
||||
```ts
|
||||
// src/lib/navigation.ts
|
||||
import { resolveLinkHref } from '@intecion/ipal-kit'
|
||||
import type { CmsLink } from '@/payload-types'
|
||||
import { i18nConfig } from '@/i18n.config'
|
||||
import { getSettings } from '@/lib/content'
|
||||
|
||||
export type NavItem = { href: string; label: string; newTab: boolean; subItems: NavItem[] }
|
||||
|
||||
type NavSource = { link?: CmsLink | null; subItems?: { link?: CmsLink | null }[] | null }
|
||||
|
||||
function toNavItem(link: CmsLink | null | undefined, locale: string, homeSlug?: string): NavItem | null {
|
||||
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
|
||||
if (!link || !href || !link.label) return null
|
||||
return { href, label: link.label, newTab: Boolean(link.newTab), subItems: [] }
|
||||
}
|
||||
|
||||
export async function resolveNav(items: NavSource[] | null | undefined, locale: string): Promise<NavItem[]> {
|
||||
const settings = await getSettings(locale)
|
||||
const home = settings?.homepage
|
||||
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
|
||||
|
||||
return (items ?? []).flatMap((item) => {
|
||||
const node = toNavItem(item.link, locale, homeSlug)
|
||||
if (!node) return []
|
||||
node.subItems = (item.subItems ?? []).flatMap((sub) => {
|
||||
const child = toNavItem(sub.link, locale, homeSlug)
|
||||
return child ? [child] : []
|
||||
})
|
||||
return [node]
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// src/components/layout/Header.tsx — serwer
|
||||
import Link from 'next/link'
|
||||
import type { Header as HeaderData } from '@/payload-types'
|
||||
import { resolveNav } from '@/lib/navigation'
|
||||
import { CMSLink } from '@/components/ui/CMSLink'
|
||||
import { MobileNav } from './MobileNav'
|
||||
|
||||
export async function Header({ header, locale }: { header: HeaderData; locale: string }) {
|
||||
const items = await resolveNav(header.navItems, locale)
|
||||
return (
|
||||
<header className="border-b">
|
||||
<nav className="container flex items-center justify-between py-4">
|
||||
{/* logo: Site Settings → <Media> */}
|
||||
<ul className="hidden gap-6 md:flex">
|
||||
{items.map((item) => (
|
||||
<li key={item.href}>
|
||||
<Link href={item.href} {...(item.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})}>
|
||||
{item.label}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{header.links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
|
||||
<MobileNav items={items} menuLabel={header.menuLabel ?? ''} />
|
||||
</nav>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// src/components/layout/MobileNav.tsx — klient, tylko stan otwarcia
|
||||
'use client'
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import type { NavItem } from '@/lib/navigation' // import TYPU — nie ciągnie kodu serwera
|
||||
|
||||
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<div className="md:hidden">
|
||||
<button type="button" aria-expanded={open} aria-label={menuLabel} onClick={() => setOpen(!open)}>
|
||||
<span aria-hidden>☰</span>
|
||||
</button>
|
||||
{open && (
|
||||
<ul>
|
||||
{items.map((item) => (
|
||||
<li key={item.href}>
|
||||
<Link href={item.href} onClick={() => setOpen(false)}>{item.label}</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: ipal-plugin-gap
|
||||
description: Handles the moment when @intecion/ipal-kit seems to lack a feature or behaves wrongly — verifies against the plugin docs and type definitions first, then writes a structured report for the plugin instead of patching the project with hooks, hardcoded values or copied plugin code. Use when tempted to work around the plugin, when a plugin function errors or is missing, or when the same need appears in several projects.
|
||||
---
|
||||
|
||||
# ipal-plugin-gap
|
||||
|
||||
Reguła: AGENT.md §1.3 — **nie łataj w projekcie**.
|
||||
|
||||
## 1. Sprawdź, czy plugin tego nie ma
|
||||
- `ls node_modules/@intecion/ipal-kit/docs/` — przeczytaj plik modułu,
|
||||
- `grep -rn "<słowo kluczowe>" node_modules/@intecion/ipal-kit/dist --include=*.d.ts`,
|
||||
- sprawdź wersję: `grep '"version"' node_modules/@intecion/ipal-kit/package.json`
|
||||
(może problem jest naprawiony w nowszej — skill **ipal-upgrade**).
|
||||
|
||||
Plugin to ma → użyj go i powiedz użytkownikowi, gdzie to było.
|
||||
|
||||
## 2. Raport (gdy naprawdę brakuje albo nie działa)
|
||||
Zapisz w `docs/plugin-requests/<data>-<temat>.md` projektu i pokaż użytkownikowi:
|
||||
|
||||
```markdown
|
||||
# <temat>
|
||||
**Projekt:** <nazwa> · **ipal-kit:** <wersja>
|
||||
## Problem
|
||||
<co nie działa / czego brakuje; komunikat błędu; kroki odtworzenia>
|
||||
## Dlaczego to do pluginu
|
||||
<czy przyda się w innych projektach — konkretnie>
|
||||
## Proponowane API
|
||||
<sygnatura funkcji / opcja ipalKit / pole w panelu; przykład użycia w projekcie>
|
||||
## Obejście tymczasowe (jeśli konieczne)
|
||||
<minimalne, w jednym pliku, z komentarzem TODO odsyłającym do tego raportu>
|
||||
```
|
||||
|
||||
## 3. Czego nie robić
|
||||
- hooka z zaszytą domeną/nazwą/kolorem klienta,
|
||||
- kopii komponentu pluginu do projektu (np. `Analytics`, `CookieBanner`),
|
||||
- `as any` / `@ts-ignore` żeby „przeszło”,
|
||||
- dynamicznego `import()` przez zmienną (nie wbundluje się).
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: ipal-setup
|
||||
description: Sets up a new client project on Payload 3 + Next 16 + @intecion/ipal-kit from an empty folder — registry and dependencies, version overrides, i18n config, payload.config with ipalKit (2FA injected, white-label), core collections, design tokens, UI primitives, proxy, layout and catch-all page, SEO routes, security headers, env validation. Use when starting a new website project or when a project is missing its ipal-kit foundation.
|
||||
---
|
||||
|
||||
# ipal-setup
|
||||
|
||||
Kod i szczegóły: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md` §1–2
|
||||
(przed instalacją pakietu: poproś użytkownika o ten plik albo działaj wg kroków
|
||||
poniżej i doczytaj po `pnpm add`). Reguły: `docs/agent/AGENT.md`.
|
||||
|
||||
**Jeden etap = jeden commit. Po każdym etapie pokaż wynik i czekaj na OK.**
|
||||
|
||||
1. **Instalacja** — `.npmrc` (`@intecion:registry=…`, `legacy-peer-deps=true`),
|
||||
`pnpm add @intecion/ipal-kit` + zależności z PROGRAMISTA §1, `pnpm.overrides`
|
||||
na wersję `payload` dla wszystkich `@payloadcms/*`, build z `--webpack`.
|
||||
Nigdy instalacja z gita. Nie twórz `middleware.ts`.
|
||||
2. **Skille i AGENTS.md** — skopiuj skille (AGENT.md §14), utwórz `AGENTS.md`
|
||||
wg AGENT.md §13 z danymi od użytkownika (zapytaj o: klient, domena, rynek,
|
||||
języki, R2/lokalnie, SMTP/Graph).
|
||||
3. **Konfiguracja** — `src/i18n.config.ts` (`as const satisfies I18nConfig`),
|
||||
`payload.config.ts` wg PROGRAMISTA §2.3: `twoFactor` z **wstrzykniętym**
|
||||
`payloadTotp`, `whiteLabel: true`, `email: mailAdapter()`.
|
||||
4. **Rdzeń** — wspólne pola i prymitywy (`../ipal-block/resources/kod-sekcji.md`), `Pages`, `Media`
|
||||
(PROGRAMISTA §2.4). Żadnych innych kolekcji.
|
||||
5. **Style** — `styles.css` z `@theme` z `DESIGN.md` (jeśli brak — zapytaj o
|
||||
Impeccable albo załóż neutralne tokeny), `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`).
|
||||
6. **Routing** — `proxy.ts` (`createProxy`), `lib/content.ts`, layout bez
|
||||
`<head>`, catch-all z ISR + `generateStaticParams` + `resolveRedirect`,
|
||||
`not-found.tsx` z `LocaleView` — bez `headers()`, wersja na każdy język (PROGRAMISTA §2.6–2.8, pages.md).
|
||||
7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, llms.txt, health
|
||||
(wszystkie z `force-dynamic`), `htmlLimitedBots`, `buildSecurityHeaders`,
|
||||
`instrumentation.ts` z `assertEnv` (PROGRAMISTA §2.8–2.9).
|
||||
8. **Nawigacja** — skill **ipal-nav**.
|
||||
9. `pnpm generate:types`, `pnpm payload generate:importmap`, skill **ipal-audit**
|
||||
(pełny), lista kroków w panelu dla użytkownika (PROGRAMISTA §2.11).
|
||||
|
||||
Dalej: bloki (skill **ipal-block**), kolekcje treści (**ipal-collection**).
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: ipal-upgrade
|
||||
description: Upgrades an existing project to the latest @intecion/ipal-kit and replaces hand-written code that the plugin now provides — proxy, route handlers, consent wrapper, language switcher, rich text parser, form logic, noindex, redirects, env validation, privacy link label, 404 page, CTA field zoo. Use when the user asks to update ipal-kit, migrate an older project, or clean up duplicated logic in a project.
|
||||
---
|
||||
|
||||
# ipal-upgrade
|
||||
|
||||
Lista zmian: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md` §6.
|
||||
Zasada: gdy plugin dostarcza coś, co projekt ma ręcznie — **usuń lokalną wersję**.
|
||||
|
||||
## 1. Aktualizacja pakietu
|
||||
```bash
|
||||
pnpm add @intecion/ipal-kit@latest
|
||||
rm -rf .next
|
||||
```
|
||||
Skopiuj skille na nowo (AGENT.md §14) — mogły się zmienić.
|
||||
Postgres z migracjami: nowe pola pluginu (np. `privacyLinkLabel`) →
|
||||
`pnpm payload migrate:create`.
|
||||
|
||||
## 2. Inwentaryzacja (bez zmian w kodzie)
|
||||
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
|
||||
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
|
||||
Wynik: lista do zrobienia z priorytetem. Czekaj na OK.
|
||||
|
||||
## 3. Pozycja po pozycji
|
||||
Jedna pozycja = jedna zmiana = jeden commit:
|
||||
1. przeczytaj wskazany plik docs,
|
||||
2. zastąp lokalny kod funkcją pluginu, usuń stary kod (nie zostawiaj obu),
|
||||
3. `pnpm build`, pokaż wynik.
|
||||
|
||||
Pozycje zmieniające nazwy pól w bazie (np. refaktor `ctaLabel` → `links`)
|
||||
wymagają **migracji danych przed** usunięciem starych pól — zapytaj
|
||||
użytkownika, czy projekt ma już treść.
|
||||
|
||||
## 4. Koniec
|
||||
Pełny **ipal-audit** bez błędów + lista rzeczy do sprawdzenia w panelu.
|
||||
@@ -1,276 +0,0 @@
|
||||
<!--
|
||||
SZABLON agents.md dla projektów na @intecion/ipal-kit.
|
||||
|
||||
UŻYCIE: skopiuj ten plik do ROOTA nowego projektu jako `agents.md` (albo
|
||||
AGENTS.md). Agenci (Antigravity, Claude Code, Cursor) czytają go automatycznie.
|
||||
NIE zostawiaj go w docs/ — musi być w katalogu głównym projektu.
|
||||
|
||||
Dostosuj tylko to, co oznaczone <!-- DOSTOSUJ -->; reszta to uniwersalne
|
||||
reguły ekosystemu ipal-kit (nie zmieniaj bez powodu).
|
||||
|
||||
Źródło prawdy dla szczegółów: node_modules/@intecion/ipal-kit/docs/
|
||||
-->
|
||||
|
||||
# Zasady i Standardy Projektowe — Payload CMS 3 + Next 16 + @intecion/ipal-kit
|
||||
|
||||
> **Projekt:** <!-- DOSTOSUJ: nazwa klienta, domena, rynek (PL/AU/US), branża -->
|
||||
|
||||
|
||||
Niniejszy dokument stanowi bezwzględnie obowiązujące reguły pracy dla agenta (Antigravity) w niniejszym projekcie. Został sporządzony na podstawie dokumentacji w `/docs`. Każda zasada musi być ściśle przestrzegana, bez wyjątków i bez stosowania obejść/prowizorek.
|
||||
|
||||
---
|
||||
|
||||
## 1. ZASADA NADRZĘDNA: ipal-kit JEST OBOWIĄZKOWY
|
||||
|
||||
1. **Obowiązkowe użycie pluginu:**
|
||||
- Każda funkcja dostarczana przez `@intecion/ipal-kit` (i18n, SEO, formularze, consent, email, slug, bezpieczeństwo, strony systemowe, storage R2, breadcrumbs, JSON-LD) **MUSI** być realizowana przez plugin.
|
||||
- **NIGDY** nie twórz własnego kodu w projekcie dublującego możliwości pluginu.
|
||||
2. **Sprawdzaj przed pisaniem:**
|
||||
- Zanim napiszesz jakąkolwiek funkcję, helper czy komponent — sprawdź dokumentację w `node_modules/@intecion/ipal-kit/docs/` oraz definicje typów `.d.ts`. Jeśli funkcja istnieje w pluginie, **musisz** jej użyć.
|
||||
3. **Gdy w pluginie czegoś brakuje:**
|
||||
- **NIE** obchodź braku prowizorką ani własnym kodem w projekcie (to tworzy dług technologiczny i rozbieżności).
|
||||
- **Zgłoś brak funkcji do rozbudowy pluginu**, zamiast łatać to lokalnie.
|
||||
- Logika uniwersalna (przydatna w innych projektach) trafia do pluginu. W projekcie znajduje się **wyłącznie** specyfika danego klienta (jego bloki, wygląd, struktura danych).
|
||||
4. **Gdy coś w pluginie nie działa:**
|
||||
- **Zgłoś problem i błąd**, zamiast tworzyć ciche obejścia, prowizoryczne hooki czy hardkodowane patche.
|
||||
|
||||
---
|
||||
|
||||
## 2. KROK 0: INSTALACJA I DOSTĘP DO DOKUMENTACJI PLUGINU
|
||||
|
||||
1. **Utwórz `.npmrc` w katalogu projektu:**
|
||||
```ini
|
||||
legacy-peer-deps=true
|
||||
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
|
||||
```
|
||||
*(Scoped override: tylko `@intecion/*` z Gitea, rejestr publiczny bez tokena).*
|
||||
2. **Instalacja pluginu:**
|
||||
```bash
|
||||
pnpm add @intecion/ipal-kit
|
||||
```
|
||||
*(NIGDY nie instaluj z gita `git+https://...` — psuje React Client Manifest w Next).*
|
||||
3. **Lokalizacja dokumentacji źródłowej:**
|
||||
```bash
|
||||
ls node_modules/@intecion/ipal-kit/docs/
|
||||
```
|
||||
Zawsze korzystaj z plików w `docs/` pluginu (`getting-started.md`, `seo.md`, `forms.md`, `email.md`, `storage.md`, `i18n.md`, `blocks.md`, `turnstile.md` itd.).
|
||||
|
||||
---
|
||||
|
||||
## 3. ABSOLUTNY ZAKAZ HARDKODOWANIA
|
||||
|
||||
### A. Treść i teksty:
|
||||
- **ZAKAZ:** Tekst widoczny dla użytkownika wpisany w JSX, etykiety i komunikaty w kodzie, instrukcje `if (locale === 'pl')`, tablice z tekstami w kodzie.
|
||||
- **WYMAGANE:** Każdy tekst pochodzi z pola `localized: true`, pobierany z panelu CMS.
|
||||
- **Częsty błąd (ukryty hardkod w fallbacku):** `siteName || 'Nazwa Klienta'` lub `catch { return { name: 'Firma...' } }` to **niedopuszczalny hardkod**! Gdy brak danych z panelu/env: **pomiń pole** (np. `...(val ? { name: val } : {})`), nie wstawiaj danych klienta w fallbacku `||` ani w bloku `catch`.
|
||||
|
||||
### B. Obrazy i multimedia:
|
||||
- **ZAKAZ:** `import logo from '@/assets/...'`, ścieżki `src="/images/..."`.
|
||||
- **WYMAGANE:** Pole `type: 'upload', relationTo: 'media'`, renderowane z `media.url`. Do kolekcji `Media` obowiązkowo wepnij `normalizeFilenameHook`.
|
||||
- **Preconnect:** Użyj `<MediaPreconnect />` z pluginu (czyta `R2_PUBLIC_URL` z env), nigdy sztywnego tagu `<link>` z domeną.
|
||||
- **Favicon:** Użyj `buildIconsMetadata(settings.favicon)` z panelu (format PNG, nie ręczny SVG).
|
||||
|
||||
### C. Linki i routing:
|
||||
- **ZAKAZ:** `href="/pl/kontakt"`, menu jako statyczna tablica w kodzie, oraz **sztywna mapa zlokalizowanych ścieżek** (`const localizedRoutes = {...}` — kardynalny antywzorzec).
|
||||
- **WYMAGANE:** `getLocalizedSlugs` / `switchLocalePath` z bazy danych, `getSystemPagePath`, relacje `relationship -> pages` w panelu CMS.
|
||||
|
||||
### D. Konfiguracja i dane firmy:
|
||||
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
|
||||
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
|
||||
|
||||
### E. Renderer bloków, kolekcje, formularze (częste błędy):
|
||||
- **Renderer rich text:** ZAWSZE `RenderRichText` z pluginu (`@intecion/ipal-kit/rsc`, wrapper nad oficjalnym konwerterem Lexical). NIGDY własny parser Lexical (switch po node.type, flagi node.format, dangerouslySetInnerHTML, hardkod `.pl`). Styl przez `converters`. Patrz richtext.md.
|
||||
- **Renderer bloków:** ZAWSZE `RenderBlocks` z pluginu + mapa `registry`. NIGDY własny `switch (block.blockType)` — to gadatliwe, bez enhanceProps, rośnie liniowo. Mapa deklaratywna, silnik z pluginu.
|
||||
- **MINIMUM kolekcji, nie maksimum:** Domyślnie tylko rdzeń (pages, media, settings, navigation, footer + globale). Kolekcję treści (blog/produkty) TYLKO gdy klient JAWNIE wymaga. NIGDY nie twórz: `users` (WBUDOWANE w Payload — nie duplikuj!), `daneFirmy`/`settings` jako kolekcje (to GLOBALE), FAQ/hero/features jako kolekcje (to BLOKI). Test przed stworzeniem: lista rekordów + własny URL + jawna potrzeba + Payload nie ma wbudowanego. Patrz `kolekcje-katalog.md`.
|
||||
- **Formularze z buildera:** ZAWSZE pola/etykiety/komunikaty z buildera w panelu (kolekcja Forms) + `submitForm`. NIGDY nie hardkoduj pól ani tekstów w JSX. Turnstile: `TurnstileProvider` (siteKey raz w layoutcie) + `useTurnstile()`.
|
||||
- **Logika formularza z pluginu:** stan/walidacja/Turnstile/submit przez `useForm` (dowolne pola) lub `useContactForm` (preset) z `@intecion/ipal-kit/client` — hooki NIE renderują markupu, wygląd zostaje w projekcie. NIGDY nie kopiuj ręcznej hydrauliki (useState na pola, regex e-maila, obsługa tokenu, try/catch submitu) do projektu — to antywzorzec, który hook eliminuje. Walidacja przez `buildValidator` + reguły (`required`, `email`, `minLength`, `pattern`…). Patrz `forms.md`.
|
||||
- **Wartości lokalizowane:** ZAWSZE `resolveLocalized(value, locale)` z pluginu. NIGDY własny `getSafeString`/`(v as any)[locale]` kopiowany do JSON-LD, rich text czy topiców formularza.
|
||||
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
|
||||
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
|
||||
|
||||
---
|
||||
|
||||
## 4. ARCHITEKTURA I STRUKTURA PROJEKTU
|
||||
|
||||
### A. Next 16 + Payload 3:
|
||||
- **NIGDY nie twórz `middleware.ts`.** W Next 16 stosuje się **WYŁĄCZNIE `proxy.ts`** (funkcja `proxy`). Jeśli plik `middleware.ts` istnieje — usuń go natychmiast.
|
||||
- **Struktura katalogów:**
|
||||
```
|
||||
src/
|
||||
app/
|
||||
(frontend)/
|
||||
styles.css # Tailwind + @source na plugin
|
||||
[locale]/
|
||||
layout.tsx # root layout bez sztywnego <head>
|
||||
not-found.tsx # 404 (treść z panelu)
|
||||
[[...slug]]/
|
||||
page.tsx # render stron z bloków (podwójne nawiasy!)
|
||||
(payload)/ # panel admina
|
||||
manifest.ts # PWA z panelu — WYMAGANE export const dynamic = 'force-dynamic'
|
||||
sitemap.ts # z lib/content + export const dynamic = 'force-dynamic'
|
||||
robots.ts # z lib/content
|
||||
instrumentation.ts # assertEnv(ipalEnvRules(...)) — walidacja ENV na starcie
|
||||
blocks/
|
||||
<NazwaBloku>/
|
||||
config.ts # schemat pól bloku
|
||||
Component.tsx # render komponentu
|
||||
registry.ts # mapa blockType -> komponent
|
||||
collections/
|
||||
Pages.ts # layout typu blocks
|
||||
Media.ts # upload + normalizeFilenameHook
|
||||
globals/ # siteSettings, siteIntegrations, navigation, footer
|
||||
lib/
|
||||
content.ts # createContentHelpers — JEDNO źródło
|
||||
payload.ts # helpery projektu (getSettings...)
|
||||
i18n.config.ts # locale — jedno źródło
|
||||
payload.config.ts
|
||||
proxy.ts # routing locale (NIE middleware.ts)
|
||||
```
|
||||
|
||||
### B. Przepływ danych i zależności:
|
||||
- **Brak cykli importów:** Warstwa niższa (bloki) **NIE** może importować warstwy wyższej (`lib/*`). Dane zewnętrzne (np. klucze Turnstile) przekazuj przez `enhanceProps` w `page.tsx`.
|
||||
- **Dostęp do Payloada:** Jedno źródło `getCachedPayload` w `lib/content.ts`.
|
||||
- **Server Components (RSC) domyślnie:** Pobieranie danych po stronie serwera; `'use client'` stosuj wyłącznie dla komponentów z lokalnym stanem/interakcją. Chroń wrażliwe moduły przez `import 'server-only'`.
|
||||
|
||||
### C. Kluczowe wymagania SEO i Renderingu:
|
||||
1. **Brak jawnego `<head>` w layoutcie:** Sztywny `<head>` wypycha metatagi Next.js do `<body>`. Pozwól Next.js zarządzać nagłówkiem. `<MediaPreconnect />` umieszczaj w `<body>` (React 19 automatycznie hoistuje tag link do head).
|
||||
2. **Wymagane ISR:** `export const revalidate = 3600` w `page.tsx` stron (zapobiega race condition streamingu metadanych i zapewnia TTFB ~20ms).
|
||||
3. **Wymagane `generateStaticParams`:** W `[[...slug]]/page.tsx` eksportuj `generateStaticParams` z `lib/content` (`export { generateStaticParams } from '@/lib/content'`). Gwarantuje synchroniczne generowanie metadanych w `<head>` dla robotów.
|
||||
4. **`htmlLimitedBots`:** Skonfiguruj w `next.config.ts` zgodnie z `seo.md`.
|
||||
5. **`export const dynamic = 'force-dynamic'` na route'ach odpytujących bazę:** `manifest.ts`, `llms.txt/route.ts`, `sitemap.xml/route.ts`. Bez tego Next próbuje prerenderować je podczas `docker build` (baza offline → crash). Handlery pluginu mają try/catch jako drugą warstwę, ale `dynamic` to eksport modułowy — MUSI być w pliku route'a, handler nie ustawi go za Ciebie.
|
||||
6. **Walidacja ENV na starcie:** `instrumentation.ts` z `assertEnv(ipalEnvRules({ ... }))` — fail fast przy brakującej konfiguracji, zamiast kryptograficznego crashu w buildzie. Patrz `env.md`.
|
||||
|
||||
---
|
||||
|
||||
## 5. STANDARDY KODU I TYPOWANIA (POZIOM SENIOR)
|
||||
|
||||
1. **Zero `any` i zero `@ts-ignore`:**
|
||||
- Zawsze typuj precyzyjnie. Jeśli kształt danych z zewnątrz jest nieznany, użyj `unknown` + zawężenie (type guard).
|
||||
- Wyjątek: wąskie rzutowanie `as unknown as Record<string, unknown>` przy udokumentowanych rozbieżnościach generatora Payload (np. pole zlokalizowane przy `locale: 'all'`).
|
||||
2. **Typy generowane:** Importuj typy z `@/payload-types` (`pnpm generate:types`), nie twórz ręcznych duplikatów interfejsów.
|
||||
3. **Generyki przy wywołaniu:** Stosuj np. `getSiteSettings<SiteSetting>(payload)`, a nie rzutowanie `as SiteSetting` na wyniku.
|
||||
4. **`satisfies` dla konfiguracji:** Używaj `as const satisfies I18nConfig`.
|
||||
5. **Obsługa błędów:** Nigdy nie połykaj błędów (`catch {}`). Loguj konkretny komunikat i zwracaj kontrolowany błąd. Stosuj guard clauses (płaski kod).
|
||||
6. **Transakcje i hooki:** W hookach Payload zawsze przekazuj `req` do kolejnych operacji bazodanowych. Chroń hooki przed nieskończonymi pętlami za pomocą flagi w `context` (np. `context.skip`). Przy `payload.find` pamiętaj o `overrideAccess: false`, jeśli operacja ma respektować uprawnienia usera.
|
||||
|
||||
---
|
||||
|
||||
## 6. NAZEWNICTWO I KONWENCJE
|
||||
|
||||
- **Foldery bloków i pliki kolekcji:** PascalCase (`blocks/HeroSection/`, `collections/Pages.ts`).
|
||||
- **Pliki bloku:** `config.ts` + `Component.tsx` w jednym folderze.
|
||||
- **Slugi kolekcji:** camelCase, liczba mnoga (`pages`, `blogPosts`, `products`).
|
||||
- **Slugi bloków:** camelCase (`hero`, `textSection`). Klucz w `registry.ts` musi być identyczny ze slugiem bloku.
|
||||
- **Wspólne nazwy pól (obowiązkowe w każdym projekcie):**
|
||||
- Nagłówek: `heading`
|
||||
- Podtytuł: `subheading`
|
||||
- Treść: `body` (textarea) lub `content` (richText)
|
||||
- Obraz: `image` (upload -> media)
|
||||
- Przycisk CTA: `ctaLabel` (text, localized)
|
||||
- Cel CTA: `ctaTarget` (relationship -> pages)
|
||||
- Link zewn.: `url` (text)
|
||||
- Zgoda prawna: `consent` (checkbox)
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Globale Company/Header/Footer → PROJEKT, nie plugin.** Model danych firmy różni się per kraj (NIP/PL, ABN/AU, EIN/US) i branżę. NIE szukaj buildCompanyGlobal w pluginie — zdefiniuj własny src/globals/Company.ts. Schema.org: klocki pluginu (buildOrganizationJsonLd...) + JsonLdGraph, zmapuj SWOJE dane na @type (LegalService/PL, HVACBusiness/AU). Patrz seo.md.
|
||||
|
||||
## 6b. WYMAGANIA PRAWNE (COMPLIANCE)
|
||||
|
||||
Każda strona (PL/EU) MUSI mieć: polityka prywatności, polityka cookies, baner
|
||||
zgody cookies, zgoda RODO w formularzach. Plugin dostarcza MECHANIZM:
|
||||
- **Strony polityk** → System Pages (role: privacyPolicy, cookiePolicy, termsOfService), linkowane przez `getSystemPagePath`.
|
||||
- **Baner cookies** → CookieBanner + CookieButton + ConsentProvider (analytics/marketing gated — NIE ładują się przed zgodą).
|
||||
- **Zgoda RODO** → checkbox `consent` w formularzu (enforcement server-side w submitForm).
|
||||
- **Strony noindex** → polityki/regulamin zaznacz `noindex` w panelu SEO (kanibalizacja fraz).
|
||||
- **Ochrona:** hook `buildPreventDeleteSystemPage` blokuje usunięcie strony systemowej.
|
||||
|
||||
Granica: MY dostarczamy mechanizm, TREŚĆ prawną (tekst polityk) tworzy klient/prawnik.
|
||||
|
||||
**Widget dostępności (a11y)** — OPCJONALNY, NIE dodawaj domyślnie. Wymagany tylko
|
||||
dla podmiotów publicznych / części e-commerce (European Accessibility Act). Dla
|
||||
zwykłych stron komercyjnych to opcja — dodawaj GDY klient wymaga (AccessibilityProvider
|
||||
+ AccessibilityWidget + CSS projektu). Patrz `accessibility.md`.
|
||||
Patrz `wymagania-prawne.md`.
|
||||
|
||||
## 6c. HOOKI PLUGINU (automatyzacja)
|
||||
|
||||
Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`):
|
||||
- **buildRevalidateHook** (afterChange/afterDelete) — ISR odświeżany po zapisie (redaktor od razu widzi zmianę). `revalidatePath` wstrzykiwany z projektu.
|
||||
- **trackSlugHistoryHook** (beforeChange) — zmiana slug → zapis starego slug. Odczyt robi **resolveRedirect** (patrz niżej) — NIE pisz własnego lookupu.
|
||||
- **resolveRedirect** (moduł content) — w catch-all, gdy `resolveRoute` nic nie znajdzie: czyta slugHistory i zwraca cel 301/308; projekt woła `permanentRedirect` (plugin nie importuje `next/navigation`). Domyka trackSlugHistoryHook.
|
||||
- **buildCrossLocaleFieldSync** (afterChange) — kopiuje pola wspólne dla języków (obrazki) wewnątrz lokalizowanego `blocks` między locale. Lista języków z `config` (NIGDY hardkod `['pl','en',…]`). Zastępuje ręczny hook z zahardkodowaną listą.
|
||||
- **buildNoindexField** (pole, nie hook) — sidebarowy checkbox `noindex` zgrany z `meta.noindex`, bez `any`. Zamiast ręcznego checkboxa + hooka glue.
|
||||
- **setPublishedAtHook** — auto-data publikacji (blog).
|
||||
- **normalizeFilenameHook** — czyste nazwy plików (Media, obowiązkowo).
|
||||
- **buildPreventDeleteSystemPage** / **buildValidateUniqueRole** — ochrona stron systemowych.
|
||||
|
||||
## 6d. BEZPIECZEŃSTWO (nagłówki)
|
||||
|
||||
- **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne).
|
||||
- **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`.
|
||||
- **2FA WYMUSZONE** — `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`, potem WSTRZYKNIJ: `import { payloadTotp } from '@clocklimited/payload-2fa'` + `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', plugin: payloadTotp } })`. Wstrzyknięcie obowiązkowe — bez niego plugin robi dynamiczny import, którego Next nie wbundluje → „Cannot find module" na froncie. (Ewentualnie: `serverExternalPackages: ['@clocklimited/payload-2fa']` w next.config.) Wymuszone dla WSZYSTKICH (forceSetup), bez opcji per user. NIE `twoFactor: false` (chyba że klient wprost odmawia). Patrz security.md.
|
||||
- **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona).
|
||||
- CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA).
|
||||
|
||||
## 7. PODZIAŁ PRACY I RÓL
|
||||
|
||||
- **Antigravity (Agent):** Buduje architekturę, logikę, kolekcje, bloki, routing, edytowalność przez panel, integracje oraz dba o brak hardkodów.
|
||||
- **Impeccable (osobne narzędzie):** Dopracowuje wygląd, system wizualny na bazie `PRODUCT.md` i `DESIGN.md`. Antigravity nie „dopieszcza" styli ad-hoc kosztem logiki i edytowalności.
|
||||
- **Klient / Redaktor:** Samodzielnie zarządza każdą treścią z poziomu panelu CMS.
|
||||
|
||||
---
|
||||
|
||||
## 8. PROCEDURA RAPORTOWANIA DO PLUGINU
|
||||
|
||||
Jeśli w trakcie pracy:
|
||||
1. Funkcja okaże się brakująca w `@intecion/ipal-kit`,
|
||||
2. Wystąpi błąd wewnętrzny w bibliotece pluginu,
|
||||
3. Pojawi się powtarzalna potrzeba biznesowa przydatna w wielu projektach,
|
||||
|
||||
**Należy natychmiast przygotować raport proponowanej zmiany/rozbudowy pluginu:**
|
||||
- Dokładny opis problemu / brakującej funkcjonalności,
|
||||
- Proponowany interfejs API / sygnatura funkcji lub konfiguracji,
|
||||
- Uzasadnienie uniwersalności dla innych projektów.
|
||||
**Nie wolno tworzyć cichej łaty w kodzie projektu.**
|
||||
|
||||
---
|
||||
|
||||
## 9. MAPA DOKUMENTACJI — gdzie szukać szczegółów
|
||||
|
||||
Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-kit/docs/`:
|
||||
|
||||
| Chcę... | Plik |
|
||||
|---|---|
|
||||
| Zbudować projekt od zera | `getting-started.md` |
|
||||
| Strukturę, nazewnictwo, konwencje | `fundamenty-projektu.md` |
|
||||
| Jakie kolekcje budować (minimum!) | `kolekcje-katalog.md` |
|
||||
| SEO, metadane, sitemap, favicon, structured data, llms.txt | `seo.md` |
|
||||
| Hooki (revalidate, slug history, cross-locale sync, ochrona) | `hooks.md` |
|
||||
| Redirecty 301/308 (resolveRedirect) | `content.md` |
|
||||
| Walidacja ENV na starcie (assertEnv) | `env.md` |
|
||||
| Czytelność dla AI: Markdown per strona, llms-full, boty AI w robots | `content.md`, `seo.md` |
|
||||
| Serwer MCP strony (Claude podłącza się do treści) | `mcp.md` |
|
||||
| GTM + Meta Pixel — konfiguracja krok po kroku | `gtm-meta-pixel.md` |
|
||||
| White-label panelu admina (logo/nazwa z SiteSettings) | `white-label.md` |
|
||||
| Bezpieczeństwo, CSP, COOP | `security.md` |
|
||||
| Formularze, Turnstile, submitForm, useForm/useContactForm | `forms.md`, `turnstile.md` |
|
||||
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
|
||||
| Strony systemowe, routing | `pages.md` |
|
||||
| Bloki, RenderBlocks | `blocks.md` |
|
||||
| Media, R2, MediaPreconnect | `storage.md` |
|
||||
| Email (SMTP/Graph) | `email.md` |
|
||||
| Consent, cookies | `consent.md` |
|
||||
| Deployment, ISR/SSG, Coolify | `deployment.md` |
|
||||
| Wymagania prawne, compliance | `wymagania-prawne.md` |
|
||||
| Filozofia CMS, edytowalność, Impeccable | `architektura-tresci.md` |
|
||||
| Standardy kodu, antywzorce | `standardy-kodu.md` |
|
||||
|
||||
---
|
||||
|
||||
## 10. ZAPISZ REGUŁY PROJEKTU
|
||||
|
||||
Kluczowe ustalenia projektu (stack, decyzje, tryby stron) zapisz we własnym pliku
|
||||
kontekstu (`agents.md` / `.agents/context/`), żeby nie gubić ich między sesjami.
|
||||
Nie polegaj tylko na pamięci sesji.
|
||||
+241
-11
@@ -1,22 +1,58 @@
|
||||
# analytics
|
||||
|
||||
Ładuje GA4 albo Google Tag Manager, spięte z modułem consent: Consent Mode
|
||||
dostaje decyzję odwiedzającego, zanim tag się załaduje, i aktualizację w
|
||||
momencie kliknięcia w banerze.
|
||||
Ładuje tagi analityczne i marketingowe wpisane w panelu, każdy zgodnie ze
|
||||
zgodą z modułu consent:
|
||||
|
||||
- **Google (GA4 / GTM)** — przez Consent Mode v2: tag ładuje się od razu, ale
|
||||
dostaje decyzję odwiedzającego, zanim cokolwiek zmierzy.
|
||||
- **Pozostałe (Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel)** —
|
||||
nie mają Consent Mode, więc ładują się **dopiero po zgodzie** na właściwą
|
||||
kategorię. Reagują na żywo: klik „Akceptuj” → tag startuje bez przeładowania.
|
||||
|
||||
## Config
|
||||
|
||||
Brak opcji w `payload.config` — plugin czyta ID z globala **Site Integrations**
|
||||
(Settings → Site Integrations):
|
||||
|
||||
- **GA4 Measurement ID** — `G-XXXXXXXXXX`
|
||||
- **GTM Container ID** — `GTM-XXXXXXX`
|
||||
| Pole | Format | Kategoria zgody |
|
||||
|---|---|---|
|
||||
| GA4 Measurement ID | `G-XXXXXXXXXX` | Consent Mode (analytics_storage) |
|
||||
| GTM Container ID | `GTM-XXXXXXX` | Consent Mode (wszystkie sygnały) |
|
||||
| Meta Pixel ID | `1234567890123456` | **marketing** |
|
||||
| Microsoft Clarity Project ID | `abcdefghij` | **analytics** |
|
||||
| LinkedIn Partner ID | `1234567` | **marketing** |
|
||||
| TikTok Pixel ID | `CXXXXXXXXXXXXXXXXXXX` | **marketing** |
|
||||
|
||||
Gdy ustawione są oba, wygrywa GTM. Gdy żadne — komponent nie robi nic.
|
||||
GA4 + GTM ustawione jednocześnie → wygrywa GTM. Puste pole = tag się nie ładuje.
|
||||
|
||||
To jedyne pola z Site Integrations, które trafiają na klienta — są publiczne
|
||||
(widać je w źródle każdej strony z GA). `getAnalyticsConfig` czyta wyłącznie je,
|
||||
więc sekrety (Turnstile, SMTP) nie mają jak wyciec.
|
||||
Wszystkie te ID są publiczne (widać je w źródle strony). `getAnalyticsConfig`
|
||||
czyta wyłącznie je, więc sekrety (Turnstile, SMTP) nie mają jak wyciec.
|
||||
|
||||
### Pixel w panelu czy w GTM?
|
||||
|
||||
**Jedno albo drugie, nigdy oba** — inaczej każde zdarzenie liczy się
|
||||
podwójnie. Zasada:
|
||||
|
||||
- Klient bez GTM / prosta strona → wpisz Pixel ID w panelu (najprościej,
|
||||
zgoda obsłużona automatycznie).
|
||||
- Klient ma agencję/marketera, który zarządza tagami w GTM → zostaw pole Pixel
|
||||
puste, Pixel konfiguruje się w GTM z warunkiem `ad_storage` (patrz sekcja
|
||||
„Meta Pixel przez GTM” niżej).
|
||||
|
||||
### Zdarzenia konwersji (non-Google)
|
||||
|
||||
`Analytics` wysyła tylko `PageView`. Konwersje (np. Lead po formularzu) wołasz
|
||||
sam — globale istnieją dopiero po zgodzie, więc zawsze ze strażnikiem:
|
||||
|
||||
```ts
|
||||
window.fbq?.('track', 'Lead') // Meta
|
||||
window.ttq?.track('SubmitForm') // TikTok
|
||||
window.lintrk?.('track', { conversion_id: 123 }) // LinkedIn
|
||||
```
|
||||
|
||||
Niskopoziomowe loadery (`loadMetaPixel`, `loadClarity`, `loadLinkedIn`,
|
||||
`loadTikTok`) są eksportowane z `/client`, ale normalnie nie są potrzebne —
|
||||
NIE wołaj ich z pominięciem zgody.
|
||||
|
||||
## Front
|
||||
|
||||
@@ -41,7 +77,30 @@ export default async function LocaleLayout({ children, params }) {
|
||||
```
|
||||
|
||||
`Analytics` nie renderuje nic — wstrzykuje skrypty. Zamontuj raz, wysoko w
|
||||
drzewie.
|
||||
drzewie. **Musi być wewnątrz `ConsentProvider`** (od 1.7.12 czyta stan zgody na
|
||||
żywo — poza providerem rzuci błąd kontekstu).
|
||||
|
||||
## Tryb Core Web Vitals — `defer` (opcjonalny)
|
||||
|
||||
```tsx
|
||||
<Analytics {...analytics} defer /> // domyślnie 3500 ms
|
||||
<Analytics {...analytics} defer deferTimeoutMs={5000} />
|
||||
```
|
||||
|
||||
Wszystkie tagi (GA4/GTM i pixele) ładują się z sieci dopiero przy **pierwszej
|
||||
interakcji** (scroll, klik, dotyk, klawisz) albo `deferTimeoutMs` po `load`,
|
||||
w zależności od tego, co nastąpi pierwsze. ~100+ KiB JS wypada z okna FCP/LCP.
|
||||
|
||||
Defer zmienia **kiedy**, nigdy **czy**:
|
||||
- domyślny stan Consent Mode nadal idzie od razu (to tylko push do dataLayer, bez
|
||||
ruchu sieciowego), więc GA nigdy nie startuje bez niego;
|
||||
- pixele non-Google nadal wymagają zgody na swoją kategorię.
|
||||
|
||||
Koszt: odwiedzający, którzy wyjdą przed interakcją i przed upływem timeoutu, nie
|
||||
zostaną policzeni (trochę mniej sesji w GA). Domyślnie `defer` jest wyłączony.
|
||||
|
||||
**Nie kopiuj `Analytics` do projektu, żeby to zmienić.** Brakujące opcje dodajemy
|
||||
w ipal-kit (core = engine).
|
||||
|
||||
## Jak działa Consent Mode
|
||||
|
||||
@@ -68,6 +127,11 @@ W konsoli: `window.dataLayer` — powinien zawierać `Arguments(3)` z `consent`
|
||||
Ciasteczko `_ga` pojawia się dopiero po zgodzie na analytics — to jest sedno
|
||||
Consent Mode.
|
||||
|
||||
Pixele non-Google: przed zgodą w Network **nie może** być żądań do
|
||||
`connect.facebook.net`, `clarity.ms`, `snap.licdn.com`, `analytics.tiktok.com`.
|
||||
Po kliknięciu zgody pojawiają się od razu. Meta Pixel Helper (rozszerzenie
|
||||
Chrome) powinien pokazać `PageView` dopiero po akceptacji marketingu.
|
||||
|
||||
## Zdarzenia do GTM — pushDataLayer
|
||||
|
||||
Do wypchnięcia własnego zdarzenia (np. `form_submit` pod tag Lead w GTM) jest
|
||||
@@ -95,4 +159,170 @@ czysty event, na którym tag może się odpalić, gdy zgoda jest udzielona.
|
||||
Publish, nie sam zapis) tagu GA4 w kontenerze wszystko wygląda dobrze:
|
||||
`gtm.load` w dataLayer, Tag Assistant widzi kontener — a `_ga` nie ma, bo nic go
|
||||
nie tworzy. Przy debugowaniu warto tymczasowo wyczyścić GTM Container ID i
|
||||
zostawić samo GA4, żeby wyeliminować kontener jako zmienną.
|
||||
zostawić samo GA4, żeby wyeliminować kontener jako zmienną.
|
||||
|
||||
---
|
||||
|
||||
## Meta Pixel przez GTM — krok po kroku
|
||||
|
||||
Wariant dla klientów, u których tagami zarządza marketer w GTM (wtedy pole
|
||||
**Meta Pixel ID** w panelu zostaje **puste** — inaczej podwójne zliczanie).
|
||||
Plugin ładuje kontener i obsługuje Consent Mode v2 (`marketing` →
|
||||
`ad_storage`, `ad_user_data`, `ad_personalization`); zdarzenie `form_submit`
|
||||
z parametrami ustawia się w panelu formularza. W kodzie projektu nic poza
|
||||
jednorazowym `onSuccess` w rendererze formularza.
|
||||
|
||||
### 0. Wymagania wstępne (panel Payload)
|
||||
|
||||
1. **GTM Container ID** w Settings → Site Integrations (`GTM-XXXXXXX`).
|
||||
2. **Baner cookies** aktywny (`CookieBanner` + `ConsentProvider`) — inaczej
|
||||
Consent Mode nie dostanie decyzji.
|
||||
3. **Pole analityki na formularzu** — dodaj `buildFormAnalyticsFields()` do
|
||||
kolekcji Forms (patrz [forms.md](./forms.md) → „Zarządzanie z panelu"), a w
|
||||
rendererze: `onSuccess: formAnalyticsOnSuccess(form.analytics)`. W panelu (po
|
||||
angielsku), na formularzu kontaktowym w grupie **Analytics (GTM / dataLayer)**
|
||||
ustaw: **Event name** `form_submit`, parametr `form_name = $topic` (albo
|
||||
stała, np. `kontakt`).
|
||||
|
||||
---
|
||||
|
||||
### 1. Pixel ID jako zmienna GTM
|
||||
|
||||
Events Manager → Źródła danych → Twój pixel → skopiuj **Pixel ID** (15–16 cyfr).
|
||||
|
||||
GTM → Zmienne → Zmienne zdefiniowane przez użytkownika → **Nowa** → **Stała** →
|
||||
wartość = Pixel ID → nazwij `Meta Pixel ID`.
|
||||
|
||||
### 2. Szablon tagu Meta
|
||||
|
||||
Meta nie ma natywnego tagu w GTM. Dwie drogi:
|
||||
|
||||
- **Szablon społeczności (wygodniej):** Szablony → Szablony tagów → Przeszukaj
|
||||
galerię → „Facebook Pixel" → Dodaj do obszaru roboczego.
|
||||
- **Custom HTML:** wklej kod bazowy pixela z Events Manera (wariant dla pełnej
|
||||
kontroli; wtedy pomijasz szablon i robisz tagi jako Custom HTML).
|
||||
|
||||
Poniżej zakładam szablon.
|
||||
|
||||
### 3. Tag bazowy — PageView
|
||||
|
||||
Tagi → **Nowy** → typ **Facebook Pixel**:
|
||||
- **Pixel ID:** `{{Meta Pixel ID}}`
|
||||
- **Event:** Standard → `PageView`
|
||||
- **Ustawienia zgody** (Zaawansowane → Consent Settings): wymagaj **`ad_storage`**.
|
||||
- **Trigger:** `All Pages` + (dla Next.js) drugi trigger **History Change** —
|
||||
patrz sekcja SPA niżej.
|
||||
|
||||
Nazwij np. `Meta – Base + PageView`.
|
||||
|
||||
### 4. Zmienna dla parametru z formularza
|
||||
|
||||
Zmienne → **Nowa** → **Zmienna warstwy danych**:
|
||||
- Nazwa zmiennej warstwy danych: `form_name`
|
||||
- Wersja: Wersja 2
|
||||
- Nazwij u góry dokładnie `DLV – form_name`.
|
||||
|
||||
> Nazwa w tagu i w zmiennej musi być **znak w znak** taka sama, łącznie z
|
||||
> myślnikiem. Jeśli w tagu jest długi myślnik „–", a w zmiennej wpiszesz zwykły
|
||||
> „-", GTM uzna to za dwie różne zmienne. Najbezpieczniej skopiuj tekst spomiędzy
|
||||
> `{{` a `}}`.
|
||||
|
||||
### 5. Trigger — wysłanie formularza
|
||||
|
||||
Triggery → **Nowy** → **Zdarzenie niestandardowe**:
|
||||
- Nazwa zdarzenia: `form_submit` (dokładnie tak, jak event z panelu formularza)
|
||||
- Uruchamiany na: Wszystkie zdarzenia niestandardowe.
|
||||
|
||||
Nazwij `CE – form_submit`.
|
||||
|
||||
### 6. Tag konwersji — Lead
|
||||
|
||||
Tagi → **Nowy** → **Facebook Pixel**:
|
||||
- **Pixel ID:** `{{Meta Pixel ID}}`
|
||||
- **Event:** Standard → `Lead`
|
||||
- **Object Properties / parametry:** `content_name` = `{{DLV – form_name}}`
|
||||
- **Ustawienia zgody:** wymagaj **`ad_storage`** (tak samo jak tag bazowy).
|
||||
- **Trigger:** `CE – form_submit`.
|
||||
|
||||
Nazwij `Meta – Lead`.
|
||||
|
||||
Inne konwersje analogicznie, każda jako osobny tag z tego samego szablonu:
|
||||
- **Contact** — trigger na kliknięcie w `tel:` / `mailto:`.
|
||||
- **ViewContent / AddToCart / Purchase** — parametry (`value`, `currency`,
|
||||
`content_ids`) ze zmiennych warstwy danych; zdarzenie pushowane z kodu/panelu
|
||||
tam, gdzie zachodzi akcja.
|
||||
|
||||
---
|
||||
|
||||
### 7. Zgoda (RODO) — krytyczne
|
||||
|
||||
Pixel marketingowy **nie może odpalić przed zgodą**. W każdym tagu Meta ustaw
|
||||
Consent Settings → wymagaj `ad_storage`. Plugin trzyma `ad_storage = denied` do
|
||||
czasu akceptacji w banerze i wysyła `update` po kliknięciu — tag odpali się
|
||||
dopiero wtedy. Bez tego warunku pixel strzeli mimo braku zgody (naruszenie RODO).
|
||||
|
||||
W Podglądzie sprawdź: **przed** akceptacją baner → tag `Meta – Base + PageView`
|
||||
ma być **zablokowany**; **po** akceptacji → „Uruchomiono".
|
||||
|
||||
### 8. Next.js / SPA — PageView przy zmianie trasy
|
||||
|
||||
Przy nawigacji po stronie klienta (routing Next.js bez pełnego przeładowania)
|
||||
`All Pages` odpali się tylko raz. Dwie opcje:
|
||||
|
||||
- **W GTM (bez kodu, zalecane):** dodaj do tagu PageView drugi trigger typu
|
||||
**Zmiana historii** (History Change). GTM łapie zmianę trasy.
|
||||
- **Z kodu (jeśli wolisz jawne eventy):** pushuj `page_view` do dataLayer przy
|
||||
zmianie trasy (`pushDataLayer('page_view')` na zmianę `usePathname`) i zrób
|
||||
trigger `CE – page_view`.
|
||||
|
||||
W Podglądzie / Events Manager policz: ma być **jeden** PageView na zmianę
|
||||
podstrony i brak podwójnego liczenia pierwszego wejścia.
|
||||
|
||||
### 9. Duplikaty
|
||||
|
||||
Jeśli pixel jest też wklejony na sztywno w kodzie strony albo przez inną wtyczkę
|
||||
— **usuń go stamtąd**. Ma być tylko w GTM, inaczej zdarzenia liczą się podwójnie.
|
||||
|
||||
---
|
||||
|
||||
### 10. Test
|
||||
|
||||
1. **Podgląd GTM** (prawy górny róg) → podaj adres strony.
|
||||
2. Zaakceptuj cookies marketingowe.
|
||||
3. Tag Assistant: `Meta – Base + PageView` = „Uruchomiono" (przed zgodą
|
||||
zablokowany).
|
||||
4. Wyślij formularz → w lewej kolumnie zdarzenie `form_submit`, przy nim tag
|
||||
`Meta – Lead` „Uruchomiono"; w zakładce Zmienne `DLV – form_name` ma wartość
|
||||
(np. `kontakt`).
|
||||
5. **Meta Pixel Helper** (rozszerzenie Chrome) → widzi PageView i Lead.
|
||||
6. **Events Manager → Testuj zdarzenia** → wpisz adres → `PageView` i po
|
||||
wysłaniu formularza `Lead` z parametrem `content_name`.
|
||||
|
||||
### 11. Publikacja
|
||||
|
||||
GTM → **Prześlij** → nazwa wersji (np. „Meta Pixel – PageView + Lead") →
|
||||
**Opublikuj**. Do tego momentu nic nie działa na produkcji — sam zapis tagu nie
|
||||
wystarczy.
|
||||
|
||||
---
|
||||
|
||||
### 12. (Opcjonalnie) Conversions API (CAPI)
|
||||
|
||||
Żeby wysyłać zdarzenia także z serwera (odporność na blokery/iOS), każde
|
||||
zdarzenie potrzebuje wspólnego `event_id` w pixelu i w CAPI, żeby Meta mogła je
|
||||
deduplikować. To osobny temat (server-side GTM albo wysyłka z backendu) — w tym
|
||||
stacku `submitForm` (server) mógłby generować `event_id`, a `pushDataLayer`
|
||||
używałby tego samego. Jeśli wchodzicie w CAPI, zgłoś — to rozszerzenie modułu
|
||||
forms + analytics, nie konfiguracja GTM.
|
||||
|
||||
---
|
||||
|
||||
### Ściąga — kto co robi
|
||||
|
||||
| Element | Gdzie |
|
||||
|---|---|
|
||||
| Ładowanie GTM, Consent Mode | plugin (auto) |
|
||||
| Event `form_submit` + parametry | panel Payload (grupa „Analytics" na formularzu) |
|
||||
| Pixel ID, tagi, triggery, warunki zgody | panel GTM |
|
||||
| Publikacja kontenera | panel GTM |
|
||||
| Kod projektu | nic (poza jednorazowym `onSuccess` w rendererze) |
|
||||
|
||||
+1
-1
@@ -84,4 +84,4 @@ bloków żadnym markupem.
|
||||
export function Hero(props) {
|
||||
return <section className="py-16">{/* ... */}</section>
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
+19
-8
@@ -20,6 +20,20 @@ treścią bannera (message, przyciski, kategorie, settingsTitle) w panelu,
|
||||
localized. Link do polityki prywatności bierze się z system pages
|
||||
(`privacyPolicy`), nie z osobnego pola.
|
||||
|
||||
**Link do polityki prywatności w banerze (od 1.7.12)** — zero kodu:
|
||||
|
||||
| Co | Skąd |
|
||||
|---|---|
|
||||
| Dokąd prowadzi | Site Settings → System Pages → Privacy Policy |
|
||||
| Tekst linku | Cookie Settings → `privacyLinkLabel` (per język) |
|
||||
| Gdy tekst pusty | tytuł strony polityki w danym języku |
|
||||
|
||||
Opcje `privacyPolicy` w `getConsentTexts`: pomiń (automat), `false` (bez
|
||||
linku), `{ page }` (własna strona, odczytana z `locale: 'all'`). Parametr
|
||||
`label` jest **przestarzały** — tekst wpisany w kodzie łamie A0 przy kilku
|
||||
językach; działa tylko, gdy pole w panelu jest puste. Usuń go z projektów przy
|
||||
okazji aktualizacji.
|
||||
|
||||
## Front — Provider + banner
|
||||
|
||||
Provider owija aplikację, banner i button renderują się same. Import z
|
||||
@@ -34,12 +48,9 @@ export default async function Layout({ children, params }) {
|
||||
const { locale } = await params
|
||||
const payload = await getPayload({ config })
|
||||
|
||||
// teksty z CookieSettings + link do polityki z system pages
|
||||
const settings = await payload.findGlobal({ slug: 'site-settings', locale: 'all', depth: 1 })
|
||||
const texts = await getConsentTexts({
|
||||
payload, config: i18nConfig, locale,
|
||||
privacyPolicy: { label: 'Polityka prywatności', page: settings.privacyPolicy },
|
||||
})
|
||||
// teksty z Cookie Settings; link do polityki automatycznie:
|
||||
// cel = System Pages → Privacy Policy, tekst = Cookie Settings → privacyLinkLabel
|
||||
const texts = await getConsentTexts({ payload, config: i18nConfig, locale })
|
||||
|
||||
return (
|
||||
<ConsentProvider texts={texts}>
|
||||
@@ -131,7 +142,7 @@ Dostępne tokeny (każdy ma odpowiednik `-dark` używany pod `dark:`):
|
||||
| `--ipal-hover` | `#f5f5f5` | hover przycisków drugorzędnych |
|
||||
| `--ipal-radius` | `0.375rem` | zaokrąglenie przycisków |
|
||||
|
||||
Wymaga `@source` skanującego pakiet (patrz getting-started.md) — inaczej Tailwind
|
||||
Wymaga `@source` skanującego pakiet (patrz PROGRAMISTA.md §2.5) — inaczej Tailwind
|
||||
nie wygeneruje tych klas.
|
||||
|
||||
### Gdy tokeny nie wystarczą
|
||||
@@ -188,4 +199,4 @@ Przekazana mapa zastępuje domyślną — pamiętaj dołączyć `NEXT_LOCALE`, j
|
||||
chcesz zachować sprzątanie locale (albo zaimportuj `LOCALE_COOKIE_NAME` i dodaj).
|
||||
|
||||
> Mechanizm zgody dla locale jest opisany też od strony i18n:
|
||||
> [i18n.md](./i18n.md#cookie-locale-a-zgoda-rodo).
|
||||
> [i18n.md](./i18n.md#cookie-locale-a-zgoda-rodo).
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user