Compare commits

...
120 Commits
Author SHA1 Message Date
radoslaw.smolinski e6eada5d39 1.6.6 2026-10-10 00:17:23 +02:00
radoslaw.smolinski 1b52060dce Added healhtRoute, honeypot, ConsentScript, asserEnv 2026-10-10 00:17:13 +02:00
radoslaw.smolinski 52977e67fc 1.6.5 2026-10-09 20:18:24 +02:00
radoslaw.smolinski b25f221a50 Added support for crossLocaleFieldSync 2026-10-09 20:18:16 +02:00
radoslaw.smolinski f9d3d9ae97 1.6.4 2026-10-09 19:10:25 +02:00
radoslaw.smolinski 962b9cb640 Fixed buildManifest.ts 2026-10-09 19:10:20 +02:00
radoslaw.smolinski 9b9bbc1a9f 1.6.3 2026-10-09 18:23:18 +02:00
radoslaw.smolinski abf2e7d40f Added form validators 2026-10-09 18:23:08 +02:00
radoslaw.smolinski d500d9412f 1.6.2 2026-10-09 18:00:32 +02:00
radoslaw.smolinski d034ddf990 Security patch for contact 2026-10-09 18:00:24 +02:00
radoslaw.smolinski 2dfacb0414 1.6.1 2026-10-09 17:25:28 +02:00
radoslaw.smolinski eb6efa26f6 Added JsonLdGraph.tsx 2026-10-09 17:25:22 +02:00
radoslaw.smolinski f5a4ceb5bf 1.6.0 2026-10-09 17:02:07 +02:00
radoslaw.smolinski d041fd4bc6 Added languageswitcher, alternatelinkscontext components support 2026-10-09 17:01:52 +02:00
radoslaw.smolinski e232e6d2a5 1.5.7 2026-10-09 16:44:39 +02:00
radoslaw.smolinski c738435fe0 Added richtext support, and helpers for proxy, llms route 2026-10-09 16:44:28 +02:00
radoslaw.smolinski cca2b20c3d 1.5.6 2026-09-28 19:44:34 +02:00
radoslaw.smolinski 105c454d73 Added OG support 2026-09-28 19:44:28 +02:00
radoslaw.smolinski cf6feefebc 1.5.5 2026-09-28 16:47:11 +02:00
radoslaw.smolinski 1857c8f771 Sitemap language normalize trough all websites 2026-09-28 16:47:06 +02:00
radoslaw.smolinski 542ad4ab9c 1.5.4 2026-09-28 16:35:00 +02:00
radoslaw.smolinski 9bf8599116 Fix for plugin.ts 2026-09-28 16:34:54 +02:00
radoslaw.smolinski 170c9a53f1 1.5.3 2026-09-28 16:25:36 +02:00
radoslaw.smolinski e0d5095099 Fix for sitemap.css n2 2026-09-28 16:22:49 +02:00
radoslaw.smolinski 08a8a10478 1.5.2 2026-09-28 16:13:46 +02:00
radoslaw.smolinski 7bbaf14d14 Fixed sitemap.css 2026-09-28 16:13:33 +02:00
radoslaw.smolinski b7d0b01122 1.5.1 2026-09-28 16:01:09 +02:00
radoslaw.smolinski 4627266577 2FA Fix 2026-09-28 16:01:03 +02:00
radoslaw.smolinski 471ec4b12a 1.5.0 2026-09-28 15:49:57 +02:00
radoslaw.smolinski 060a61fd41 Added secuirty 2FA for users 2026-09-28 15:49:36 +02:00
radoslaw.smolinski 7cef95225a 1.4.4 2026-09-28 14:57:54 +02:00
radoslaw.smolinski 0ae62226bc Path fix for sitemap css asset 2026-09-28 14:57:49 +02:00
radoslaw.smolinski 610ab6fdf5 1.4.3 2026-09-28 14:54:30 +02:00
radoslaw.smolinski 81275c0395 Added css asset for sitemap 2026-09-28 14:54:21 +02:00
radoslaw.smolinski 4a46651839 1.4.2 2026-09-28 14:47:19 +02:00
radoslaw.smolinski e7f06548fb Added styling for sitemap generator 2026-09-28 14:47:13 +02:00
radoslaw.smolinski e2a703fc72 1.4.1 2026-09-28 14:29:50 +02:00
radoslaw.smolinski de75d8374d Rebuilded sitemap generator 2026-09-28 14:29:42 +02:00
radoslaw.smolinski b807fbe69a 1.4.0 2026-09-26 22:30:13 +02:00
radoslaw.smolinski 827cd9bcbc Added accessibility support 2026-09-26 22:29:53 +02:00
radoslaw.smolinski fa2b607979 1.3.2 2026-09-26 20:07:35 +02:00
radoslaw.smolinski 4fe690e1e2 Added i18n exports 2026-09-26 20:07:29 +02:00
radoslaw.smolinski 3553daa086 1.3.1 2026-09-26 16:20:40 +02:00
radoslaw.smolinski a4c5bcfbdf Fix buildLlmsTxt.ts 2026-09-26 16:20:31 +02:00
radoslaw.smolinski 026c2696b6 1.3.0 2026-09-25 12:50:35 +02:00
radoslaw.smolinski 6cb4168f44 Turnstile improvement 2026-09-25 12:50:15 +02:00
radoslaw.smolinski b82ef82f50 Added protecting hooks 2026-09-25 12:42:38 +02:00
radoslaw.smolinski 9a18434f4a 1.2.13 2026-09-19 22:32:36 +02:00
radoslaw.smolinski f126eacf8c Fixed builCsp.ts 2026-09-19 22:32:29 +02:00
radoslaw.smolinski 848b12ce5d 1.2.12 2026-09-19 22:24:42 +02:00
radoslaw.smolinski 3d350bd9e5 Added styled Xml 2026-09-19 22:24:36 +02:00
radoslaw.smolinski e03dd8c5a6 1.2.11 2026-09-19 22:08:02 +02:00
radoslaw.smolinski 9101a5b48e Added security scripts support 2026-09-19 22:07:57 +02:00
radoslaw.smolinski 1186f4f620 1.2.10 2026-09-15 22:16:04 +02:00
radoslaw.smolinski 988fcaf855 fix createContentHelpers.ts 2026-09-15 22:16:01 +02:00
radoslaw.smolinski b27031f7c4 1.2.9 2026-09-15 21:55:51 +02:00
radoslaw.smolinski 7ee60e7313 SEO: multilingual homepage (homeSlug per locale in path/sitemap), Article + llms.txt generators, siteDescription fallback, composeTitle dedup 2026-09-15 21:55:48 +02:00
radoslaw.smolinski 671090b1b1 1.2.8 2026-09-15 21:16:59 +02:00
radoslaw.smolinski 0f03bb7446 SEO: multilingual homepage (homeSlug per locale in path/sitemap), Article + llms.txt generators, siteDescription fallback, composeTitle dedup 2026-09-15 21:16:53 +02:00
radoslaw.smolinski 55a1e5bf8f 1.2.7 2026-09-15 15:31:12 +02:00
radoslaw.smolinski 33ae035adc SEO: multilingual homepage (homeSlug per locale in path/sitemap), Article + llms.txt generators, siteDescription fallback, composeTitle dedup 2026-09-15 15:31:08 +02:00
radoslaw.smolinski 87d575f335 1.2.6 2026-09-09 22:21:09 +02:00
radoslaw.smolinski e4329f76b1 Fixed buildSitemapEntries.ts 2026-09-09 22:21:04 +02:00
radoslaw.smolinski fa4cf20022 1.2.5 2026-09-09 09:57:00 +02:00
radoslaw.smolinski 2ecfc2e12d Fixed support for multi-langual slugs 2026-09-09 09:56:47 +02:00
radoslaw.smolinski db2ac80a1e 1.2.4 2026-09-09 00:06:27 +02:00
radoslaw.smolinski 99490bfc4d Updated docs 2026-09-09 00:06:18 +02:00
radoslaw.smolinski fce17654f8 1.2.3 2026-09-08 18:13:16 +02:00
radoslaw.smolinski 419207ac12 Added support for single localization 2026-09-08 18:12:58 +02:00
radoslaw.smolinski e30ac71044 1.2.2 2026-09-08 14:25:26 +02:00
radoslaw.smolinski 781e348ded Page title generator on browser tab rebuilded. 2026-09-08 14:25:15 +02:00
radoslaw.smolinski e16a18e488 1.2.1 2026-09-08 13:14:15 +02:00
radoslaw.smolinski 7cd3cbaae5 1.2.0: local SEO structured data (LocalBusiness, Service, FAQPage), noindex per page, exclude 404 from sitemap, robots param docs 2026-09-08 13:14:05 +02:00
radoslaw.smolinski 60f07fddc9 1.2.0 2026-09-08 12:49:49 +02:00
radoslaw.smolinski 068415849f 1.2.0: local SEO structured data (LocalBusiness, Service, FAQPage), noindex per page 2026-09-08 12:49:49 +02:00
radoslaw.smolinski e39e2a361a 1.1.2 2026-08-28 15:51:02 +02:00
radoslaw.smolinski 9d3e749c38 1.1.1 2026-08-28 15:50:42 +02:00
radoslaw.smolinski b7c6cb4d81 1.1.0 2026-08-28 15:50:29 +02:00
radoslaw.smolinski c41b75e364 1.1.0: R2 storage, media preconnect/normalization, favicon + SEO structured data, x-default hreflang 2026-08-28 15:50:25 +02:00
radoslaw.smolinski 41630bb8c5 1.1.1 2026-08-28 00:09:20 +02:00
radoslaw.smolinski b9430e7ab6 SEO: favicon metadata, Organization JSON-LD, favicon validation; R2 media (preconnect, generateFileURL per-collection), filename normalization 2026-08-28 00:08:35 +02:00
radoslaw.smolinski f1f808d079 1.1.0 2026-08-27 20:21:01 +02:00
radoslaw.smolinski a8a632e1b0 R2 storage, media preconnect, filename normalization, graph email 2026-08-27 20:20:56 +02:00
radoslaw.smolinski a695ec7319 1.0.22 2026-08-27 18:57:18 +02:00
radoslaw.smolinski c6730335ef R2 storage (generateFileURL per-collection) + filename normalization 2026-08-27 18:57:14 +02:00
radoslaw.smolinski 247b849759 1.0.21 2026-08-27 15:41:48 +02:00
radoslaw.smolinski 0dee178ded R2 storage from env + filename normalization 2026-08-27 15:41:47 +02:00
radoslaw.smolinski 9359f26788 1.0.20 2026-08-27 12:45:47 +02:00
radoslaw.smolinski 5630765215 R2 storage from env + filename normalization 2026-08-27 12:45:47 +02:00
radoslaw.smolinski ed4a78b109 1.0.19 2026-08-27 12:31:09 +02:00
radoslaw.smolinski 9acb22e2f9 R2 storage from env + filename normalization 2026-08-27 12:31:09 +02:00
radoslaw.smolinski 6a8361d710 1.0.18 2026-08-26 13:53:44 +02:00
radoslaw.smolinski 502ffee31f i18n: NEXT_LOCALE cookie; graph: sender display name from panel 2026-08-26 13:53:41 +02:00
radoslaw.smolinski 5a322230ae 1.0.17 2026-08-24 19:06:11 +02:00
radoslaw.smolinski f919c288b2 i18n: rename locale cookie to NEXT_LOCALE (Next.js convention) 2026-08-24 19:06:06 +02:00
radoslaw.smolinski 21b948a4f8 1.0.16 2026-08-24 00:29:26 +02:00
radoslaw.smolinski d04271f942 ship docs/ in npm package for agent access 2026-08-24 00:29:25 +02:00
radoslaw.smolinski 4f08e9ea4d 1.0.15 2026-08-22 23:05:06 +02:00
radoslaw.smolinski 67347f1e34 graph: sender display name from panel 2026-08-22 23:05:05 +02:00
radoslaw.smolinski 75f2b6400d 1.0.14 2026-08-22 22:50:34 +02:00
radoslaw.smolinski 26aec1c5af graph: sender display name from panel (address stays sender, no Send-As) 2026-08-22 22:50:31 +02:00
radoslaw.smolinski 0fe7ca0575 1.0.13 2026-08-22 22:35:59 +02:00
radoslaw.smolinski d745a764fe 1.0.12 2026-08-22 22:35:33 +02:00
radoslaw.smolinski 6c273118a2 declare @payloadcms/ui, next, react-dom as peer deps 2026-08-22 22:35:29 +02:00
radoslaw.smolinski a010a7368a 1.0.11 2026-08-22 22:26:50 +02:00
radoslaw.smolinski 08bd00f01f graph: use replyTo instead of from to avoid ErrorSendAsDenied 2026-08-22 22:26:47 +02:00
radoslaw.smolinski cef7f46718 1.0.10 2026-08-22 17:55:47 +02:00
radoslaw.smolinski ac48f1e9d1 graph + mail dispatcher, test-email endpoint, notifications global 2026-08-22 17:55:43 +02:00
radoslaw.smolinski 3d8bc9019f 1.0.9 2026-08-21 19:24:08 +02:00
radoslaw.smolinski cd65c2799f 1.0.8 2026-08-21 19:23:21 +02:00
radoslaw.smolinski 282be290cd security headers, notifications, GDPR consent, masked fields, captcha fix, locale switching 2026-08-21 19:23:17 +02:00
radoslaw.smolinski 080f41c7d8 1.0.7 2026-08-21 19:12:22 +02:00
radoslaw.smolinski 37e417e057 1.0.6 2026-08-21 19:03:56 +02:00
radoslaw.smolinski 05b3dc8cb1 security headers, notifications, GDPR consent, masked fields 2026-08-21 19:03:14 +02:00
radoslaw.smolinski 81fa409513 1.0.5 2026-08-21 17:15:50 +02:00
radoslaw.smolinski 90068c7952 1.0.4 2026-08-21 17:15:42 +02:00
radoslaw.smolinski 2215766940 added validation for forms, sensitive text fields have been masked 2026-08-21 17:15:02 +02:00
radoslaw.smolinski 5aa66ff37a 1.0.3 2026-08-19 23:54:27 +02:00
radoslaw.smolinski eb043bba4a exempt captcha keys from unknown_fields validation 2026-08-19 23:54:09 +02:00
radoslaw.smolinski 68560534ac exempt captcha keys from unknown_fields validation 2026-08-19 23:53:51 +02:00
440 changed files with 16941 additions and 964 deletions
+256
View File
@@ -0,0 +1,256 @@
# 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** — `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy' } })` + `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`. Wymuszone dla WSZYSTKICH użytkowników (forceSetup), bez opcji wyłączenia per user. NIE ustawiaj `twoFactor: false` (chyba że klient wprost odmawia). Bez zależności = błąd buildu. 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` |
| 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.
+17 -1
View File
@@ -1,3 +1,7 @@
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
export { AccessibilityProvider, AccessibilityWidget, useAccessibility, } from '../modules/accessibility/client.js';
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
@@ -6,7 +10,19 @@ 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 { 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';
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 { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath, } from '../modules/i18n/index.js';
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js';
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks, } from '../modules/i18n/index.js';
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js';
export { Turnstile } from '../modules/turnstile/client.js';
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
export type { TurnstileProps } from '../modules/turnstile/client.js';
+13 -1
View File
@@ -1,4 +1,7 @@
'use client';
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
@@ -6,7 +9,16 @@ export { Analytics } from '../modules/analytics/client.js';
* 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 { 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';
// Pure i18n path helpers — no server/RSC deps, safe to import in client
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js';
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks } from '../modules/i18n/index.js';
export { Turnstile } from '../modules/turnstile/client.js';
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
//# sourceMappingURL=client.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\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'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","Turnstile"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,SAAS,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'\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'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.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","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,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"}
+1
View File
@@ -7,3 +7,4 @@
*/
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js';
export type { LocaleMiddlewareResult } from '../modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js';
+1
View File
@@ -5,5 +5,6 @@
* client project's middleware.ts. Kept as a thin re-export so the Next-facing
* surface is separate from the main package export.
*/ export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js';
//# sourceMappingURL=next-middleware.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/next-middleware.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/next/middleware\n *\n * Re-exports the locale middleware factory and default matcher for use in a\n * client project's middleware.ts. Kept as a thin re-export so the Next-facing\n * surface is separate from the main package export.\n */\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from '../modules/i18n/index.js'\n"],"names":["createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,sBAAsB,EAAEC,0BAA0B,QAAQ,2BAA0B"}
{"version":3,"sources":["../../src/exports/next-middleware.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/next/middleware\n *\n * Re-exports the locale middleware factory and default matcher for use in a\n * client project's middleware.ts. Kept as a thin re-export so the Next-facing\n * surface is separate from the main package export.\n */\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from '../modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from '../modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from '../modules/i18n/index.js'\n"],"names":["createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,sBAAsB,EAAEC,0BAA0B,QAAQ,2BAA0B;AAE7F,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,2BAA0B"}
+4
View File
@@ -7,3 +7,7 @@
*/
export { RenderBlocks } from '../modules/blocks/index.js';
export type { BlockComponentMap, BlockData, EnhanceProps, RenderBlocksProps, } from '../modules/blocks/index.js';
export { RenderRichText } from '../modules/richtext/index.js';
export type { RenderRichTextProps } from '../modules/richtext/index.js';
export { JsonLdGraph } from '../modules/seo/index.js';
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js';
+3
View File
@@ -5,5 +5,8 @@
* lives here rather than in the main package entry to keep React out of the
* server-config bundle.
*/ export { RenderBlocks } from '../modules/blocks/index.js';
export { RenderRichText } from '../modules/richtext/index.js';
export { JsonLdGraph } from '../modules/seo/index.js';
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js';
//# sourceMappingURL=rsc.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/rsc\n *\n * Server-component exports. RenderBlocks is a React Server Component, so it\n * lives here rather than in the main package entry to keep React out of the\n * server-config bundle.\n */\nexport { RenderBlocks } from '../modules/blocks/index.js'\nexport type {\n BlockComponentMap,\n BlockData,\n EnhanceProps,\n RenderBlocksProps,\n} from '../modules/blocks/index.js'\n"],"names":["RenderBlocks"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,YAAY,QAAQ,6BAA4B"}
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/rsc\n *\n * Server-component exports. RenderBlocks is a React Server Component, so it\n * lives here rather than in the main package entry to keep React out of the\n * server-config bundle.\n */\nexport { RenderBlocks } from '../modules/blocks/index.js'\nexport type {\n BlockComponentMap,\n BlockData,\n EnhanceProps,\n RenderBlocksProps,\n} from '../modules/blocks/index.js'\nexport { RenderRichText } from '../modules/richtext/index.js'\nexport type { RenderRichTextProps } from '../modules/richtext/index.js'\nexport { JsonLdGraph } from '../modules/seo/index.js'\nexport { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'\n"],"names":["RenderBlocks","RenderRichText","JsonLdGraph","MediaPreconnect"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,YAAY,QAAQ,6BAA4B;AAOzD,SAASC,cAAc,QAAQ,+BAA8B;AAE7D,SAASC,WAAW,QAAQ,0BAAyB;AACrD,SAASC,eAAe,QAAQ,wCAAuC"}
+13
View File
@@ -0,0 +1,13 @@
import type { Field } from 'payload';
/**
* Fields for the Notifications global — localized user-facing texts for action
* results (form submission outcomes, and future contexts). Every text is
* localized: true so each language has its own value. Empty fields fall back to
* built-in English defaults (see modules/notifications/defaults).
*
* Grouped per context. `form` holds the outcomes of submitForm; more groups
* (e.g. `newsletter`, `system`) can be added the same way without touching
* consumers — getNotificationTexts resolves whatever exists, falling back
* per field.
*/
export declare const notificationsFields: Field[];
+82
View File
@@ -0,0 +1,82 @@
/**
* Fields for the Notifications global — localized user-facing texts for action
* results (form submission outcomes, and future contexts). Every text is
* localized: true so each language has its own value. Empty fields fall back to
* built-in English defaults (see modules/notifications/defaults).
*
* Grouped per context. `form` holds the outcomes of submitForm; more groups
* (e.g. `newsletter`, `system`) can be added the same way without touching
* consumers — getNotificationTexts resolves whatever exists, falling back
* per field.
*/ export const notificationsFields = [
{
name: 'form',
type: 'group',
admin: {
description: 'Messages shown after a form is submitted. Leave a field empty to use the built-in default.'
},
fields: [
{
name: 'success',
type: 'text',
admin: {
placeholder: 'Thank you — your message has been sent.'
},
localized: true
},
{
name: 'error',
type: 'text',
admin: {
placeholder: 'Something went wrong. Please try again later.'
},
localized: true
},
{
name: 'rateLimited',
type: 'text',
admin: {
placeholder: 'Too many attempts. Please wait a moment and try again.'
},
localized: true
},
{
name: 'turnstile',
type: 'text',
admin: {
placeholder: 'Captcha verification failed. Please try again.'
},
localized: true
},
{
name: 'validation',
type: 'text',
admin: {
description: 'Shown on a validation error. Use {field} to insert the offending field name.',
placeholder: 'Please check the {field} field and try again.'
},
localized: true
},
{
name: 'consent',
type: 'text',
admin: {
description: 'Shown when the GDPR consent checkbox is left unchecked.',
placeholder: 'Please accept the privacy policy to continue.'
},
localized: true
},
{
name: 'notFound',
type: 'text',
admin: {
placeholder: 'This form is no longer available.'
},
localized: true
}
],
label: 'Form messages'
}
];
//# sourceMappingURL=fields.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/globals/Notifications/fields.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Fields for the Notifications global — localized user-facing texts for action\n * results (form submission outcomes, and future contexts). Every text is\n * localized: true so each language has its own value. Empty fields fall back to\n * built-in English defaults (see modules/notifications/defaults).\n *\n * Grouped per context. `form` holds the outcomes of submitForm; more groups\n * (e.g. `newsletter`, `system`) can be added the same way without touching\n * consumers — getNotificationTexts resolves whatever exists, falling back\n * per field.\n */\nexport const notificationsFields: Field[] = [\n {\n name: 'form',\n type: 'group',\n admin: {\n description:\n 'Messages shown after a form is submitted. Leave a field empty to use the built-in default.',\n },\n fields: [\n {\n name: 'success',\n type: 'text',\n admin: { placeholder: 'Thank you — your message has been sent.' },\n localized: true,\n },\n {\n name: 'error',\n type: 'text',\n admin: { placeholder: 'Something went wrong. Please try again later.' },\n localized: true,\n },\n {\n name: 'rateLimited',\n type: 'text',\n admin: { placeholder: 'Too many attempts. Please wait a moment and try again.' },\n localized: true,\n },\n {\n name: 'turnstile',\n type: 'text',\n admin: { placeholder: 'Captcha verification failed. Please try again.' },\n localized: true,\n },\n {\n name: 'validation',\n type: 'text',\n admin: {\n description:\n 'Shown on a validation error. Use {field} to insert the offending field name.',\n placeholder: 'Please check the {field} field and try again.',\n },\n localized: true,\n },\n {\n name: 'consent',\n type: 'text',\n admin: {\n description: 'Shown when the GDPR consent checkbox is left unchecked.',\n placeholder: 'Please accept the privacy policy to continue.',\n },\n localized: true,\n },\n {\n name: 'notFound',\n type: 'text',\n admin: { placeholder: 'This form is no longer available.' },\n localized: true,\n },\n ],\n label: 'Form messages',\n },\n]\n"],"names":["notificationsFields","name","type","admin","description","fields","placeholder","localized","label"],"mappings":"AAEA;;;;;;;;;;CAUC,GACD,OAAO,MAAMA,sBAA+B;IAC1C;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aACE;QACJ;QACAC,QAAQ;YACN;gBACEJ,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEG,aAAa;gBAA0C;gBAChEC,WAAW;YACb;YACA;gBACEN,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEG,aAAa;gBAAgD;gBACtEC,WAAW;YACb;YACA;gBACEN,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEG,aAAa;gBAAyD;gBAC/EC,WAAW;YACb;YACA;gBACEN,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEG,aAAa;gBAAiD;gBACvEC,WAAW;YACb;YACA;gBACEN,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBACLC,aACE;oBACFE,aAAa;gBACf;gBACAC,WAAW;YACb;YACA;gBACEN,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBACLC,aAAa;oBACbE,aAAa;gBACf;gBACAC,WAAW;YACb;YACA;gBACEN,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEG,aAAa;gBAAoC;gBAC1DC,WAAW;YACb;SACD;QACDC,OAAO;IACT;CACD,CAAA"}
+7
View File
@@ -0,0 +1,7 @@
import type { GlobalConfig } from 'payload';
/**
* Builds the Notifications global — localized action-result texts. Readable by
* any authenticated panel user; server-side helpers read it with overrideAccess
* so the frontend can resolve texts without a session.
*/
export declare function buildNotifications(): GlobalConfig;
+17
View File
@@ -0,0 +1,17 @@
import { notificationsFields } from './fields.js';
/**
* Builds the Notifications global — localized action-result texts. Readable by
* any authenticated panel user; server-side helpers read it with overrideAccess
* so the frontend can resolve texts without a session.
*/ export function buildNotifications() {
return {
slug: 'notifications',
access: {
read: ()=>true
},
fields: notificationsFields,
label: 'Notifications'
};
}
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/globals/Notifications/index.ts"],"sourcesContent":["import type { GlobalConfig } from 'payload'\n\nimport { notificationsFields } from './fields.js'\n\n/**\n * Builds the Notifications global — localized action-result texts. Readable by\n * any authenticated panel user; server-side helpers read it with overrideAccess\n * so the frontend can resolve texts without a session.\n */\nexport function buildNotifications(): GlobalConfig {\n return {\n slug: 'notifications',\n access: {\n read: () => true, // texts are public-facing (shown to end users)\n },\n fields: notificationsFields,\n label: 'Notifications',\n }\n}\n"],"names":["notificationsFields","buildNotifications","slug","access","read","fields","label"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,cAAa;AAEjD;;;;CAIC,GACD,OAAO,SAASC;IACd,OAAO;QACLC,MAAM;QACNC,QAAQ;YACNC,MAAM,IAAM;QACd;QACAC,QAAQL;QACRM,OAAO;IACT;AACF"}
@@ -0,0 +1,3 @@
import type { TextFieldClientComponent } from 'payload';
export declare const MaskedField: TextFieldClientComponent;
export default MaskedField;
+54
View File
@@ -0,0 +1,54 @@
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
export const MaskedField = (props)=>{
const { field, path, value: propValue, setValue: propSetValue, onChange: propOnChange } = props || {};
const [internalValue, setInternalValue] = useState(propValue ?? '');
const [revealed, setRevealed] = useState(false);
const label = typeof field?.label === 'string' ? field.label : field?.name ?? path;
const handleChange = (e)=>{
const newVal = e.target.value;
setInternalValue(newVal);
if (typeof propSetValue === 'function') {
propSetValue(newVal);
}
if (typeof propOnChange === 'function') {
propOnChange(e);
}
};
const currentValue = propValue !== undefined ? propValue : internalValue;
return /*#__PURE__*/ _jsxs("div", {
className: "field-type text",
children: [
label && /*#__PURE__*/ _jsx("label", {
className: "field-label",
children: label
}),
/*#__PURE__*/ _jsxs("div", {
style: {
display: 'flex',
gap: '.5rem'
},
children: [
/*#__PURE__*/ _jsx("input", {
autoComplete: "off",
onChange: handleChange,
style: {
flex: 1
},
type: revealed ? 'text' : 'password',
value: currentValue ?? ''
}),
/*#__PURE__*/ _jsx("button", {
onClick: ()=>setRevealed((r)=>!r),
type: "button",
children: revealed ? 'Hide' : 'Reveal'
})
]
})
]
});
};
export default MaskedField;
//# sourceMappingURL=MaskedField.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/components/MaskedField.tsx"],"sourcesContent":["'use client'\nimport type { TextFieldClientComponent } from 'payload'\nimport { useState } from 'react'\n\nexport const MaskedField: TextFieldClientComponent = (props: any) => {\n const { field, path, value: propValue, setValue: propSetValue, onChange: propOnChange } = props || {}\n const [internalValue, setInternalValue] = useState(propValue ?? '')\n const [revealed, setRevealed] = useState(false)\n const label = typeof field?.label === 'string' ? field.label : (field?.name ?? path)\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const newVal = e.target.value\n setInternalValue(newVal)\n if (typeof propSetValue === 'function') {\n propSetValue(newVal)\n }\n if (typeof propOnChange === 'function') {\n propOnChange(e)\n }\n }\n\n const currentValue = propValue !== undefined ? propValue : internalValue\n\n return (\n <div className=\"field-type text\">\n {label && <label className=\"field-label\">{label}</label>}\n <div style={{ display: 'flex', gap: '.5rem' }}>\n <input\n autoComplete=\"off\"\n onChange={handleChange}\n style={{ flex: 1 }}\n type={revealed ? 'text' : 'password'}\n value={currentValue ?? ''}\n />\n <button onClick={() => setRevealed((r) => !r)} type=\"button\">\n {revealed ? 'Hide' : 'Reveal'}\n </button>\n </div>\n </div>\n )\n}\n\nexport default MaskedField\n"],"names":["useState","MaskedField","props","field","path","value","propValue","setValue","propSetValue","onChange","propOnChange","internalValue","setInternalValue","revealed","setRevealed","label","name","handleChange","e","newVal","target","currentValue","undefined","div","className","style","display","gap","input","autoComplete","flex","type","button","onClick","r"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,QAAQ,QAAO;AAEhC,OAAO,MAAMC,cAAwC,CAACC;IACpD,MAAM,EAAEC,KAAK,EAAEC,IAAI,EAAEC,OAAOC,SAAS,EAAEC,UAAUC,YAAY,EAAEC,UAAUC,YAAY,EAAE,GAAGR,SAAS,CAAC;IACpG,MAAM,CAACS,eAAeC,iBAAiB,GAAGZ,SAASM,aAAa;IAChE,MAAM,CAACO,UAAUC,YAAY,GAAGd,SAAS;IACzC,MAAMe,QAAQ,OAAOZ,OAAOY,UAAU,WAAWZ,MAAMY,KAAK,GAAIZ,OAAOa,QAAQZ;IAE/E,MAAMa,eAAe,CAACC;QACpB,MAAMC,SAASD,EAAEE,MAAM,CAACf,KAAK;QAC7BO,iBAAiBO;QACjB,IAAI,OAAOX,iBAAiB,YAAY;YACtCA,aAAaW;QACf;QACA,IAAI,OAAOT,iBAAiB,YAAY;YACtCA,aAAaQ;QACf;IACF;IAEA,MAAMG,eAAef,cAAcgB,YAAYhB,YAAYK;IAE3D,qBACE,MAACY;QAAIC,WAAU;;YACZT,uBAAS,KAACA;gBAAMS,WAAU;0BAAeT;;0BAC1C,MAACQ;gBAAIE,OAAO;oBAAEC,SAAS;oBAAQC,KAAK;gBAAQ;;kCAC1C,KAACC;wBACCC,cAAa;wBACbpB,UAAUQ;wBACVQ,OAAO;4BAAEK,MAAM;wBAAE;wBACjBC,MAAMlB,WAAW,SAAS;wBAC1BR,OAAOgB,gBAAgB;;kCAEzB,KAACW;wBAAOC,SAAS,IAAMnB,YAAY,CAACoB,IAAM,CAACA;wBAAIH,MAAK;kCACjDlB,WAAW,SAAS;;;;;;AAK/B,EAAC;AAED,eAAeZ,YAAW"}
@@ -0,0 +1,11 @@
/**
* Admin UI: a small "send test email" tool for the SiteIntegrations email tab.
* Enter an address, click Send, and it POSTs to /api/ipal/test-email, which
* sends through the currently-selected transport (SMTP or Graph). Shows the
* result inline so you can confirm delivery — or read the exact error — without
* leaving the panel.
*
* Assigned via a `ui` field's admin.components.Field.
*/
export declare const TestEmailButton: () => import("react/jsx-runtime").JSX.Element;
export default TestEmailButton;
@@ -0,0 +1,131 @@
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
/**
* Admin UI: a small "send test email" tool for the SiteIntegrations email tab.
* Enter an address, click Send, and it POSTs to /api/ipal/test-email, which
* sends through the currently-selected transport (SMTP or Graph). Shows the
* result inline so you can confirm delivery — or read the exact error — without
* leaving the panel.
*
* Assigned via a `ui` field's admin.components.Field.
*/ export const TestEmailButton = ()=>{
const [to, setTo] = useState('');
const [status, setStatus] = useState({
kind: 'idle'
});
const send = async ()=>{
if (!to.trim()) {
setStatus({
kind: 'error',
msg: 'Enter a recipient address.'
});
return;
}
setStatus({
kind: 'sending'
});
try {
const res = await fetch('/api/ipal/test-email', {
body: JSON.stringify({
to: to.trim()
}),
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
});
const data = await res.json();
if (data.ok) {
setStatus({
kind: 'ok',
msg: data.message ?? 'Test email sent.'
});
} else {
setStatus({
kind: 'error',
msg: data.error ?? 'Send failed.'
});
}
} catch {
setStatus({
kind: 'error',
msg: 'Request failed. Is the server running?'
});
}
};
return /*#__PURE__*/ _jsxs("div", {
className: "field-type",
style: {
marginTop: '1rem'
},
children: [
/*#__PURE__*/ _jsx("label", {
className: "field-label",
children: "Send a test email"
}),
/*#__PURE__*/ _jsx("p", {
style: {
fontSize: '.85rem',
marginTop: 0,
opacity: 0.7
},
children: "Sends through the transport selected above. Save your changes first."
}),
/*#__PURE__*/ _jsxs("div", {
style: {
alignItems: 'center',
display: 'flex',
flexWrap: 'wrap',
gap: '.5rem'
},
children: [
/*#__PURE__*/ _jsx("input", {
onChange: (e)=>setTo(e.target.value),
placeholder: "[email protected]",
style: {
flex: 1,
minWidth: '220px'
},
type: "email",
value: to
}),
/*#__PURE__*/ _jsx("button", {
className: "btn btn--style-secondary",
disabled: status.kind === 'sending',
onClick: send,
style: {
whiteSpace: 'nowrap'
},
type: "button",
children: status.kind === 'sending' ? 'Sending…' : 'Send test'
})
]
}),
status.kind === 'ok' && /*#__PURE__*/ _jsxs("p", {
style: {
color: 'var(--theme-success-500, green)',
marginTop: '.5rem'
},
children: [
"✓ ",
status.msg
]
}),
status.kind === 'error' && /*#__PURE__*/ _jsxs("p", {
style: {
color: 'var(--theme-error-500, crimson)',
marginTop: '.5rem'
},
children: [
"✗ ",
status.msg
]
})
]
});
};
export default TestEmailButton;
//# sourceMappingURL=TestEmailButton.js.map
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/components/TestEmailButton.tsx"],"sourcesContent":["'use client'\n\nimport { useState } from 'react'\n\n/**\n * Admin UI: a small \"send test email\" tool for the SiteIntegrations email tab.\n * Enter an address, click Send, and it POSTs to /api/ipal/test-email, which\n * sends through the currently-selected transport (SMTP or Graph). Shows the\n * result inline so you can confirm delivery — or read the exact error — without\n * leaving the panel.\n *\n * Assigned via a `ui` field's admin.components.Field.\n */\nexport const TestEmailButton = () => {\n const [to, setTo] = useState('')\n const [status, setStatus] = useState<\n | { kind: 'error'; msg: string }\n | { kind: 'idle' }\n | { kind: 'ok'; msg: string }\n | { kind: 'sending' }\n >({ kind: 'idle' })\n\n const send = async () => {\n if (!to.trim()) {\n setStatus({ kind: 'error', msg: 'Enter a recipient address.' })\n return\n }\n setStatus({ kind: 'sending' })\n try {\n const res = await fetch('/api/ipal/test-email', {\n body: JSON.stringify({ to: to.trim() }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n const data = await res.json()\n if (data.ok) {\n setStatus({ kind: 'ok', msg: data.message ?? 'Test email sent.' })\n } else {\n setStatus({ kind: 'error', msg: data.error ?? 'Send failed.' })\n }\n } catch {\n setStatus({ kind: 'error', msg: 'Request failed. Is the server running?' })\n }\n }\n\n return (\n <div className=\"field-type\" style={{ marginTop: '1rem' }}>\n <label className=\"field-label\">Send a test email</label>\n <p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>\n Sends through the transport selected above. Save your changes first.\n </p>\n <div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem' }}>\n <input\n onChange={(e) => setTo(e.target.value)}\n placeholder=\"[email protected]\"\n style={{ flex: 1, minWidth: '220px' }}\n type=\"email\"\n value={to}\n />\n <button\n className=\"btn btn--style-secondary\"\n disabled={status.kind === 'sending'}\n onClick={send}\n style={{ whiteSpace: 'nowrap' }}\n type=\"button\"\n >\n {status.kind === 'sending' ? 'Sending…' : 'Send test'}\n </button>\n </div>\n {status.kind === 'ok' && (\n <p style={{ color: 'var(--theme-success-500, green)', marginTop: '.5rem' }}>\n ✓ {status.msg}\n </p>\n )}\n {status.kind === 'error' && (\n <p style={{ color: 'var(--theme-error-500, crimson)', marginTop: '.5rem' }}>\n ✗ {status.msg}\n </p>\n )}\n </div>\n )\n}\n\nexport default TestEmailButton\n"],"names":["useState","TestEmailButton","to","setTo","status","setStatus","kind","send","trim","msg","res","fetch","body","JSON","stringify","credentials","headers","method","data","json","ok","message","error","div","className","style","marginTop","label","p","fontSize","opacity","alignItems","display","flexWrap","gap","input","onChange","e","target","value","placeholder","flex","minWidth","type","button","disabled","onClick","whiteSpace","color"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,QAAQ,QAAO;AAEhC;;;;;;;;CAQC,GACD,OAAO,MAAMC,kBAAkB;IAC7B,MAAM,CAACC,IAAIC,MAAM,GAAGH,SAAS;IAC7B,MAAM,CAACI,QAAQC,UAAU,GAAGL,SAK1B;QAAEM,MAAM;IAAO;IAEjB,MAAMC,OAAO;QACX,IAAI,CAACL,GAAGM,IAAI,IAAI;YACdH,UAAU;gBAAEC,MAAM;gBAASG,KAAK;YAA6B;YAC7D;QACF;QACAJ,UAAU;YAAEC,MAAM;QAAU;QAC5B,IAAI;YACF,MAAMI,MAAM,MAAMC,MAAM,wBAAwB;gBAC9CC,MAAMC,KAAKC,SAAS,CAAC;oBAAEZ,IAAIA,GAAGM,IAAI;gBAAG;gBACrCO,aAAa;gBACbC,SAAS;oBAAE,gBAAgB;gBAAmB;gBAC9CC,QAAQ;YACV;YACA,MAAMC,OAAO,MAAMR,IAAIS,IAAI;YAC3B,IAAID,KAAKE,EAAE,EAAE;gBACXf,UAAU;oBAAEC,MAAM;oBAAMG,KAAKS,KAAKG,OAAO,IAAI;gBAAmB;YAClE,OAAO;gBACLhB,UAAU;oBAAEC,MAAM;oBAASG,KAAKS,KAAKI,KAAK,IAAI;gBAAe;YAC/D;QACF,EAAE,OAAM;YACNjB,UAAU;gBAAEC,MAAM;gBAASG,KAAK;YAAyC;QAC3E;IACF;IAEA,qBACE,MAACc;QAAIC,WAAU;QAAaC,OAAO;YAAEC,WAAW;QAAO;;0BACrD,KAACC;gBAAMH,WAAU;0BAAc;;0BAC/B,KAACI;gBAAEH,OAAO;oBAAEI,UAAU;oBAAUH,WAAW;oBAAGI,SAAS;gBAAI;0BAAG;;0BAG9D,MAACP;gBAAIE,OAAO;oBAAEM,YAAY;oBAAUC,SAAS;oBAAQC,UAAU;oBAAQC,KAAK;gBAAQ;;kCAClF,KAACC;wBACCC,UAAU,CAACC,IAAMlC,MAAMkC,EAAEC,MAAM,CAACC,KAAK;wBACrCC,aAAY;wBACZf,OAAO;4BAAEgB,MAAM;4BAAGC,UAAU;wBAAQ;wBACpCC,MAAK;wBACLJ,OAAOrC;;kCAET,KAAC0C;wBACCpB,WAAU;wBACVqB,UAAUzC,OAAOE,IAAI,KAAK;wBAC1BwC,SAASvC;wBACTkB,OAAO;4BAAEsB,YAAY;wBAAS;wBAC9BJ,MAAK;kCAEJvC,OAAOE,IAAI,KAAK,YAAY,aAAa;;;;YAG7CF,OAAOE,IAAI,KAAK,sBACf,MAACsB;gBAAEH,OAAO;oBAAEuB,OAAO;oBAAmCtB,WAAW;gBAAQ;;oBAAG;oBACvEtB,OAAOK,GAAG;;;YAGhBL,OAAOE,IAAI,KAAK,yBACf,MAACsB;gBAAEH,OAAO;oBAAEuB,OAAO;oBAAmCtB,WAAW;gBAAQ;;oBAAG;oBACvEtB,OAAOK,GAAG;;;;;AAKvB,EAAC;AAED,eAAeR,gBAAe"}
+36 -1
View File
@@ -5,8 +5,30 @@
* user), so all fields — including the password — stay editable in the admin
* panel while remaining inaccessible to anonymous API requests.
*/ export const smtpFields = [
{
name: 'emailTransport',
type: 'select',
admin: {
description: 'How outbound email is sent. "Microsoft Graph" is only available when configured by the administrator (Intecion).'
},
defaultValue: 'smtp',
options: [
{
label: 'SMTP',
value: 'smtp'
},
{
label: 'Microsoft Graph (Exchange)',
value: 'graph'
}
]
},
{
type: 'row',
admin: {
// Hide SMTP fields when Graph is selected — they're not used then.
condition: (_, siblingData)=>siblingData?.emailTransport !== 'graph'
},
fields: [
{
name: 'smtpHost',
@@ -37,7 +59,11 @@
name: 'smtpPassword',
type: 'text',
admin: {
description: 'SMTP account password.'
description: 'SMTP account password.',
// Masked in the UI (••••) — stored plaintext, readable for SMTP auth.
components: {
Field: '@intecion/ipal-kit/client#MaskedField'
}
}
},
{
@@ -53,6 +79,15 @@
admin: {
description: 'Default "from" display name.'
}
},
{
name: 'emailTest',
type: 'ui',
admin: {
components: {
Field: '@intecion/ipal-kit/client#TestEmailButton'
}
}
}
];
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/smtp.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * SMTP transport settings for outbound email.\n *\n * Protected at the global level (SiteIntegrations requires an authenticated\n * user), so all fields — including the password — stay editable in the admin\n * panel while remaining inaccessible to anonymous API requests.\n */\nexport const smtpFields: Field[] = [\n {\n type: 'row',\n fields: [\n {\n name: 'smtpHost',\n type: 'text',\n admin: { placeholder: 'smtp.example.com', width: '70%' },\n },\n {\n name: 'smtpPort',\n type: 'number',\n admin: { width: '30%' },\n defaultValue: 587,\n },\n ],\n },\n {\n name: 'smtpUser',\n type: 'text',\n admin: {\n description: 'SMTP account username.',\n },\n },\n {\n name: 'smtpPassword',\n type: 'text',\n admin: {\n description: 'SMTP account password.',\n },\n },\n {\n name: 'smtpFromAddress',\n type: 'email',\n admin: {\n description: 'Default \"from\" address for outgoing mail.',\n },\n },\n {\n name: 'smtpFromName',\n type: 'text',\n admin: {\n description: 'Default \"from\" display name.',\n },\n },\n]\n"],"names":["smtpFields","type","fields","name","admin","placeholder","width","defaultValue","description"],"mappings":"AAEA;;;;;;CAMC,GACD,OAAO,MAAMA,aAAsB;IACjC;QACEC,MAAM;QACNC,QAAQ;YACN;gBACEC,MAAM;gBACNF,MAAM;gBACNG,OAAO;oBAAEC,aAAa;oBAAoBC,OAAO;gBAAM;YACzD;YACA;gBACEH,MAAM;gBACNF,MAAM;gBACNG,OAAO;oBAAEE,OAAO;gBAAM;gBACtBC,cAAc;YAChB;SACD;IACH;IACA;QACEJ,MAAM;QACNF,MAAM;QACNG,OAAO;YACLI,aAAa;QACf;IACF;IACA;QACEL,MAAM;QACNF,MAAM;QACNG,OAAO;YACLI,aAAa;QACf;IACF;IACA;QACEL,MAAM;QACNF,MAAM;QACNG,OAAO;YACLI,aAAa;QACf;IACF;IACA;QACEL,MAAM;QACNF,MAAM;QACNG,OAAO;YACLI,aAAa;QACf;IACF;CACD,CAAA"}
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/smtp.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * SMTP transport settings for outbound email.\n *\n * Protected at the global level (SiteIntegrations requires an authenticated\n * user), so all fields — including the password — stay editable in the admin\n * panel while remaining inaccessible to anonymous API requests.\n */\nexport const smtpFields: Field[] = [\n {\n name: 'emailTransport',\n type: 'select',\n admin: {\n description:\n 'How outbound email is sent. \"Microsoft Graph\" is only available when configured by the administrator (Intecion).',\n // The Graph option only makes sense when agency credentials exist in env.\n // We can't read process.env in the admin UI directly, so a client project\n // that hasn't set up Graph should filter this option via integrationsFields\n // override, or simply leave it on 'smtp'. The adapter enforces the real\n // availability at send time regardless of what's selected here.\n },\n defaultValue: 'smtp',\n options: [\n { label: 'SMTP', value: 'smtp' },\n { label: 'Microsoft Graph (Exchange)', value: 'graph' },\n ],\n },\n {\n type: 'row',\n admin: {\n // Hide SMTP fields when Graph is selected — they're not used then.\n condition: (_, siblingData) => siblingData?.emailTransport !== 'graph',\n },\n fields: [\n {\n name: 'smtpHost',\n type: 'text',\n admin: { placeholder: 'smtp.example.com', width: '70%' },\n },\n {\n name: 'smtpPort',\n type: 'number',\n admin: { width: '30%' },\n defaultValue: 587,\n },\n ],\n },\n {\n name: 'smtpUser',\n type: 'text',\n admin: {\n description: 'SMTP account username.',\n },\n },\n {\n name: 'smtpPassword',\n type: 'text',\n admin: {\n description: 'SMTP account password.',\n // Masked in the UI (••••) — stored plaintext, readable for SMTP auth.\n components: {\n Field: '@intecion/ipal-kit/client#MaskedField',\n },\n },\n },\n {\n name: 'smtpFromAddress',\n type: 'email',\n admin: {\n description: 'Default \"from\" address for outgoing mail.',\n },\n },\n {\n name: 'smtpFromName',\n type: 'text',\n admin: {\n description: 'Default \"from\" display name.',\n },\n },\n {\n name: 'emailTest',\n type: 'ui',\n admin: {\n components: {\n Field: '@intecion/ipal-kit/client#TestEmailButton',\n },\n },\n },\n]\n"],"names":["smtpFields","name","type","admin","description","defaultValue","options","label","value","condition","_","siblingData","emailTransport","fields","placeholder","width","components","Field"],"mappings":"AAEA;;;;;;CAMC,GACD,OAAO,MAAMA,aAAsB;IACjC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aACE;QAMJ;QACAC,cAAc;QACdC,SAAS;YACP;gBAAEC,OAAO;gBAAQC,OAAO;YAAO;YAC/B;gBAAED,OAAO;gBAA8BC,OAAO;YAAQ;SACvD;IACH;IACA;QACEN,MAAM;QACNC,OAAO;YACL,mEAAmE;YACnEM,WAAW,CAACC,GAAGC,cAAgBA,aAAaC,mBAAmB;QACjE;QACAC,QAAQ;YACN;gBACEZ,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEW,aAAa;oBAAoBC,OAAO;gBAAM;YACzD;YACA;gBACEd,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEY,OAAO;gBAAM;gBACtBV,cAAc;YAChB;SACD;IACH;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACb,sEAAsE;YACtEY,YAAY;gBACVC,OAAO;YACT;QACF;IACF;IACA;QACEhB,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLa,YAAY;gBACVC,OAAO;YACT;QACF;IACF;CACD,CAAA"}
+5 -1
View File
@@ -31,7 +31,11 @@
name: 'r2SecretAccessKey',
type: 'text',
admin: {
description: 'R2 secret access key.'
description: 'R2 secret access key.',
// Masked in the UI (••••) — stored plaintext, readable for R2 auth.
components: {
Field: '@intecion/ipal-kit/client#MaskedField'
}
}
}
];
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/storage.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Cloudflare R2 storage credentials.\n * Reserved for future use — media offloading to R2.\n *\n * Protected at the global level (SiteIntegrations requires an authenticated\n * user), so the access keys stay editable in the admin panel while remaining\n * inaccessible to anonymous API requests.\n */\nexport const storageFields: Field[] = [\n {\n name: 'r2Bucket',\n type: 'text',\n admin: {\n description: 'R2 bucket name.',\n },\n },\n {\n name: 'r2Endpoint',\n type: 'text',\n admin: {\n description: 'R2 S3-compatible endpoint URL.',\n },\n },\n {\n name: 'r2AccessKeyId',\n type: 'text',\n admin: {\n description: 'R2 access key ID.',\n },\n },\n {\n name: 'r2SecretAccessKey',\n type: 'text',\n admin: {\n description: 'R2 secret access key.',\n },\n },\n]\n"],"names":["storageFields","name","type","admin","description"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,MAAMA,gBAAyB;IACpC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;CACD,CAAA"}
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/storage.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Cloudflare R2 storage credentials.\n * Reserved for future use — media offloading to R2.\n *\n * Protected at the global level (SiteIntegrations requires an authenticated\n * user), so the access keys stay editable in the admin panel while remaining\n * inaccessible to anonymous API requests.\n */\nexport const storageFields: Field[] = [\n {\n name: 'r2Bucket',\n type: 'text',\n admin: {\n description: 'R2 bucket name.',\n },\n },\n {\n name: 'r2Endpoint',\n type: 'text',\n admin: {\n description: 'R2 S3-compatible endpoint URL.',\n },\n },\n {\n name: 'r2AccessKeyId',\n type: 'text',\n admin: {\n description: 'R2 access key ID.',\n },\n },\n {\n name: 'r2SecretAccessKey',\n type: 'text',\n admin: {\n description: 'R2 secret access key.',\n // Masked in the UI (••••) — stored plaintext, readable for R2 auth.\n components: {\n Field: '@intecion/ipal-kit/client#MaskedField',\n },\n },\n },\n]\n"],"names":["storageFields","name","type","admin","description","components","Field"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,MAAMA,gBAAyB;IACpC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACb,oEAAoE;YACpEC,YAAY;gBACVC,OAAO;YACT;QACF;IACF;CACD,CAAA"}
+5 -1
View File
@@ -17,7 +17,11 @@
name: 'turnstileSecretKey',
type: 'text',
admin: {
description: 'Secret key used for server-side verification.'
description: 'Secret key used for server-side verification.',
// Masked in the UI (••••) — stored plaintext, readable for verification.
components: {
Field: '@intecion/ipal-kit/client#MaskedField'
}
}
}
];
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/turnstile.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Cloudflare Turnstile credentials.\n *\n * siteKey is public (rendered in the widget); secretKey is used for\n * server-side verification. Both are protected at the global level\n * (SiteIntegrations requires an authenticated user) rather than per-field,\n * so they remain editable in the admin panel.\n */\nexport const turnstileFields: Field[] = [\n {\n name: 'turnstileSiteKey',\n type: 'text',\n admin: {\n description: 'Public site key rendered in the Turnstile widget.',\n },\n },\n {\n name: 'turnstileSecretKey',\n type: 'text',\n admin: {\n description: 'Secret key used for server-side verification.',\n },\n },\n]\n"],"names":["turnstileFields","name","type","admin","description"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;CACD,CAAA"}
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/turnstile.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Cloudflare Turnstile credentials.\n *\n * siteKey is public (rendered in the widget); secretKey is used for\n * server-side verification. Both are protected at the global level\n * (SiteIntegrations requires an authenticated user) rather than per-field,\n * so they remain editable in the admin panel.\n */\nexport const turnstileFields: Field[] = [\n {\n name: 'turnstileSiteKey',\n type: 'text',\n admin: {\n description: 'Public site key rendered in the Turnstile widget.',\n },\n },\n {\n name: 'turnstileSecretKey',\n type: 'text',\n admin: {\n description: 'Secret key used for server-side verification.',\n // Masked in the UI (••••) — stored plaintext, readable for verification.\n components: {\n Field: '@intecion/ipal-kit/client#MaskedField',\n },\n },\n },\n]\n"],"names":["turnstileFields","name","type","admin","description","components","Field"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACb,yEAAyE;YACzEC,YAAY;gBACVC,OAAO;YACT;QACF;IACF;CACD,CAAA"}
+4
View File
@@ -14,6 +14,10 @@ type BuildSiteIntegrationsArgs = {
* impossible to enter.)
*
* Unnamed tabs keep data flat (siteIntegrations.ga4MeasurementId).
*
* Note: R2 storage credentials are NOT here — storage is infrastructure and
* binds at boot, so its config lives in .env (R2_BUCKET, R2_ENDPOINT, ...),
* consumed by buildR2Storage. See docs/storage.md.
*/
export declare function buildSiteIntegrations({ additionalFields, }?: BuildSiteIntegrationsArgs): GlobalConfig;
export {};
+4 -5
View File
@@ -1,7 +1,6 @@
import { isAdmin } from '../../modules/access/index.js';
import { analyticsFields } from './fields/analytics.js';
import { smtpFields } from './fields/smtp.js';
import { storageFields } from './fields/storage.js';
import { turnstileFields } from './fields/turnstile.js';
/**
* Builds the SiteIntegrations global.
@@ -14,6 +13,10 @@ import { turnstileFields } from './fields/turnstile.js';
* impossible to enter.)
*
* Unnamed tabs keep data flat (siteIntegrations.ga4MeasurementId).
*
* Note: R2 storage credentials are NOT here — storage is infrastructure and
* binds at boot, so its config lives in .env (R2_BUCKET, R2_ENDPOINT, ...),
* consumed by buildR2Storage. See docs/storage.md.
*/ export function buildSiteIntegrations({ additionalFields } = {}) {
return {
slug: 'site-integrations',
@@ -42,10 +45,6 @@ import { turnstileFields } from './fields/turnstile.js';
fields: smtpFields,
label: 'SMTP'
},
{
fields: storageFields,
label: 'Storage'
},
...additionalFields?.length ? [
{
fields: additionalFields,
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/globals/SiteIntegrations/index.ts"],"sourcesContent":["import type { Field, GlobalConfig } from 'payload'\n\nimport { isAdmin } from '../../modules/access/index.js'\nimport { analyticsFields } from './fields/analytics.js'\nimport { smtpFields } from './fields/smtp.js'\nimport { storageFields } from './fields/storage.js'\nimport { turnstileFields } from './fields/turnstile.js'\n\ntype BuildSiteIntegrationsArgs = {\n /** Extra fields injected by the client project */\n additionalFields?: Field[]\n}\n\n/**\n * Builds the SiteIntegrations global.\n *\n * Holds third-party service credentials. Access is enforced at the global\n * level — the whole global requires an authenticated user — so secrets stay\n * out of anonymous API responses while remaining editable in the admin panel\n * and readable via the server-side Local API. (Field-level read:false was\n * avoided because it also hides fields from the admin UI, making them\n * impossible to enter.)\n *\n * Unnamed tabs keep data flat (siteIntegrations.ga4MeasurementId).\n */\nexport function buildSiteIntegrations({\n additionalFields,\n}: BuildSiteIntegrationsArgs = {}): GlobalConfig {\n return {\n slug: 'site-integrations',\n access: {\n // Admin-only — secrets live here. Anonymous and non-admin users get\n // nothing through the API; admins read/edit in the panel and via Local API.\n read: ({ req: { user } }) => isAdmin(user),\n update: ({ req: { user } }) => isAdmin(user),\n },\n admin: {\n group: 'Settings',\n },\n fields: [\n {\n type: 'tabs',\n tabs: [\n { fields: analyticsFields, label: 'Analytics' },\n { fields: turnstileFields, label: 'Turnstile' },\n { fields: smtpFields, label: 'SMTP' },\n { fields: storageFields, label: 'Storage' },\n ...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),\n ],\n },\n ],\n label: 'Site Integrations',\n }\n}\n"],"names":["isAdmin","analyticsFields","smtpFields","storageFields","turnstileFields","buildSiteIntegrations","additionalFields","slug","access","read","req","user","update","admin","group","fields","type","tabs","label","length"],"mappings":"AAEA,SAASA,OAAO,QAAQ,gCAA+B;AACvD,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,aAAa,QAAQ,sBAAqB;AACnD,SAASC,eAAe,QAAQ,wBAAuB;AAOvD;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,sBAAsB,EACpCC,gBAAgB,EACU,GAAG,CAAC,CAAC;IAC/B,OAAO;QACLC,MAAM;QACNC,QAAQ;YACN,oEAAoE;YACpE,4EAA4E;YAC5EC,MAAM,CAAC,EAAEC,KAAK,EAAEC,IAAI,EAAE,EAAE,GAAKX,QAAQW;YACrCC,QAAQ,CAAC,EAAEF,KAAK,EAAEC,IAAI,EAAE,EAAE,GAAKX,QAAQW;QACzC;QACAE,OAAO;YACLC,OAAO;QACT;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;oBACJ;wBAAEF,QAAQd;wBAAiBiB,OAAO;oBAAY;oBAC9C;wBAAEH,QAAQX;wBAAiBc,OAAO;oBAAY;oBAC9C;wBAAEH,QAAQb;wBAAYgB,OAAO;oBAAO;oBACpC;wBAAEH,QAAQZ;wBAAee,OAAO;oBAAU;uBACtCZ,kBAAkBa,SAAS;wBAAC;4BAAEJ,QAAQT;4BAAkBY,OAAO;wBAAS;qBAAE,GAAG,EAAE;iBACpF;YACH;SACD;QACDA,OAAO;IACT;AACF"}
{"version":3,"sources":["../../../src/globals/SiteIntegrations/index.ts"],"sourcesContent":["import type { Field, GlobalConfig } from 'payload'\n\nimport { isAdmin } from '../../modules/access/index.js'\nimport { analyticsFields } from './fields/analytics.js'\nimport { smtpFields } from './fields/smtp.js'\nimport { turnstileFields } from './fields/turnstile.js'\n\ntype BuildSiteIntegrationsArgs = {\n /** Extra fields injected by the client project */\n additionalFields?: Field[]\n}\n\n/**\n * Builds the SiteIntegrations global.\n *\n * Holds third-party service credentials. Access is enforced at the global\n * level — the whole global requires an authenticated user — so secrets stay\n * out of anonymous API responses while remaining editable in the admin panel\n * and readable via the server-side Local API. (Field-level read:false was\n * avoided because it also hides fields from the admin UI, making them\n * impossible to enter.)\n *\n * Unnamed tabs keep data flat (siteIntegrations.ga4MeasurementId).\n *\n * Note: R2 storage credentials are NOT here — storage is infrastructure and\n * binds at boot, so its config lives in .env (R2_BUCKET, R2_ENDPOINT, ...),\n * consumed by buildR2Storage. See docs/storage.md.\n */\nexport function buildSiteIntegrations({\n additionalFields,\n}: BuildSiteIntegrationsArgs = {}): GlobalConfig {\n return {\n slug: 'site-integrations',\n access: {\n // Admin-only — secrets live here. Anonymous and non-admin users get\n // nothing through the API; admins read/edit in the panel and via Local API.\n read: ({ req: { user } }) => isAdmin(user),\n update: ({ req: { user } }) => isAdmin(user),\n },\n admin: {\n group: 'Settings',\n },\n fields: [\n {\n type: 'tabs',\n tabs: [\n { fields: analyticsFields, label: 'Analytics' },\n { fields: turnstileFields, label: 'Turnstile' },\n { fields: smtpFields, label: 'SMTP' },\n ...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),\n ],\n },\n ],\n label: 'Site Integrations',\n }\n}\n"],"names":["isAdmin","analyticsFields","smtpFields","turnstileFields","buildSiteIntegrations","additionalFields","slug","access","read","req","user","update","admin","group","fields","type","tabs","label","length"],"mappings":"AAEA,SAASA,OAAO,QAAQ,gCAA+B;AACvD,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,eAAe,QAAQ,wBAAuB;AAOvD;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASC,sBAAsB,EACpCC,gBAAgB,EACU,GAAG,CAAC,CAAC;IAC/B,OAAO;QACLC,MAAM;QACNC,QAAQ;YACN,oEAAoE;YACpE,4EAA4E;YAC5EC,MAAM,CAAC,EAAEC,KAAK,EAAEC,IAAI,EAAE,EAAE,GAAKV,QAAQU;YACrCC,QAAQ,CAAC,EAAEF,KAAK,EAAEC,IAAI,EAAE,EAAE,GAAKV,QAAQU;QACzC;QACAE,OAAO;YACLC,OAAO;QACT;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;oBACJ;wBAAEF,QAAQb;wBAAiBgB,OAAO;oBAAY;oBAC9C;wBAAEH,QAAQX;wBAAiBc,OAAO;oBAAY;oBAC9C;wBAAEH,QAAQZ;wBAAYe,OAAO;oBAAO;uBAChCZ,kBAAkBa,SAAS;wBAAC;4BAAEJ,QAAQT;4BAAkBY,OAAO;wBAAS;qBAAE,GAAG,EAAE;iBACpF;YACH;SACD;QACDA,OAAO;IACT;AACF"}
+16 -1
View File
@@ -1,3 +1,4 @@
import { validateFaviconField } from '../../../modules/seo/index.js';
/**
* General site identity fields.
* Consumed by SEO/OG (siteName, defaultShareImage) and frontend (logo).
@@ -11,6 +12,14 @@
localized: true,
required: true
},
{
name: 'siteDescription',
type: 'textarea',
admin: {
description: 'Fallback meta description when a page has none. Also used for llms.txt and Open Graph.'
},
localized: true
},
{
name: 'titleOrder',
type: 'select',
@@ -79,7 +88,13 @@
name: 'favicon',
type: 'upload',
admin: {
description: 'Square source icon (PNG or SVG) for the browser tab. Rendered by the frontend.'
description: 'Square icon, PNG or SVG, min. 48×48px (Google requires this to show it in search). Rendered via buildIconsMetadata.'
},
hooks: {
// Warn the editor if the favicon is too small / not square for Google.
beforeValidate: [
validateFaviconField
]
},
relationTo: 'media'
}
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../../src/globals/SiteSettings/fields/general.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * General site identity fields.\n * Consumed by SEO/OG (siteName, defaultShareImage) and frontend (logo).\n */\nexport const generalFields: Field[] = [\n {\n name: 'siteName',\n type: 'text',\n admin: {\n description: 'Used in page titles and Open Graph metadata.',\n },\n localized: true,\n required: true,\n },\n {\n name: 'titleOrder',\n type: 'select',\n admin: {\n description: 'Which comes first in browser tabs.',\n },\n defaultValue: 'page-first',\n options: [\n { label: 'Page first — About Us | Acme', value: 'page-first' },\n { label: 'Site first — Acme | About Us', value: 'site-first' },\n ],\n },\n {\n name: 'titleSeparator',\n type: 'select',\n admin: {\n description: 'Separates the page title from the site name in browser tabs.',\n },\n defaultValue: '|',\n options: [\n { label: 'Pipe — Page | Site', value: '|' },\n { label: 'Dash — Page – Site', value: '–' },\n { label: 'Hyphen — Page - Site', value: '-' },\n { label: 'Bullet — Page · Site', value: '·' },\n { label: 'Slash — Page / Site', value: '/' },\n ],\n },\n {\n name: 'logo',\n type: 'upload',\n admin: {\n description: 'Primary site logo.',\n },\n relationTo: 'media',\n },\n {\n name: 'defaultShareImage',\n type: 'upload',\n admin: {\n description: 'Fallback Open Graph image when a page has none.',\n },\n relationTo: 'media',\n },\n {\n name: 'favicon',\n type: 'upload',\n admin: {\n description: 'Square source icon (PNG or SVG) for the browser tab. Rendered by the frontend.',\n },\n relationTo: 'media',\n },\n]\n"],"names":["generalFields","name","type","admin","description","localized","required","defaultValue","options","label","value","relationTo"],"mappings":"AAEA;;;CAGC,GACD,OAAO,MAAMA,gBAAyB;IACpC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;QACXC,UAAU;IACZ;IACA;QACEL,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAG,cAAc;QACdC,SAAS;YACP;gBAAEC,OAAO;gBAAkCC,OAAO;YAAa;YAC/D;gBAAED,OAAO;gBAAkCC,OAAO;YAAa;SAChE;IACH;IACA;QACET,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAG,cAAc;QACdC,SAAS;YACP;gBAAEC,OAAO;gBAAwBC,OAAO;YAAI;YAC5C;gBAAED,OAAO;gBAAwBC,OAAO;YAAI;YAC5C;gBAAED,OAAO;gBAA0BC,OAAO;YAAI;YAC9C;gBAAED,OAAO;gBAA0BC,OAAO;YAAI;YAC9C;gBAAED,OAAO;gBAAyBC,OAAO;YAAI;SAC9C;IACH;IACA;QACET,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAO,YAAY;IACd;IACA;QACEV,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAO,YAAY;IACd;IACA;QACEV,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAO,YAAY;IACd;CACD,CAAA"}
{"version":3,"sources":["../../../../src/globals/SiteSettings/fields/general.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport { validateFaviconField } from '../../../modules/seo/index.js'\n\n/**\n * General site identity fields.\n * Consumed by SEO/OG (siteName, defaultShareImage) and frontend (logo).\n */\nexport const generalFields: Field[] = [\n {\n name: 'siteName',\n type: 'text',\n admin: {\n description: 'Used in page titles and Open Graph metadata.',\n },\n localized: true,\n required: true,\n },\n {\n name: 'siteDescription',\n type: 'textarea',\n admin: {\n description:\n 'Fallback meta description when a page has none. Also used for llms.txt and Open Graph.',\n },\n localized: true,\n },\n {\n name: 'titleOrder',\n type: 'select',\n admin: {\n description: 'Which comes first in browser tabs.',\n },\n defaultValue: 'page-first',\n options: [\n { label: 'Page first — About Us | Acme', value: 'page-first' },\n { label: 'Site first — Acme | About Us', value: 'site-first' },\n ],\n },\n {\n name: 'titleSeparator',\n type: 'select',\n admin: {\n description: 'Separates the page title from the site name in browser tabs.',\n },\n defaultValue: '|',\n options: [\n { label: 'Pipe — Page | Site', value: '|' },\n { label: 'Dash — Page – Site', value: '–' },\n { label: 'Hyphen — Page - Site', value: '-' },\n { label: 'Bullet — Page · Site', value: '·' },\n { label: 'Slash — Page / Site', value: '/' },\n ],\n },\n {\n name: 'logo',\n type: 'upload',\n admin: {\n description: 'Primary site logo.',\n },\n relationTo: 'media',\n },\n {\n name: 'defaultShareImage',\n type: 'upload',\n admin: {\n description: 'Fallback Open Graph image when a page has none.',\n },\n relationTo: 'media',\n },\n {\n name: 'favicon',\n type: 'upload',\n admin: {\n description:\n 'Square icon, PNG or SVG, min. 48×48px (Google requires this to show it in search). Rendered via buildIconsMetadata.',\n },\n hooks: {\n // Warn the editor if the favicon is too small / not square for Google.\n beforeValidate: [validateFaviconField],\n },\n relationTo: 'media',\n },\n]\n"],"names":["validateFaviconField","generalFields","name","type","admin","description","localized","required","defaultValue","options","label","value","relationTo","hooks","beforeValidate"],"mappings":"AAEA,SAASA,oBAAoB,QAAQ,gCAA+B;AAEpE;;;CAGC,GACD,OAAO,MAAMC,gBAAyB;IACpC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAC,WAAW;QACXC,UAAU;IACZ;IACA;QACEL,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aACE;QACJ;QACAC,WAAW;IACb;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAG,cAAc;QACdC,SAAS;YACP;gBAAEC,OAAO;gBAAkCC,OAAO;YAAa;YAC/D;gBAAED,OAAO;gBAAkCC,OAAO;YAAa;SAChE;IACH;IACA;QACET,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAG,cAAc;QACdC,SAAS;YACP;gBAAEC,OAAO;gBAAwBC,OAAO;YAAI;YAC5C;gBAAED,OAAO;gBAAwBC,OAAO;YAAI;YAC5C;gBAAED,OAAO;gBAA0BC,OAAO;YAAI;YAC9C;gBAAED,OAAO;gBAA0BC,OAAO;YAAI;YAC9C;gBAAED,OAAO;gBAAyBC,OAAO;YAAI;SAC9C;IACH;IACA;QACET,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAO,YAAY;IACd;IACA;QACEV,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;QACAO,YAAY;IACd;IACA;QACEV,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aACE;QACJ;QACAQ,OAAO;YACL,uEAAuE;YACvEC,gBAAgB;gBAACd;aAAqB;QACxC;QACAY,YAAY;IACd;CACD,CAAA"}
+33 -1
View File
@@ -1,29 +1,61 @@
export type { AccessOption, Role } from './modules/access/index.js';
export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, authenticated, hasMinimumRole, isAdmin, isEditor, requireRole, requireRoleField, ROLE_HIERARCHY, } from './modules/access/index.js';
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y, } from './modules/accessibility/index.js';
export type { A11yState } from './modules/accessibility/index.js';
export type { AnalyticsConfig } from './modules/analytics/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 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, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRedirect, resolveRoute, } from './modules/content/index.js';
export type { ArchiveEntries } 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 { 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 { 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 { 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';
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 { buildSecurityHeaders } from './modules/security/index.js';
export { buildCsp } from './modules/security/index.js';
export type { BuildCspArgs } from './modules/security/index.js';
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js';
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js';
export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js';
export type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js';
export { 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 { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd, } from './modules/seo/index.js';
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd, } from './modules/seo/index.js';
export { buildArticleJsonLd } from './modules/seo/index.js';
export { buildLlmsTxt } from './modules/seo/index.js';
export { buildSitemapXml } from './modules/seo/index.js';
export { buildSlugField, toSlug } from './modules/slug/index.js';
export { buildR2Storage } from './modules/storage/index.js';
export { ipalKit } from './plugin.js';
export type { IpalOptions } from './types.js';
+30 -1
View File
@@ -1,20 +1,49 @@
export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, authenticated, hasMinimumRole, isAdmin, isEditor, requireRole, requireRoleField, ROLE_HIERARCHY } from './modules/access/index.js';
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, buildArchivePath, buildEntryPath, getArchiveEntries, parsePageParam, resolveRedirect, resolveRoute } 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';
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';
// 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';
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';
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 { 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 { 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';
export { buildArticleJsonLd } from './modules/seo/index.js';
export { buildLlmsTxt } from './modules/seo/index.js';
export { buildSitemapXml } from './modules/seo/index.js';
export { buildSlugField, toSlug } from './modules/slug/index.js';
export { buildR2Storage } from './modules/storage/index.js';
export { ipalKit } from './plugin.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
File diff suppressed because one or more lines are too long
+29
View File
@@ -0,0 +1,29 @@
import { type A11yState } from './state.js';
type A11yContextValue = {
reset: () => void;
set: <K extends keyof A11yState>(key: K, value: A11yState[K]) => void;
state: A11yState;
};
/**
* Provides accessibility preferences, persists them in a cookie, and applies them
* as data-attributes on <html> so the project's CSS can react. Like
* ConsentProvider for cookies — wrap the app once; the widget/button consume it.
*
* The plugin ships NO styles: it only sets attributes (data-a11y-*). The project
* writes CSS for those it supports (see docs/accessibility.md). This keeps the
* design in the project's hands.
*
* // layout.tsx
* import { AccessibilityProvider } from '@intecion/ipal-kit/client'
* <AccessibilityProvider>{children}</AccessibilityProvider>
*
* To avoid a flash, the project can read the a11y-prefs cookie server-side and
* set the attributes on <html> during SSR (see docs). This provider re-applies
* on the client and keeps them in sync.
*/
export declare function AccessibilityProvider({ children }: {
children: React.ReactNode;
}): import("react/jsx-runtime").JSX.Element;
/** Access accessibility preferences + setters. Use inside AccessibilityProvider. */
export declare function useAccessibility(): A11yContextValue;
export {};
+87
View File
@@ -0,0 +1,87 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, use, useCallback, useEffect, useState } from 'react';
import { A11Y_COOKIE, A11Y_COOKIE_MAX_AGE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './state.js';
const A11yContext = /*#__PURE__*/ createContext(null);
function readCookie(name) {
if (typeof document === 'undefined') {
return undefined;
}
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : undefined;
}
/**
* Provides accessibility preferences, persists them in a cookie, and applies them
* as data-attributes on <html> so the project's CSS can react. Like
* ConsentProvider for cookies — wrap the app once; the widget/button consume it.
*
* The plugin ships NO styles: it only sets attributes (data-a11y-*). The project
* writes CSS for those it supports (see docs/accessibility.md). This keeps the
* design in the project's hands.
*
* // layout.tsx
* import { AccessibilityProvider } from '@intecion/ipal-kit/client'
* <AccessibilityProvider>{children}</AccessibilityProvider>
*
* To avoid a flash, the project can read the a11y-prefs cookie server-side and
* set the attributes on <html> during SSR (see docs). This provider re-applies
* on the client and keeps them in sync.
*/ export function AccessibilityProvider({ children }) {
const [state, setState] = useState(A11Y_DEFAULT);
// Hydrate from cookie on mount.
useEffect(()=>{
setState(parseA11y(readCookie(A11Y_COOKIE)));
}, []);
// Apply attributes to <html> whenever state changes.
useEffect(()=>{
const el = document.documentElement;
const attrs = a11yAttributes(state);
for (const [attr, value] of Object.entries(attrs)){
if (value === null) {
el.removeAttribute(attr);
} else {
el.setAttribute(attr, value);
}
}
}, [
state
]);
const persist = useCallback((next)=>{
document.cookie = `${A11Y_COOKIE}=${encodeURIComponent(serializeA11y(next))}; path=/; max-age=${A11Y_COOKIE_MAX_AGE}; samesite=lax`;
}, []);
const set = useCallback((key, value)=>{
setState((prev)=>{
const next = {
...prev,
[key]: value
};
persist(next);
return next;
});
}, [
persist
]);
const reset = useCallback(()=>{
setState(A11Y_DEFAULT);
persist(A11Y_DEFAULT);
}, [
persist
]);
return /*#__PURE__*/ _jsx(A11yContext, {
value: {
reset,
set,
state
},
children: children
});
}
/** Access accessibility preferences + setters. Use inside AccessibilityProvider. */ export function useAccessibility() {
const ctx = use(A11yContext);
if (!ctx) {
throw new Error('useAccessibility must be used within <AccessibilityProvider>');
}
return ctx;
}
//# sourceMappingURL=AccessibilityProvider.js.map
File diff suppressed because one or more lines are too long
+41
View File
@@ -0,0 +1,41 @@
export type A11yTexts = {
bigCursor?: string;
close?: string;
contrast?: string;
contrastHigh?: string;
contrastInverted?: string;
grayscale?: string;
lineHeight?: string;
open?: string;
readableFont?: string;
reduceMotion?: string;
reset?: string;
textSize?: string;
title?: string;
underlineLinks?: string;
};
export type A11yClassNames = {
active?: string;
button?: string;
closeButton?: string;
control?: string;
label?: string;
panel?: string;
resetButton?: string;
row?: string;
};
/**
* Accessibility toolbar: a floating button that opens a panel of options (text
* size, line height, contrast, grayscale, underline links, readable font, reduce
* motion, big cursor). Choices persist in a cookie and apply as data-attributes
* on <html> (the project's CSS styles them).
*
* Unstyled by default — pass classNames to match the project's design (like
* CookieBanner). Wrap the app in <AccessibilityProvider> first.
*
* <AccessibilityWidget classNames={{ button: 'a11y-btn', panel: 'a11y-panel' }} />
*/
export declare function AccessibilityWidget({ classNames, texts, }: {
classNames?: A11yClassNames;
texts?: A11yTexts;
}): import("react/jsx-runtime").JSX.Element;
+188
View File
@@ -0,0 +1,188 @@
'use client';
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'
};
/**
* Accessibility toolbar: a floating button that opens a panel of options (text
* size, line height, contrast, grayscale, underline links, readable font, reduce
* motion, big cursor). Choices persist in a cookie and apply as data-attributes
* on <html> (the project's CSS styles them).
*
* Unstyled by default — pass classNames to match the project's design (like
* CookieBanner). Wrap the app in <AccessibilityProvider> first.
*
* <AccessibilityWidget classNames={{ button: 'a11y-btn', panel: 'a11y-panel' }} />
*/ export function AccessibilityWidget({ classNames, texts }) {
const { reset, set, state } = useAccessibility();
const [open, setOpen] = useState(false);
const t = {
...DEFAULT_TEXTS,
...texts
};
const cn = classNames ?? {};
const toggle = (key)=>set(key, !state[key]);
const isActive = (on)=>on ? cn.active ?? '' : '';
return /*#__PURE__*/ _jsxs(_Fragment, {
children: [
/*#__PURE__*/ _jsx("button", {
"aria-expanded": open,
"aria-label": t.open,
className: cn.button,
onClick: ()=>setOpen((o)=>!o),
type: "button",
children: /*#__PURE__*/ _jsx("span", {
"aria-hidden": "true",
children: "♿"
})
}),
open && /*#__PURE__*/ _jsxs("div", {
"aria-label": t.title,
className: cn.panel,
role: "dialog",
children: [
/*#__PURE__*/ _jsxs("div", {
className: cn.row,
children: [
/*#__PURE__*/ _jsx("span", {
className: cn.label,
children: t.textSize
}),
/*#__PURE__*/ _jsx("div", {
className: cn.control,
children: [
0,
1,
2,
3
].map((n)=>/*#__PURE__*/ _jsxs("button", {
className: isActive(state.textSize === n),
onClick: ()=>set('textSize', n),
type: "button",
children: [
"A",
n > 0 ? '+'.repeat(n) : ''
]
}, n))
})
]
}),
/*#__PURE__*/ _jsxs("div", {
className: cn.row,
children: [
/*#__PURE__*/ _jsx("span", {
className: cn.label,
children: t.lineHeight
}),
/*#__PURE__*/ _jsx("div", {
className: cn.control,
children: [
0,
1,
2
].map((n)=>/*#__PURE__*/ _jsx("button", {
className: isActive(state.lineHeight === n),
onClick: ()=>set('lineHeight', n),
type: "button",
children: n === 0 ? '—' : '≡'.repeat(n)
}, n))
})
]
}),
/*#__PURE__*/ _jsxs("div", {
className: cn.row,
children: [
/*#__PURE__*/ _jsx("span", {
className: cn.label,
children: t.contrast
}),
/*#__PURE__*/ _jsxs("div", {
className: cn.control,
children: [
/*#__PURE__*/ _jsx("button", {
className: isActive(state.contrast === 'high'),
onClick: ()=>set('contrast', state.contrast === 'high' ? 'default' : 'high'),
type: "button",
children: t.contrastHigh
}),
/*#__PURE__*/ _jsx("button", {
className: isActive(state.contrast === 'inverted'),
onClick: ()=>set('contrast', state.contrast === 'inverted' ? 'default' : 'inverted'),
type: "button",
children: t.contrastInverted
})
]
})
]
}),
[
[
'grayscale',
t.grayscale
],
[
'underlineLinks',
t.underlineLinks
],
[
'readableFont',
t.readableFont
],
[
'reduceMotion',
t.reduceMotion
],
[
'bigCursor',
t.bigCursor
]
].map(([key, label])=>/*#__PURE__*/ _jsxs("div", {
className: cn.row,
children: [
/*#__PURE__*/ _jsx("span", {
className: cn.label,
children: label
}),
/*#__PURE__*/ _jsx("button", {
"aria-pressed": Boolean(state[key]),
className: `${cn.control ?? ''} ${isActive(Boolean(state[key]))}`,
onClick: ()=>toggle(key),
type: "button",
children: state[key] ? 'ON' : 'OFF'
})
]
}, key)),
/*#__PURE__*/ _jsx("button", {
className: cn.resetButton,
onClick: reset,
type: "button",
children: t.reset
}),
/*#__PURE__*/ _jsx("button", {
className: cn.closeButton,
onClick: ()=>setOpen(false),
type: "button",
children: t.close
})
]
})
]
});
}
//# sourceMappingURL=AccessibilityWidget.js.map
File diff suppressed because one or more lines are too long
+5
View File
@@ -0,0 +1,5 @@
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js';
export { AccessibilityWidget } from './AccessibilityWidget.js';
export type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js';
export type { A11yState } from './state.js';
export { A11Y_COOKIE, a11yAttributes, parseA11y } from './state.js';
+6
View File
@@ -0,0 +1,6 @@
'use client';
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js';
export { AccessibilityWidget } from './AccessibilityWidget.js';
export { A11Y_COOKIE, a11yAttributes, parseA11y } from './state.js';
//# sourceMappingURL=client.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/accessibility/client.ts"],"sourcesContent":["'use client'\nexport { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js'\nexport { AccessibilityWidget } from './AccessibilityWidget.js'\nexport type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js'\nexport type { A11yState } from './state.js'\nexport { A11Y_COOKIE, a11yAttributes, parseA11y } from './state.js'\n"],"names":["AccessibilityProvider","useAccessibility","AccessibilityWidget","A11Y_COOKIE","a11yAttributes","parseA11y"],"mappings":"AAAA;AACA,SAASA,qBAAqB,EAAEC,gBAAgB,QAAQ,6BAA4B;AACpF,SAASC,mBAAmB,QAAQ,2BAA0B;AAG9D,SAASC,WAAW,EAAEC,cAAc,EAAEC,SAAS,QAAQ,aAAY"}
+5
View File
@@ -0,0 +1,5 @@
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js';
export { AccessibilityWidget } from './AccessibilityWidget.js';
export type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js';
export { A11Y_COOKIE, A11Y_COOKIE_MAX_AGE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y, } from './state.js';
export type { A11yState } from './state.js';
+5
View File
@@ -0,0 +1,5 @@
export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js';
export { AccessibilityWidget } from './AccessibilityWidget.js';
export { A11Y_COOKIE, A11Y_COOKIE_MAX_AGE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './state.js';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/accessibility/index.ts"],"sourcesContent":["export { AccessibilityProvider, useAccessibility } from './AccessibilityProvider.js'\nexport { AccessibilityWidget } from './AccessibilityWidget.js'\nexport type { A11yClassNames, A11yTexts } from './AccessibilityWidget.js'\nexport {\n A11Y_COOKIE,\n A11Y_COOKIE_MAX_AGE,\n A11Y_DEFAULT,\n a11yAttributes,\n parseA11y,\n serializeA11y,\n} from './state.js'\nexport type { A11yState } from './state.js'\n"],"names":["AccessibilityProvider","useAccessibility","AccessibilityWidget","A11Y_COOKIE","A11Y_COOKIE_MAX_AGE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y"],"mappings":"AAAA,SAASA,qBAAqB,EAAEC,gBAAgB,QAAQ,6BAA4B;AACpF,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SACEC,WAAW,EACXC,mBAAmB,EACnBC,YAAY,EACZC,cAAc,EACdC,SAAS,EACTC,aAAa,QACR,aAAY"}
+37
View File
@@ -0,0 +1,37 @@
/**
* Accessibility preferences state. Each option maps to a data-attribute on
* <html> (e.g. data-a11y-contrast="high"); the PROJECT's CSS reacts to those
* attributes. The plugin sets the attributes and persists the choice — it does
* NOT ship styles, so it never fights the project's design.
*/
export type A11yState = {
/** Larger cursor. */
bigCursor: boolean;
/** 'default' | 'high' (high contrast) | 'inverted' (dark-on-light flip). */
contrast: 'default' | 'high' | 'inverted';
/** Grayscale filter on the whole page. */
grayscale: boolean;
/** Line spacing: 0 = default, 1..2 = looser. */
lineHeight: 0 | 1 | 2;
/** Readable font (project maps this to a dyslexia-friendly / simple font). */
readableFont: boolean;
/** Stop animations / transitions (prefers-reduced-motion equivalent). */
reduceMotion: boolean;
/** Text size step: 0 = default, 1..3 = larger. */
textSize: 0 | 1 | 2 | 3;
/** Underline all links (WCAG: don't rely on color alone). */
underlineLinks: boolean;
};
export declare const A11Y_DEFAULT: A11yState;
export declare const A11Y_COOKIE = "a11y-prefs";
export declare const A11Y_COOKIE_MAX_AGE: number;
/** Serialize for the cookie (compact). */
export declare function serializeA11y(state: A11yState): string;
/** Parse from the cookie; falls back to defaults on any bad value. */
export declare function parseA11y(raw: null | string | undefined): A11yState;
/**
* Maps state → data-attributes to set on <html>. Returns { attr: value|null };
* null means remove the attribute (option is at default). The project's CSS
* targets these, e.g. `[data-a11y-contrast="high"] { … }`.
*/
export declare function a11yAttributes(state: A11yState): Record<string, null | string>;
+53
View File
@@ -0,0 +1,53 @@
/**
* Accessibility preferences state. Each option maps to a data-attribute on
* <html> (e.g. data-a11y-contrast="high"); the PROJECT's CSS reacts to those
* attributes. The plugin sets the attributes and persists the choice — it does
* NOT ship styles, so it never fights the project's design.
*/ export const A11Y_DEFAULT = {
bigCursor: false,
contrast: 'default',
grayscale: false,
lineHeight: 0,
readableFont: false,
reduceMotion: false,
textSize: 0,
underlineLinks: false
};
export const A11Y_COOKIE = 'a11y-prefs';
export const A11Y_COOKIE_MAX_AGE = 60 * 60 * 24 * 365 // 1 year
;
/** Serialize for the cookie (compact). */ export function serializeA11y(state) {
return JSON.stringify(state);
}
/** Parse from the cookie; falls back to defaults on any bad value. */ export function parseA11y(raw) {
if (!raw) {
return A11Y_DEFAULT;
}
try {
const parsed = JSON.parse(raw);
return {
...A11Y_DEFAULT,
...parsed
};
} catch {
return A11Y_DEFAULT;
}
}
/**
* Maps state → data-attributes to set on <html>. Returns { attr: value|null };
* null means remove the attribute (option is at default). The project's CSS
* targets these, e.g. `[data-a11y-contrast="high"] { … }`.
*/ export function a11yAttributes(state) {
return {
'data-a11y-contrast': state.contrast !== 'default' ? state.contrast : null,
'data-a11y-cursor': state.bigCursor ? 'big' : null,
'data-a11y-font': state.readableFont ? 'readable' : null,
'data-a11y-grayscale': state.grayscale ? 'on' : null,
'data-a11y-line': state.lineHeight > 0 ? String(state.lineHeight) : null,
'data-a11y-motion': state.reduceMotion ? 'reduce' : null,
'data-a11y-text': state.textSize > 0 ? String(state.textSize) : null,
'data-a11y-underline': state.underlineLinks ? 'on' : null
};
}
//# sourceMappingURL=state.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/accessibility/state.ts"],"sourcesContent":["/**\n * Accessibility preferences state. Each option maps to a data-attribute on\n * <html> (e.g. data-a11y-contrast=\"high\"); the PROJECT's CSS reacts to those\n * attributes. The plugin sets the attributes and persists the choice — it does\n * NOT ship styles, so it never fights the project's design.\n */\nexport type A11yState = {\n /** Larger cursor. */\n bigCursor: boolean\n /** 'default' | 'high' (high contrast) | 'inverted' (dark-on-light flip). */\n contrast: 'default' | 'high' | 'inverted'\n /** Grayscale filter on the whole page. */\n grayscale: boolean\n /** Line spacing: 0 = default, 1..2 = looser. */\n lineHeight: 0 | 1 | 2\n /** Readable font (project maps this to a dyslexia-friendly / simple font). */\n readableFont: boolean\n /** Stop animations / transitions (prefers-reduced-motion equivalent). */\n reduceMotion: boolean\n /** Text size step: 0 = default, 1..3 = larger. */\n textSize: 0 | 1 | 2 | 3\n /** Underline all links (WCAG: don't rely on color alone). */\n underlineLinks: boolean\n}\n\nexport const A11Y_DEFAULT: A11yState = {\n bigCursor: false,\n contrast: 'default',\n grayscale: false,\n lineHeight: 0,\n readableFont: false,\n reduceMotion: false,\n textSize: 0,\n underlineLinks: false,\n}\n\nexport const A11Y_COOKIE = 'a11y-prefs'\nexport const A11Y_COOKIE_MAX_AGE = 60 * 60 * 24 * 365 // 1 year\n\n/** Serialize for the cookie (compact). */\nexport function serializeA11y(state: A11yState): string {\n return JSON.stringify(state)\n}\n\n/** Parse from the cookie; falls back to defaults on any bad value. */\nexport function parseA11y(raw: null | string | undefined): A11yState {\n if (!raw) {return A11Y_DEFAULT}\n try {\n const parsed = JSON.parse(raw) as Partial<A11yState>\n return { ...A11Y_DEFAULT, ...parsed }\n } catch {\n return A11Y_DEFAULT\n }\n}\n\n/**\n * Maps state → data-attributes to set on <html>. Returns { attr: value|null };\n * null means remove the attribute (option is at default). The project's CSS\n * targets these, e.g. `[data-a11y-contrast=\"high\"] { … }`.\n */\nexport function a11yAttributes(state: A11yState): Record<string, null | string> {\n return {\n 'data-a11y-contrast': state.contrast !== 'default' ? state.contrast : null,\n 'data-a11y-cursor': state.bigCursor ? 'big' : null,\n 'data-a11y-font': state.readableFont ? 'readable' : null,\n 'data-a11y-grayscale': state.grayscale ? 'on' : null,\n 'data-a11y-line': state.lineHeight > 0 ? String(state.lineHeight) : null,\n 'data-a11y-motion': state.reduceMotion ? 'reduce' : null,\n 'data-a11y-text': state.textSize > 0 ? String(state.textSize) : null,\n 'data-a11y-underline': state.underlineLinks ? 'on' : null,\n }\n}\n"],"names":["A11Y_DEFAULT","bigCursor","contrast","grayscale","lineHeight","readableFont","reduceMotion","textSize","underlineLinks","A11Y_COOKIE","A11Y_COOKIE_MAX_AGE","serializeA11y","state","JSON","stringify","parseA11y","raw","parsed","parse","a11yAttributes","String"],"mappings":"AAAA;;;;;CAKC,GAoBD,OAAO,MAAMA,eAA0B;IACrCC,WAAW;IACXC,UAAU;IACVC,WAAW;IACXC,YAAY;IACZC,cAAc;IACdC,cAAc;IACdC,UAAU;IACVC,gBAAgB;AAClB,EAAC;AAED,OAAO,MAAMC,cAAc,aAAY;AACvC,OAAO,MAAMC,sBAAsB,KAAK,KAAK,KAAK,IAAI,SAAS;CAAV;AAErD,wCAAwC,GACxC,OAAO,SAASC,cAAcC,KAAgB;IAC5C,OAAOC,KAAKC,SAAS,CAACF;AACxB;AAEA,oEAAoE,GACpE,OAAO,SAASG,UAAUC,GAA8B;IACtD,IAAI,CAACA,KAAK;QAAC,OAAOhB;IAAY;IAC9B,IAAI;QACF,MAAMiB,SAASJ,KAAKK,KAAK,CAACF;QAC1B,OAAO;YAAE,GAAGhB,YAAY;YAAE,GAAGiB,MAAM;QAAC;IACtC,EAAE,OAAM;QACN,OAAOjB;IACT;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASmB,eAAeP,KAAgB;IAC7C,OAAO;QACL,sBAAsBA,MAAMV,QAAQ,KAAK,YAAYU,MAAMV,QAAQ,GAAG;QACtE,oBAAoBU,MAAMX,SAAS,GAAG,QAAQ;QAC9C,kBAAkBW,MAAMP,YAAY,GAAG,aAAa;QACpD,uBAAuBO,MAAMT,SAAS,GAAG,OAAO;QAChD,kBAAkBS,MAAMR,UAAU,GAAG,IAAIgB,OAAOR,MAAMR,UAAU,IAAI;QACpE,oBAAoBQ,MAAMN,YAAY,GAAG,WAAW;QACpD,kBAAkBM,MAAML,QAAQ,GAAG,IAAIa,OAAOR,MAAML,QAAQ,IAAI;QAChE,uBAAuBK,MAAMJ,cAAc,GAAG,OAAO;IACvD;AACF"}
+49
View File
@@ -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
View File
@@ -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
File diff suppressed because one or more lines are too long
+8
View File
@@ -4,6 +4,7 @@ import { Cookie } from 'lucide-react';
import { useEffect, useState } from 'react';
import { CONSENT_CATEGORIES } from './categories.js';
import { useConsentContext } from './ConsentContext.js';
import { useIsMounted } from './useIsMounted.js';
/**
* Colours and radius come from CSS custom properties with built-in fallbacks,
* so the banner looks right with no setup, and re-skinning per client means
@@ -36,6 +37,7 @@ const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dar
const strongText = 'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]';
const mutedText = 'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]';
export function CookieBanner({ classNames } = {}) {
const isMounted = useIsMounted();
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext();
const [showSettings, setShowSettings] = useState(false);
const [choices, setChoices] = useState(state);
@@ -44,6 +46,12 @@ export function CookieBanner({ classNames } = {}) {
}, [
state
]);
// Render nothing until mounted — avoids the React 19 hydration mismatch that
// projects used to work around with a setTimeout ConsentWrapper. No wrapper
// needed now.
if (!isMounted) {
return null;
}
if (decided) {
return null;
}
File diff suppressed because one or more lines are too long
+7
View File
@@ -2,6 +2,7 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { Cookie } from 'lucide-react';
import { useConsentContext } from './ConsentContext.js';
import { useIsMounted } from './useIsMounted.js';
/**
* Floating "cookie settings" button — lets visitors reopen the consent panel
* after deciding (GDPR: withdrawing consent must be as easy as giving it).
@@ -12,7 +13,13 @@ import { useConsentContext } from './ConsentContext.js';
* palette applies to both without touching either component. Pass className to
* replace the styling outright.
*/ export function CookieButton({ className } = {}) {
const isMounted = useIsMounted();
const { decided, reopen } = useConsentContext();
// Render nothing until mounted — prevents hydration mismatch (no project
// ConsentWrapper workaround needed).
if (!isMounted) {
return null;
}
if (!decided) {
return null;
}
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/consent/CookieButton.tsx"],"sourcesContent":["'use client'\nimport { Cookie } from 'lucide-react'\n\nimport { useConsentContext } from './ConsentContext.js'\n\n/**\n * Floating \"cookie settings\" button — lets visitors reopen the consent panel\n * after deciding (GDPR: withdrawing consent must be as easy as giving it).\n * Hidden while the banner is showing.\n *\n * Colours follow the same CSS custom properties as CookieBanner\n * (--ipal-surface, --ipal-border, --ipal-hover, --ipal-text), so a client's\n * palette applies to both without touching either component. Pass className to\n * replace the styling outright.\n */\nexport function CookieButton({ className }: { className?: string } = {}) {\n const { decided, reopen } = useConsentContext()\n\n if (!decided) {return null}\n\n const cls =\n className ??\n 'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +\n 'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' +\n 'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'\n\n return (\n <button aria-label=\"Cookie settings\" className={cls} data-ipal=\"cookie-button\" onClick={reopen}>\n <Cookie\n aria-hidden=\"true\"\n className=\"h-5 w-5 text-[var(--ipal-text,#525252)] dark:text-[var(--ipal-text-dark,#d4d4d4)]\"\n />\n </button>\n )\n}\n"],"names":["Cookie","useConsentContext","CookieButton","className","decided","reopen","cls","button","aria-label","data-ipal","onClick","aria-hidden"],"mappings":"AAAA;;AACA,SAASA,MAAM,QAAQ,eAAc;AAErC,SAASC,iBAAiB,QAAQ,sBAAqB;AAEvD;;;;;;;;;CASC,GACD,OAAO,SAASC,aAAa,EAAEC,SAAS,EAA0B,GAAG,CAAC,CAAC;IACrE,MAAM,EAAEC,OAAO,EAAEC,MAAM,EAAE,GAAGJ;IAE5B,IAAI,CAACG,SAAS;QAAC,OAAO;IAAI;IAE1B,MAAME,MACJH,aACA,2HACE,4GACA;IAEJ,qBACE,KAACI;QAAOC,cAAW;QAAkBL,WAAWG;QAAKG,aAAU;QAAgBC,SAASL;kBACtF,cAAA,KAACL;YACCW,eAAY;YACZR,WAAU;;;AAIlB"}
{"version":3,"sources":["../../../src/modules/consent/CookieButton.tsx"],"sourcesContent":["'use client'\nimport { Cookie } from 'lucide-react'\n\nimport { useConsentContext } from './ConsentContext.js'\nimport { useIsMounted } from './useIsMounted.js'\n\n/**\n * Floating \"cookie settings\" button — lets visitors reopen the consent panel\n * after deciding (GDPR: withdrawing consent must be as easy as giving it).\n * Hidden while the banner is showing.\n *\n * Colours follow the same CSS custom properties as CookieBanner\n * (--ipal-surface, --ipal-border, --ipal-hover, --ipal-text), so a client's\n * palette applies to both without touching either component. Pass className to\n * replace the styling outright.\n */\nexport function CookieButton({ className }: { className?: string } = {}) {\n const isMounted = useIsMounted()\n const { decided, reopen } = useConsentContext()\n\n // Render nothing until mounted — prevents hydration mismatch (no project\n // ConsentWrapper workaround needed).\n if (!isMounted) {return null}\n if (!decided) {return null}\n\n const cls =\n className ??\n 'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +\n 'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' +\n 'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'\n\n return (\n <button aria-label=\"Cookie settings\" className={cls} data-ipal=\"cookie-button\" onClick={reopen}>\n <Cookie\n aria-hidden=\"true\"\n className=\"h-5 w-5 text-[var(--ipal-text,#525252)] dark:text-[var(--ipal-text-dark,#d4d4d4)]\"\n />\n </button>\n )\n}\n"],"names":["Cookie","useConsentContext","useIsMounted","CookieButton","className","isMounted","decided","reopen","cls","button","aria-label","data-ipal","onClick","aria-hidden"],"mappings":"AAAA;;AACA,SAASA,MAAM,QAAQ,eAAc;AAErC,SAASC,iBAAiB,QAAQ,sBAAqB;AACvD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD;;;;;;;;;CASC,GACD,OAAO,SAASC,aAAa,EAAEC,SAAS,EAA0B,GAAG,CAAC,CAAC;IACrE,MAAMC,YAAYH;IAClB,MAAM,EAAEI,OAAO,EAAEC,MAAM,EAAE,GAAGN;IAE5B,yEAAyE;IACzE,qCAAqC;IACrC,IAAI,CAACI,WAAW;QAAC,OAAO;IAAI;IAC5B,IAAI,CAACC,SAAS;QAAC,OAAO;IAAI;IAE1B,MAAME,MACJJ,aACA,2HACE,4GACA;IAEJ,qBACE,KAACK;QAAOC,cAAW;QAAkBN,WAAWI;QAAKG,aAAU;QAAgBC,SAASL;kBACtF,cAAA,KAACP;YACCa,eAAY;YACZT,WAAU;;;AAIlB"}
+1
View File
@@ -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';
+1
View File
@@ -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.
+1 -1
View File
@@ -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"}
+1
View File
@@ -4,3 +4,4 @@ export { getConsentTexts } from './getConsentTexts.js';
export { setDefaultConsent, updateConsent } from './googleConsent.js';
export { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, parseConsent, serializeConsent, } from './storage.js';
export type { ConsentTexts } from './texts.js';
export { useIsMounted } from './useIsMounted.js';
+1
View File
@@ -5,5 +5,6 @@ export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, DEFAULT_CONSENT, REJECT_ALL_CON
export { getConsentTexts } from './getConsentTexts.js';
export { setDefaultConsent, updateConsent } from './googleConsent.js';
export { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, parseConsent, serializeConsent } from './storage.js';
export { useIsMounted } from './useIsMounted.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/consent/index.ts"],"sourcesContent":["// Server-safe exports (logic, types, helper). Client components (banner,\n// provider, hook) are exported separately via ./client to keep the RSC/client\n// boundary clean.\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n DEFAULT_CONSENT,\n REJECT_ALL_CONSENT,\n} from './categories.js'\nexport type { ConsentCategory, ConsentState } from './categories.js'\nexport { getConsentTexts } from './getConsentTexts.js'\nexport { setDefaultConsent, updateConsent } from './googleConsent.js'\nexport {\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n parseConsent,\n serializeConsent,\n} from './storage.js'\nexport type { ConsentTexts } from './texts.js'\n"],"names":["ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","DEFAULT_CONSENT","REJECT_ALL_CONSENT","getConsentTexts","setDefaultConsent","updateConsent","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","parseConsent","serializeConsent"],"mappings":"AAAA,yEAAyE;AACzE,8EAA8E;AAC9E,kBAAkB;AAClB,SACEA,kBAAkB,EAClBC,kBAAkB,EAClBC,eAAe,EACfC,kBAAkB,QACb,kBAAiB;AAExB,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,iBAAiB,EAAEC,aAAa,QAAQ,qBAAoB;AACrE,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,gBAAgB,QACX,eAAc"}
{"version":3,"sources":["../../../src/modules/consent/index.ts"],"sourcesContent":["// Server-safe exports (logic, types, helper). Client components (banner,\n// provider, hook) are exported separately via ./client to keep the RSC/client\n// boundary clean.\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n DEFAULT_CONSENT,\n REJECT_ALL_CONSENT,\n} from './categories.js'\nexport type { ConsentCategory, ConsentState } from './categories.js'\nexport { getConsentTexts } from './getConsentTexts.js'\nexport { setDefaultConsent, updateConsent } from './googleConsent.js'\nexport {\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n parseConsent,\n serializeConsent,\n} from './storage.js'\nexport type { ConsentTexts } from './texts.js'\nexport { useIsMounted } from './useIsMounted.js'\n"],"names":["ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","DEFAULT_CONSENT","REJECT_ALL_CONSENT","getConsentTexts","setDefaultConsent","updateConsent","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","parseConsent","serializeConsent","useIsMounted"],"mappings":"AAAA,yEAAyE;AACzE,8EAA8E;AAC9E,kBAAkB;AAClB,SACEA,kBAAkB,EAClBC,kBAAkB,EAClBC,eAAe,EACfC,kBAAkB,QACb,kBAAiB;AAExB,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,iBAAiB,EAAEC,aAAa,QAAQ,qBAAoB;AACrE,SACEC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,gBAAgB,QACX,eAAc;AAErB,SAASC,YAAY,QAAQ,oBAAmB"}
+8
View File
@@ -0,0 +1,8 @@
/**
* Returns true only after the component has mounted on the client. Used to gate
* consent UI (CookieBanner, CookieButton) so it renders nothing during SSR /
* first paint — preventing the React 19 / Next hydration mismatch that projects
* were working around with their own setTimeout-based ConsentWrapper. Built into
* the components now, so no project wrapper is needed.
*/
export declare function useIsMounted(): boolean;
+17
View File
@@ -0,0 +1,17 @@
'use client';
import { useEffect, useState } from 'react';
/**
* Returns true only after the component has mounted on the client. Used to gate
* consent UI (CookieBanner, CookieButton) so it renders nothing during SSR /
* first paint — preventing the React 19 / Next hydration mismatch that projects
* were working around with their own setTimeout-based ConsentWrapper. Built into
* the components now, so no project wrapper is needed.
*/ export function useIsMounted() {
const [mounted, setMounted] = useState(false);
useEffect(()=>{
setMounted(true);
}, []);
return mounted;
}
//# sourceMappingURL=useIsMounted.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/consent/useIsMounted.ts"],"sourcesContent":["'use client'\nimport { useEffect, useState } from 'react'\n\n/**\n * Returns true only after the component has mounted on the client. Used to gate\n * consent UI (CookieBanner, CookieButton) so it renders nothing during SSR /\n * first paint — preventing the React 19 / Next hydration mismatch that projects\n * were working around with their own setTimeout-based ConsentWrapper. Built into\n * the components now, so no project wrapper is needed.\n */\nexport function useIsMounted(): boolean {\n const [mounted, setMounted] = useState(false)\n useEffect(() => {\n setMounted(true)\n }, [])\n return mounted\n}\n"],"names":["useEffect","useState","useIsMounted","mounted","setMounted"],"mappings":"AAAA;AACA,SAASA,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAE3C;;;;;;CAMC,GACD,OAAO,SAASC;IACd,MAAM,CAACC,SAASC,WAAW,GAAGH,SAAS;IACvCD,UAAU;QACRI,WAAW;IACb,GAAG,EAAE;IACL,OAAOD;AACT"}
+1
View File
@@ -2,6 +2,7 @@ export { buildArchiveFields } from './archiveFields.js';
export { getArchiveEntries } from './getArchiveEntries.js';
export type { ArchiveEntries } from './getArchiveEntries.js';
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
export { resolveRedirect } from './resolveRedirect.js';
export { resolveRoute } from './resolveRoute.js';
export type { ResolvedRoute } from './resolveRoute.js';
export type { ContentCollectionOption, ContentOption } from './types.js';
+1
View File
@@ -1,6 +1,7 @@
export { buildArchiveFields } from './archiveFields.js';
export { getArchiveEntries } from './getArchiveEntries.js';
export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js';
export { resolveRedirect } from './resolveRedirect.js';
export { resolveRoute } from './resolveRoute.js';
export { archiveFieldName } from './types.js';
+1 -1
View File
@@ -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 { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","getArchiveEntries","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAGhD,SAASC,gBAAgB,QAAQ,aAAY"}
+59
View File
@@ -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
View File
@@ -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
File diff suppressed because one or more lines are too long
+25
View File
@@ -0,0 +1,25 @@
import type { PayloadEmailAdapter } from 'payload';
export type GraphAdapterArgs = {
fallbackFromAddress?: string;
fallbackFromName?: string;
};
/**
* Payload email adapter that sends through Microsoft Graph (our Exchange),
* using app-only client-credentials auth. Drop-in alternative to
* panelSmtpAdapter — same PayloadEmailAdapter contract, so payload.sendEmail
* and the form-builder's submission emails work unchanged.
*
* Split of configuration (deliberate):
* - Graph credentials (tenant/client/secret/sender) = AGENCY secrets, from env.
* The client never sees or sets them — it's our Exchange, one mailbox
* (GRAPH_SENDER, e.g. [email protected]) for every project.
* - From-display + recipient = per-project, from the panel (SiteIntegrations),
* so an editor controls how the mail is labelled and where it lands.
*
* Wiring: email: process.env.GRAPH_CLIENT_ID ? graphAdapter() : panelSmtpAdapter()
*
* Azure setup (one-time, our side): App registration → Mail.Send APPLICATION
* permission → admin consent → in Exchange, grant the app "Send As" on the
* shared mailbox GRAPH_SENDER.
*/
export declare const graphAdapter: (args?: GraphAdapterArgs) => PayloadEmailAdapter;
+189
View File
@@ -0,0 +1,189 @@
import { getSiteIntegrations } from '../payload/index.js';
/** Reads + validates the agency Graph credentials from env. */ function readGraphEnv() {
const tenantId = process.env.GRAPH_TENANT_ID;
const clientId = process.env.GRAPH_CLIENT_ID;
const clientSecret = process.env.GRAPH_CLIENT_SECRET;
const sender = process.env.GRAPH_SENDER;
if (!tenantId || !clientId || !clientSecret || !sender) {
return null;
}
return {
clientId,
clientSecret,
sender,
tenantId
};
}
/**
* Fetches an app-only access token via the OAuth2 client-credentials flow.
* Scope MUST be '.../.default' — passing 'Mail.Send' directly is rejected
* (AADSTS1002012). Tokens last ~1h; we fetch per send for simplicity and to
* avoid holding state in a possibly multi-instance deployment. If you send at
* high volume, cache by expiry.
*/ async function getAccessToken(env) {
const url = `https://login.microsoftonline.com/${env.tenantId}/oauth2/v2.0/token`;
const body = new URLSearchParams({
client_id: env.clientId,
client_secret: env.clientSecret,
grant_type: 'client_credentials',
scope: 'https://graph.microsoft.com/.default'
});
const res = await fetch(url, {
body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST'
});
if (!res.ok) {
const detail = await res.text();
throw new Error(`Graph token request failed (${res.status}): ${detail}`);
}
const data = await res.json();
if (!data.access_token) {
throw new Error('Graph token response had no access_token');
}
return data.access_token;
}
/** Normalizes Payload's to/cc (string | string[] | Address[]) into Graph recipients. */ function toRecipients(value) {
if (!value) {
return [];
}
const list = Array.isArray(value) ? value : [
value
];
return list.map((v)=>typeof v === 'string' ? v : v.address).filter((a)=>typeof a === 'string' && a.length > 0).map((address)=>({
emailAddress: {
address
}
}));
}
/**
* Payload email adapter that sends through Microsoft Graph (our Exchange),
* using app-only client-credentials auth. Drop-in alternative to
* panelSmtpAdapter — same PayloadEmailAdapter contract, so payload.sendEmail
* and the form-builder's submission emails work unchanged.
*
* Split of configuration (deliberate):
* - Graph credentials (tenant/client/secret/sender) = AGENCY secrets, from env.
* The client never sees or sets them — it's our Exchange, one mailbox
* (GRAPH_SENDER, e.g. [email protected]) for every project.
* - From-display + recipient = per-project, from the panel (SiteIntegrations),
* so an editor controls how the mail is labelled and where it lands.
*
* Wiring: email: process.env.GRAPH_CLIENT_ID ? graphAdapter() : panelSmtpAdapter()
*
* Azure setup (one-time, our side): App registration → Mail.Send APPLICATION
* permission → admin consent → in Exchange, grant the app "Send As" on the
* shared mailbox GRAPH_SENDER.
*/ export const graphAdapter = (args = {})=>({ payload })=>({
name: 'ipal-graph',
defaultFromAddress: args.fallbackFromAddress ?? 'noreply@localhost',
defaultFromName: args.fallbackFromName ?? 'Website',
sendEmail: async (message)=>{
const env = readGraphEnv();
if (!env) {
payload.logger.error('[ipal] Email not sent: Graph is not configured. Set GRAPH_TENANT_ID, GRAPH_CLIENT_ID, GRAPH_CLIENT_SECRET, GRAPH_SENDER.');
return {
error: 'Graph is not configured (missing env vars).',
sent: false
};
}
// Display name on the From, WITHOUT triggering Send-As.
//
// The trick: we may set a `from` as long as its ADDRESS stays the sender
// mailbox (GRAPH_SENDER) — only the display NAME changes. Exchange only
// demands Send-As when the from ADDRESS differs from the mailbox, so a
// same-address / custom-name From is allowed and gives each project its
// own sender label (e.g. "Kancelaria Kędzierski") over the shared mailbox.
//
// The panel's from-address becomes Reply-To (so replies reach the client),
// and the panel's from-name becomes the sender display name.
const panel = await getSiteIntegrations(payload);
const replyToAddress = panel.smtpFromAddress || undefined;
const senderName = panel.smtpFromName || undefined;
const to = toRecipients(message.to);
if (to.length === 0) {
payload.logger.error('[ipal] Email not sent: no valid recipient.');
return {
error: 'No valid recipient.',
sent: false
};
}
// Graph accepts either HTML or Text; Payload gives us html and/or text.
const isHtml = typeof message.html === 'string' && message.html.length > 0;
const content = isHtml ? String(message.html) : String(message.text ?? '');
// Reply-To: prefer whatever the caller set; otherwise the panel address.
const replyTo = message.replyTo ? toRecipients(message.replyTo) : replyToAddress ? [
{
emailAddress: {
address: replyToAddress
}
}
] : [];
const graphMessage = {
body: {
content,
contentType: isHtml ? 'HTML' : 'Text'
},
subject: message.subject ?? '',
toRecipients: to,
...message.cc ? {
ccRecipients: toRecipients(message.cc)
} : {},
...message.bcc ? {
bccRecipients: toRecipients(message.bcc)
} : {},
// From with the sender's OWN address (no Send-As) plus an optional
// display name from the panel. Omit entirely when no name is set —
// Graph then uses the mailbox's default name.
...senderName ? {
from: {
emailAddress: {
name: senderName,
address: env.sender
}
}
} : {},
...replyTo.length > 0 ? {
replyTo
} : {}
};
try {
const token = await getAccessToken(env);
// App-only: MUST target /users/{sender}, never /me.
const res = await fetch(`https://graph.microsoft.com/v1.0/users/${encodeURIComponent(env.sender)}/sendMail`, {
body: JSON.stringify({
message: graphMessage,
saveToSentItems: false
}),
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
method: 'POST'
});
// sendMail returns 202 Accepted with an empty body on success.
if (res.status === 202) {
return {
sent: true
};
}
const detail = await res.text();
payload.logger.error(`[ipal] Graph sendMail failed (${res.status}): ${detail}`);
return {
error: `Graph sendMail failed (${res.status}).`,
sent: false
};
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
payload.logger.error(`[ipal] Graph send error: ${msg}`);
return {
error: 'Graph send error.',
sent: false
};
}
}
});
//# sourceMappingURL=graphAdapter.js.map
File diff suppressed because one or more lines are too long
+4
View File
@@ -1,2 +1,6 @@
export { graphAdapter } from './graphAdapter.js';
export type { GraphAdapterArgs } from './graphAdapter.js';
export { mailAdapter } from './mailAdapter.js';
export type { MailAdapterArgs } from './mailAdapter.js';
export { sendEmail } from './sendEmail.js';
export type { SendEmailArgs, SendEmailResult } from './sendEmail.js';
+2
View File
@@ -1,3 +1,5 @@
export { graphAdapter } from './graphAdapter.js';
export { mailAdapter } from './mailAdapter.js';
// Server-only exports. sendEmail imports 'server-only' (SMTP password, nodemailer)
// so this must never be imported from a client component.
export { sendEmail } from './sendEmail.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/email/index.ts"],"sourcesContent":["// Server-only exports. sendEmail imports 'server-only' (SMTP password, nodemailer)\n// so this must never be imported from a client component.\nexport { sendEmail } from './sendEmail.js'\nexport type { SendEmailArgs, SendEmailResult } from './sendEmail.js'\n"],"names":["sendEmail"],"mappings":"AAAA,mFAAmF;AACnF,0DAA0D;AAC1D,SAASA,SAAS,QAAQ,iBAAgB"}
{"version":3,"sources":["../../../src/modules/email/index.ts"],"sourcesContent":["export { graphAdapter } from './graphAdapter.js'\nexport type { GraphAdapterArgs } from './graphAdapter.js'\nexport { mailAdapter } from './mailAdapter.js'\nexport type { MailAdapterArgs } from './mailAdapter.js'\n// Server-only exports. sendEmail imports 'server-only' (SMTP password, nodemailer)\n// so this must never be imported from a client component.\nexport { sendEmail } from './sendEmail.js'\nexport type { SendEmailArgs, SendEmailResult } from './sendEmail.js'\n"],"names":["graphAdapter","mailAdapter","sendEmail"],"mappings":"AAAA,SAASA,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,mFAAmF;AACnF,0DAA0D;AAC1D,SAASC,SAAS,QAAQ,iBAAgB"}
+28
View File
@@ -0,0 +1,28 @@
import type { PayloadEmailAdapter } from 'payload';
import { type GraphAdapterArgs } from './graphAdapter.js';
import { type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js';
export type MailAdapterArgs = {
fallbackFromAddress?: string;
fallbackFromName?: string;
graph?: GraphAdapterArgs;
smtp?: PanelSmtpAdapterArgs;
};
/**
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
* (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations.
* This is what makes the choice switchable in the panel — Payload builds the
* email adapter at boot and can't swap it at runtime, so instead of choosing
* between two adapters at boot we install one that delegates on every send.
*
* Availability guard: Graph only runs if its agency credentials exist in env
* (this is *our* Exchange). If the panel says 'graph' but env isn't set up,
* we DON'T silently fail — we log clearly and fall back to SMTP, so a client
* flipping the switch without the backing config still gets mail out (over SMTP)
* rather than silent nothing. If neither is usable, the send reports an error.
*
* @example
* // payload.config.ts
* import { mailAdapter } from '@intecion/ipal-kit'
* email: mailAdapter()
*/
export declare const mailAdapter: (args?: MailAdapterArgs) => PayloadEmailAdapter;
+58
View File
@@ -0,0 +1,58 @@
import { getSiteIntegrations } from '../payload/index.js';
import { graphAdapter } from './graphAdapter.js';
import { panelSmtpAdapter } from './panelSmtpAdapter.js';
/** True when the agency Graph credentials are present in the environment. */ function graphAvailable() {
return Boolean(process.env.GRAPH_TENANT_ID && process.env.GRAPH_CLIENT_ID && process.env.GRAPH_CLIENT_SECRET && process.env.GRAPH_SENDER);
}
/**
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
* (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations.
* This is what makes the choice switchable in the panel — Payload builds the
* email adapter at boot and can't swap it at runtime, so instead of choosing
* between two adapters at boot we install one that delegates on every send.
*
* Availability guard: Graph only runs if its agency credentials exist in env
* (this is *our* Exchange). If the panel says 'graph' but env isn't set up,
* we DON'T silently fail — we log clearly and fall back to SMTP, so a client
* flipping the switch without the backing config still gets mail out (over SMTP)
* rather than silent nothing. If neither is usable, the send reports an error.
*
* @example
* // payload.config.ts
* import { mailAdapter } from '@intecion/ipal-kit'
* email: mailAdapter()
*/ export const mailAdapter = (args = {})=>(deps)=>{
// Build both delegates once; each still resolves its own config per send.
const smtp = panelSmtpAdapter({
fallbackFromAddress: args.fallbackFromAddress,
fallbackFromName: args.fallbackFromName,
...args.smtp
})(deps);
const graph = graphAdapter({
fallbackFromAddress: args.fallbackFromAddress,
fallbackFromName: args.fallbackFromName,
...args.graph
})(deps);
const { payload } = deps;
return {
name: 'ipal-mail-dispatcher',
defaultFromAddress: smtp.defaultFromAddress,
defaultFromName: smtp.defaultFromName,
sendEmail: async (message)=>{
const settings = await getSiteIntegrations(payload);
const choice = settings.emailTransport ?? 'smtp';
if (choice === 'graph') {
if (graphAvailable()) {
return graph.sendEmail(message);
}
// Panel asked for Graph but the agency creds aren't configured for
// this project. Fall back to SMTP rather than silently dropping mail.
payload.logger.warn('[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.');
return smtp.sendEmail(message);
}
return smtp.sendEmail(message);
}
};
};
//# sourceMappingURL=mailAdapter.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/email/mailAdapter.ts"],"sourcesContent":["import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'\n\nimport { getSiteIntegrations } from '../payload/index.js'\nimport { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'\nimport { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'\n\ntype TransportIntegrations = {\n /** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */\n emailTransport?: 'graph' | 'smtp' | null\n}\n\nexport type MailAdapterArgs = {\n fallbackFromAddress?: string\n fallbackFromName?: string\n graph?: GraphAdapterArgs\n smtp?: PanelSmtpAdapterArgs\n}\n\n/** True when the agency Graph credentials are present in the environment. */\nfunction graphAvailable(): boolean {\n return Boolean(\n process.env.GRAPH_TENANT_ID &&\n process.env.GRAPH_CLIENT_ID &&\n process.env.GRAPH_CLIENT_SECRET &&\n process.env.GRAPH_SENDER,\n )\n}\n\n/**\n * Dispatcher email adapter: wired into the config ONCE, but picks the transport\n * (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations.\n * This is what makes the choice switchable in the panel — Payload builds the\n * email adapter at boot and can't swap it at runtime, so instead of choosing\n * between two adapters at boot we install one that delegates on every send.\n *\n * Availability guard: Graph only runs if its agency credentials exist in env\n * (this is *our* Exchange). If the panel says 'graph' but env isn't set up,\n * we DON'T silently fail — we log clearly and fall back to SMTP, so a client\n * flipping the switch without the backing config still gets mail out (over SMTP)\n * rather than silent nothing. If neither is usable, the send reports an error.\n *\n * @example\n * // payload.config.ts\n * import { mailAdapter } from '@intecion/ipal-kit'\n * email: mailAdapter()\n */\nexport const mailAdapter =\n (args: MailAdapterArgs = {}): PayloadEmailAdapter =>\n (deps) => {\n // Build both delegates once; each still resolves its own config per send.\n const smtp = panelSmtpAdapter({\n fallbackFromAddress: args.fallbackFromAddress,\n fallbackFromName: args.fallbackFromName,\n ...args.smtp,\n })(deps)\n const graph = graphAdapter({\n fallbackFromAddress: args.fallbackFromAddress,\n fallbackFromName: args.fallbackFromName,\n ...args.graph,\n })(deps)\n\n const { payload } = deps\n\n return {\n name: 'ipal-mail-dispatcher',\n defaultFromAddress: smtp.defaultFromAddress,\n defaultFromName: smtp.defaultFromName,\n\n sendEmail: async (message: SendEmailOptions) => {\n const settings = await getSiteIntegrations<TransportIntegrations>(payload)\n const choice = settings.emailTransport ?? 'smtp'\n\n if (choice === 'graph') {\n if (graphAvailable()) {\n return graph.sendEmail(message)\n }\n // Panel asked for Graph but the agency creds aren't configured for\n // this project. Fall back to SMTP rather than silently dropping mail.\n payload.logger.warn(\n '[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',\n )\n return smtp.sendEmail(message)\n }\n\n return smtp.sendEmail(message)\n },\n }\n }\n"],"names":["getSiteIntegrations","graphAdapter","panelSmtpAdapter","graphAvailable","Boolean","process","env","GRAPH_TENANT_ID","GRAPH_CLIENT_ID","GRAPH_CLIENT_SECRET","GRAPH_SENDER","mailAdapter","args","deps","smtp","fallbackFromAddress","fallbackFromName","graph","payload","name","defaultFromAddress","defaultFromName","sendEmail","message","settings","choice","emailTransport","logger","warn"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,sBAAqB;AACzD,SAASC,YAAY,QAA+B,oBAAmB;AACvE,SAASC,gBAAgB,QAAmC,wBAAuB;AAcnF,2EAA2E,GAC3E,SAASC;IACP,OAAOC,QACLC,QAAQC,GAAG,CAACC,eAAe,IAC3BF,QAAQC,GAAG,CAACE,eAAe,IAC3BH,QAAQC,GAAG,CAACG,mBAAmB,IAC/BJ,QAAQC,GAAG,CAACI,YAAY;AAE5B;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMC,cACX,CAACC,OAAwB,CAAC,CAAC,GAC3B,CAACC;QACC,0EAA0E;QAC1E,MAAMC,OAAOZ,iBAAiB;YAC5Ba,qBAAqBH,KAAKG,mBAAmB;YAC7CC,kBAAkBJ,KAAKI,gBAAgB;YACvC,GAAGJ,KAAKE,IAAI;QACd,GAAGD;QACH,MAAMI,QAAQhB,aAAa;YACzBc,qBAAqBH,KAAKG,mBAAmB;YAC7CC,kBAAkBJ,KAAKI,gBAAgB;YACvC,GAAGJ,KAAKK,KAAK;QACf,GAAGJ;QAEH,MAAM,EAAEK,OAAO,EAAE,GAAGL;QAEpB,OAAO;YACLM,MAAM;YACNC,oBAAoBN,KAAKM,kBAAkB;YAC3CC,iBAAiBP,KAAKO,eAAe;YAErCC,WAAW,OAAOC;gBAChB,MAAMC,WAAW,MAAMxB,oBAA2CkB;gBAClE,MAAMO,SAASD,SAASE,cAAc,IAAI;gBAE1C,IAAID,WAAW,SAAS;oBACtB,IAAItB,kBAAkB;wBACpB,OAAOc,MAAMK,SAAS,CAACC;oBACzB;oBACA,mEAAmE;oBACnE,sEAAsE;oBACtEL,QAAQS,MAAM,CAACC,IAAI,CACjB;oBAEF,OAAOd,KAAKQ,SAAS,CAACC;gBACxB;gBAEA,OAAOT,KAAKQ,SAAS,CAACC;YACxB;QACF;IACF,EAAC"}
+15
View File
@@ -0,0 +1,15 @@
import type { Endpoint } from 'payload';
/**
* Custom endpoint: send a test email to a given address through whatever
* transport is currently active (SMTP or Graph — mailAdapter reads the panel
* setting per send, so the test exercises the REAL path a form email would
* take). Mounted at POST /api/ipal/test-email.
*
* Admin-only: uses payload.sendEmail (server-side), and requires an
* authenticated admin user — a test-send button must never be open to the
* public (it would be an open relay / spam vector).
*
* Returns the adapter's own result so the panel can show exactly what happened,
* including the transport-specific error (SMTP auth failure, Graph 401, etc.).
*/
export declare const testEmailEndpoint: Endpoint;
+74
View File
@@ -0,0 +1,74 @@
import { addDataAndFileToRequest } from 'payload';
/**
* Custom endpoint: send a test email to a given address through whatever
* transport is currently active (SMTP or Graph — mailAdapter reads the panel
* setting per send, so the test exercises the REAL path a form email would
* take). Mounted at POST /api/ipal/test-email.
*
* Admin-only: uses payload.sendEmail (server-side), and requires an
* authenticated admin user — a test-send button must never be open to the
* public (it would be an open relay / spam vector).
*
* Returns the adapter's own result so the panel can show exactly what happened,
* including the transport-specific error (SMTP auth failure, Graph 401, etc.).
*/ export const testEmailEndpoint = {
handler: async (req)=>{
// Auth: only signed-in admins may trigger a send.
if (!req.user) {
return Response.json({
error: 'Unauthorized',
ok: false
}, {
status: 401
});
}
await addDataAndFileToRequest(req);
const to = req.data?.to?.trim();
if (!to || !/^[^@\s]+@[^\s@][^\s.@]*\.[^\s@]+$/.test(to)) {
return Response.json({
error: 'Provide a valid recipient address.',
ok: false
}, {
status: 400
});
}
try {
const info = await req.payload.sendEmail({
html: '<p>This is a test message from <strong>ipal-kit</strong>. If you received it, outbound email is configured correctly.</p>',
subject: 'ipal-kit — test email',
text: 'This is a test message from ipal-kit. If you received it, outbound email is configured correctly.',
to
});
// Payload's sendEmail resolves with the adapter's result. Our adapters
// return { sent: boolean, error?: string }; nodemailer returns info with
// messageId. Normalize to a simple ok/message for the panel.
const sent = info && typeof info === 'object' && 'sent' in info ? info.sent !== false : true;
if (!sent) {
const error = info?.error ?? 'Send failed (see server logs).';
return Response.json({
error,
ok: false
}, {
status: 502
});
}
return Response.json({
message: `Test email sent to ${to}.`,
ok: true
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
req.payload.logger.error(`[ipal] Test email failed: ${message}`);
return Response.json({
error: 'Send failed. Check transport settings and server logs.',
ok: false
}, {
status: 502
});
}
},
method: 'post',
path: '/ipal/test-email'
};
//# sourceMappingURL=testEmailEndpoint.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/modules/email/test/testEmailEndpoint.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload'\n\nimport { addDataAndFileToRequest } from 'payload'\n\n/**\n * Custom endpoint: send a test email to a given address through whatever\n * transport is currently active (SMTP or Graph — mailAdapter reads the panel\n * setting per send, so the test exercises the REAL path a form email would\n * take). Mounted at POST /api/ipal/test-email.\n *\n * Admin-only: uses payload.sendEmail (server-side), and requires an\n * authenticated admin user — a test-send button must never be open to the\n * public (it would be an open relay / spam vector).\n *\n * Returns the adapter's own result so the panel can show exactly what happened,\n * including the transport-specific error (SMTP auth failure, Graph 401, etc.).\n */\nexport const testEmailEndpoint: Endpoint = {\n handler: async (req: PayloadRequest) => {\n // Auth: only signed-in admins may trigger a send.\n if (!req.user) {\n return Response.json({ error: 'Unauthorized', ok: false }, { status: 401 })\n }\n\n await addDataAndFileToRequest(req)\n const to = (req.data?.to as string | undefined)?.trim()\n\n if (!to || !/^[^@\\s]+@[^\\s@][^\\s.@]*\\.[^\\s@]+$/.test(to)) {\n return Response.json(\n { error: 'Provide a valid recipient address.', ok: false },\n { status: 400 },\n )\n }\n\n try {\n const info = await req.payload.sendEmail({\n html: '<p>This is a test message from <strong>ipal-kit</strong>. If you received it, outbound email is configured correctly.</p>',\n subject: 'ipal-kit — test email',\n text: 'This is a test message from ipal-kit. If you received it, outbound email is configured correctly.',\n to,\n })\n\n // Payload's sendEmail resolves with the adapter's result. Our adapters\n // return { sent: boolean, error?: string }; nodemailer returns info with\n // messageId. Normalize to a simple ok/message for the panel.\n const sent =\n info && typeof info === 'object' && 'sent' in info\n ? (info as { sent?: boolean }).sent !== false\n : true\n\n if (!sent) {\n const error = (info as { error?: string })?.error ?? 'Send failed (see server logs).'\n return Response.json({ error, ok: false }, { status: 502 })\n }\n\n return Response.json({ message: `Test email sent to ${to}.`, ok: true })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n req.payload.logger.error(`[ipal] Test email failed: ${message}`)\n return Response.json(\n { error: 'Send failed. Check transport settings and server logs.', ok: false },\n { status: 502 },\n )\n }\n },\n method: 'post',\n path: '/ipal/test-email',\n}\n"],"names":["addDataAndFileToRequest","testEmailEndpoint","handler","req","user","Response","json","error","ok","status","to","data","trim","test","info","payload","sendEmail","html","subject","text","sent","message","err","Error","String","logger","method","path"],"mappings":"AAEA,SAASA,uBAAuB,QAAQ,UAAS;AAEjD;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,oBAA8B;IACzCC,SAAS,OAAOC;QACd,kDAAkD;QAClD,IAAI,CAACA,IAAIC,IAAI,EAAE;YACb,OAAOC,SAASC,IAAI,CAAC;gBAAEC,OAAO;gBAAgBC,IAAI;YAAM,GAAG;gBAAEC,QAAQ;YAAI;QAC3E;QAEA,MAAMT,wBAAwBG;QAC9B,MAAMO,KAAMP,IAAIQ,IAAI,EAAED,IAA2BE;QAEjD,IAAI,CAACF,MAAM,CAAC,oCAAoCG,IAAI,CAACH,KAAK;YACxD,OAAOL,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAAsCC,IAAI;YAAM,GACzD;gBAAEC,QAAQ;YAAI;QAElB;QAEA,IAAI;YACF,MAAMK,OAAO,MAAMX,IAAIY,OAAO,CAACC,SAAS,CAAC;gBACvCC,MAAM;gBACNC,SAAS;gBACTC,MAAM;gBACNT;YACF;YAEA,uEAAuE;YACvE,yEAAyE;YACzE,6DAA6D;YAC7D,MAAMU,OACJN,QAAQ,OAAOA,SAAS,YAAY,UAAUA,OAC1C,AAACA,KAA4BM,IAAI,KAAK,QACtC;YAEN,IAAI,CAACA,MAAM;gBACT,MAAMb,QAAQ,AAACO,MAA6BP,SAAS;gBACrD,OAAOF,SAASC,IAAI,CAAC;oBAAEC;oBAAOC,IAAI;gBAAM,GAAG;oBAAEC,QAAQ;gBAAI;YAC3D;YAEA,OAAOJ,SAASC,IAAI,CAAC;gBAAEe,SAAS,CAAC,mBAAmB,EAAEX,GAAG,CAAC,CAAC;gBAAEF,IAAI;YAAK;QACxE,EAAE,OAAOc,KAAK;YACZ,MAAMD,UAAUC,eAAeC,QAAQD,IAAID,OAAO,GAAGG,OAAOF;YAC5DnB,IAAIY,OAAO,CAACU,MAAM,CAAClB,KAAK,CAAC,CAAC,0BAA0B,EAAEc,SAAS;YAC/D,OAAOhB,SAASC,IAAI,CAClB;gBAAEC,OAAO;gBAA0DC,IAAI;YAAM,GAC7E;gBAAEC,QAAQ;YAAI;QAElB;IACF;IACAiB,QAAQ;IACRC,MAAM;AACR,EAAC"}
+49
View File
@@ -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;
+101
View File
@@ -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
File diff suppressed because one or more lines are too long
+4
View File
@@ -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';
+4
View File
@@ -0,0 +1,4 @@
export { assertEnv } from './assertEnv.js';
export { ipalEnvRules } from './ipalEnvRules.js';
//# sourceMappingURL=index.js.map
+1
View File
@@ -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"}
+44
View File
@@ -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 {};
+95
View File
@@ -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
File diff suppressed because one or more lines are too long
+46
View File
@@ -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;
+50
View File
@@ -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
+1
View File
@@ -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"}
+7
View File
@@ -1,8 +1,15 @@
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';
export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js';
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js';
export { useContactForm } from './useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js';
export { useForm } from './useForm.js';
export type { FormErrors, FormSubmitAction, Validator } from './useForm.js';
export { validateSubmission } from './validateSubmission.js';
export type { FormValidationResult } from './validateSubmission.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './validators.js';
export type { Rule } from './validators.js';
+7
View File
@@ -1,8 +1,15 @@
// 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';
// Generic form engine (any field set) + the standard contact-form preset.
export { useForm } from './useForm.js';
export { validateSubmission } from './validateSubmission.js';
// Composable validation rules (pure — safe on server or client).
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './validators.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -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 { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,kBAAkB,QAAQ,0BAAyB"}
{"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'\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":["buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","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,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"}

Some files were not shown because too many files have changed in this diff Show More