Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f5ed75f9e | ||
|
|
4eb2b627f0 | ||
|
|
a92fc02cdf | ||
|
|
7aebe24236 | ||
|
|
c852d7bdae | ||
|
|
24fa3fdcdf | ||
|
|
73eacb09c2 | ||
|
|
2665cfa7b6 | ||
|
|
5c466b664c | ||
|
|
78e2f8fc7f | ||
|
|
13d669b757 | ||
|
|
a3938cacd9 | ||
|
|
2ef602b3ec | ||
|
|
1f55c2406e | ||
|
|
10d1806130 | ||
|
|
6be783bc5a | ||
|
|
fd6fb426b3 | ||
|
|
09925e4cfd | ||
|
|
e6eada5d39 | ||
|
|
1b52060dce | ||
|
|
52977e67fc | ||
|
|
b25f221a50 | ||
|
|
f9d3d9ae97 | ||
|
|
962b9cb640 |
@@ -0,0 +1,260 @@
|
||||
# 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.
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Entry point: @intecion/ipal-kit/admin
|
||||
*
|
||||
* Admin-panel UI components (white-label branding). Separate export so Payload's
|
||||
* importMap can resolve them by a stable path when ipalKit injects
|
||||
* admin.components.graphics.Logo/Icon.
|
||||
*/
|
||||
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js';
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Entry point: @intecion/ipal-kit/admin
|
||||
*
|
||||
* Admin-panel UI components (white-label branding). Separate export so Payload's
|
||||
* importMap can resolve them by a stable path when ipalKit injects
|
||||
* admin.components.graphics.Logo/Icon.
|
||||
*/ export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js';
|
||||
|
||||
//# sourceMappingURL=admin.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../src/exports/admin.ts"],"sourcesContent":["/**\n * Entry point: @intecion/ipal-kit/admin\n *\n * Admin-panel UI components (white-label branding). Separate export so Payload's\n * importMap can resolve them by a stable path when ipalKit injects\n * admin.components.graphics.Logo/Icon.\n */\nexport { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'\n"],"names":["AdminIcon","AdminLogo","IntecionCredit"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,+BAA8B"}
|
||||
Vendored
+7
-1
@@ -3,6 +3,9 @@ export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmai
|
||||
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
|
||||
*
|
||||
@@ -10,8 +13,11 @@ export { Analytics } from '../modules/analytics/client.js';
|
||||
* components. Kept separate from the main entry so server bundles don't pull in
|
||||
* client-only code.
|
||||
*/
|
||||
export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js';
|
||||
export { ConsentProvider, ConsentScript, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js';
|
||||
export type { CookieBannerClassNames } from '../modules/consent/client.js';
|
||||
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 { useForm } from '../modules/forms/useForm.js';
|
||||
|
||||
Vendored
+5
-1
@@ -3,13 +3,17 @@ export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
|
||||
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
|
||||
*
|
||||
* Client-side ('use client') exports — React hooks, providers, and UI
|
||||
* components. Kept separate from the main entry so server bundles don't pull in
|
||||
* client-only code.
|
||||
*/ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js';
|
||||
*/ export { ConsentProvider, ConsentScript, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js';
|
||||
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js';
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||
export { useForm } from '../modules/forms/useForm.js';
|
||||
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from '../modules/forms/validators.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'\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 CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.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","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","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;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,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 {\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 type { AnalyticsProps } from '../modules/analytics/client.js'\n\nexport { pushDataLayer } from '../modules/analytics/client.js'\nexport {\n loadClarity,\n loadLinkedIn,\n loadMetaPixel,\n loadTikTok,\n} 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 {\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","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","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;AAG1D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SACEC,WAAW,EACXC,YAAY,EACZC,aAAa,EACbC,UAAU,QACL,iCAAgC;AACvC;;;;;;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"}
|
||||
+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
+14
-3
@@ -7,27 +7,34 @@ 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, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRoute, } 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';
|
||||
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js';
|
||||
export { mailAdapter } from './modules/email/mailAdapter.js';
|
||||
export type { MailAdapterArgs } from './modules/email/mailAdapter.js';
|
||||
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
|
||||
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js';
|
||||
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
|
||||
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js';
|
||||
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js';
|
||||
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
|
||||
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption, } from './modules/forms/types.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';
|
||||
export type { Rule } from './modules/forms/validators.js';
|
||||
export { createContentHelpers } from './modules/frontend/index.js';
|
||||
export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js';
|
||||
export { createHealthRoute } from './modules/health/index.js';
|
||||
export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js';
|
||||
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js';
|
||||
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath, } from './modules/i18n/index.js';
|
||||
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 { createMcpRoute } from './modules/mcp/index.js';
|
||||
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
|
||||
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage, } from './modules/notifications/index.js';
|
||||
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js';
|
||||
@@ -35,6 +42,7 @@ export type { PagesOption, SystemPageRole } from './modules/pages/index.js';
|
||||
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js';
|
||||
export type { GlobalQueryOptions } from './modules/payload/index.js';
|
||||
export { getGlobal, getSiteIntegrations, getSiteSettings, SITE_INTEGRATIONS_SLUG, SITE_SETTINGS_SLUG, } from './modules/payload/index.js';
|
||||
export { lexicalToMarkdown } from './modules/richtext/index.js';
|
||||
export { buildSecurityHeaders } from './modules/security/index.js';
|
||||
export { buildCsp } from './modules/security/index.js';
|
||||
export type { BuildCspArgs } from './modules/security/index.js';
|
||||
@@ -42,9 +50,12 @@ export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/securit
|
||||
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 { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta, } 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';
|
||||
export { buildNoindexField } from './modules/seo/index.js';
|
||||
export { buildSpeakableJsonLd } from './modules/seo/index.js';
|
||||
export { buildSummaryField } from './modules/seo/index.js';
|
||||
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd, } from './modules/seo/index.js';
|
||||
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd, } from './modules/seo/index.js';
|
||||
export { buildArticleJsonLd } from './modules/seo/index.js';
|
||||
|
||||
Vendored
+17
-3
@@ -2,34 +2,48 @@ 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, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRoute } 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
|
||||
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
|
||||
// Payload loads the config (or runs generate:importmap) as a plain Node script.
|
||||
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
|
||||
// Boot-time environment validation (fail fast on misconfigured deploys).
|
||||
export { assertEnv, ipalEnvRules } from './modules/env/index.js';
|
||||
// Panel-managed form analytics (config-time field builder).
|
||||
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js';
|
||||
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js';
|
||||
// Validation rules are pure — exported server-side too, for re-validating a
|
||||
// submission inside a server action. (useForm/useContactForm are client-only →
|
||||
// '@intecion/ipal-kit/client'.)
|
||||
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './modules/forms/validators.js';
|
||||
export { createContentHelpers } from './modules/frontend/index.js';
|
||||
export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js';
|
||||
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
|
||||
export { createHealthRoute } from './modules/health/index.js';
|
||||
export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js';
|
||||
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } 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';
|
||||
// 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';
|
||||
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js';
|
||||
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js';
|
||||
export { getGlobal, getSiteIntegrations, getSiteSettings, SITE_INTEGRATIONS_SLUG, SITE_SETTINGS_SLUG } from './modules/payload/index.js';
|
||||
// Lexical → Markdown (pure, no React) — for AI-readable output.
|
||||
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 { buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta } 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';
|
||||
export { buildNoindexField } from './modules/seo/index.js';
|
||||
export { buildSpeakableJsonLd } from './modules/seo/index.js';
|
||||
export { buildSummaryField } from './modules/seo/index.js';
|
||||
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js';
|
||||
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
|
||||
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js';
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -34,6 +34,16 @@ export type A11yClassNames = {
|
||||
* CookieBanner). Wrap the app in <AccessibilityProvider> first.
|
||||
*
|
||||
* <AccessibilityWidget classNames={{ button: 'a11y-btn', panel: 'a11y-panel' }} />
|
||||
*
|
||||
* Labels default to English; localize per locale by passing `texts` for the
|
||||
* active language. Keep the translations in the project (or a localized global)
|
||||
* and pass the active locale's set — the plugin stays content-agnostic:
|
||||
*
|
||||
* const A11Y: Record<string, A11yTexts> = {
|
||||
* pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', … },
|
||||
* de: { title: 'Barrierefreiheit', … },
|
||||
* }
|
||||
* <AccessibilityWidget texts={A11Y[locale]} classNames={…} />
|
||||
*/
|
||||
export declare function AccessibilityWidget({ classNames, texts, }: {
|
||||
classNames?: A11yClassNames;
|
||||
|
||||
+29
-15
@@ -2,21 +2,25 @@
|
||||
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
||||
import { useState } from 'react';
|
||||
import { useAccessibility } from './AccessibilityProvider.js';
|
||||
const DEFAULT_TEXTS = {
|
||||
bigCursor: 'Duży kursor',
|
||||
close: 'Zamknij',
|
||||
contrast: 'Kontrast',
|
||||
contrastHigh: 'Wysoki',
|
||||
contrastInverted: 'Odwrócony',
|
||||
grayscale: 'Skala szarości',
|
||||
lineHeight: 'Odstęp między liniami',
|
||||
open: 'Otwórz panel dostępności',
|
||||
readableFont: 'Czytelna czcionka',
|
||||
reduceMotion: 'Wyłącz animacje',
|
||||
reset: 'Resetuj',
|
||||
textSize: 'Rozmiar tekstu',
|
||||
title: 'Dostępność',
|
||||
underlineLinks: 'Podkreśl linki'
|
||||
/**
|
||||
* English defaults. The widget is end-user facing and multilingual projects run
|
||||
* in many locales, so the plugin ships a neutral English baseline — NOT Polish.
|
||||
* Localize by passing `texts` for the active locale (see the component doc).
|
||||
*/ const DEFAULT_TEXTS = {
|
||||
bigCursor: 'Large cursor',
|
||||
close: 'Close',
|
||||
contrast: 'Contrast',
|
||||
contrastHigh: 'High',
|
||||
contrastInverted: 'Inverted',
|
||||
grayscale: 'Grayscale',
|
||||
lineHeight: 'Line spacing',
|
||||
open: 'Open accessibility panel',
|
||||
readableFont: 'Readable font',
|
||||
reduceMotion: 'Reduce motion',
|
||||
reset: 'Reset',
|
||||
textSize: 'Text size',
|
||||
title: 'Accessibility',
|
||||
underlineLinks: 'Underline links'
|
||||
};
|
||||
/**
|
||||
* Accessibility toolbar: a floating button that opens a panel of options (text
|
||||
@@ -28,6 +32,16 @@ const DEFAULT_TEXTS = {
|
||||
* CookieBanner). Wrap the app in <AccessibilityProvider> first.
|
||||
*
|
||||
* <AccessibilityWidget classNames={{ button: 'a11y-btn', panel: 'a11y-panel' }} />
|
||||
*
|
||||
* Labels default to English; localize per locale by passing `texts` for the
|
||||
* active language. Keep the translations in the project (or a localized global)
|
||||
* and pass the active locale's set — the plugin stays content-agnostic:
|
||||
*
|
||||
* const A11Y: Record<string, A11yTexts> = {
|
||||
* pl: { title: 'Dostępność', textSize: 'Rozmiar tekstu', … },
|
||||
* de: { title: 'Barrierefreiheit', … },
|
||||
* }
|
||||
* <AccessibilityWidget texts={A11Y[locale]} classNames={…} />
|
||||
*/ export function AccessibilityWidget({ classNames, texts }) {
|
||||
const { reset, set, state } = useAccessibility();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
+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
+3
@@ -1 +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
+4
@@ -1,4 +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'\n"],"names":["Analytics"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB"}
|
||||
{"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
+19
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Pushes an event onto the GTM `window.dataLayer`. SSR-safe (no-op on the
|
||||
* server), and tolerant of GTM not being present yet — the array is created so
|
||||
* the event is buffered and picked up once GTM loads.
|
||||
*
|
||||
* The bridge between the form engine and GTM: fire a `form_submit` event after
|
||||
* a successful submit so a Meta Pixel / GA "Lead" tag can trigger on it.
|
||||
*
|
||||
* import { pushDataLayer } from '@intecion/ipal-kit/client'
|
||||
* const f = useContactForm({
|
||||
* submitAction,
|
||||
* onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }),
|
||||
* })
|
||||
*
|
||||
* The GTM "Lead" tag then reads `form_name` via a Data Layer Variable
|
||||
* (`DLV – form_name`) and fires on the custom event `form_submit`. Consent still
|
||||
* gates the tag in GTM (ad_storage) — this only emits the event.
|
||||
*/
|
||||
export declare function pushDataLayer(event: string, params?: Record<string, unknown>): void;
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Pushes an event onto the GTM `window.dataLayer`. SSR-safe (no-op on the
|
||||
* server), and tolerant of GTM not being present yet — the array is created so
|
||||
* the event is buffered and picked up once GTM loads.
|
||||
*
|
||||
* The bridge between the form engine and GTM: fire a `form_submit` event after
|
||||
* a successful submit so a Meta Pixel / GA "Lead" tag can trigger on it.
|
||||
*
|
||||
* import { pushDataLayer } from '@intecion/ipal-kit/client'
|
||||
* const f = useContactForm({
|
||||
* submitAction,
|
||||
* onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }),
|
||||
* })
|
||||
*
|
||||
* The GTM "Lead" tag then reads `form_name` via a Data Layer Variable
|
||||
* (`DLV – form_name`) and fires on the custom event `form_submit`. Consent still
|
||||
* gates the tag in GTM (ad_storage) — this only emits the event.
|
||||
*/ export function pushDataLayer(event, params = {}) {
|
||||
if (typeof window === 'undefined') return;
|
||||
const w = window;
|
||||
w.dataLayer = w.dataLayer || [];
|
||||
w.dataLayer.push({
|
||||
event,
|
||||
...params
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=pushDataLayer.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/analytics/pushDataLayer.ts"],"sourcesContent":["/**\n * Pushes an event onto the GTM `window.dataLayer`. SSR-safe (no-op on the\n * server), and tolerant of GTM not being present yet — the array is created so\n * the event is buffered and picked up once GTM loads.\n *\n * The bridge between the form engine and GTM: fire a `form_submit` event after\n * a successful submit so a Meta Pixel / GA \"Lead\" tag can trigger on it.\n *\n * import { pushDataLayer } from '@intecion/ipal-kit/client'\n * const f = useContactForm({\n * submitAction,\n * onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' }),\n * })\n *\n * The GTM \"Lead\" tag then reads `form_name` via a Data Layer Variable\n * (`DLV – form_name`) and fires on the custom event `form_submit`. Consent still\n * gates the tag in GTM (ad_storage) — this only emits the event.\n */\nexport function pushDataLayer(event: string, params: Record<string, unknown> = {}): void {\n if (typeof window === 'undefined') return\n const w = window as unknown as { dataLayer?: unknown[] }\n w.dataLayer = w.dataLayer || []\n w.dataLayer.push({ event, ...params })\n}\n"],"names":["pushDataLayer","event","params","window","w","dataLayer","push"],"mappings":"AAAA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASA,cAAcC,KAAa,EAAEC,SAAkC,CAAC,CAAC;IAC/E,IAAI,OAAOC,WAAW,aAAa;IACnC,MAAMC,IAAID;IACVC,EAAEC,SAAS,GAAGD,EAAEC,SAAS,IAAI,EAAE;IAC/BD,EAAEC,SAAS,CAACC,IAAI,CAAC;QAAEL;QAAO,GAAGC,MAAM;IAAC;AACtC"}
|
||||
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"}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* 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,
|
||||
* set by the editor in the panel — not hardcoded per project. Wired
|
||||
* 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.
|
||||
*
|
||||
* A0: no client brand in code. The logo/name come from the panel; if nothing is
|
||||
* set, nothing is forced.
|
||||
*/
|
||||
type BrandingProps = {
|
||||
/** Upload field to render as the image. Default 'logo' (Logo) / 'favicon' (Icon). */
|
||||
imageField?: string;
|
||||
/** Field holding the site name. Default 'siteName'. */
|
||||
nameField?: string;
|
||||
/** SiteSettings global slug. Default 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
};
|
||||
/**
|
||||
* Admin panel logo — this is the LARGE logo on the login / unauthorized screens
|
||||
* (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`,
|
||||
* falls back to `siteName` text. Sized generously for the login screen.
|
||||
*/
|
||||
export declare function AdminLogo(props?: BrandingProps): Promise<import("react/jsx-runtime").JSX.Element | null>;
|
||||
/** Admin panel icon (small nav glyph). SiteSettings `favicon`, falls back to initials. */
|
||||
export declare function AdminIcon(props?: BrandingProps): Promise<import("react/jsx-runtime").JSX.Element | null>;
|
||||
/**
|
||||
* Discreet vendor credit: "Technology supported by Intecion.com". This is the
|
||||
* PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client
|
||||
* data — a sensible default here is fine and A0-safe. The client's own brand
|
||||
* still owns the logo/name; this is a small line stating who supports the tech.
|
||||
* Text/URL overridable; turn it off with `whiteLabel: { credit: false }`.
|
||||
*
|
||||
* Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin
|
||||
* (login screen footer). `variant` adjusts placement:
|
||||
* - 'nav' → left-aligned line under the nav links
|
||||
* - 'login' → centered line below the login form
|
||||
*/
|
||||
export declare function IntecionCredit(props?: {
|
||||
text?: string;
|
||||
url?: string;
|
||||
variant?: 'login' | 'nav';
|
||||
}): import("react/jsx-runtime").JSX.Element;
|
||||
export {};
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import { getPayload } from 'payload';
|
||||
async function loadBranding(settingsSlug, nameField, imageField) {
|
||||
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 settings = await payload.findGlobal({
|
||||
slug: settingsSlug,
|
||||
depth: 1
|
||||
});
|
||||
const name = typeof settings[nameField] === 'string' ? settings[nameField] : null;
|
||||
const image = settings[imageField];
|
||||
const url = image && typeof image === 'object' && typeof image.url === 'string' ? image.url : null;
|
||||
return {
|
||||
name,
|
||||
url
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
name: null,
|
||||
url: null
|
||||
};
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Admin panel logo — this is the LARGE logo on the login / unauthorized screens
|
||||
* (Payload uses `graphics.Icon` for the small nav glyph). SiteSettings `logo`,
|
||||
* 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);
|
||||
if (url) {
|
||||
return /*#__PURE__*/ _jsx("img", {
|
||||
alt: name ?? '',
|
||||
src: url,
|
||||
style: {
|
||||
height: 'auto',
|
||||
maxHeight: 120,
|
||||
maxWidth: 420,
|
||||
width: 'auto'
|
||||
}
|
||||
});
|
||||
}
|
||||
if (name) {
|
||||
return /*#__PURE__*/ _jsx("div", {
|
||||
style: {
|
||||
fontSize: '2rem',
|
||||
fontWeight: 600
|
||||
},
|
||||
children: name
|
||||
});
|
||||
}
|
||||
return null // nothing configured → Payload's default
|
||||
;
|
||||
}
|
||||
/** 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);
|
||||
if (url) {
|
||||
return /*#__PURE__*/ _jsx("img", {
|
||||
alt: name ?? '',
|
||||
src: url,
|
||||
style: {
|
||||
height: 'auto',
|
||||
maxHeight: 28,
|
||||
maxWidth: 28,
|
||||
width: 'auto'
|
||||
}
|
||||
});
|
||||
}
|
||||
if (name) {
|
||||
return /*#__PURE__*/ _jsx("div", {
|
||||
style: {
|
||||
fontWeight: 700
|
||||
},
|
||||
children: name.slice(0, 2).toUpperCase()
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Discreet vendor credit: "Technology supported by Intecion.com". This is the
|
||||
* PLUGIN VENDOR's credit (Intecion ships ipal-kit, the framework), not client
|
||||
* data — a sensible default here is fine and A0-safe. The client's own brand
|
||||
* still owns the logo/name; this is a small line stating who supports the tech.
|
||||
* Text/URL overridable; turn it off with `whiteLabel: { credit: false }`.
|
||||
*
|
||||
* Wired by ipalKit into admin.components.afterNavLinks (nav) AND afterLogin
|
||||
* (login screen footer). `variant` adjusts placement:
|
||||
* - 'nav' → left-aligned line under the nav links
|
||||
* - 'login' → centered line below the login form
|
||||
*/ export function IntecionCredit(props = {}) {
|
||||
const { text = 'Technology supported by Intecion.com', url = 'https://intecion.com', variant = 'nav' } = props;
|
||||
const style = variant === 'login' ? {
|
||||
color: 'inherit',
|
||||
display: 'block',
|
||||
fontSize: '0.75rem',
|
||||
marginTop: '2rem',
|
||||
opacity: 0.6,
|
||||
padding: '0.5rem',
|
||||
textAlign: 'center',
|
||||
textDecoration: 'none'
|
||||
} : {
|
||||
color: 'inherit',
|
||||
display: 'block',
|
||||
fontSize: '0.75rem',
|
||||
opacity: 0.6,
|
||||
padding: '0.75rem 1rem',
|
||||
textDecoration: 'none'
|
||||
};
|
||||
return /*#__PURE__*/ _jsx("a", {
|
||||
href: url,
|
||||
rel: "noopener noreferrer",
|
||||
style: style,
|
||||
target: "_blank",
|
||||
children: text
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=adminGraphics.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -0,0 +1 @@
|
||||
export { AdminIcon, AdminLogo, IntecionCredit } from './adminGraphics.js';
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
export { AdminIcon, AdminLogo, IntecionCredit } from './adminGraphics.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/branding/index.ts"],"sourcesContent":["export { AdminIcon, AdminLogo, IntecionCredit } from './adminGraphics.js'\n"],"names":["AdminIcon","AdminLogo","IntecionCredit"],"mappings":"AAAA,SAASA,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,qBAAoB"}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import type { ConsentCategory } from './categories.js';
|
||||
type ConsentScriptProps = {
|
||||
/** Default true. */
|
||||
async?: boolean;
|
||||
/** Extra attributes on the <script> (e.g. { 'data-domain': 'x.com' }). */
|
||||
attributes?: Record<string, string>;
|
||||
/**
|
||||
* Consent category that must be granted before the script loads. Typically
|
||||
* 'analytics' (GA, Plausible) or 'marketing' (Meta Pixel, ads, chat widgets).
|
||||
*/
|
||||
category: ConsentCategory;
|
||||
/**
|
||||
* Inline JS to run once granted. If `src` is also set, it runs after the
|
||||
* external script loads (so init code can rely on the library). A plain
|
||||
* string of code — NOT user input (you control it), it goes into a <script>.
|
||||
*/
|
||||
code?: string;
|
||||
defer?: boolean;
|
||||
/** Stable id used to dedupe — the script is injected at most once. */
|
||||
id?: string;
|
||||
/** External script URL. Injected only once the category is granted. */
|
||||
src?: string;
|
||||
};
|
||||
/**
|
||||
* Loads a third-party script ONLY after the visitor has granted consent for its
|
||||
* category — the GDPR-correct default for anything that isn't strictly
|
||||
* necessary. Renders nothing until then. Reacts live to the consent context, so
|
||||
* a script appears the moment the visitor accepts in the banner, with no reload.
|
||||
*
|
||||
* Use this for third parties that have NO Google Consent Mode of their own (Meta
|
||||
* Pixel, LinkedIn Insight, chat widgets, custom analytics). GA/GTM are better
|
||||
* handled by Consent Mode (the module's updateConsent already does that) — reach
|
||||
* for ConsentScript when a vendor can't be gated that way.
|
||||
*
|
||||
* Must be rendered inside <ConsentProvider>.
|
||||
*
|
||||
* <ConsentScript category="marketing" src="https://connect.facebook.net/en_US/fbevents.js" />
|
||||
* <ConsentScript category="analytics"
|
||||
* src="https://plausible.io/js/script.js"
|
||||
* attributes={{ 'data-domain': 'example.com' }} />
|
||||
* <ConsentScript category="marketing" code={`fbq('init','123');fbq('track','PageView')`} />
|
||||
*
|
||||
* Note on withdrawal: once a script has loaded it keeps running for that page
|
||||
* (a <script> tag can't be truly unloaded) — withdrawing consent stops the NEXT
|
||||
* load. For vendors that support it, prefer Consent Mode so running tags honor
|
||||
* the change immediately; ConsentScript gates the initial load.
|
||||
*/
|
||||
export declare function ConsentScript({ id, async: asyncAttr, attributes, category, code, defer, src, }: ConsentScriptProps): null;
|
||||
export default ConsentScript;
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
'use client';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useConsentContext } from './ConsentContext.js';
|
||||
/**
|
||||
* Loads a third-party script ONLY after the visitor has granted consent for its
|
||||
* category — the GDPR-correct default for anything that isn't strictly
|
||||
* necessary. Renders nothing until then. Reacts live to the consent context, so
|
||||
* a script appears the moment the visitor accepts in the banner, with no reload.
|
||||
*
|
||||
* Use this for third parties that have NO Google Consent Mode of their own (Meta
|
||||
* Pixel, LinkedIn Insight, chat widgets, custom analytics). GA/GTM are better
|
||||
* handled by Consent Mode (the module's updateConsent already does that) — reach
|
||||
* for ConsentScript when a vendor can't be gated that way.
|
||||
*
|
||||
* Must be rendered inside <ConsentProvider>.
|
||||
*
|
||||
* <ConsentScript category="marketing" src="https://connect.facebook.net/en_US/fbevents.js" />
|
||||
* <ConsentScript category="analytics"
|
||||
* src="https://plausible.io/js/script.js"
|
||||
* attributes={{ 'data-domain': 'example.com' }} />
|
||||
* <ConsentScript category="marketing" code={`fbq('init','123');fbq('track','PageView')`} />
|
||||
*
|
||||
* Note on withdrawal: once a script has loaded it keeps running for that page
|
||||
* (a <script> tag can't be truly unloaded) — withdrawing consent stops the NEXT
|
||||
* load. For vendors that support it, prefer Consent Mode so running tags honor
|
||||
* the change immediately; ConsentScript gates the initial load.
|
||||
*/ export function ConsentScript({ id, async: asyncAttr = true, attributes, category, code, defer, src }) {
|
||||
const { state } = useConsentContext();
|
||||
const granted = state[category] === true;
|
||||
const injectedRef = useRef(false);
|
||||
useEffect(()=>{
|
||||
if (!granted || injectedRef.current) {
|
||||
return;
|
||||
}
|
||||
if (!src && !code) {
|
||||
return;
|
||||
}
|
||||
const dedupeId = id ?? (src ? `ipal-cs-${src}` : undefined);
|
||||
if (dedupeId && document.getElementById(dedupeId)) {
|
||||
injectedRef.current = true;
|
||||
return;
|
||||
}
|
||||
injectedRef.current = true;
|
||||
const runInline = ()=>{
|
||||
if (!code) {
|
||||
return;
|
||||
}
|
||||
const inline = document.createElement('script');
|
||||
if (dedupeId) {
|
||||
inline.id = `${dedupeId}-inline`;
|
||||
}
|
||||
inline.textContent = code;
|
||||
document.head.appendChild(inline);
|
||||
};
|
||||
if (src) {
|
||||
const el = document.createElement('script');
|
||||
el.src = src;
|
||||
if (dedupeId) {
|
||||
el.id = dedupeId;
|
||||
}
|
||||
if (asyncAttr) {
|
||||
el.async = true;
|
||||
}
|
||||
if (defer) {
|
||||
el.defer = true;
|
||||
}
|
||||
if (attributes) {
|
||||
for (const [k, v] of Object.entries(attributes)){
|
||||
el.setAttribute(k, v);
|
||||
}
|
||||
}
|
||||
el.addEventListener('load', runInline, {
|
||||
once: true
|
||||
});
|
||||
document.head.appendChild(el);
|
||||
} else {
|
||||
runInline();
|
||||
}
|
||||
// Deliberately no removal on cleanup: a loaded third-party script can't be
|
||||
// meaningfully unloaded. Withdrawal is handled by not re-injecting (and, for
|
||||
// vendors that support it, Consent Mode). See the component doc.
|
||||
}, [
|
||||
granted,
|
||||
src,
|
||||
code,
|
||||
id,
|
||||
attributes,
|
||||
asyncAttr,
|
||||
defer
|
||||
]);
|
||||
return null;
|
||||
}
|
||||
export default ConsentScript;
|
||||
|
||||
//# sourceMappingURL=ConsentScript.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+1
@@ -1,4 +1,5 @@
|
||||
export { ConsentProvider, useConsentContext } from './ConsentContext.js';
|
||||
export { ConsentScript } from './ConsentScript.js';
|
||||
export { CookieBanner } from './CookieBanner.js';
|
||||
export type { CookieBannerClassNames } from './CookieBanner.js';
|
||||
export { CookieButton } from './CookieButton.js';
|
||||
|
||||
Vendored
+1
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
export { ConsentProvider, useConsentContext } from './ConsentContext.js';
|
||||
export { ConsentScript } from './ConsentScript.js';
|
||||
export { CookieBanner } from './CookieBanner.js';
|
||||
export { CookieButton } from './CookieButton.js';
|
||||
// Client-only consent exports — hook, provider, and UI components.
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/consent/client.ts"],"sourcesContent":["'use client'\nexport { ConsentProvider, useConsentContext } from './ConsentContext.js'\nexport { CookieBanner } from './CookieBanner.js'\nexport type { CookieBannerClassNames } from './CookieBanner.js'\nexport { CookieButton } from './CookieButton.js'\n// Client-only consent exports — hook, provider, and UI components.\nexport { useConsent } from './useConsent.js'\n"],"names":["ConsentProvider","useConsentContext","CookieBanner","CookieButton","useConsent"],"mappings":"AAAA;AACA,SAASA,eAAe,EAAEC,iBAAiB,QAAQ,sBAAqB;AACxE,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,YAAY,QAAQ,oBAAmB;AAChD,mEAAmE;AACnE,SAASC,UAAU,QAAQ,kBAAiB"}
|
||||
{"version":3,"sources":["../../../src/modules/consent/client.ts"],"sourcesContent":["'use client'\nexport { ConsentProvider, useConsentContext } from './ConsentContext.js'\nexport { ConsentScript } from './ConsentScript.js'\nexport { CookieBanner } from './CookieBanner.js'\nexport type { CookieBannerClassNames } from './CookieBanner.js'\nexport { CookieButton } from './CookieButton.js'\n// Client-only consent exports — hook, provider, and UI components.\nexport { useConsent } from './useConsent.js'\n"],"names":["ConsentProvider","useConsentContext","ConsentScript","CookieBanner","CookieButton","useConsent"],"mappings":"AAAA;AACA,SAASA,eAAe,EAAEC,iBAAiB,QAAQ,sBAAqB;AACxE,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,YAAY,QAAQ,oBAAmB;AAChD,mEAAmE;AACnE,SAASC,UAAU,QAAQ,kBAAiB"}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Converts a page's `blocks` layout to Markdown by CONVENTION — the same field
|
||||
* names the project already standardises on (heading, subheading, body,
|
||||
* content, image, items/faq/…; see the naming rules in agents.md). The plugin
|
||||
* can't know each project's block shapes, but it CAN rely on those conventions,
|
||||
* so most blocks convert with zero per-project wiring. Special blocks get an
|
||||
* `overrides` entry keyed by blockType.
|
||||
*
|
||||
* Output is for AI/agent consumption (per-page Markdown, llms-full.txt), not
|
||||
* on-page rendering — it extracts readable text, not pixel-perfect layout.
|
||||
*
|
||||
* blocksToMarkdown(page.layout)
|
||||
* blocksToMarkdown(page.layout, {
|
||||
* overrides: { gallery: (b) => `(${(b.images as unknown[])?.length ?? 0} photos)` },
|
||||
* })
|
||||
*/
|
||||
type Block = Record<string, unknown> & {
|
||||
blockType?: string;
|
||||
};
|
||||
type BlockToMarkdown = (block: Block) => string;
|
||||
type BlocksToMarkdownArgs = {
|
||||
/** Per-blockType custom renderers. Return '' to omit a block. */
|
||||
overrides?: Record<string, BlockToMarkdown>;
|
||||
};
|
||||
export declare function blocksToMarkdown(layout: unknown, args?: BlocksToMarkdownArgs): string;
|
||||
export {};
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
// Import the leaf, not the richtext barrel — the barrel re-exports
|
||||
// RenderRichText (a React component), which would pull React into this pure,
|
||||
// server-usable module.
|
||||
import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js';
|
||||
const HEADING_KEYS = new Set([
|
||||
'heading',
|
||||
'title'
|
||||
]);
|
||||
const SUBHEADING_KEYS = new Set([
|
||||
'subheading',
|
||||
'subtitle'
|
||||
]);
|
||||
const QUESTION_KEYS = new Set([
|
||||
'question'
|
||||
]);
|
||||
const TEXT_KEYS = new Set([
|
||||
'body',
|
||||
'text',
|
||||
'description',
|
||||
'excerpt',
|
||||
'summary',
|
||||
'answer',
|
||||
'caption',
|
||||
'label',
|
||||
'content'
|
||||
]);
|
||||
const ARRAY_KEYS = new Set([
|
||||
'items',
|
||||
'features',
|
||||
'faq',
|
||||
'faqs',
|
||||
'cards',
|
||||
'columns',
|
||||
'rows',
|
||||
'questions',
|
||||
'services',
|
||||
'steps',
|
||||
'points',
|
||||
'benefits',
|
||||
'list'
|
||||
]);
|
||||
/** A populated richText value is an object with a `root`. */ function isRichText(v) {
|
||||
return !!v && typeof v === 'object' && 'root' in v;
|
||||
}
|
||||
/** A populated upload (image) is an object with a `url`. */ function imageMarkdown(v) {
|
||||
if (!v || typeof v !== 'object') return '';
|
||||
const o = v;
|
||||
const url = typeof o.url === 'string' ? o.url : '';
|
||||
const alt = typeof o.alt === 'string' ? o.alt : '';
|
||||
return url ? `` : '';
|
||||
}
|
||||
/** Extract readable Markdown from one block's known content fields. */ function extractBlock(block, depth) {
|
||||
const lines = [];
|
||||
for (const [key, value] of Object.entries(block)){
|
||||
if (value == null) continue;
|
||||
if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`## ${value.trim()}`);
|
||||
} else if (SUBHEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`### ${value.trim()}`);
|
||||
} else if (QUESTION_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`**${value.trim()}**`);
|
||||
} else if (key === 'image') {
|
||||
const img = imageMarkdown(value);
|
||||
if (img) lines.push(img);
|
||||
} else if (isRichText(value)) {
|
||||
const md = lexicalToMarkdown(value);
|
||||
if (md) lines.push(md);
|
||||
} else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(value.trim());
|
||||
} else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) {
|
||||
for (const item of value){
|
||||
if (item && typeof item === 'object') {
|
||||
const sub = extractBlock(item, depth + 1);
|
||||
if (sub.trim()) lines.push(sub);
|
||||
} else if (typeof item === 'string' && item.trim()) {
|
||||
lines.push(`- ${item.trim()}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines.join('\n\n');
|
||||
}
|
||||
export function blocksToMarkdown(layout, args = {}) {
|
||||
if (!Array.isArray(layout)) return '';
|
||||
const { overrides = {} } = args;
|
||||
const out = [];
|
||||
for (const block of layout){
|
||||
if (!block || typeof block !== 'object') continue;
|
||||
const b = block;
|
||||
const type = typeof b.blockType === 'string' ? b.blockType : '';
|
||||
if (type && overrides[type]) {
|
||||
const md = overrides[type](b);
|
||||
if (md.trim()) out.push(md.trim());
|
||||
continue;
|
||||
}
|
||||
const md = extractBlock(b, 0);
|
||||
if (md.trim()) out.push(md.trim());
|
||||
}
|
||||
return out.join('\n\n').trim();
|
||||
}
|
||||
|
||||
//# sourceMappingURL=blocksToMarkdown.js.map
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,52 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { ContentOption } from './types.js';
|
||||
type CreateMarkdownRendererArgs = {
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string;
|
||||
/** Archive-backed collections, same value as the plugin option (optional). */
|
||||
content?: ContentOption;
|
||||
/** Prepend a YAML frontmatter block (title/description/locale). Default true. */
|
||||
frontmatter?: boolean;
|
||||
/** Field holding the block layout. Default 'layout'. */
|
||||
layoutField?: string;
|
||||
/** Per-blockType overrides passed to blocksToMarkdown. */
|
||||
overrides?: Record<string, (block: Record<string, unknown>) => string>;
|
||||
/** SiteSettings global slug. Default 'site-settings'. */
|
||||
settingsSlug?: string;
|
||||
};
|
||||
type MarkdownContext = {
|
||||
locale: string;
|
||||
payload: BasePayload;
|
||||
/** Route slug segments; empty/undefined = locale root (home). */
|
||||
slug?: string[];
|
||||
};
|
||||
/**
|
||||
* Returns a function that renders a page (or archive/entry) to clean Markdown —
|
||||
* title, meta description, then the block layout via blocksToMarkdown. The
|
||||
* point is AI-readability: an agent (Claude's WebFetch, GPT, Perplexity) gets
|
||||
* structured Markdown instead of parsing HTML, so it reads the page reliably.
|
||||
*
|
||||
* Mirrors createPageMetadata: the plugin can't call getPayload, so it returns a
|
||||
* function the project invokes from its route handler.
|
||||
*
|
||||
* // app/md/[locale]/[[...slug]]/route.ts (serves /md/pl/o-nas as text/markdown)
|
||||
* import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit'
|
||||
* import { getPayload } from 'payload'
|
||||
* import config from '@payload-config'
|
||||
* const render = createMarkdownRenderer({ content })
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) {
|
||||
* const { locale, slug } = await params
|
||||
* const md = await render({ payload: await getPayload({ config }), locale, slug })
|
||||
* return markdownResponse(md)
|
||||
* }
|
||||
*
|
||||
* Returns null when the route doesn't resolve (so the handler can 404).
|
||||
*/
|
||||
export declare function createMarkdownRenderer(args?: CreateMarkdownRendererArgs): ({ slug, locale, payload }: MarkdownContext) => Promise<null | string>;
|
||||
/**
|
||||
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
|
||||
* Uses the global Response — no next/server import.
|
||||
*/
|
||||
export declare function markdownResponse(md: null | string): Response;
|
||||
export {};
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { blocksToMarkdown } from './blocksToMarkdown.js';
|
||||
import { resolveRoute } from './resolveRoute.js';
|
||||
function yamlEscape(v) {
|
||||
return `"${v.replace(/"/g, '\\"')}"`;
|
||||
}
|
||||
/**
|
||||
* Returns a function that renders a page (or archive/entry) to clean Markdown —
|
||||
* title, meta description, then the block layout via blocksToMarkdown. The
|
||||
* point is AI-readability: an agent (Claude's WebFetch, GPT, Perplexity) gets
|
||||
* structured Markdown instead of parsing HTML, so it reads the page reliably.
|
||||
*
|
||||
* Mirrors createPageMetadata: the plugin can't call getPayload, so it returns a
|
||||
* function the project invokes from its route handler.
|
||||
*
|
||||
* // app/md/[locale]/[[...slug]]/route.ts (serves /md/pl/o-nas as text/markdown)
|
||||
* import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit'
|
||||
* import { getPayload } from 'payload'
|
||||
* import config from '@payload-config'
|
||||
* const render = createMarkdownRenderer({ content })
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) {
|
||||
* const { locale, slug } = await params
|
||||
* const md = await render({ payload: await getPayload({ config }), locale, slug })
|
||||
* return markdownResponse(md)
|
||||
* }
|
||||
*
|
||||
* Returns null when the route doesn't resolve (so the handler can 404).
|
||||
*/ export function createMarkdownRenderer(args = {}) {
|
||||
const { collection = 'pages', content, frontmatter = true, layoutField = 'layout', overrides, settingsSlug = 'site-settings' } = args;
|
||||
return async function render({ slug, locale, payload }) {
|
||||
const route = await resolveRoute({
|
||||
content,
|
||||
locale,
|
||||
pagesSlug: collection,
|
||||
payload,
|
||||
segments: slug,
|
||||
settingsSlug
|
||||
});
|
||||
if (!route) {
|
||||
return null;
|
||||
}
|
||||
const doc = route.doc;
|
||||
const title = typeof doc.title === 'string' ? doc.title : '';
|
||||
const description = typeof doc.meta?.description === 'string' ? doc.meta.description : '';
|
||||
const body = blocksToMarkdown(doc[layoutField], {
|
||||
overrides
|
||||
});
|
||||
const parts = [];
|
||||
if (frontmatter) {
|
||||
const fm = [
|
||||
'---',
|
||||
`locale: ${locale}`
|
||||
];
|
||||
if (title) {
|
||||
fm.push(`title: ${yamlEscape(title)}`);
|
||||
}
|
||||
if (description) {
|
||||
fm.push(`description: ${yamlEscape(description)}`);
|
||||
}
|
||||
fm.push('---');
|
||||
parts.push(fm.join('\n'));
|
||||
}
|
||||
if (title) {
|
||||
parts.push(`# ${title}`);
|
||||
}
|
||||
if (description) {
|
||||
parts.push(`_${description}_`);
|
||||
}
|
||||
if (body) {
|
||||
parts.push(body);
|
||||
}
|
||||
const md = parts.join('\n\n').trim();
|
||||
return md || null;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
|
||||
* Uses the global Response — no next/server import.
|
||||
*/ export function markdownResponse(md) {
|
||||
if (md == null) {
|
||||
return new Response('Not found', {
|
||||
headers: {
|
||||
'content-type': 'text/plain'
|
||||
},
|
||||
status: 404
|
||||
});
|
||||
}
|
||||
return new Response(md, {
|
||||
headers: {
|
||||
'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400',
|
||||
'content-type': 'text/markdown; charset=utf-8'
|
||||
},
|
||||
status: 200
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=createMarkdownRenderer.js.map
|
||||
File diff suppressed because one or more lines are too long
+36
@@ -0,0 +1,36 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
type CreateSearchRouteArgs = {
|
||||
/** Absolute origin to prefix result URLs with. */
|
||||
baseUrl?: string;
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string;
|
||||
config: I18nConfig;
|
||||
/** Default result cap when ?limit is absent. Default 10. */
|
||||
defaultLimit?: number;
|
||||
getCachedPayload: () => Promise<BasePayload>;
|
||||
/** Home slug map/string so the home result collapses to root. */
|
||||
homeSlug?: Record<string, string> | string;
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
||||
summaryField?: string;
|
||||
};
|
||||
/**
|
||||
* A JSON content-search endpoint. Powers both the site's own search UI and
|
||||
* external agents — one ranking, one source of truth (shares searchContent with
|
||||
* the MCP server's search_content tool).
|
||||
*
|
||||
* // app/api/search/route.ts
|
||||
* import { createSearchRoute } from '@intecion/ipal-kit'
|
||||
* import { getCachedPayload } from '@/lib/content'
|
||||
* import { i18nConfig } from '@/i18n.config'
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,
|
||||
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
|
||||
*
|
||||
* Query params: `q` (required), `locale`, `limit`. Response:
|
||||
* { query, locale, count, results: [{ title, url, description?, slug }] }
|
||||
*
|
||||
* Uses the global Request/Response — no next/server import.
|
||||
*/
|
||||
export declare function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response>;
|
||||
export {};
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import { searchContent } from './searchContent.js';
|
||||
/**
|
||||
* A JSON content-search endpoint. Powers both the site's own search UI and
|
||||
* external agents — one ranking, one source of truth (shares searchContent with
|
||||
* the MCP server's search_content tool).
|
||||
*
|
||||
* // app/api/search/route.ts
|
||||
* import { createSearchRoute } from '@intecion/ipal-kit'
|
||||
* import { getCachedPayload } from '@/lib/content'
|
||||
* import { i18nConfig } from '@/i18n.config'
|
||||
* export const dynamic = 'force-dynamic'
|
||||
* export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,
|
||||
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
|
||||
*
|
||||
* Query params: `q` (required), `locale`, `limit`. Response:
|
||||
* { query, locale, count, results: [{ title, url, description?, slug }] }
|
||||
*
|
||||
* Uses the global Request/Response — no next/server import.
|
||||
*/ export function createSearchRoute(args) {
|
||||
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args;
|
||||
return async (req)=>{
|
||||
const url = new URL(req.url);
|
||||
const query = url.searchParams.get('q')?.trim() ?? '';
|
||||
const locale = url.searchParams.get('locale') ?? undefined;
|
||||
const limitParam = url.searchParams.get('limit');
|
||||
const limit = limitParam ? Number(limitParam) : defaultLimit;
|
||||
if (!query) {
|
||||
return Response.json({
|
||||
count: 0,
|
||||
error: 'Missing ?q',
|
||||
query: '',
|
||||
results: []
|
||||
}, {
|
||||
headers: {
|
||||
'cache-control': 'no-store'
|
||||
},
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
try {
|
||||
const payload = await getCachedPayload();
|
||||
const results = await searchContent({
|
||||
baseUrl,
|
||||
collection,
|
||||
config,
|
||||
homeSlug,
|
||||
limit,
|
||||
locale,
|
||||
payload,
|
||||
query,
|
||||
summaryField
|
||||
});
|
||||
return Response.json({
|
||||
count: results.length,
|
||||
locale: locale ?? config.defaultLocale,
|
||||
query,
|
||||
results
|
||||
}, {
|
||||
headers: {
|
||||
'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600'
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
// DB unreachable (build) or unexpected — empty result rather than 500.
|
||||
console.warn('[ipal] createSearchRoute: search failed:', err);
|
||||
return Response.json({
|
||||
count: 0,
|
||||
query,
|
||||
results: []
|
||||
}, {
|
||||
headers: {
|
||||
'cache-control': 'no-store'
|
||||
},
|
||||
status: 200
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=createSearchRoute.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/content/createSearchRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { I18nConfig } from '../i18n/index.js'\n\nimport { searchContent } from './searchContent.js'\n\ntype CreateSearchRouteArgs = {\n /** Absolute origin to prefix result URLs with. */\n baseUrl?: string\n /** Pages collection. Default 'pages'. */\n collection?: string\n config: I18nConfig\n /** Default result cap when ?limit is absent. Default 10. */\n defaultLimit?: number\n getCachedPayload: () => Promise<BasePayload>\n /** Home slug map/string so the home result collapses to root. */\n homeSlug?: Record<string, string> | string\n /** Field holding a richer AI summary (buildSummaryField) to prefer as description. */\n summaryField?: string\n}\n\n/**\n * A JSON content-search endpoint. Powers both the site's own search UI and\n * external agents — one ranking, one source of truth (shares searchContent with\n * the MCP server's search_content tool).\n *\n * // app/api/search/route.ts\n * import { createSearchRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * import { i18nConfig } from '@/i18n.config'\n * export const dynamic = 'force-dynamic'\n * export const GET = createSearchRoute({ getCachedPayload, config: i18nConfig,\n * baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })\n *\n * Query params: `q` (required), `locale`, `limit`. Response:\n * { query, locale, count, results: [{ title, url, description?, slug }] }\n *\n * Uses the global Request/Response — no next/server import.\n */\nexport function createSearchRoute(\n args: CreateSearchRouteArgs,\n): (req: Request) => Promise<Response> {\n const {\n baseUrl,\n collection = 'pages',\n config,\n defaultLimit = 10,\n getCachedPayload,\n homeSlug,\n summaryField,\n } = args\n\n return async (req: Request) => {\n const url = new URL(req.url)\n const query = url.searchParams.get('q')?.trim() ?? ''\n const locale = url.searchParams.get('locale') ?? undefined\n const limitParam = url.searchParams.get('limit')\n const limit = limitParam ? Number(limitParam) : defaultLimit\n\n if (!query) {\n return Response.json(\n { count: 0, error: 'Missing ?q', query: '', results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 400 },\n )\n }\n\n try {\n const payload = await getCachedPayload()\n const results = await searchContent({\n baseUrl,\n collection,\n config,\n homeSlug,\n limit,\n locale,\n payload,\n query,\n summaryField,\n })\n return Response.json(\n { count: results.length, locale: locale ?? config.defaultLocale, query, results },\n {\n headers: {\n 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600',\n },\n },\n )\n } catch (err) {\n // DB unreachable (build) or unexpected — empty result rather than 500.\n console.warn('[ipal] createSearchRoute: search failed:', err)\n return Response.json(\n { count: 0, query, results: [] },\n { headers: { 'cache-control': 'no-store' }, status: 200 },\n )\n }\n }\n}\n"],"names":["searchContent","createSearchRoute","args","baseUrl","collection","config","defaultLimit","getCachedPayload","homeSlug","summaryField","req","url","URL","query","searchParams","get","trim","locale","undefined","limitParam","limit","Number","Response","json","count","error","results","headers","status","payload","length","defaultLocale","err","console","warn"],"mappings":"AAIA,SAASA,aAAa,QAAQ,qBAAoB;AAiBlD;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASC,kBACdC,IAA2B;IAE3B,MAAM,EACJC,OAAO,EACPC,aAAa,OAAO,EACpBC,MAAM,EACNC,eAAe,EAAE,EACjBC,gBAAgB,EAChBC,QAAQ,EACRC,YAAY,EACb,GAAGP;IAEJ,OAAO,OAAOQ;QACZ,MAAMC,MAAM,IAAIC,IAAIF,IAAIC,GAAG;QAC3B,MAAME,QAAQF,IAAIG,YAAY,CAACC,GAAG,CAAC,MAAMC,UAAU;QACnD,MAAMC,SAASN,IAAIG,YAAY,CAACC,GAAG,CAAC,aAAaG;QACjD,MAAMC,aAAaR,IAAIG,YAAY,CAACC,GAAG,CAAC;QACxC,MAAMK,QAAQD,aAAaE,OAAOF,cAAcb;QAEhD,IAAI,CAACO,OAAO;YACV,OAAOS,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAGC,OAAO;gBAAcZ,OAAO;gBAAIa,SAAS,EAAE;YAAC,GACxD;gBAAEC,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;QAEA,IAAI;YACF,MAAMC,UAAU,MAAMtB;YACtB,MAAMmB,UAAU,MAAM1B,cAAc;gBAClCG;gBACAC;gBACAC;gBACAG;gBACAY;gBACAH;gBACAY;gBACAhB;gBACAJ;YACF;YACA,OAAOa,SAASC,IAAI,CAClB;gBAAEC,OAAOE,QAAQI,MAAM;gBAAEb,QAAQA,UAAUZ,OAAO0B,aAAa;gBAAElB;gBAAOa;YAAQ,GAChF;gBACEC,SAAS;oBACP,iBAAiB;gBACnB;YACF;QAEJ,EAAE,OAAOK,KAAK;YACZ,uEAAuE;YACvEC,QAAQC,IAAI,CAAC,4CAA4CF;YACzD,OAAOV,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAGX;gBAAOa,SAAS,EAAE;YAAC,GAC/B;gBAAEC,SAAS;oBAAE,iBAAiB;gBAAW;gBAAGC,QAAQ;YAAI;QAE5D;IACF;AACF"}
|
||||
Vendored
+8
@@ -1,8 +1,16 @@
|
||||
export { buildArchiveFields } from './archiveFields.js';
|
||||
export { blocksToMarkdown } from './blocksToMarkdown.js';
|
||||
export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js';
|
||||
export { createSearchRoute } from './createSearchRoute.js';
|
||||
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';
|
||||
export { searchContent } from './searchContent.js';
|
||||
export type { SearchResult } from './searchContent.js';
|
||||
export type { ContentCollectionOption, ContentOption } from './types.js';
|
||||
export { archiveFieldName } from './types.js';
|
||||
|
||||
Vendored
+7
@@ -1,7 +1,14 @@
|
||||
export { buildArchiveFields } from './archiveFields.js';
|
||||
export { blocksToMarkdown } from './blocksToMarkdown.js';
|
||||
export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js';
|
||||
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';
|
||||
export { archiveFieldName } from './types.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","getArchiveEntries","buildArchivePath","buildEntryPath","parsePageParam","resolveRoute","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,YAAY,QAAQ,oBAAmB;AAGhD,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"}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable
|
||||
* and negotiable, so AI agents reliably find and read it.
|
||||
*
|
||||
* Two mechanisms:
|
||||
* - `markdownHref` — the `<link rel="alternate" type="text/markdown">` href a
|
||||
* page advertises, so an agent fetching the HTML sees there's a Markdown
|
||||
* version and can switch to it.
|
||||
* - `prefersMarkdown` — reads the Accept header, so the same URL can serve
|
||||
* Markdown when asked (content negotiation via a proxy rewrite).
|
||||
*/
|
||||
/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */
|
||||
export declare const MARKDOWN_PREFIX = "/md";
|
||||
/**
|
||||
* The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so
|
||||
* the discovery link and the route agree.
|
||||
*
|
||||
* markdownHref('/pl/o-nas') // '/md/pl/o-nas'
|
||||
* markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas'
|
||||
*
|
||||
* Advertise it from Next metadata so every page's <head> points to its Markdown:
|
||||
*
|
||||
* // generateMetadata
|
||||
* return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }
|
||||
*/
|
||||
export declare function markdownHref(pathname: string, prefix?: string): string;
|
||||
/**
|
||||
* True when the client asked for Markdown via the Accept header (q-values
|
||||
* respected: a higher-weighted text/html wins). Accepts a header string, a
|
||||
* Headers object, or a Request. Use it in proxy.ts to serve the same URL as
|
||||
* Markdown when an agent negotiates for it:
|
||||
*
|
||||
* // proxy.ts
|
||||
* if (prefersMarkdown(request)) {
|
||||
* return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url))
|
||||
* }
|
||||
*/
|
||||
export declare function prefersMarkdown(input: Headers | null | Request | string | undefined): boolean;
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable
|
||||
* and negotiable, so AI agents reliably find and read it.
|
||||
*
|
||||
* Two mechanisms:
|
||||
* - `markdownHref` — the `<link rel="alternate" type="text/markdown">` href a
|
||||
* page advertises, so an agent fetching the HTML sees there's a Markdown
|
||||
* version and can switch to it.
|
||||
* - `prefersMarkdown` — reads the Accept header, so the same URL can serve
|
||||
* Markdown when asked (content negotiation via a proxy rewrite).
|
||||
*/ /** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */ export const MARKDOWN_PREFIX = '/md';
|
||||
/**
|
||||
* The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so
|
||||
* the discovery link and the route agree.
|
||||
*
|
||||
* markdownHref('/pl/o-nas') // '/md/pl/o-nas'
|
||||
* markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas'
|
||||
*
|
||||
* Advertise it from Next metadata so every page's <head> points to its Markdown:
|
||||
*
|
||||
* // generateMetadata
|
||||
* return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }
|
||||
*/ export function markdownHref(pathname, prefix = MARKDOWN_PREFIX) {
|
||||
const clean = pathname.startsWith('/') ? pathname : `/${pathname}`;
|
||||
const p = prefix.replace(/\/$/, '');
|
||||
return `${p}${clean === '/' ? '' : clean}` || p;
|
||||
}
|
||||
/**
|
||||
* True when the client asked for Markdown via the Accept header (q-values
|
||||
* respected: a higher-weighted text/html wins). Accepts a header string, a
|
||||
* Headers object, or a Request. Use it in proxy.ts to serve the same URL as
|
||||
* Markdown when an agent negotiates for it:
|
||||
*
|
||||
* // proxy.ts
|
||||
* if (prefersMarkdown(request)) {
|
||||
* return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url))
|
||||
* }
|
||||
*/ export function prefersMarkdown(input) {
|
||||
let accept = null;
|
||||
if (!input) {
|
||||
return false;
|
||||
}
|
||||
if (typeof input === 'string') {
|
||||
accept = input;
|
||||
} else if (input instanceof Headers) {
|
||||
accept = input.get('accept');
|
||||
} else if ('headers' in input && input.headers) {
|
||||
accept = input.headers.get('accept');
|
||||
}
|
||||
if (!accept) {
|
||||
return false;
|
||||
}
|
||||
// Parse "type/subtype;q=0.8" entries into {type, q}.
|
||||
const entries = accept.split(',').map((part)=>{
|
||||
const [type, ...params] = part.trim().split(';');
|
||||
const qParam = params.find((p)=>p.trim().startsWith('q='));
|
||||
const q = qParam ? Number(qParam.split('=')[1]) : 1;
|
||||
return {
|
||||
type: type.trim().toLowerCase(),
|
||||
q: Number.isFinite(q) ? q : 1
|
||||
};
|
||||
});
|
||||
const md = entries.find((e)=>e.type === 'text/markdown');
|
||||
if (!md) {
|
||||
return false;
|
||||
}
|
||||
// Markdown must be at least as preferred as html (and html not strictly higher).
|
||||
const html = entries.find((e)=>e.type === 'text/html');
|
||||
return !html || md.q >= html.q;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=markdownNegotiation.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/content/markdownNegotiation.ts"],"sourcesContent":["/**\n * Helpers for making the per-page Markdown (createMarkdownRenderer) discoverable\n * and negotiable, so AI agents reliably find and read it.\n *\n * Two mechanisms:\n * - `markdownHref` — the `<link rel=\"alternate\" type=\"text/markdown\">` href a\n * page advertises, so an agent fetching the HTML sees there's a Markdown\n * version and can switch to it.\n * - `prefersMarkdown` — reads the Accept header, so the same URL can serve\n * Markdown when asked (content negotiation via a proxy rewrite).\n */\n\n/** Default URL prefix the Markdown route is mounted at (see createMarkdownRenderer). */\nexport const MARKDOWN_PREFIX = '/md'\n\n/**\n * The Markdown URL for a given page path. Keeps the `/md` prefix in ONE place so\n * the discovery link and the route agree.\n *\n * markdownHref('/pl/o-nas') // '/md/pl/o-nas'\n * markdownHref('/pl/o-nas', '/ai') // '/ai/pl/o-nas'\n *\n * Advertise it from Next metadata so every page's <head> points to its Markdown:\n *\n * // generateMetadata\n * return { ...meta, alternates: { ...meta.alternates, types: { 'text/markdown': markdownHref(path) } } }\n */\nexport function markdownHref(pathname: string, prefix: string = MARKDOWN_PREFIX): string {\n const clean = pathname.startsWith('/') ? pathname : `/${pathname}`\n const p = prefix.replace(/\\/$/, '')\n return `${p}${clean === '/' ? '' : clean}` || p\n}\n\n/**\n * True when the client asked for Markdown via the Accept header (q-values\n * respected: a higher-weighted text/html wins). Accepts a header string, a\n * Headers object, or a Request. Use it in proxy.ts to serve the same URL as\n * Markdown when an agent negotiates for it:\n *\n * // proxy.ts\n * if (prefersMarkdown(request)) {\n * return NextResponse.rewrite(new URL(markdownHref(request.nextUrl.pathname), request.url))\n * }\n */\nexport function prefersMarkdown(input: Headers | null | Request | string | undefined): boolean {\n let accept: null | string = null\n if (!input) {return false}\n if (typeof input === 'string') {accept = input}\n else if (input instanceof Headers) {accept = input.get('accept')}\n else if ('headers' in input && input.headers) {accept = input.headers.get('accept')}\n if (!accept) {return false}\n\n // Parse \"type/subtype;q=0.8\" entries into {type, q}.\n const entries = accept.split(',').map((part) => {\n const [type, ...params] = part.trim().split(';')\n const qParam = params.find((p) => p.trim().startsWith('q='))\n const q = qParam ? Number(qParam.split('=')[1]) : 1\n return { type: type.trim().toLowerCase(), q: Number.isFinite(q) ? q : 1 }\n })\n\n const md = entries.find((e) => e.type === 'text/markdown')\n if (!md) {return false}\n // Markdown must be at least as preferred as html (and html not strictly higher).\n const html = entries.find((e) => e.type === 'text/html')\n return !html || md.q >= html.q\n}\n"],"names":["MARKDOWN_PREFIX","markdownHref","pathname","prefix","clean","startsWith","p","replace","prefersMarkdown","input","accept","Headers","get","headers","entries","split","map","part","type","params","trim","qParam","find","q","Number","toLowerCase","isFinite","md","e","html"],"mappings":"AAAA;;;;;;;;;;CAUC,GAED,sFAAsF,GACtF,OAAO,MAAMA,kBAAkB,MAAK;AAEpC;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,aAAaC,QAAgB,EAAEC,SAAiBH,eAAe;IAC7E,MAAMI,QAAQF,SAASG,UAAU,CAAC,OAAOH,WAAW,CAAC,CAAC,EAAEA,UAAU;IAClE,MAAMI,IAAIH,OAAOI,OAAO,CAAC,OAAO;IAChC,OAAO,GAAGD,IAAIF,UAAU,MAAM,KAAKA,OAAO,IAAIE;AAChD;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASE,gBAAgBC,KAAoD;IAClF,IAAIC,SAAwB;IAC5B,IAAI,CAACD,OAAO;QAAC,OAAO;IAAK;IACzB,IAAI,OAAOA,UAAU,UAAU;QAACC,SAASD;IAAK,OACzC,IAAIA,iBAAiBE,SAAS;QAACD,SAASD,MAAMG,GAAG,CAAC;IAAS,OAC3D,IAAI,aAAaH,SAASA,MAAMI,OAAO,EAAE;QAACH,SAASD,MAAMI,OAAO,CAACD,GAAG,CAAC;IAAS;IACnF,IAAI,CAACF,QAAQ;QAAC,OAAO;IAAK;IAE1B,qDAAqD;IACrD,MAAMI,UAAUJ,OAAOK,KAAK,CAAC,KAAKC,GAAG,CAAC,CAACC;QACrC,MAAM,CAACC,MAAM,GAAGC,OAAO,GAAGF,KAAKG,IAAI,GAAGL,KAAK,CAAC;QAC5C,MAAMM,SAASF,OAAOG,IAAI,CAAC,CAAChB,IAAMA,EAAEc,IAAI,GAAGf,UAAU,CAAC;QACtD,MAAMkB,IAAIF,SAASG,OAAOH,OAAON,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI;QAClD,OAAO;YAAEG,MAAMA,KAAKE,IAAI,GAAGK,WAAW;YAAIF,GAAGC,OAAOE,QAAQ,CAACH,KAAKA,IAAI;QAAE;IAC1E;IAEA,MAAMI,KAAKb,QAAQQ,IAAI,CAAC,CAACM,IAAMA,EAAEV,IAAI,KAAK;IAC1C,IAAI,CAACS,IAAI;QAAC,OAAO;IAAK;IACtB,iFAAiF;IACjF,MAAME,OAAOf,QAAQQ,IAAI,CAAC,CAACM,IAAMA,EAAEV,IAAI,KAAK;IAC5C,OAAO,CAACW,QAAQF,GAAGJ,CAAC,IAAIM,KAAKN,CAAC;AAChC"}
|
||||
+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"}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
type RedirectCollection = {
|
||||
/**
|
||||
* Array field holding past slugs, each row `{ slug }`. Default 'slugHistory'
|
||||
* — the field `trackSlugHistoryHook` writes. The subfield queried is
|
||||
* `<field>.slug`.
|
||||
*/
|
||||
historyField?: string;
|
||||
/** Collection slug to search, e.g. 'pages'. */
|
||||
slug: string;
|
||||
/** Current-slug field on the doc. Default 'slug'. */
|
||||
slugField?: string;
|
||||
};
|
||||
type ResolveRedirectArgs = {
|
||||
/**
|
||||
* Collections to search, in order. Default [{ slug: 'pages' }]. A collection
|
||||
* without a slug-history field is skipped safely (no crash), so passing a
|
||||
* collection that lacks it costs nothing.
|
||||
*/
|
||||
collections?: RedirectCollection[];
|
||||
config: I18nConfig;
|
||||
/** Home slug map/string, so a renamed homepage still collapses to the root. */
|
||||
homeSlug?: Record<string, string> | string;
|
||||
/** Active locale (the request's locale). */
|
||||
locale: string;
|
||||
payload: BasePayload;
|
||||
/** Incoming route segments (what 404'd), e.g. ['uslugi', 'stara-nazwa']. */
|
||||
segments: string[] | undefined;
|
||||
};
|
||||
/**
|
||||
* Resolves a 301/308 destination for a URL that no longer matches any current
|
||||
* slug, by looking the old slug up in each collection's slug-history. Returns
|
||||
* the current localized path to redirect to, or null when nothing matches.
|
||||
*
|
||||
* This is the read side of `trackSlugHistoryHook`: that hook records old slugs
|
||||
* on save; this turns them back into a redirect so a renamed page never 404s
|
||||
* (a real SEO loss). The plugin only COMPUTES the destination — the project
|
||||
* issues the redirect, keeping the peer-dep boundary (no next/navigation import
|
||||
* here):
|
||||
*
|
||||
* // app/[locale]/[[...slug]]/page.tsx (or app/[[...slug]] when single-locale)
|
||||
* const route = await resolveRoute({ ... })
|
||||
* if (!route) {
|
||||
* const dest = await resolveRedirect({
|
||||
* payload, locale, segments: slug, config: i18nConfig, homeSlug,
|
||||
* collections: [{ slug: 'pages' }],
|
||||
* })
|
||||
* if (dest) permanentRedirect(dest) // from 'next/navigation' → HTTP 308 (SEO-equivalent to 301)
|
||||
* notFound()
|
||||
* }
|
||||
*
|
||||
* Multi-segment slugs (an editor slug like 'uslugi/biznesowe') are matched as
|
||||
* the joined path, so they work unchanged. Archive ENTRY URLs
|
||||
* (/artykuly/<entry>) aren't handled here yet — only flat collections; pass
|
||||
* the collections whose slugs map directly to a path.
|
||||
*/
|
||||
export declare function resolveRedirect({ collections, config, homeSlug, locale, payload, segments, }: ResolveRedirectArgs): Promise<null | string>;
|
||||
export {};
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import { buildLocalizedPath } from '../i18n/index.js';
|
||||
/**
|
||||
* Resolves a 301/308 destination for a URL that no longer matches any current
|
||||
* slug, by looking the old slug up in each collection's slug-history. Returns
|
||||
* the current localized path to redirect to, or null when nothing matches.
|
||||
*
|
||||
* This is the read side of `trackSlugHistoryHook`: that hook records old slugs
|
||||
* on save; this turns them back into a redirect so a renamed page never 404s
|
||||
* (a real SEO loss). The plugin only COMPUTES the destination — the project
|
||||
* issues the redirect, keeping the peer-dep boundary (no next/navigation import
|
||||
* here):
|
||||
*
|
||||
* // app/[locale]/[[...slug]]/page.tsx (or app/[[...slug]] when single-locale)
|
||||
* const route = await resolveRoute({ ... })
|
||||
* if (!route) {
|
||||
* const dest = await resolveRedirect({
|
||||
* payload, locale, segments: slug, config: i18nConfig, homeSlug,
|
||||
* collections: [{ slug: 'pages' }],
|
||||
* })
|
||||
* if (dest) permanentRedirect(dest) // from 'next/navigation' → HTTP 308 (SEO-equivalent to 301)
|
||||
* notFound()
|
||||
* }
|
||||
*
|
||||
* Multi-segment slugs (an editor slug like 'uslugi/biznesowe') are matched as
|
||||
* the joined path, so they work unchanged. Archive ENTRY URLs
|
||||
* (/artykuly/<entry>) aren't handled here yet — only flat collections; pass
|
||||
* the collections whose slugs map directly to a path.
|
||||
*/ export async function resolveRedirect({ collections = [
|
||||
{
|
||||
slug: 'pages'
|
||||
}
|
||||
], config, homeSlug, locale, payload, segments }) {
|
||||
const oldSlug = (segments ?? []).filter(Boolean).join('/');
|
||||
// Root never redirects — there's no "old slug" for the locale home.
|
||||
if (!oldSlug) {
|
||||
return null;
|
||||
}
|
||||
for (const col of collections){
|
||||
const historyField = col.historyField ?? 'slugHistory';
|
||||
const slugField = col.slugField ?? 'slug';
|
||||
let currentSlug;
|
||||
try {
|
||||
const res = await payload.find({
|
||||
collection: col.slug,
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
locale: locale,
|
||||
pagination: false,
|
||||
where: {
|
||||
[`${historyField}.slug`]: {
|
||||
equals: oldSlug
|
||||
}
|
||||
}
|
||||
});
|
||||
const doc = res?.docs?.[0] ?? null;
|
||||
if (doc && typeof doc[slugField] === 'string') {
|
||||
currentSlug = doc[slugField];
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (!currentSlug || currentSlug === oldSlug) {
|
||||
continue;
|
||||
}
|
||||
const dest = buildLocalizedPath({
|
||||
config,
|
||||
homeSlug,
|
||||
locale,
|
||||
slugs: {
|
||||
[locale]: currentSlug
|
||||
}
|
||||
});
|
||||
// Never redirect a path to itself (would loop).
|
||||
if (dest && dest !== `/${oldSlug}` && dest !== `/${locale}/${oldSlug}`) {
|
||||
return dest;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=resolveRedirect.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+14
@@ -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
+43
@@ -0,0 +1,43 @@
|
||||
import type { BasePayload } from 'payload';
|
||||
import type { I18nConfig } from '../i18n/index.js';
|
||||
export type SearchResult = {
|
||||
description?: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
/** Locale-aware path, prefixed with baseUrl when given. */
|
||||
url: string;
|
||||
};
|
||||
type SearchContentArgs = {
|
||||
/** Absolute origin to prefix URLs with. Omit for relative paths. */
|
||||
baseUrl?: string;
|
||||
/** Pages collection. Default 'pages'. */
|
||||
collection?: string;
|
||||
config: I18nConfig;
|
||||
/** Home slug map/string so the home result collapses to root. */
|
||||
homeSlug?: Record<string, string> | string;
|
||||
/** Max results. Default 10, clamped 1–50. */
|
||||
limit?: number;
|
||||
/** Locale to search/return. Defaults to config.defaultLocale; invalid → default. */
|
||||
locale?: string;
|
||||
payload: BasePayload;
|
||||
/** Keywords. */
|
||||
query: string;
|
||||
/**
|
||||
* Field holding a richer AI summary (see buildSummaryField). When set and
|
||||
* present on a doc, it's preferred over meta.description for the result's
|
||||
* description.
|
||||
*/
|
||||
summaryField?: string;
|
||||
};
|
||||
/**
|
||||
* Shared content search: title / meta-description keyword match over a
|
||||
* collection, returning structured results (published, non-noindex only). One
|
||||
* implementation behind BOTH the JSON search route (createSearchRoute) and the
|
||||
* MCP server's search_content tool — so site search, API and AI all rank the
|
||||
* same way.
|
||||
*
|
||||
* Degrades to [] (never throws) when the collection's fields aren't queryable —
|
||||
* same guard class as the drafts/_status lesson.
|
||||
*/
|
||||
export declare function searchContent({ baseUrl, collection, config, homeSlug, limit, locale, payload, query, summaryField, }: SearchContentArgs): Promise<SearchResult[]>;
|
||||
export {};
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/index.js';
|
||||
/**
|
||||
* Shared content search: title / meta-description keyword match over a
|
||||
* collection, returning structured results (published, non-noindex only). One
|
||||
* implementation behind BOTH the JSON search route (createSearchRoute) and the
|
||||
* MCP server's search_content tool — so site search, API and AI all rank the
|
||||
* same way.
|
||||
*
|
||||
* Degrades to [] (never throws) when the collection's fields aren't queryable —
|
||||
* same guard class as the drafts/_status lesson.
|
||||
*/ export async function searchContent({ baseUrl, collection = 'pages', config, homeSlug, limit = 10, locale, payload, query, summaryField }) {
|
||||
const q = query.trim();
|
||||
if (!q) {
|
||||
return [];
|
||||
}
|
||||
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config);
|
||||
const max = Math.min(Math.max(Math.trunc(limit) || 10, 1), 50);
|
||||
const origin = baseUrl?.replace(/\/$/, '') ?? '';
|
||||
let docs = [];
|
||||
try {
|
||||
const res = await payload.find({
|
||||
collection: collection,
|
||||
depth: 0,
|
||||
limit: max * 3,
|
||||
locale: loc,
|
||||
where: {
|
||||
or: [
|
||||
{
|
||||
title: {
|
||||
like: q
|
||||
}
|
||||
},
|
||||
{
|
||||
'meta.description': {
|
||||
like: q
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
docs = res?.docs ?? [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const results = [];
|
||||
for (const doc of docs){
|
||||
if (doc._status && doc._status !== 'published') {
|
||||
continue;
|
||||
}
|
||||
if (doc.noindex || doc.meta?.noindex) {
|
||||
continue;
|
||||
}
|
||||
const title = typeof doc.title === 'string' ? doc.title : undefined;
|
||||
const slug = typeof doc.slug === 'string' ? doc.slug : undefined;
|
||||
if (!title || !slug) {
|
||||
continue;
|
||||
}
|
||||
const path = buildLocalizedPath({
|
||||
config,
|
||||
homeSlug,
|
||||
locale: loc,
|
||||
slugs: {
|
||||
[loc]: slug
|
||||
}
|
||||
});
|
||||
// Prefer the richer AI summary when configured and present, else meta.description.
|
||||
const summary = summaryField && typeof doc[summaryField] === 'string' ? doc[summaryField] : undefined;
|
||||
const description = summary?.trim() || (typeof doc.meta?.description === 'string' ? doc.meta.description : undefined);
|
||||
results.push({
|
||||
slug,
|
||||
title,
|
||||
url: `${origin}${path ?? `/${slug}`}`,
|
||||
...description ? {
|
||||
description
|
||||
} : {}
|
||||
});
|
||||
if (results.length >= max) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=searchContent.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Zero-dependency environment validation. The plugin deliberately does NOT pull
|
||||
* in zod — forcing a validation library on every project would be a dependency
|
||||
* the project didn't ask for (against the A0 "no imposed deps" rule). This is a
|
||||
* tiny validator that does the one thing we need: check the vars a deploy needs
|
||||
* and FAIL FAST with a readable, all-at-once message instead of a cryptic
|
||||
* runtime crash (e.g. `getaddrinfo ENOTFOUND` halfway through a Docker build).
|
||||
*/
|
||||
export type EnvKind = 'boolean' | 'email' | 'number' | 'port' | 'string' | 'url';
|
||||
export type EnvRule = {
|
||||
/** Shown in the error to tell the deployer what the var is for. */
|
||||
description?: string;
|
||||
/** Shape check applied when a value is present. Default 'string' (non-empty). */
|
||||
kind?: EnvKind;
|
||||
/** Variable name, e.g. 'DATABASE_URI'. */
|
||||
name: string;
|
||||
/** Allowed values (e.g. NODE_ENV). Checked when a value is present. */
|
||||
oneOf?: readonly string[];
|
||||
/** Default true. When false, the var is only validated if present. */
|
||||
required?: boolean;
|
||||
/** Custom check: return true if OK, or an error message string. */
|
||||
validate?: (value: string) => string | true;
|
||||
};
|
||||
export type AssertEnvOptions = {
|
||||
/** Source of values. Default process.env. */
|
||||
env?: Record<string, string | undefined>;
|
||||
/** Error prefix. Default '[ipal]'. */
|
||||
label?: string;
|
||||
};
|
||||
/**
|
||||
* Validates the given rules against the environment and THROWS a single,
|
||||
* aggregated error listing every problem at once (not just the first). Call it
|
||||
* once at boot — in payload.config.ts, or Next's instrumentation.ts register().
|
||||
*
|
||||
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
|
||||
* assertEnv(ipalEnvRules({ storage: true, turnstile: true }))
|
||||
*
|
||||
* or with hand-written rules:
|
||||
*
|
||||
* assertEnv([
|
||||
* { name: 'DATABASE_URI', description: 'MongoDB connection string' },
|
||||
* { name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },
|
||||
* { name: 'NODE_ENV', oneOf: ['development', 'production', 'test'] },
|
||||
* ])
|
||||
*
|
||||
* Runs server-side only (reads process.env) — never import it into a client
|
||||
* component.
|
||||
*/
|
||||
export declare function assertEnv(rules: EnvRule[], options?: AssertEnvOptions): void;
|
||||
Vendored
+101
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Zero-dependency environment validation. The plugin deliberately does NOT pull
|
||||
* in zod — forcing a validation library on every project would be a dependency
|
||||
* the project didn't ask for (against the A0 "no imposed deps" rule). This is a
|
||||
* tiny validator that does the one thing we need: check the vars a deploy needs
|
||||
* and FAIL FAST with a readable, all-at-once message instead of a cryptic
|
||||
* runtime crash (e.g. `getaddrinfo ENOTFOUND` halfway through a Docker build).
|
||||
*/ const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
|
||||
/** Validate one present value against its rule. Returns an error message or null. */ function checkValue(rule, value) {
|
||||
const { name, kind = 'string', oneOf } = rule;
|
||||
if (oneOf && !oneOf.includes(value)) {
|
||||
return `${name} must be one of: ${oneOf.join(', ')} (got "${value}")`;
|
||||
}
|
||||
switch(kind){
|
||||
case 'boolean':
|
||||
if (!/^(true|false|1|0|yes|no)$/i.test(value)) {
|
||||
return `${name} must be a boolean (true/false/1/0/yes/no, got "${value}")`;
|
||||
}
|
||||
break;
|
||||
case 'email':
|
||||
if (!EMAIL_RE.test(value)) {
|
||||
return `${name} must be an e-mail address (got "${value}")`;
|
||||
}
|
||||
break;
|
||||
case 'number':
|
||||
if (!Number.isFinite(Number(value))) {
|
||||
return `${name} must be a number (got "${value}")`;
|
||||
}
|
||||
break;
|
||||
case 'port':
|
||||
{
|
||||
const n = Number(value);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 65535) {
|
||||
return `${name} must be a port 1–65535 (got "${value}")`;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'url':
|
||||
try {
|
||||
new URL(value);
|
||||
} catch {
|
||||
return `${name} must be a valid URL (got "${value}")`;
|
||||
}
|
||||
break;
|
||||
case 'string':
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (rule.validate) {
|
||||
const res = rule.validate(value);
|
||||
if (res !== true) {
|
||||
return typeof res === 'string' ? res : `${name} is invalid`;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Validates the given rules against the environment and THROWS a single,
|
||||
* aggregated error listing every problem at once (not just the first). Call it
|
||||
* once at boot — in payload.config.ts, or Next's instrumentation.ts register().
|
||||
*
|
||||
* import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
|
||||
* assertEnv(ipalEnvRules({ storage: true, turnstile: true }))
|
||||
*
|
||||
* or with hand-written rules:
|
||||
*
|
||||
* assertEnv([
|
||||
* { name: 'DATABASE_URI', description: 'MongoDB connection string' },
|
||||
* { name: 'NEXT_PUBLIC_SERVER_URL', kind: 'url' },
|
||||
* { name: 'NODE_ENV', oneOf: ['development', 'production', 'test'] },
|
||||
* ])
|
||||
*
|
||||
* Runs server-side only (reads process.env) — never import it into a client
|
||||
* component.
|
||||
*/ export function assertEnv(rules, options = {}) {
|
||||
const env = options.env ?? process.env;
|
||||
const label = options.label ?? '[ipal]';
|
||||
const problems = [];
|
||||
for (const rule of rules){
|
||||
const raw = env[rule.name];
|
||||
const value = typeof raw === 'string' ? raw.trim() : '';
|
||||
const required = rule.required !== false;
|
||||
if (!value) {
|
||||
if (required) {
|
||||
problems.push(`${rule.name} is required but missing${rule.description ? ` — ${rule.description}` : ''}`);
|
||||
}
|
||||
continue; // optional + absent → nothing to check
|
||||
}
|
||||
const err = checkValue(rule, value);
|
||||
if (err) {
|
||||
problems.push(`${err}${rule.description ? ` — ${rule.description}` : ''}`);
|
||||
}
|
||||
}
|
||||
if (problems.length === 0) {
|
||||
return;
|
||||
}
|
||||
const message = `${label} Environment validation failed (${problems.length} ` + `problem${problems.length === 1 ? '' : 's'}):\n` + problems.map((p)=>` • ${p}`).join('\n') + `\nSet these in your environment (Coolify → Environment, or .env) and redeploy.`;
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=assertEnv.js.map
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
export { assertEnv } from './assertEnv.js';
|
||||
export type { EnvRule, EnvKind, AssertEnvOptions } from './assertEnv.js';
|
||||
export { ipalEnvRules } from './ipalEnvRules.js';
|
||||
export type { IpalEnvFeatures } from './ipalEnvRules.js';
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
export { assertEnv } from './assertEnv.js';
|
||||
export { ipalEnvRules } from './ipalEnvRules.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/env/index.ts"],"sourcesContent":["export { assertEnv } from './assertEnv.js'\nexport type { EnvRule, EnvKind, AssertEnvOptions } from './assertEnv.js'\nexport { ipalEnvRules } from './ipalEnvRules.js'\nexport type { IpalEnvFeatures } from './ipalEnvRules.js'\n"],"names":["assertEnv","ipalEnvRules"],"mappings":"AAAA,SAASA,SAAS,QAAQ,iBAAgB;AAE1C,SAASC,YAAY,QAAQ,oBAAmB"}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
import type { EnvRule } from './assertEnv.js';
|
||||
type TurnstileNames = {
|
||||
secretVar?: string;
|
||||
siteKeyVar?: string;
|
||||
};
|
||||
export type IpalEnvFeatures = {
|
||||
/** Override the database var. Default 'DATABASE_URI'. */
|
||||
databaseVar?: string;
|
||||
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
|
||||
emailGraph?: boolean;
|
||||
/** Override the Payload secret var. Default 'PAYLOAD_SECRET'. */
|
||||
secretVar?: string;
|
||||
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
|
||||
serverUrlVar?: string;
|
||||
/** R2 object storage (buildR2Storage). Adds the R2_* vars. */
|
||||
storage?: boolean;
|
||||
/**
|
||||
* Cloudflare Turnstile. true uses the common var names
|
||||
* (NEXT_PUBLIC_TURNSTILE_SITE_KEY + TURNSTILE_SECRET_KEY); pass an object to
|
||||
* override either name if your project differs.
|
||||
*/
|
||||
turnstile?: boolean | TurnstileNames;
|
||||
};
|
||||
/**
|
||||
* The env schema for a standard ipal-kit deploy, assembled from the features the
|
||||
* project actually uses — so a site on local-disk storage isn't forced to set
|
||||
* R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a
|
||||
* fixed required set (A0: the plugin never demands config a project doesn't use).
|
||||
*
|
||||
* Variable names match what the plugin's own modules read (R2_*, GRAPH_*,
|
||||
* NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core.
|
||||
* Override any name via the options if your project names them differently.
|
||||
*
|
||||
* assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true }))
|
||||
*
|
||||
* Extend with project-specific vars by spreading:
|
||||
*
|
||||
* assertEnv([
|
||||
* ...ipalEnvRules({ storage: true }),
|
||||
* { name: 'MY_API_KEY', description: 'Third-party integration key' },
|
||||
* ])
|
||||
*/
|
||||
export declare function ipalEnvRules(features?: IpalEnvFeatures): EnvRule[];
|
||||
export {};
|
||||
Vendored
+95
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* The env schema for a standard ipal-kit deploy, assembled from the features the
|
||||
* project actually uses — so a site on local-disk storage isn't forced to set
|
||||
* R2_*, and a site with no forms isn't forced to set Turnstile. Opt-in, not a
|
||||
* fixed required set (A0: the plugin never demands config a project doesn't use).
|
||||
*
|
||||
* Variable names match what the plugin's own modules read (R2_*, GRAPH_*,
|
||||
* NEXT_PUBLIC_SERVER_URL). DATABASE_URI and PAYLOAD_SECRET are Payload-core.
|
||||
* Override any name via the options if your project names them differently.
|
||||
*
|
||||
* assertEnv(ipalEnvRules({ storage: true, emailGraph: true, turnstile: true }))
|
||||
*
|
||||
* Extend with project-specific vars by spreading:
|
||||
*
|
||||
* assertEnv([
|
||||
* ...ipalEnvRules({ storage: true }),
|
||||
* { name: 'MY_API_KEY', description: 'Third-party integration key' },
|
||||
* ])
|
||||
*/ export function ipalEnvRules(features = {}) {
|
||||
const { databaseVar = 'DATABASE_URI', emailGraph = false, secretVar = 'PAYLOAD_SECRET', serverUrlVar = 'NEXT_PUBLIC_SERVER_URL', storage = false, turnstile = false } = features;
|
||||
const rules = [
|
||||
{
|
||||
name: databaseVar,
|
||||
description: 'Database connection string (e.g. MongoDB URI)'
|
||||
},
|
||||
{
|
||||
name: secretVar,
|
||||
description: 'Payload secret used to sign tokens'
|
||||
},
|
||||
{
|
||||
name: serverUrlVar,
|
||||
description: 'Public site origin, e.g. https://example.com',
|
||||
kind: 'url'
|
||||
},
|
||||
{
|
||||
name: 'NODE_ENV',
|
||||
description: 'Node environment',
|
||||
oneOf: [
|
||||
'development',
|
||||
'production',
|
||||
'test'
|
||||
],
|
||||
required: false
|
||||
}
|
||||
];
|
||||
if (storage) {
|
||||
rules.push({
|
||||
name: 'R2_BUCKET',
|
||||
description: 'R2 bucket name'
|
||||
}, {
|
||||
name: 'R2_ACCESS_KEY_ID',
|
||||
description: 'R2 access key id'
|
||||
}, {
|
||||
name: 'R2_SECRET_ACCESS_KEY',
|
||||
description: 'R2 secret access key'
|
||||
}, {
|
||||
name: 'R2_ENDPOINT',
|
||||
description: 'R2 S3 API endpoint URL',
|
||||
kind: 'url'
|
||||
}, {
|
||||
name: 'R2_PUBLIC_URL',
|
||||
description: 'Public base URL media is served from',
|
||||
kind: 'url'
|
||||
});
|
||||
}
|
||||
if (emailGraph) {
|
||||
rules.push({
|
||||
name: 'GRAPH_TENANT_ID',
|
||||
description: 'Microsoft Graph tenant id'
|
||||
}, {
|
||||
name: 'GRAPH_CLIENT_ID',
|
||||
description: 'Microsoft Graph client id'
|
||||
}, {
|
||||
name: 'GRAPH_CLIENT_SECRET',
|
||||
description: 'Microsoft Graph client secret'
|
||||
}, {
|
||||
name: 'GRAPH_SENDER',
|
||||
description: 'From-address mail is sent as',
|
||||
kind: 'email'
|
||||
});
|
||||
}
|
||||
if (turnstile) {
|
||||
const names = typeof turnstile === 'object' ? turnstile : {};
|
||||
rules.push({
|
||||
name: names.siteKeyVar ?? 'NEXT_PUBLIC_TURNSTILE_SITE_KEY',
|
||||
description: 'Cloudflare Turnstile public site key'
|
||||
}, {
|
||||
name: names.secretVar ?? 'TURNSTILE_SECRET_KEY',
|
||||
description: 'Cloudflare Turnstile secret key'
|
||||
});
|
||||
}
|
||||
return rules;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=ipalEnvRules.js.map
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
+29
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Shape of the per-form analytics config an editor fills in the panel (see
|
||||
* buildFormAnalyticsFields). Loose by design — it comes from Payload.
|
||||
*/
|
||||
export type FormAnalyticsConfig = {
|
||||
event?: null | string;
|
||||
params?: {
|
||||
key?: null | string;
|
||||
value?: null | string;
|
||||
}[] | null;
|
||||
} | null | undefined;
|
||||
/**
|
||||
* Builds an `onSuccess` handler from a form's panel-configured analytics, so the
|
||||
* GTM `dataLayer` event is emitted on submit with ZERO per-form code. Wire it
|
||||
* once in the shared form renderer — every form then gets its tracking from the
|
||||
* panel:
|
||||
*
|
||||
* const f = useContactForm({
|
||||
* submitAction,
|
||||
* onSuccess: formAnalyticsOnSuccess(form.analytics),
|
||||
* })
|
||||
*
|
||||
* A param value starting with `$` is resolved from the submitted values, so an
|
||||
* editor can set `form_name = $topic` and get the chosen topic with no code.
|
||||
* No event name configured → the returned handler is a no-op.
|
||||
*/
|
||||
export declare function formAnalyticsOnSuccess<T extends Record<string, unknown>>(config: FormAnalyticsConfig): (result: {
|
||||
success: boolean;
|
||||
}, values: T) => void;
|
||||
Vendored
+35
@@ -0,0 +1,35 @@
|
||||
import { pushDataLayer } from '../analytics/pushDataLayer.js';
|
||||
/**
|
||||
* Builds an `onSuccess` handler from a form's panel-configured analytics, so the
|
||||
* GTM `dataLayer` event is emitted on submit with ZERO per-form code. Wire it
|
||||
* once in the shared form renderer — every form then gets its tracking from the
|
||||
* panel:
|
||||
*
|
||||
* const f = useContactForm({
|
||||
* submitAction,
|
||||
* onSuccess: formAnalyticsOnSuccess(form.analytics),
|
||||
* })
|
||||
*
|
||||
* A param value starting with `$` is resolved from the submitted values, so an
|
||||
* editor can set `form_name = $topic` and get the chosen topic with no code.
|
||||
* No event name configured → the returned handler is a no-op.
|
||||
*/ export function formAnalyticsOnSuccess(config) {
|
||||
return (_result, values)=>{
|
||||
const event = config?.event?.trim();
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
const params = {};
|
||||
for (const p of config?.params ?? []){
|
||||
const key = p?.key?.trim();
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
const raw = typeof p?.value === 'string' ? p.value : '';
|
||||
params[key] = raw.startsWith('$') ? values[raw.slice(1)] ?? '' : raw;
|
||||
}
|
||||
pushDataLayer(event, params);
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=formAnalytics.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/forms/formAnalytics.ts"],"sourcesContent":["import { pushDataLayer } from '../analytics/pushDataLayer.js'\n\n/**\n * Shape of the per-form analytics config an editor fills in the panel (see\n * buildFormAnalyticsFields). Loose by design — it comes from Payload.\n */\nexport type FormAnalyticsConfig =\n | {\n event?: null | string\n params?: { key?: null | string; value?: null | string }[] | null\n }\n | null\n | undefined\n\n/**\n * Builds an `onSuccess` handler from a form's panel-configured analytics, so the\n * GTM `dataLayer` event is emitted on submit with ZERO per-form code. Wire it\n * once in the shared form renderer — every form then gets its tracking from the\n * panel:\n *\n * const f = useContactForm({\n * submitAction,\n * onSuccess: formAnalyticsOnSuccess(form.analytics),\n * })\n *\n * A param value starting with `$` is resolved from the submitted values, so an\n * editor can set `form_name = $topic` and get the chosen topic with no code.\n * No event name configured → the returned handler is a no-op.\n */\nexport function formAnalyticsOnSuccess<T extends Record<string, unknown>>(\n config: FormAnalyticsConfig,\n): (result: { success: boolean }, values: T) => void {\n return (_result, values) => {\n const event = config?.event?.trim()\n if (!event) {return}\n const params: Record<string, unknown> = {}\n for (const p of config?.params ?? []) {\n const key = p?.key?.trim()\n if (!key) {continue}\n const raw = typeof p?.value === 'string' ? p.value : ''\n params[key] = raw.startsWith('$') ? (values[raw.slice(1)] ?? '') : raw\n }\n pushDataLayer(event, params)\n }\n}\n"],"names":["pushDataLayer","formAnalyticsOnSuccess","config","_result","values","event","trim","params","p","key","raw","value","startsWith","slice"],"mappings":"AAAA,SAASA,aAAa,QAAQ,gCAA+B;AAc7D;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,uBACdC,MAA2B;IAE3B,OAAO,CAACC,SAASC;QACf,MAAMC,QAAQH,QAAQG,OAAOC;QAC7B,IAAI,CAACD,OAAO;YAAC;QAAM;QACnB,MAAME,SAAkC,CAAC;QACzC,KAAK,MAAMC,KAAKN,QAAQK,UAAU,EAAE,CAAE;YACpC,MAAME,MAAMD,GAAGC,KAAKH;YACpB,IAAI,CAACG,KAAK;gBAAC;YAAQ;YACnB,MAAMC,MAAM,OAAOF,GAAGG,UAAU,WAAWH,EAAEG,KAAK,GAAG;YACrDJ,MAAM,CAACE,IAAI,GAAGC,IAAIE,UAAU,CAAC,OAAQR,MAAM,CAACM,IAAIG,KAAK,CAAC,GAAG,IAAI,KAAMH;QACrE;QACAV,cAAcK,OAAOE;IACvB;AACF"}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import type { Field } from 'payload';
|
||||
/**
|
||||
* Panel fields that let an EDITOR configure a form's analytics event — the GTM
|
||||
* `dataLayer` push fired on successful submit — without any code change. Add
|
||||
* them to the Forms collection via the plugin's `formOverrides`:
|
||||
*
|
||||
* ipalKit({
|
||||
* forms: {
|
||||
* formOverrides: {
|
||||
* fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()],
|
||||
* },
|
||||
* },
|
||||
* })
|
||||
*
|
||||
* The front reads this config and emits the event automatically via
|
||||
* `formAnalyticsOnSuccess` (see forms.md) — so adding a tracked form, or
|
||||
* changing its event name/params, is panel-only. The GTM side (the Lead/Pixel
|
||||
* tag, its trigger and consent gate) stays in GTM, which is itself a no-code
|
||||
* panel for tags.
|
||||
*/
|
||||
export declare function buildFormAnalyticsFields(): Field[];
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Panel fields that let an EDITOR configure a form's analytics event — the GTM
|
||||
* `dataLayer` push fired on successful submit — without any code change. Add
|
||||
* them to the Forms collection via the plugin's `formOverrides`:
|
||||
*
|
||||
* ipalKit({
|
||||
* forms: {
|
||||
* formOverrides: {
|
||||
* fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()],
|
||||
* },
|
||||
* },
|
||||
* })
|
||||
*
|
||||
* The front reads this config and emits the event automatically via
|
||||
* `formAnalyticsOnSuccess` (see forms.md) — so adding a tracked form, or
|
||||
* changing its event name/params, is panel-only. The GTM side (the Lead/Pixel
|
||||
* tag, its trigger and consent gate) stays in GTM, which is itself a no-code
|
||||
* panel for tags.
|
||||
*/ export function buildFormAnalyticsFields() {
|
||||
return [
|
||||
{
|
||||
name: 'analytics',
|
||||
type: 'group',
|
||||
admin: {
|
||||
description: 'Event pushed to the dataLayer on a successful submit. In GTM, attach a tag (e.g. Lead) with a trigger on this event name.'
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'event',
|
||||
type: 'text',
|
||||
admin: {
|
||||
description: 'Empty = nothing is pushed. Default "form_submit" — attach your GTM trigger to it.'
|
||||
},
|
||||
defaultValue: 'form_submit',
|
||||
label: 'Event name'
|
||||
},
|
||||
{
|
||||
name: 'params',
|
||||
type: 'array',
|
||||
admin: {
|
||||
description: 'Key/value pairs sent with the event. A value starting with "$" is taken from a form field, e.g. $topic → the chosen topic.'
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'key',
|
||||
type: 'text',
|
||||
required: true
|
||||
},
|
||||
{
|
||||
name: 'value',
|
||||
type: 'text',
|
||||
required: true
|
||||
}
|
||||
],
|
||||
label: 'Event parameters'
|
||||
}
|
||||
],
|
||||
label: 'Analytics (GTM / dataLayer)'
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
//# sourceMappingURL=formAnalyticsFields.js.map
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/forms/formAnalyticsFields.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Panel fields that let an EDITOR configure a form's analytics event — the GTM\n * `dataLayer` push fired on successful submit — without any code change. Add\n * them to the Forms collection via the plugin's `formOverrides`:\n *\n * ipalKit({\n * forms: {\n * formOverrides: {\n * fields: ({ defaultFields }) => [...defaultFields, ...buildFormAnalyticsFields()],\n * },\n * },\n * })\n *\n * The front reads this config and emits the event automatically via\n * `formAnalyticsOnSuccess` (see forms.md) — so adding a tracked form, or\n * changing its event name/params, is panel-only. The GTM side (the Lead/Pixel\n * tag, its trigger and consent gate) stays in GTM, which is itself a no-code\n * panel for tags.\n */\nexport function buildFormAnalyticsFields(): Field[] {\n return [\n {\n name: 'analytics',\n type: 'group',\n admin: {\n description:\n 'Event pushed to the dataLayer on a successful submit. In GTM, attach a tag (e.g. Lead) with a trigger on this event name.',\n },\n fields: [\n {\n name: 'event',\n type: 'text',\n admin: {\n description:\n 'Empty = nothing is pushed. Default \"form_submit\" — attach your GTM trigger to it.',\n },\n defaultValue: 'form_submit',\n label: 'Event name',\n },\n {\n name: 'params',\n type: 'array',\n admin: {\n description:\n 'Key/value pairs sent with the event. A value starting with \"$\" is taken from a form field, e.g. $topic → the chosen topic.',\n },\n fields: [\n { name: 'key', type: 'text', required: true },\n { name: 'value', type: 'text', required: true },\n ],\n label: 'Event parameters',\n },\n ],\n label: 'Analytics (GTM / dataLayer)',\n },\n ]\n}\n"],"names":["buildFormAnalyticsFields","name","type","admin","description","fields","defaultValue","label","required"],"mappings":"AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASA;IACd,OAAO;QACL;YACEC,MAAM;YACNC,MAAM;YACNC,OAAO;gBACLC,aACE;YACJ;YACAC,QAAQ;gBACN;oBACEJ,MAAM;oBACNC,MAAM;oBACNC,OAAO;wBACLC,aACE;oBACJ;oBACAE,cAAc;oBACdC,OAAO;gBACT;gBACA;oBACEN,MAAM;oBACNC,MAAM;oBACNC,OAAO;wBACLC,aACE;oBACJ;oBACAC,QAAQ;wBACN;4BAAEJ,MAAM;4BAAOC,MAAM;4BAAQM,UAAU;wBAAK;wBAC5C;4BAAEP,MAAM;4BAASC,MAAM;4BAAQM,UAAU;wBAAK;qBAC/C;oBACDD,OAAO;gBACT;aACD;YACDA,OAAO;QACT;KACD;AACH"}
|
||||
Vendored
+46
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* A honeypot: a hidden field real users never see or fill, but naive bots do.
|
||||
* A cheap, zero-friction second layer alongside Turnstile — no network call, no
|
||||
* user interaction. Pure functions, usable on client (render the input) and
|
||||
* server (check it in the action).
|
||||
*/
|
||||
/**
|
||||
* Default field name. Looks like a real field a bot would want to fill, but is
|
||||
* not one your form uses. Override per project if you like — just keep the
|
||||
* client and server in sync.
|
||||
*/
|
||||
export declare const HONEYPOT_FIELD = "company_url";
|
||||
/**
|
||||
* Props for the hidden input. Hidden from sight AND from assistive tech and tab
|
||||
* order, so no real user (sighted, screen-reader, or keyboard) ever fills it —
|
||||
* only a bot auto-filling every field.
|
||||
*
|
||||
* <input {...honeypotInputProps()} />
|
||||
* // or with your own name:
|
||||
* <input {...honeypotInputProps('website_2')} />
|
||||
*/
|
||||
export declare function honeypotInputProps(name?: string): {
|
||||
name: string;
|
||||
type: "text";
|
||||
'aria-hidden': boolean;
|
||||
autoComplete: "off";
|
||||
tabIndex: number;
|
||||
style: {
|
||||
height: string;
|
||||
left: string;
|
||||
overflow: "hidden";
|
||||
position: "absolute";
|
||||
width: string;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* True when the honeypot was filled → treat the submission as spam and drop it
|
||||
* (silently return success so the bot gets no signal). Call it FIRST in your
|
||||
* server action, before submitForm:
|
||||
*
|
||||
* if (isHoneypotTripped(values)) return { success: true } // pretend-accept
|
||||
* // strip it so submitForm doesn't see an unknown field:
|
||||
* const { [HONEYPOT_FIELD]: _hp, ...clean } = values
|
||||
* return submitForm({ ...clean })
|
||||
*/
|
||||
export declare function isHoneypotTripped(values: Record<string, unknown>, name?: string): boolean;
|
||||
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* A honeypot: a hidden field real users never see or fill, but naive bots do.
|
||||
* A cheap, zero-friction second layer alongside Turnstile — no network call, no
|
||||
* user interaction. Pure functions, usable on client (render the input) and
|
||||
* server (check it in the action).
|
||||
*/ /**
|
||||
* Default field name. Looks like a real field a bot would want to fill, but is
|
||||
* not one your form uses. Override per project if you like — just keep the
|
||||
* client and server in sync.
|
||||
*/ export const HONEYPOT_FIELD = 'company_url';
|
||||
/**
|
||||
* Props for the hidden input. Hidden from sight AND from assistive tech and tab
|
||||
* order, so no real user (sighted, screen-reader, or keyboard) ever fills it —
|
||||
* only a bot auto-filling every field.
|
||||
*
|
||||
* <input {...honeypotInputProps()} />
|
||||
* // or with your own name:
|
||||
* <input {...honeypotInputProps('website_2')} />
|
||||
*/ export function honeypotInputProps(name = HONEYPOT_FIELD) {
|
||||
return {
|
||||
name,
|
||||
type: 'text',
|
||||
'aria-hidden': true,
|
||||
autoComplete: 'off',
|
||||
tabIndex: -1,
|
||||
// Off-screen rather than display:none — some bots skip display:none fields.
|
||||
style: {
|
||||
height: '1px',
|
||||
left: '-9999px',
|
||||
overflow: 'hidden',
|
||||
position: 'absolute',
|
||||
width: '1px'
|
||||
}
|
||||
};
|
||||
}
|
||||
/**
|
||||
* True when the honeypot was filled → treat the submission as spam and drop it
|
||||
* (silently return success so the bot gets no signal). Call it FIRST in your
|
||||
* server action, before submitForm:
|
||||
*
|
||||
* if (isHoneypotTripped(values)) return { success: true } // pretend-accept
|
||||
* // strip it so submitForm doesn't see an unknown field:
|
||||
* const { [HONEYPOT_FIELD]: _hp, ...clean } = values
|
||||
* return submitForm({ ...clean })
|
||||
*/ export function isHoneypotTripped(values, name = HONEYPOT_FIELD) {
|
||||
const v = values[name];
|
||||
return typeof v === 'string' ? v.trim().length > 0 : v != null;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=honeypot.js.map
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/forms/honeypot.ts"],"sourcesContent":["/**\n * A honeypot: a hidden field real users never see or fill, but naive bots do.\n * A cheap, zero-friction second layer alongside Turnstile — no network call, no\n * user interaction. Pure functions, usable on client (render the input) and\n * server (check it in the action).\n */\n\n/**\n * Default field name. Looks like a real field a bot would want to fill, but is\n * not one your form uses. Override per project if you like — just keep the\n * client and server in sync.\n */\nexport const HONEYPOT_FIELD = 'company_url'\n\n/**\n * Props for the hidden input. Hidden from sight AND from assistive tech and tab\n * order, so no real user (sighted, screen-reader, or keyboard) ever fills it —\n * only a bot auto-filling every field.\n *\n * <input {...honeypotInputProps()} />\n * // or with your own name:\n * <input {...honeypotInputProps('website_2')} />\n */\nexport function honeypotInputProps(name: string = HONEYPOT_FIELD) {\n return {\n name,\n type: 'text' as const,\n 'aria-hidden': true,\n autoComplete: 'off' as const,\n tabIndex: -1,\n // Off-screen rather than display:none — some bots skip display:none fields.\n style: {\n height: '1px',\n left: '-9999px',\n overflow: 'hidden' as const,\n position: 'absolute' as const,\n width: '1px',\n },\n }\n}\n\n/**\n * True when the honeypot was filled → treat the submission as spam and drop it\n * (silently return success so the bot gets no signal). Call it FIRST in your\n * server action, before submitForm:\n *\n * if (isHoneypotTripped(values)) return { success: true } // pretend-accept\n * // strip it so submitForm doesn't see an unknown field:\n * const { [HONEYPOT_FIELD]: _hp, ...clean } = values\n * return submitForm({ ...clean })\n */\nexport function isHoneypotTripped(\n values: Record<string, unknown>,\n name: string = HONEYPOT_FIELD,\n): boolean {\n const v = values[name]\n return typeof v === 'string' ? v.trim().length > 0 : v != null\n}\n"],"names":["HONEYPOT_FIELD","honeypotInputProps","name","type","autoComplete","tabIndex","style","height","left","overflow","position","width","isHoneypotTripped","values","v","trim","length"],"mappings":"AAAA;;;;;CAKC,GAED;;;;CAIC,GACD,OAAO,MAAMA,iBAAiB,cAAa;AAE3C;;;;;;;;CAQC,GACD,OAAO,SAASC,mBAAmBC,OAAeF,cAAc;IAC9D,OAAO;QACLE;QACAC,MAAM;QACN,eAAe;QACfC,cAAc;QACdC,UAAU,CAAC;QACX,4EAA4E;QAC5EC,OAAO;YACLC,QAAQ;YACRC,MAAM;YACNC,UAAU;YACVC,UAAU;YACVC,OAAO;QACT;IACF;AACF;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,kBACdC,MAA+B,EAC/BX,OAAeF,cAAc;IAE7B,MAAMc,IAAID,MAAM,CAACX,KAAK;IACtB,OAAO,OAAOY,MAAM,WAAWA,EAAEC,IAAI,GAAGC,MAAM,GAAG,IAAIF,KAAK;AAC5D"}
|
||||
Vendored
+4
@@ -1,4 +1,8 @@
|
||||
export { formAnalyticsOnSuccess } from './formAnalytics.js';
|
||||
export type { FormAnalyticsConfig } from './formAnalytics.js';
|
||||
export { buildFormAnalyticsFields } from './formAnalyticsFields.js';
|
||||
export { buildFormsPlugin } from './formsPluginConfig.js';
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js';
|
||||
export { checkRateLimit } from './rateLimit.js';
|
||||
export type { RateLimitArgs } from './rateLimit.js';
|
||||
export { submitForm } from './submitForm.js';
|
||||
|
||||
Vendored
+5
@@ -1,6 +1,11 @@
|
||||
export { formAnalyticsOnSuccess } from './formAnalytics.js';
|
||||
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
|
||||
export { buildFormAnalyticsFields } from './formAnalyticsFields.js';
|
||||
// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only
|
||||
// (Turnstile secret) — never import it from a client component.
|
||||
export { buildFormsPlugin } from './formsPluginConfig.js';
|
||||
// Honeypot anti-spam (pure — client renders the input, server checks it).
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js';
|
||||
export { checkRateLimit } from './rateLimit.js';
|
||||
export { submitForm } from './submitForm.js';
|
||||
export { useContactForm } from './useContactForm.js';
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\n// Generic form engine (any field set) + the standard contact-form preset.\nexport { useForm } from './useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './useForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n// Composable validation rules (pure — safe on server or client).\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './validators.js'\nexport type { Rule } from './validators.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","useContactForm","useForm","validateSubmission","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,0EAA0E;AAC1E,SAASC,OAAO,QAAQ,eAAc;AAEtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,iEAAiE;AACjE,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,kBAAiB"}
|
||||
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["export { formAnalyticsOnSuccess } from './formAnalytics.js'\nexport type { FormAnalyticsConfig } from './formAnalytics.js'\n// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).\nexport { buildFormAnalyticsFields } from './formAnalyticsFields.js'\n// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\n// Honeypot anti-spam (pure — client renders the input, server checks it).\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './honeypot.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\n// Generic form engine (any field set) + the standard contact-form preset.\nexport { useForm } from './useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './useForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n// Composable validation rules (pure — safe on server or client).\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './validators.js'\nexport type { Rule } from './validators.js'\n"],"names":["formAnalyticsOnSuccess","buildFormAnalyticsFields","buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","checkRateLimit","submitForm","useContactForm","useForm","validateSubmission","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required"],"mappings":"AAAA,SAASA,sBAAsB,QAAQ,qBAAoB;AAE3D,kFAAkF;AAClF,SAASC,wBAAwB,QAAQ,2BAA0B;AACnE,6EAA6E;AAC7E,gEAAgE;AAChE,SAASC,gBAAgB,QAAQ,yBAAwB;AACzD,0EAA0E;AAC1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,gBAAe;AACrF,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,0EAA0E;AAC1E,SAASC,OAAO,QAAQ,eAAc;AAEtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,iEAAiE;AACjE,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,kBAAiB"}
|
||||
+17
-9
@@ -22,6 +22,14 @@ type UseContactFormOptions = {
|
||||
messages?: Partial<Record<keyof ContactFormValues, string>>;
|
||||
/** Minimum message length. Default 10. */
|
||||
minMessageLength?: number;
|
||||
/**
|
||||
* Called once after a successful submit — e.g. to fire a GTM `form_submit`
|
||||
* event: `onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic })`.
|
||||
*/
|
||||
onSuccess?: (result: {
|
||||
message?: string;
|
||||
success: boolean;
|
||||
}, values: ContactFormValues) => void;
|
||||
/** Whether consent is required (project passes true when consentText shown). */
|
||||
requireConsent?: boolean;
|
||||
/** Whether a topic must be chosen (project passes this when topics exist). */
|
||||
@@ -42,19 +50,19 @@ type UseContactFormOptions = {
|
||||
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
|
||||
*/
|
||||
export declare function useContactForm(options: UseContactFormOptions): {
|
||||
values: ContactFormValues;
|
||||
errors: Partial<Record<keyof ContactFormValues, string>>;
|
||||
isSubmitting: boolean;
|
||||
isSuccess: boolean;
|
||||
errorMessage: string | null;
|
||||
turnstileToken: string | null;
|
||||
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
|
||||
setValues: import("react").Dispatch<import("react").SetStateAction<ContactFormValues>>;
|
||||
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof ContactFormValues, string>>>>;
|
||||
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
||||
errors: Partial<Record<keyof ContactFormValues, string>>;
|
||||
handleSubmit: (e?: {
|
||||
preventDefault?: (() => void) | undefined;
|
||||
} | undefined) => Promise<void>;
|
||||
isSubmitting: boolean;
|
||||
isSuccess: boolean;
|
||||
reset: () => void;
|
||||
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof ContactFormValues, string>>>>;
|
||||
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
|
||||
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
||||
setValues: import("react").Dispatch<import("react").SetStateAction<ContactFormValues>>;
|
||||
turnstileToken: string | null;
|
||||
values: ContactFormValues;
|
||||
};
|
||||
export {};
|
||||
|
||||
Vendored
+2
-1
@@ -13,7 +13,7 @@ import { buildValidator, checked, email, minLength, required } from './validator
|
||||
*
|
||||
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
|
||||
*/ export function useContactForm(options) {
|
||||
const { errorFallback, initialTopic = '', messages, minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
|
||||
const { errorFallback, initialTopic = '', messages, minMessageLength = 10, onSuccess, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
|
||||
const validate = useMemo(()=>buildValidator({
|
||||
name: [
|
||||
required(messages?.name)
|
||||
@@ -52,6 +52,7 @@ import { buildValidator, checked, email, minLength, required } from './validator
|
||||
phone: '',
|
||||
topic: initialTopic
|
||||
},
|
||||
onSuccess,
|
||||
requireTurnstile,
|
||||
submitAction,
|
||||
validate
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/forms/useContactForm.ts"],"sourcesContent":["'use client'\n\nimport { useMemo } from 'react'\n\nimport { type FormSubmitAction, useForm } from './useForm.js'\nimport { buildValidator, checked, email, minLength, required } from './validators.js'\n\n/**\n * Field values of the STANDARD contact form. This is a preset shape — projects\n * that need a different field set (or dynamic builder fields) should use\n * `useForm` directly instead, where the shape is fully open.\n */\nexport type ContactFormValues = {\n consent: boolean\n email: string\n message: string\n name: string\n phone: string\n topic: string\n}\n\nexport type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>\nexport type SubmitAction = FormSubmitAction<ContactFormValues>\n\ntype UseContactFormOptions = {\n /** Generic error message shown when the action fails/throws. */\n errorFallback?: string\n initialTopic?: string\n /** Override the per-field error message (shown via `errors.<field>`). */\n messages?: Partial<Record<keyof ContactFormValues, string>>\n /** Minimum message length. Default 10. */\n minMessageLength?: number\n /** Whether consent is required (project passes true when consentText shown). */\n requireConsent?: boolean\n /** Whether a topic must be chosen (project passes this when topics exist). */\n requireTopic?: boolean\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n submitAction: SubmitAction\n}\n\n/**\n * Zero-config preset over `useForm` for the everyday contact form: standard\n * fields (name/email/phone/topic/message/consent) and standard rules, wired\n * for you. Markup and styling stay 100% in the project — this only removes the\n * duplicated logic.\n *\n * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),\n * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })\n *\n * Need custom or dynamic fields? Drop the preset and call `useForm` + validators.\n */\nexport function useContactForm(options: UseContactFormOptions) {\n const {\n errorFallback,\n initialTopic = '',\n messages,\n minMessageLength = 10,\n requireConsent = false,\n requireTopic = false,\n requireTurnstile = false,\n submitAction,\n } = options\n\n const validate = useMemo(\n () =>\n buildValidator<ContactFormValues>({\n name: [required(messages?.name)],\n email: [required(messages?.email), email(messages?.email)],\n ...(requireTopic ? { topic: [required(messages?.topic)] } : {}),\n message: [required(messages?.message), minLength(minMessageLength, messages?.message)],\n ...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),\n }),\n [requireTopic, requireConsent, minMessageLength, messages],\n )\n\n return useForm<ContactFormValues>({\n errorFallback,\n initialValues: {\n name: '',\n consent: false,\n email: '',\n message: '',\n phone: '',\n topic: initialTopic,\n },\n requireTurnstile,\n submitAction,\n validate,\n })\n}\n"],"names":["useMemo","useForm","buildValidator","checked","email","minLength","required","useContactForm","options","errorFallback","initialTopic","messages","minMessageLength","requireConsent","requireTopic","requireTurnstile","submitAction","validate","name","topic","message","consent","initialValues","phone"],"mappings":"AAAA;AAEA,SAASA,OAAO,QAAQ,QAAO;AAE/B,SAAgCC,OAAO,QAAQ,eAAc;AAC7D,SAASC,cAAc,EAAEC,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,kBAAiB;AAoCrF;;;;;;;;;;CAUC,GACD,OAAO,SAASC,eAAeC,OAA8B;IAC3D,MAAM,EACJC,aAAa,EACbC,eAAe,EAAE,EACjBC,QAAQ,EACRC,mBAAmB,EAAE,EACrBC,iBAAiB,KAAK,EACtBC,eAAe,KAAK,EACpBC,mBAAmB,KAAK,EACxBC,YAAY,EACb,GAAGR;IAEJ,MAAMS,WAAWjB,QACf,IACEE,eAAkC;YAChCgB,MAAM;gBAACZ,SAASK,UAAUO;aAAM;YAChCd,OAAO;gBAACE,SAASK,UAAUP;gBAAQA,MAAMO,UAAUP;aAAO;YAC1D,GAAIU,eAAe;gBAAEK,OAAO;oBAACb,SAASK,UAAUQ;iBAAO;YAAC,IAAI,CAAC,CAAC;YAC9DC,SAAS;gBAACd,SAASK,UAAUS;gBAAUf,UAAUO,kBAAkBD,UAAUS;aAAS;YACtF,GAAIP,iBAAiB;gBAAEQ,SAAS;oBAAClB,QAAQQ,UAAUU;iBAAS;YAAC,IAAI,CAAC,CAAC;QACrE,IACF;QAACP;QAAcD;QAAgBD;QAAkBD;KAAS;IAG5D,OAAOV,QAA2B;QAChCQ;QACAa,eAAe;YACbJ,MAAM;YACNG,SAAS;YACTjB,OAAO;YACPgB,SAAS;YACTG,OAAO;YACPJ,OAAOT;QACT;QACAK;QACAC;QACAC;IACF;AACF"}
|
||||
{"version":3,"sources":["../../../src/modules/forms/useContactForm.ts"],"sourcesContent":["'use client'\n\nimport { useMemo } from 'react'\n\nimport { type FormSubmitAction, useForm } from './useForm.js'\nimport { buildValidator, checked, email, minLength, required } from './validators.js'\n\n/**\n * Field values of the STANDARD contact form. This is a preset shape — projects\n * that need a different field set (or dynamic builder fields) should use\n * `useForm` directly instead, where the shape is fully open.\n */\nexport type ContactFormValues = {\n consent: boolean\n email: string\n message: string\n name: string\n phone: string\n topic: string\n}\n\nexport type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>\nexport type SubmitAction = FormSubmitAction<ContactFormValues>\n\ntype UseContactFormOptions = {\n /** Generic error message shown when the action fails/throws. */\n errorFallback?: string\n initialTopic?: string\n /** Override the per-field error message (shown via `errors.<field>`). */\n messages?: Partial<Record<keyof ContactFormValues, string>>\n /** Minimum message length. Default 10. */\n minMessageLength?: number\n /**\n * Called once after a successful submit — e.g. to fire a GTM `form_submit`\n * event: `onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic })`.\n */\n onSuccess?: (result: { message?: string; success: boolean }, values: ContactFormValues) => void\n /** Whether consent is required (project passes true when consentText shown). */\n requireConsent?: boolean\n /** Whether a topic must be chosen (project passes this when topics exist). */\n requireTopic?: boolean\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n submitAction: SubmitAction\n}\n\n/**\n * Zero-config preset over `useForm` for the everyday contact form: standard\n * fields (name/email/phone/topic/message/consent) and standard rules, wired\n * for you. Markup and styling stay 100% in the project — this only removes the\n * duplicated logic.\n *\n * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),\n * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })\n *\n * Need custom or dynamic fields? Drop the preset and call `useForm` + validators.\n */\nexport function useContactForm(options: UseContactFormOptions) {\n const {\n errorFallback,\n initialTopic = '',\n messages,\n minMessageLength = 10,\n onSuccess,\n requireConsent = false,\n requireTopic = false,\n requireTurnstile = false,\n submitAction,\n } = options\n\n const validate = useMemo(\n () =>\n buildValidator<ContactFormValues>({\n name: [required(messages?.name)],\n email: [required(messages?.email), email(messages?.email)],\n ...(requireTopic ? { topic: [required(messages?.topic)] } : {}),\n message: [required(messages?.message), minLength(minMessageLength, messages?.message)],\n ...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),\n }),\n [requireTopic, requireConsent, minMessageLength, messages],\n )\n\n return useForm<ContactFormValues>({\n errorFallback,\n initialValues: {\n name: '',\n consent: false,\n email: '',\n message: '',\n phone: '',\n topic: initialTopic,\n },\n onSuccess,\n requireTurnstile,\n submitAction,\n validate,\n })\n}\n"],"names":["useMemo","useForm","buildValidator","checked","email","minLength","required","useContactForm","options","errorFallback","initialTopic","messages","minMessageLength","onSuccess","requireConsent","requireTopic","requireTurnstile","submitAction","validate","name","topic","message","consent","initialValues","phone"],"mappings":"AAAA;AAEA,SAASA,OAAO,QAAQ,QAAO;AAE/B,SAAgCC,OAAO,QAAQ,eAAc;AAC7D,SAASC,cAAc,EAAEC,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,kBAAiB;AAyCrF;;;;;;;;;;CAUC,GACD,OAAO,SAASC,eAAeC,OAA8B;IAC3D,MAAM,EACJC,aAAa,EACbC,eAAe,EAAE,EACjBC,QAAQ,EACRC,mBAAmB,EAAE,EACrBC,SAAS,EACTC,iBAAiB,KAAK,EACtBC,eAAe,KAAK,EACpBC,mBAAmB,KAAK,EACxBC,YAAY,EACb,GAAGT;IAEJ,MAAMU,WAAWlB,QACf,IACEE,eAAkC;YAChCiB,MAAM;gBAACb,SAASK,UAAUQ;aAAM;YAChCf,OAAO;gBAACE,SAASK,UAAUP;gBAAQA,MAAMO,UAAUP;aAAO;YAC1D,GAAIW,eAAe;gBAAEK,OAAO;oBAACd,SAASK,UAAUS;iBAAO;YAAC,IAAI,CAAC,CAAC;YAC9DC,SAAS;gBAACf,SAASK,UAAUU;gBAAUhB,UAAUO,kBAAkBD,UAAUU;aAAS;YACtF,GAAIP,iBAAiB;gBAAEQ,SAAS;oBAACnB,QAAQQ,UAAUW;iBAAS;YAAC,IAAI,CAAC,CAAC;QACrE,IACF;QAACP;QAAcD;QAAgBF;QAAkBD;KAAS;IAG5D,OAAOV,QAA2B;QAChCQ;QACAc,eAAe;YACbJ,MAAM;YACNG,SAAS;YACTlB,OAAO;YACPiB,SAAS;YACTG,OAAO;YACPJ,OAAOV;QACT;QACAG;QACAG;QACAC;QACAC;IACF;AACF"}
|
||||
Vendored
+30
-16
@@ -11,23 +11,37 @@ export type FormErrors<T> = Partial<Record<keyof T, string>>;
|
||||
* plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.
|
||||
*/
|
||||
export type FormSubmitAction<T> = (values: T, turnstileToken?: string) => Promise<{
|
||||
success: boolean;
|
||||
message?: string;
|
||||
success: boolean;
|
||||
}>;
|
||||
/** Turns the current values into an error map. Empty map = valid. */
|
||||
export type Validator<T> = (values: T) => FormErrors<T>;
|
||||
type UseFormOptions<T extends Record<string, unknown>> = {
|
||||
/** Clear a field's error as soon as the user edits it. Default true. */
|
||||
clearErrorOnChange?: boolean;
|
||||
/** Generic error message shown when the action fails/throws with no message. */
|
||||
errorFallback?: string;
|
||||
/** Defines the field set AND the reset state. Any shape you like. */
|
||||
initialValues: T;
|
||||
/**
|
||||
* Called once after a SUCCESSFUL submit, with the submitted values and the
|
||||
* action's result. The place to fire analytics — e.g. a GTM `form_submit`
|
||||
* event so a Meta Pixel / GA "Lead" tag can trigger:
|
||||
*
|
||||
* onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' })
|
||||
*
|
||||
* Runs client-side after the server action resolves; errors thrown here are
|
||||
* swallowed so a broken analytics call can't blank out a successful submit.
|
||||
*/
|
||||
onSuccess?: (result: {
|
||||
message?: string;
|
||||
success: boolean;
|
||||
}, values: T) => void;
|
||||
/** Require a Turnstile token before submit (when the widget is shown). */
|
||||
requireTurnstile?: boolean;
|
||||
submitAction: FormSubmitAction<T>;
|
||||
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
|
||||
validate?: Validator<T>;
|
||||
/** Require a Turnstile token before submit (when the widget is shown). */
|
||||
requireTurnstile?: boolean;
|
||||
/** Generic error message shown when the action fails/throws with no message. */
|
||||
errorFallback?: string;
|
||||
/** Clear a field's error as soon as the user edits it. Default true. */
|
||||
clearErrorOnChange?: boolean;
|
||||
};
|
||||
/**
|
||||
* Fully generic form engine: state, validation, Turnstile token, submit,
|
||||
@@ -52,19 +66,19 @@ type UseFormOptions<T extends Record<string, unknown>> = {
|
||||
* <form onSubmit={f.handleSubmit}>…</form>
|
||||
*/
|
||||
export declare function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>): {
|
||||
values: T;
|
||||
errors: Partial<Record<keyof T, string>>;
|
||||
isSubmitting: boolean;
|
||||
isSuccess: boolean;
|
||||
errorMessage: string | null;
|
||||
turnstileToken: string | null;
|
||||
setField: <K extends keyof T>(key: K, value: T[K]) => void;
|
||||
setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
|
||||
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof T, string>>>>;
|
||||
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
||||
errors: Partial<Record<keyof T, string>>;
|
||||
handleSubmit: (e?: {
|
||||
preventDefault?: () => void;
|
||||
}) => Promise<void>;
|
||||
isSubmitting: boolean;
|
||||
isSuccess: boolean;
|
||||
reset: () => void;
|
||||
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof T, string>>>>;
|
||||
setField: <K extends keyof T>(key: K, value: T[K]) => void;
|
||||
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
||||
setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
|
||||
turnstileToken: string | null;
|
||||
values: T;
|
||||
};
|
||||
export {};
|
||||
|
||||
Vendored
+22
-11
@@ -1,5 +1,5 @@
|
||||
'use client';
|
||||
import { useState, useCallback, useRef, useMemo } from 'react';
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
/**
|
||||
* Fully generic form engine: state, validation, Turnstile token, submit,
|
||||
* success/error — WITHOUT any markup. The project owns 100% of the look AND
|
||||
@@ -22,7 +22,7 @@ import { useState, useCallback, useRef, useMemo } from 'react';
|
||||
* className={f.errors.email ? 'border-red-500' : '…'} />
|
||||
* <form onSubmit={f.handleSubmit}>…</form>
|
||||
*/ export function useForm(options) {
|
||||
const { initialValues, submitAction, validate, requireTurnstile = false, errorFallback = 'Something went wrong. Please try again.', clearErrorOnChange = true } = options;
|
||||
const { clearErrorOnChange = true, errorFallback = 'Something went wrong. Please try again.', initialValues, requireTurnstile = false, submitAction, validate } = options;
|
||||
// Freeze the initial snapshot so `reset` is stable even though callers pass a
|
||||
// fresh object literal every render.
|
||||
const initialRef = useRef(initialValues);
|
||||
@@ -39,7 +39,9 @@ import { useState, useCallback, useRef, useMemo } from 'react';
|
||||
}));
|
||||
if (clearErrorOnChange) {
|
||||
setErrors((prev)=>{
|
||||
if (!prev[key]) return prev;
|
||||
if (!prev[key]) {
|
||||
return prev;
|
||||
}
|
||||
const next = {
|
||||
...prev
|
||||
};
|
||||
@@ -56,12 +58,16 @@ import { useState, useCallback, useRef, useMemo } from 'react';
|
||||
valuesRef.current = values;
|
||||
const validateRef = useRef(validate);
|
||||
validateRef.current = validate;
|
||||
const onSuccessRef = useRef(options.onSuccess);
|
||||
onSuccessRef.current = options.onSuccess;
|
||||
const handleSubmit = useCallback(async (e)=>{
|
||||
e?.preventDefault?.();
|
||||
setErrorMessage(null);
|
||||
const errs = validateRef.current ? validateRef.current(valuesRef.current) : {};
|
||||
setErrors(errs);
|
||||
if (Object.keys(errs).length > 0) return;
|
||||
if (Object.keys(errs).length > 0) {
|
||||
return;
|
||||
}
|
||||
if (requireTurnstile && !turnstileToken) {
|
||||
setErrorMessage(errorFallback);
|
||||
return;
|
||||
@@ -72,6 +78,11 @@ import { useState, useCallback, useRef, useMemo } from 'react';
|
||||
if (result.success) {
|
||||
setIsSuccess(true);
|
||||
setTurnstileToken(null);
|
||||
// Fire analytics (e.g. GTM form_submit) — never let it break the submit.
|
||||
try {
|
||||
onSuccessRef.current?.(result, valuesRef.current);
|
||||
} catch {
|
||||
/* analytics must not affect the form outcome */ }
|
||||
} else {
|
||||
setErrorMessage(result.message || errorFallback);
|
||||
}
|
||||
@@ -94,18 +105,18 @@ import { useState, useCallback, useRef, useMemo } from 'react';
|
||||
setTurnstileToken(null);
|
||||
}, []);
|
||||
return useMemo(()=>({
|
||||
values,
|
||||
errorMessage,
|
||||
errors,
|
||||
handleSubmit,
|
||||
isSubmitting,
|
||||
isSuccess,
|
||||
errorMessage,
|
||||
turnstileToken,
|
||||
setField,
|
||||
setValues,
|
||||
reset,
|
||||
setErrors,
|
||||
setField,
|
||||
setTurnstileToken,
|
||||
handleSubmit,
|
||||
reset
|
||||
setValues,
|
||||
turnstileToken,
|
||||
values
|
||||
}), [
|
||||
values,
|
||||
errors,
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -62,6 +62,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;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user