Compare commits

..
22 Commits
Author SHA1 Message Date
radoslaw.smolinski 0069b28941 1.9.3
CI / check (push) Canceled after 0s
2026-10-16 12:56:14 +02:00
radoslaw.smolinskiandClaude Opus 5.5 3da9d6b1d0 Merge 1.9.3: audit catches hand-rolled links
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 12:56:13 +02:00
radoslaw.smolinskiandClaude Opus 5.5 eb52253dc4 Audit: catch hand-rolled link resolution (hardcoded homepage slug, URL built from a slug); comment filter fix
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 12:56:13 +02:00
radoslaw.smolinski f88c342be5 1.9.2
CI / check (push) Canceled after 0s
2026-10-16 11:52:43 +02:00
radoslaw.smolinskiandClaude Opus 5.5 293cd9a541 Merge 1.9.2: import instead of code
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 11:52:42 +02:00
radoslaw.smolinskiandClaude Opus 5.5 81e864bde9 Docs for 1.9.2: import instead of code; docs↔code consistency test; audit accepts one-line routes
- AGENT.md: §7 full capability catalog (need → import), §0b/§3/§6 on RenderForm, SiteProviders,
  createPageRoute, re-exported routes, plugin section fields, resolveLink/resolveNav
- PROGRAMISTA §2.4, §2.7–2.8 rewritten; §6 items 28–33 (28: FormRenderer leaked the Emails tab)
- forms, links, blocks, pages, consent, turnstile, notifications, seo, mcp, i18n, deployment docs
- ipal-form: RenderForm block, formClasses, CustomForm example (FormRenderer template removed),
  seed template handles steps and option labels per language
- ipal-nav, ipal-block, ipal-setup, ipal-upgrade, ipal-seo-check, ipal-consent-check, vibe.md
- ipal-audit: re-export routes and SiteProviders satisfy the mandatory set; flags form-engine copies,
  project section fields / navigation, server entries in client components
- test/docsConsistency: docs imports exist in code; every public export is documented
- CHANGELOG 1.9.2

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 11:52:29 +02:00
radoslaw.smolinskiandClaude Opus 5.5 412bf953a8 Import instead of code: panel forms (steps, choice lists, dates), layout, page route, GEO routes, links, section fields
- Forms: step and checkboxGroup field types (radio, date on), server validation for them,
  useBuilderForm (logic) + BuilderForm (unstyled default) + RenderForm (/rsc: rich text,
  bound action, public part of the form only — the Emails tab never reaches the browser)
- Notifications: next / back / stepOf texts
- createContentHelpers: getSiteShell, getFormTexts, getLinkOptions, resolveLink, resolveNav,
  resolvePageRedirect, one-line route handlers (llms, llms-full, md, mcp, health, indexnow, manifest)
- /rsc: SiteProviders, createPageRoute, createNotFoundPage
- resolveLink / resolveNav / homeSlugFrom, buildSectionHeaderField / buildSectionSettingsField
- Dev sandbox frontend built on these imports; tests (unit + real Payload)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 11:32:46 +02:00
radoslaw.smolinskiandClaude Opus 5.5 0cfd846dd1 Changelog: history back to 1.7.4, keep at least 20 versions
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 10:59:38 +02:00
radoslaw.smolinski 800ba30200 1.9.1
CI / check (push) Canceled after 0s
2026-10-16 10:56:18 +02:00
radoslaw.smolinskiandClaude Opus 5.5 0c5c6ac3e3 Merge 1.9.1: SEO/GEO, consent, security, forms seed, media, fluid
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 10:56:17 +02:00
radoslaw.smolinskiandClaude Opus 5.5 e301ff3d00 Release as 1.9.1 instead of 1.10.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 10:56:16 +02:00
radoslaw.smolinskiandClaude Opus 5.5 3986e70e5f Dev sandbox: enable consent log
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:27:13 +02:00
radoslaw.smolinskiandClaude Opus 5.5 de929422bb Docs for 1.10: mandatory set (18 items), setup skill, reference code, module docs, changelog
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:25:58 +02:00
radoslaw.smolinskiandClaude Opus 5.5 f52fbe6b12 Audits: performance, responsive and new mandatory items; seo-check content checks
ipal-audit: <video> outside Media, priority outside the hero, <Media> without
sizes, raw YouTube iframes, 100vh/h-screen, fixed pixel sizes, page JSON-LD,
upload sandbox headers, images preset, missing form seeds; accepts
createMarkdownRoute / createSubmitAction.
ipal-seo-check: exactly one h1, heading jumps, img alt and dimensions, LCP
priority, og:image, thin pages, internal links, X-Robots-Tag noindex left on
in production. Verified on bad and good fixtures.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:22:55 +02:00
radoslaw.smolinskiandClaude Opus 5.5 69309b09e3 Fluid scaling to 1920px and height-aware variables; speed and responsive guidelines
- fluid-wide.css: the fluid.css variables stretched over 360→1920px (export
  @intecion/ipal-kit/fluid-wide.css); fluid.css values unchanged.
- New variables in both (unused until a project opts in): --ipal-measure,
  --ipal-container(-wide), --ipal-hero-min-h (svh), --ipal-fs-display-fit,
  --ipal-fs-h1-fit, --ipal-space-section-fit — keep the hero CTA above the fold
  on 1366×768. Verified in Chromium at 360…1920 widths.
- AGENT.md §6.11a (scaling, viewport test list incl. 13–15" laptops and 125/150 %
  zoom) and §6.11b (Core Web Vitals table: LCP image, sizes, placeholders, video
  modes, YouTube facade, images preset, fonts).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:21:38 +02:00
radoslaw.smolinskiandClaude Opus 5.5 55fc27a13f Media performance tools: image/video props, upload placeholders, images preset, YouTube facade
Headless helpers for the project's own <Media> (look stays in the project):
- mediaImageProps: dimensions from the doc (no CLS), lazy by default, LCP image
  gets preload + fetchPriority=high + eager (Next 16 replaced 'priority'),
  focal point → object-position, blur placeholder + dominant colour.
- MEDIA_SIZES suggestions for 'sizes' (any string still works).
- videoProps: 'background' (muted loop, respects reduced motion) or 'player'
  (controls, preload=none, poster).
- buildMediaPlaceholderHook/Field: tiny WebP blur + dominant colour at upload
  via the configured sharp (no new dependency).
- buildImagesConfig: AVIF/WebP, R2 remotePatterns, 31-day cache.
- <YouTubeEmbed> (/client): poster + button, youtube-nocookie iframe on click.
- buildCsp youtube allows the i.ytimg.com poster. kod-sekcji Media template
  uses the helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:19:38 +02:00
radoslaw.smolinskiandClaude Opus 5.5 f7466cf77f noindex tooling, content/noindex/component/testing guidelines for agents
- IPAL_NOINDEX=1: whole-site noindex for staging (robots Disallow /, robots
  meta noindex,nofollow, X-Robots-Tag via buildSecurityHeaders).
- Markdown mirrors and llms files: X-Robots-Tag noindex; Markdown adds a
  Link rel=canonical to the HTML page.
- buildNoindexField refuses noindex on the homepage and archive pages.
- AGENT.md §0c: writing pages for Google and AI (structure, answer-first,
  facts, E-E-A-T, entity consistency, sameAs, aiSummary, meta) and a
  when-to-noindex table (legal pages stay indexed by default; drafts instead
  of noindexed pages; staging via env).
- AGENT.md §6.0: ten component rules (small, Button styled once, buttons as
  '+ Add Button' array, variants, panel clarity); audit warns on buttons
  styled inside sections.
- AGENT.md §8a + smoke.spec.template.ts: what to test in a client project;
  PROGRAMISTA §8.1a: how the plugin itself is tested.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:13:44 +02:00
radoslaw.smolinskiandClaude Opus 5.5 8e2dd28b83 Form seed template: fields, confirmation, company notification and sender confirmation in every language
The ipal-form skill now requires seeding each form (scripts/seed-form-*.ts):
idempotent, reads the notification inbox from the panel and stops without
one, adds both e-mails ({{email}} is safe since submitForm accepts exactly one
address). Verified on the dev sandbox in pl + en. Dev sandbox enables forms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:08:56 +02:00
radoslaw.smolinskiandClaude Opus 5.5 9e49856611 Security review: drafts no longer public, submissions staff-only, safe links, upload sandbox
- Fix: resolveRoute served never-published drafts by URL (Payload's find
  returns them with _status 'draft') — also via Markdown, MCP get_page and
  metadata. Drafts are dropped on every branch; `draft: true` for previews.
- Fix: getArchiveEntries listed drafts in archive pages despite its comment;
  `_status: published` is added automatically when the collection has drafts.
- form-submissions readable only by editor+ (form-builder default: any account
  of the admin collection, incl. plain users from an open sign-up); delete admin.
- Forms stay public for rendering, but the Emails tab (recipients) is hidden
  from anonymous REST reads.
- safeHref: CMS links only http(s), mailto, tel, sms, #, / — javascript:, data:
  and control-character tricks are dropped in resolveLinkHref.
- Analytics IDs validated in the panel and before reaching the browser.
- buildUploadSecurityHeaders: sandbox CSP for /api/<upload>/file/* so an
  uploaded SVG can't run script on the site's origin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:06:26 +02:00
radoslaw.smolinskiandClaude Opus 5.5 ebf70d49bd Consent: withdrawal clears tool cookies, policy version, consent log, cookie scan; form input hardening
Consent (GDPR)
- Withdrawing consent now deletes GA/Meta/Ads/Clarity/LinkedIn/TikTok/Hotjar
  cookies (prefix patterns) on the host AND parent domains — previously only
  the locale cookie was removed and _ga & co. stayed. Projects extend the list
  via <ConsentProvider cookieMap>, merged with the defaults.
- Cookie Settings → Policy version: raising it asks every visitor again.
- <CookieBanner equalChoice>: Reject styled like Accept (UODO/EDPB), opt-in.
- Opt-in consent log (ipalKit({ consentLog: true }) + logEndpoint): random id,
  choices, version, time — no IP/UA; admin-only collection, retention purge.
- Cookie Settings → Cookies + getCookieTable + unstyled <CookieTable> (/rsc).
- Consent cookie gets Secure on HTTPS; consent id stored with the decision.
- ipal-consent-check: cookie-scan.mjs (before/after consent, known-tool
  catalog PL/EN, flags non-necessary cookies set before consent) and
  import-cookies.ts into the panel (idempotent, keeps editor edits).

Forms
- Server-side type checks per field from the panel definition: email = one
  address (blocks "a@x, b@y" recipient injection into {{email}} confirmations
  and CR/LF header injection), select/radio only configured options, numbers,
  booleans; objects/arrays rejected; control and bidi characters stripped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 02:31:58 +02:00
radoslaw.smolinskiandClaude Opus 5.5 c9a50abc33 SEO/GEO tools and project requests: site index, IndexNow, page JSON-LD, fixes
GEO / SEO
- collectSiteIndex: one list of public docs per locale (pages + archive
  entries) on sitemap rules; llms.txt/llms-full and MCP list_pages now include
  blog/content entries and every language. Fixes hard-coded "## Strony" heading
  and homepage not collapsing to the locale root in llms.txt.
- Markdown frontmatter: canonical url + updated date.
- Metadata: X/Twitter card, OG image width/height/alt, og:type article with
  published/modified times for entries.
- Fix: Site Settings "defaultShareImage" was never used — now the OG fallback.
- getPageJsonLd (createContentHelpers): WebPage/CollectionPage/BlogPosting,
  BreadcrumbList from the real route, FAQPage via a project mapper.
- IndexNow (opt-in ipalKit({ indexNow: true })): submit published URLs in all
  languages, key generated in Site Integrations or INDEXNOW_KEY, key route.
- sameAs profiles in Site Settings + sameAsUrls(); sitemap <image:image>.

From project reports
- Fix: package exports were missing ./env and ./fluid.css although the docs
  import them (TS2307); regression test checks every documented subpath.
- Fix: plugins run before Payload adds its default users collection, so roles
  and 2FA had nothing to attach to — ipalKit injects an auth collection when
  the project has none (project's own one wins). Audit no longer errors on it.
- createMarkdownRoute, createSubmitAction (/server, headers injected).
- formatOpeningHours (PL/EN/DE text → schema.org), used by
  buildLocalBusinessJsonLd, which also takes a schema.org `type`.
- buildNavigationJsonLd straight from the header global.
- buildCsp googleMaps: full Maps JS API domain set; values de-duplicated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 02:19:08 +02:00
radoslaw.smolinskiandClaude Opus 5.5 9e40d74bb3 Normalize bin path (npm pkg fix) to silence publish warning
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 01:27:21 +02:00
147 changed files with 7532 additions and 835 deletions
@@ -0,0 +1,18 @@
import { notFound, permanentRedirect } from 'next/navigation.js'
import { createPageRoute } from '@intecion/ipal-kit/rsc'
import { FormBlock } from '../../../../blocks/FormBlock.js'
import * as content from '../../../../lib/content.js'
import { sendForm } from '../actions.js'
export const revalidate = 3600
const route = createPageRoute(content, {
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
blocks: { formBlock: FormBlock },
notFound,
permanentRedirect,
})
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams
+7
View File
@@ -0,0 +1,7 @@
'use server'
import { headers } from 'next/headers.js'
import { createSubmitAction } from '@intecion/ipal-kit/server'
import { getCachedPayload } from '../../../lib/content.js'
export const sendForm = createSubmitAction({ getCachedPayload, headers })
+22
View File
@@ -0,0 +1,22 @@
import { notFound } from 'next/navigation.js'
import { CookieBanner } from '@intecion/ipal-kit/client'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
import { getConfiguredLocales, getSiteShell } from '../../../lib/content.js'
import './styles.css'
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
export default async function LocaleLayout({ children, params }: Props) {
const { locale } = await params
if (!(await getConfiguredLocales()).includes(locale)) notFound()
return (
<html lang={locale}>
<body>
<SiteProviders banner={<CookieBanner equalChoice />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)}>
<main>{children}</main>
</SiteProviders>
</body>
</html>
)
}
@@ -0,0 +1,6 @@
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import { FormBlock } from '../../../blocks/FormBlock.js'
import * as content from '../../../lib/content.js'
export default createNotFoundPage(content, { blocks: { formBlock: FormBlock }, fallback: <h1>404</h1> })
+10
View File
@@ -0,0 +1,10 @@
/* Sandbox look — in a project this is the design system. */
body { font-family: system-ui, sans-serif; margin: 0 auto; max-width: 40rem; padding: 1rem; }
.grid { display: grid; gap: 1rem; grid-template-columns: repeat(2, 1fr); }
.field { grid-column: span 2; } .half { grid-column: span 1; }
.label, legend { display: block; font-weight: 600; margin-bottom: .25rem; }
.input { border: 1px solid #999; border-radius: 6px; box-sizing: border-box; padding: .5rem; width: 100%; }
.choices { border: 0; display: grid; gap: .25rem; margin: 0; padding: 0; } .choice { display: flex; gap: .5rem; }
.error { color: #b00020; } .progress { color: #555; } .step-title { font-size: 1.25rem; font-weight: 700; }
.actions { display: flex; gap: .5rem; margin-top: 1rem; } .btn { background: #111; border: 0; border-radius: 6px; color: #fff; padding: .6rem 1rem; }
.btn-secondary { background: #ddd; color: #111; } .success { background: #e7f7ec; padding: 1rem; }
+2
View File
@@ -0,0 +1,2 @@
export { mcpGET as GET, mcpPOST as POST } from '../../../lib/content.js'
export const dynamic = 'force-dynamic'
+2
View File
@@ -0,0 +1,2 @@
export { llmsRoute as GET } from '../../lib/content.js'
export const dynamic = 'force-dynamic'
+16
View File
@@ -0,0 +1,16 @@
import type { FormNotificationTexts } from '@intecion/ipal-kit'
import { RenderForm, type SendFormAction } from '@intecion/ipal-kit/rsc'
// Classes set once per project — here plain names the sandbox CSS styles.
const formClasses = {
actions: 'actions', back: 'btn btn-secondary', choice: 'choice', choices: 'choices', error: 'error', field: 'field',
fieldHalf: 'half', fields: 'grid', form: 'form', formError: 'error', input: 'input', label: 'label', progress: 'progress',
select: 'input', stepTitle: 'step-title', submit: 'btn', success: 'success', textarea: 'input',
}
type Props = { form?: unknown; formTexts?: FormNotificationTexts; locale: string; sendForm?: SendFormAction }
export function FormBlock({ form, formTexts, locale, sendForm }: Props) {
if (!formTexts || !sendForm) return null
return <RenderForm action={sendForm} classNames={formClasses} form={form as never} locale={locale} requiredMark=" *" texts={formTexts} />
}
+7
View File
@@ -0,0 +1,7 @@
export const i18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
} as const
+11
View File
@@ -0,0 +1,11 @@
// Sandbox data layer — the same one line every project has (PROGRAMISTA §2.7).
import config from '@payload-config'
import { createContentHelpers } from '@intecion/ipal-kit'
import { i18nConfig } from '../i18n.config.js'
export const {
generatePageMetadata, generateStaticParams, getCachedPayload, getConfiguredLocales, getFormTexts, getLinkOptions,
getNotFoundPage, getPageJsonLd, getSettings, getSiteShell, healthRoute, i18n, llmsRoute, mcpGET, mcpPOST,
resolveNav, resolvePageRedirect, resolveRoute,
} = createContentHelpers({ baseUrl: 'http://localhost:3000', config, i18n: i18nConfig, mcp: { serverName: 'ipal-sandbox' } })
+596
View File
@@ -71,6 +71,9 @@ export interface Config {
pages: Page; pages: Page;
posts: Post; posts: Post;
media: Media; media: Media;
forms: Form;
'form-submissions': FormSubmission;
'consent-records': ConsentRecord;
'payload-kv': PayloadKv; 'payload-kv': PayloadKv;
'payload-locked-documents': PayloadLockedDocument; 'payload-locked-documents': PayloadLockedDocument;
'payload-preferences': PayloadPreference; 'payload-preferences': PayloadPreference;
@@ -82,6 +85,9 @@ export interface Config {
pages: PagesSelect<false> | PagesSelect<true>; pages: PagesSelect<false> | PagesSelect<true>;
posts: PostsSelect<false> | PostsSelect<true>; posts: PostsSelect<false> | PostsSelect<true>;
media: MediaSelect<false> | MediaSelect<true>; media: MediaSelect<false> | MediaSelect<true>;
forms: FormsSelect<false> | FormsSelect<true>;
'form-submissions': FormSubmissionsSelect<false> | FormSubmissionsSelect<true>;
'consent-records': ConsentRecordsSelect<false> | ConsentRecordsSelect<true>;
'payload-kv': PayloadKvSelect<false> | PayloadKvSelect<true>; 'payload-kv': PayloadKvSelect<false> | PayloadKvSelect<true>;
'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>; 'payload-locked-documents': PayloadLockedDocumentsSelect<false> | PayloadLockedDocumentsSelect<true>;
'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>; 'payload-preferences': PayloadPreferencesSelect<false> | PayloadPreferencesSelect<true>;
@@ -168,6 +174,15 @@ export interface User {
export interface Page { export interface Page {
id: number; id: number;
title?: string | null; title?: string | null;
slug?: string | null;
layout?:
| {
form?: (number | null) | Form;
id?: string | null;
blockName?: string | null;
blockType: 'formBlock';
}[]
| null;
meta?: { meta?: {
title?: string | null; title?: string | null;
description?: string | null; description?: string | null;
@@ -183,6 +198,235 @@ export interface Page {
updatedAt: string; updatedAt: string;
createdAt: string; createdAt: string;
} }
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "forms".
*/
export interface Form {
id: number;
title: string;
fields?:
| (
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
defaultValue?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'checkbox';
}
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'country';
}
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'email';
}
| {
message?: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ('ltr' | 'rtl') | null;
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
indent: number;
version: number;
};
[k: string]: unknown;
} | null;
id?: string | null;
blockName?: string | null;
blockType: 'message';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: number | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'number';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: string | null;
placeholder?: string | null;
options?:
| {
label: string;
value: string;
id?: string | null;
}[]
| null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'select';
}
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'state';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: string | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'text';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: string | null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'textarea';
}
| {
/**
* Technical name, e.g. "services" — no spaces.
*/
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
options?:
| {
label: string;
value: string;
id?: string | null;
}[]
| null;
/**
* Empty = no minimum (Required = at least one).
*/
minSelected?: number | null;
/**
* Empty = no limit.
*/
maxSelected?: number | null;
id?: string | null;
blockName?: string | null;
blockType: 'checkboxGroup';
}
| {
name: string;
label?: string | null;
width?: number | null;
required?: boolean | null;
defaultValue?: string | null;
id?: string | null;
blockName?: string | null;
blockType: 'date';
}
| {
name: string;
label?: string | null;
width?: number | null;
defaultValue?: string | null;
options?:
| {
label: string;
value: string;
id?: string | null;
}[]
| null;
required?: boolean | null;
id?: string | null;
blockName?: string | null;
blockType: 'radio';
}
| {
/**
* Starts a new step: the fields below it (until the next Step) are shown together, with Next / Back buttons. Leave the form without Steps for a single-screen form.
*/
title?: string | null;
description?: string | null;
id?: string | null;
blockName?: string | null;
blockType: 'step';
}
)[]
| null;
submitButtonLabel?: string | null;
confirmationType?: ('message' | 'redirect') | null;
confirmationMessage?: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ('ltr' | 'rtl') | null;
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
indent: number;
version: number;
};
[k: string]: unknown;
} | null;
redirect?: {
url: string;
};
emails?:
| {
emailTo?: string | null;
cc?: string | null;
bcc?: string | null;
replyTo?: string | null;
emailFrom?: string | null;
subject: string;
message?: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ('ltr' | 'rtl') | null;
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
indent: number;
version: number;
};
[k: string]: unknown;
} | null;
id?: string | null;
}[]
| null;
updatedAt: string;
createdAt: string;
}
/** /**
* This interface was referenced by `Config`'s JSON-Schema * This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "media". * via the `definition` "media".
@@ -223,6 +467,42 @@ export interface Post {
updatedAt: string; updatedAt: string;
createdAt: string; createdAt: string;
} }
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "form-submissions".
*/
export interface FormSubmission {
id: number;
form: number | Form;
submissionData?:
| {
field: string;
value: string;
id?: string | null;
}[]
| null;
updatedAt: string;
createdAt: string;
}
/**
* Proof of cookie consent: random id (also in the visitor cookie), choices, policy version, time. No personal data.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "consent-records".
*/
export interface ConsentRecord {
id: number;
consentId: string;
version: number;
choices?: {
necessary?: boolean | null;
functional?: boolean | null;
analytics?: boolean | null;
marketing?: boolean | null;
};
updatedAt: string;
createdAt: string;
}
/** /**
* This interface was referenced by `Config`'s JSON-Schema * This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-kv". * via the `definition` "payload-kv".
@@ -262,6 +542,18 @@ export interface PayloadLockedDocument {
| ({ | ({
relationTo: 'media'; relationTo: 'media';
value: number | Media; value: number | Media;
} | null)
| ({
relationTo: 'forms';
value: number | Form;
} | null)
| ({
relationTo: 'form-submissions';
value: number | FormSubmission;
} | null)
| ({
relationTo: 'consent-records';
value: number | ConsentRecord;
} | null); } | null);
globalSlug?: string | null; globalSlug?: string | null;
user: { user: {
@@ -335,6 +627,18 @@ export interface UsersSelect<T extends boolean = true> {
*/ */
export interface PagesSelect<T extends boolean = true> { export interface PagesSelect<T extends boolean = true> {
title?: T; title?: T;
slug?: T;
layout?:
| T
| {
formBlock?:
| T
| {
form?: T;
id?: T;
blockName?: T;
};
};
meta?: meta?:
| T | T
| { | {
@@ -380,6 +684,229 @@ export interface MediaSelect<T extends boolean = true> {
focalX?: T; focalX?: T;
focalY?: T; focalY?: T;
} }
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "forms_select".
*/
export interface FormsSelect<T extends boolean = true> {
title?: T;
fields?:
| T
| {
checkbox?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
defaultValue?: T;
id?: T;
blockName?: T;
};
country?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
id?: T;
blockName?: T;
};
email?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
id?: T;
blockName?: T;
};
message?:
| T
| {
message?: T;
id?: T;
blockName?: T;
};
number?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
required?: T;
id?: T;
blockName?: T;
};
select?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
placeholder?: T;
options?:
| T
| {
label?: T;
value?: T;
id?: T;
};
required?: T;
id?: T;
blockName?: T;
};
state?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
id?: T;
blockName?: T;
};
text?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
required?: T;
id?: T;
blockName?: T;
};
textarea?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
required?: T;
id?: T;
blockName?: T;
};
checkboxGroup?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
options?:
| T
| {
label?: T;
value?: T;
id?: T;
};
minSelected?: T;
maxSelected?: T;
id?: T;
blockName?: T;
};
date?:
| T
| {
name?: T;
label?: T;
width?: T;
required?: T;
defaultValue?: T;
id?: T;
blockName?: T;
};
radio?:
| T
| {
name?: T;
label?: T;
width?: T;
defaultValue?: T;
options?:
| T
| {
label?: T;
value?: T;
id?: T;
};
required?: T;
id?: T;
blockName?: T;
};
step?:
| T
| {
title?: T;
description?: T;
id?: T;
blockName?: T;
};
};
submitButtonLabel?: T;
confirmationType?: T;
confirmationMessage?: T;
redirect?:
| T
| {
url?: T;
};
emails?:
| T
| {
emailTo?: T;
cc?: T;
bcc?: T;
replyTo?: T;
emailFrom?: T;
subject?: T;
message?: T;
id?: T;
};
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "form-submissions_select".
*/
export interface FormSubmissionsSelect<T extends boolean = true> {
form?: T;
submissionData?:
| T
| {
field?: T;
value?: T;
id?: T;
};
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "consent-records_select".
*/
export interface ConsentRecordsSelect<T extends boolean = true> {
consentId?: T;
version?: T;
choices?:
| T
| {
necessary?: T;
functional?: T;
analytics?: T;
marketing?: T;
};
updatedAt?: T;
createdAt?: T;
}
/** /**
* This interface was referenced by `Config`'s JSON-Schema * This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "payload-kv_select". * via the `definition` "payload-kv_select".
@@ -450,6 +977,15 @@ export interface SiteSetting {
* Fallback Open Graph image when a page has none. * Fallback Open Graph image when a page has none.
*/ */
defaultShareImage?: (number | null) | Media; defaultShareImage?: (number | null) | Media;
/**
* Official profiles of this business (Google Business Profile, LinkedIn, Facebook, Wikipedia…). Tells search engines and AI which entity the site belongs to.
*/
sameAs?:
| {
url: string;
id?: string | null;
}[]
| null;
/** /**
* Square icon, PNG or SVG, min. 48×48px (Google requires this to show it in search). Rendered via buildIconsMetadata. * Square icon, PNG or SVG, min. 48×48px (Google requires this to show it in search). Rendered via buildIconsMetadata.
*/ */
@@ -539,6 +1075,10 @@ export interface SiteIntegration {
since?: string | null; since?: string | null;
checkedAt?: string | null; checkedAt?: string | null;
}; };
/**
* Key that proves this site owns its URLs to IndexNow (Bing, ChatGPT Search). Generated automatically — change only to rotate it.
*/
indexNowKey?: string | null;
updatedAt?: string | null; updatedAt?: string | null;
createdAt?: string | null; createdAt?: string | null;
} }
@@ -548,6 +1088,10 @@ export interface SiteIntegration {
*/ */
export interface CookieSetting { export interface CookieSetting {
id: number; id: number;
/**
* Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again.
*/
policyVersion: number;
/** /**
* Main consent message shown in the banner. * Main consent message shown in the banner.
*/ */
@@ -581,6 +1125,25 @@ export interface CookieSetting {
id?: string | null; id?: string | null;
}[] }[]
| null; | null;
/**
* Cookies the site uses — shown on the cookie policy page (<CookieTable>). Fill it from a scan: ipal-consent-check → cookie-scan.
*/
cookies?:
| {
name: string;
/**
* e.g. Google, this site
*/
provider?: string | null;
category: 'necessary' | 'functional' | 'analytics' | 'marketing';
purpose?: string | null;
/**
* e.g. "2 years", "session"
*/
duration?: string | null;
id?: string | null;
}[]
| null;
updatedAt?: string | null; updatedAt?: string | null;
createdAt?: string | null; createdAt?: string | null;
} }
@@ -607,6 +1170,18 @@ export interface Notification {
*/ */
consent?: string | null; consent?: string | null;
notFound?: string | null; notFound?: string | null;
/**
* Step-by-step forms: button to the next step.
*/
next?: string | null;
/**
* Step-by-step forms: button to the previous step.
*/
back?: string | null;
/**
* Progress — {current} and {total} are replaced.
*/
stepOf?: string | null;
}; };
updatedAt?: string | null; updatedAt?: string | null;
createdAt?: string | null; createdAt?: string | null;
@@ -622,6 +1197,12 @@ export interface SiteSettingsSelect<T extends boolean = true> {
titleSeparator?: T; titleSeparator?: T;
logo?: T; logo?: T;
defaultShareImage?: T; defaultShareImage?: T;
sameAs?:
| T
| {
url?: T;
id?: T;
};
favicon?: T; favicon?: T;
defaultTheme?: T; defaultTheme?: T;
allowThemeToggle?: T; allowThemeToggle?: T;
@@ -667,6 +1248,7 @@ export interface SiteIntegrationsSelect<T extends boolean = true> {
since?: T; since?: T;
checkedAt?: T; checkedAt?: T;
}; };
indexNowKey?: T;
updatedAt?: T; updatedAt?: T;
createdAt?: T; createdAt?: T;
globalType?: T; globalType?: T;
@@ -676,6 +1258,7 @@ export interface SiteIntegrationsSelect<T extends boolean = true> {
* via the `definition` "cookie-settings_select". * via the `definition` "cookie-settings_select".
*/ */
export interface CookieSettingsSelect<T extends boolean = true> { export interface CookieSettingsSelect<T extends boolean = true> {
policyVersion?: T;
message?: T; message?: T;
settingsTitle?: T; settingsTitle?: T;
privacyLinkLabel?: T; privacyLinkLabel?: T;
@@ -696,6 +1279,16 @@ export interface CookieSettingsSelect<T extends boolean = true> {
description?: T; description?: T;
id?: T; id?: T;
}; };
cookies?:
| T
| {
name?: T;
provider?: T;
category?: T;
purpose?: T;
duration?: T;
id?: T;
};
updatedAt?: T; updatedAt?: T;
createdAt?: T; createdAt?: T;
globalType?: T; globalType?: T;
@@ -715,6 +1308,9 @@ export interface NotificationsSelect<T extends boolean = true> {
validation?: T; validation?: T;
consent?: T; consent?: T;
notFound?: T; notFound?: T;
next?: T;
back?: T;
stepOf?: T;
}; };
updatedAt?: T; updatedAt?: T;
createdAt?: T; createdAt?: T;
+13 -8
View File
@@ -7,6 +7,7 @@ import sharp from 'sharp'
import { fileURLToPath } from 'url' import { fileURLToPath } from 'url'
import { testEmailAdapter } from './helpers/testEmailAdapter.js' import { testEmailAdapter } from './helpers/testEmailAdapter.js'
import { i18nConfig } from './i18n.config.js'
import { seed } from './seed.js' import { seed } from './seed.js'
const filename = fileURLToPath(import.meta.url) const filename = fileURLToPath(import.meta.url)
@@ -30,7 +31,15 @@ export default buildConfig({
}, },
{ {
slug: 'pages', slug: 'pages',
fields: [{ name: 'title', type: 'text' }], fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', index: true, localized: true },
{
name: 'layout',
type: 'blocks',
blocks: [{ slug: 'formBlock', fields: [{ name: 'form', type: 'relationship', relationTo: 'forms' }] }],
},
],
}, },
{ {
slug: 'posts', slug: 'posts',
@@ -56,13 +65,9 @@ export default buildConfig({
plugins: [ plugins: [
ipalKit({ ipalKit({
access: { authCollection: 'users' }, access: { authCollection: 'users' },
i18n: { i18n: i18nConfig,
defaultLocale: 'pl', consentLog: true,
locales: [ forms: {},
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
},
seo: { collections: ['posts', 'pages'] }, seo: { collections: ['posts', 'pages'] },
// 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator. // 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator.
twoFactor: false, twoFactor: false,
+46
View File
@@ -22,4 +22,50 @@ export const seed = async (payload: Payload) => {
}, },
}) })
} }
await seedContactPage(payload)
} }
const text = (t: string) => ({
root: {
children: [{ children: [{ detail: 0, format: 0, mode: 'normal', style: '', text: t, type: 'text', version: 1 }], direction: null, format: '', indent: 0, type: 'paragraph', version: 1 }],
direction: null,
format: '',
indent: 0,
type: 'root',
version: 1,
},
})
/** A step-by-step quote form on /pl/kontakt — exercises RenderForm, steps, choice lists, dates. */
async function seedContactPage(payload: Payload) {
const { totalDocs } = await payload.count({ collection: 'pages', where: { slug: { equals: 'kontakt' } } })
if (totalDocs) {return}
const form = await payload.create({
collection: 'forms',
data: {
confirmationMessage: text('Dziękujemy! Odezwiemy się w ciągu 24 godzin.'),
confirmationType: 'message',
fields: [
{ blockType: 'step', title: 'Kontakt' },
{ name: 'name', blockType: 'text', label: 'Imię i nazwisko', required: true, width: 50 },
{ name: 'email', blockType: 'email', label: 'E-mail', required: true, width: 50 },
{ blockType: 'step', description: 'Zaznacz, czego potrzebujesz.', title: 'Projekt' },
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', options: [{ label: 'Strona WWW', value: 'www' }, { label: 'SEO', value: 'seo' }, { label: 'Kampanie', value: 'ads' }], required: true },
{ name: 'budget', blockType: 'radio', label: 'Budżet', options: [{ label: 'do 10 tys.', value: 's' }, { label: 'powyżej 10 tys.', value: 'l' }], required: true },
{ name: 'deadline', blockType: 'date', label: 'Termin' },
{ blockType: 'message', message: text('Dane przetwarzamy wyłącznie w celu przygotowania wyceny.') },
{ name: 'consent', blockType: 'checkbox', label: 'Zgadzam się na przetwarzanie danych.', required: true },
],
submitButtonLabel: 'Wyślij zapytanie',
title: 'Wycena',
} as never,
})
const page = await payload.create({
collection: 'pages',
data: { layout: [{ blockType: 'formBlock', form: form.id }], slug: 'kontakt', title: 'Kontakt' } as never,
})
await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Sandbox' } as never })
payload.logger.info(`[seed] /pl/kontakt (page ${page.id}, form ${form.id})`)
}
+294
View File
@@ -3,6 +3,114 @@
Zmiany ważne dla projektów na ipal-kit. Jak przejść na nową wersję: skill Zmiany ważne dla projektów na ipal-kit. Jak przejść na nową wersję: skill
**ipal-upgrade** i [PROGRAMISTA.md §6](./dev/PROGRAMISTA.md). **ipal-upgrade** i [PROGRAMISTA.md §6](./dev/PROGRAMISTA.md).
Trzymamy tu co najmniej **20 ostatnich wersji** — przy aktualizacji projektu o kilka
wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” od
wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy
dopiero powyżej 20.
## 1.9.3
### Audyt
- `ipal-audit` łapie ręczne liczenie linków pod dowolną nazwą (`resolveHref`, `getHref`…):
slug strony głównej wpisany w kodzie (`=== 'home'`, `'strona-glowna'`) i URL sklejany ze sluga
(`` `/${slug}` ``, `'/' + slug`) — ERROR z odesłaniem do `resolveLink` / `resolveNav`. Taka kopia gubi
prefiks języka, stronę główną z Site Settings, filtr `javascript:` i martwe linki.
- Poprawka: komentarz zaczynający linię nie jest już zgłaszany przez reguły ignorujące komentarze
(mniej fałszywych alarmów).
- AGENT.md (zakazane zamienniki) i links.md: jak przemapować pole `page` + `url` na `resolveLink`.
### Wymaga zmian w projekcie
- Nowe ERROR-y w audycie wskazują własne funkcje linków — zamień na `resolveLink(link, locale)` z `lib/content`
(PROGRAMISTA §6 poz. 33).
## 1.9.2
Import zamiast kodu: to, co każdy projekt pisał tak samo, jest w pluginie — logika i
szkielet. Wygląd zostaje w projekcie (klasy, własny markup na hookach). Wszystko opcjonalne:
dotychczasowy kod projektów działa bez zmian.
### Wymaga zmian w projekcie
- **Bezpieczeństwo — własny `FormRenderer`:** szablon z `ipal-form` przekazywał do komponentu
klienckiego cały dokument formularza. Local API czyta z `overrideAccess`, więc w HTML/RSC
lądowała zakładka **Emails** (adresy firmy, szablony). Zamień blok na `<RenderForm>` (niżej) albo
przekazuj do klienta tylko pola, etykiety i potwierdzenie. PROGRAMISTA §6 poz. 28.
- **Postgres:** `pnpm payload migrate:create` — nowe typy pól formularza (Step, Checkbox group,
Radio, Date) i teksty `next` / `back` / `stepOf` w Notifications. MongoDB/SQLite (push) bez zmian.
### Nowe
- **Formularze z panelu w jednej linii:** `<RenderForm form action locale texts classNames>` (`/rsc`) —
rich text, wiązanie akcji, redirect, tylko publiczna część formularza w przeglądarce. Pod spodem
`BuilderForm` (`/client`, czysty dostępny HTML bez stylów, `classNames`, `renderField`) i
`useBuilderForm` (cała logika dla własnego markupu). Szablony: `ipal-form/resources/FormBlock.tsx`,
`formClasses.ts`, `CustomForm.example.tsx` (stary `FormRenderer.tsx` usunięty).
- **Formularze krokowe i listy wyboru:** w panelu bloki **Step** (podział na ekrany, tytuł i opis per
język), **Checkbox group** (wiele wyborów, min/max), **Radio**, **Date** — domyślnie włączone
(`forms.fields.<typ>: false` wyłącza). Serwer sprawdza wartości z panelu, liczbę wyborów i daty;
wybory zapisane czytelnie („www, seo”). Dalej waliduje bieżący krok, błąd z serwera wraca na krok z
polem, fokus na nowym kroku. Teksty: Notifications → `next`, `back`, `stepOf`.
- **Layout:** `getSiteShell(locale)` (zgoda, analityka, klucz Turnstile, teksty formularzy, JSON-LD
WebSite + Organization, Site Settings) + `<SiteProviders shell>` (`/rsc`) — providery, baner,
przycisk cookies, Analytics, JSON-LD i preconnect w dobrej kolejności; każda część do podmiany
albo wyłączenia. `siteJsonLd` w `createContentHelpers` dla LocalBusiness.
- **Strona i 404:** `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })`
i `createNotFoundPage(content, { blocks, fallback })` (`/rsc`).
- **Trasy z jednej linii:** `createContentHelpers` zwraca `llmsRoute`, `llmsFullRoute`,
`markdownRoute`, `mcpGET`/`mcpPOST`, `healthRoute`, `indexNowKeyRoute`, `manifest`; opcje
`summaryField`, `mcp`, `markdown`, `redirectCollections` raz w `lib/content.ts`.
- **Linki i menu:** `resolveLink` (href, `internal`, `targetProps`, `appearance`), `resolveNav`
(dowolna głębokość, martwe linki pominięte), `homeSlugFrom`; w `lib/content`: `resolveLink(link, locale)`,
`resolveNav(items, locale)`, `getLinkOptions`, `getHomeSlug`, `resolvePageRedirect`, `getFormTexts`.
- **Pola sekcji:** `buildSectionHeaderField`, `buildSectionSettingsField({ backgrounds, anchor, fields })`
— ten sam kształt danych co dawne `src/fields/section*.ts` (bez migracji).
- `useOptionalTurnstile()` — bez providera zwraca `enabled: false` zamiast rzucać.
### Dokumentacja i audyt
- AGENT.md §7 to pełny katalog „potrzeba → import”; §0b, §3, §6 i PROGRAMISTA §2.7–2.8, §6
(poz. 28–33) opisują nowy sposób; skille ipal-form, ipal-nav, ipal-block, ipal-setup, ipal-upgrade
zaktualizowane.
- `ipal-audit` przyjmuje trasy-re-eksporty i `SiteProviders`; nowe reguły: kopia silnika formularza,
`src/fields/section*.ts` / `lib/navigation.ts` (WARNING), import roota / `/rsc` / `/server` w
komponencie klienckim (ERROR).
- Test `docsConsistency`: każdy import z dokumentacji istnieje w kodzie, każdy publiczny eksport jest opisany.
- Sandbox (`dev/`) ma front zbudowany na tych importach (formularz krokowy na `/pl/kontakt`).
## 1.9.1
### Wymaga zmian w projekcie
- **Bezpieczeństwo — drafty:** nigdy nieopublikowane strony i wpisy były dostępne pod swoim adresem
(oraz w Markdown, MCP, na listach archiwum). Teraz nie są. Podgląd redaktora: `draft: true`
w `resolveRoute` / `getArchiveEntries` w trybie `draftMode()`.
- **Zgłoszenia formularzy** czytają tylko role `editor`/`admin` (wcześniej każde konto panelu);
adresy odbiorców (zakładka Emails) zniknęły z publicznego `GET /api/forms`.
- **Formularze:** pole `email` przyjmuje dokładnie jeden adres, select tylko opcje z panelu, typy
sprawdzane po stronie serwera (`kind: 'invalid_format'`). Formularz wysyłający dane w innym kształcie
zostanie odrzucony.
- **Wycofanie zgody kasuje ciasteczka narzędzi** (`_ga*`, `_fbp`, `_gcl_*`, Clarity, LinkedIn…), także
na domenie nadrzędnej.
- **Nowe pola w globalach** (Postgres: `pnpm payload migrate:create`): Site Settings → sameAs; Cookie
Settings → Policy version, Cookies; Site Integrations → IndexNow.
- **Eksporty:** `@intecion/ipal-kit/env` i `/fluid.css` w końcu działają (były w docs, nie w paczce).
- **`users`:** plugin dodaje kolekcję auth, gdy projekt jej nie ma — usuń obejścia z `payload.config`.
- Komplet AGENT.md §0b rozszerzony do 18 pozycji (`ipal-audit` zgłosi braki).
### Nowe
- SEO/GEO: `getPageJsonLd`, `buildNavigationJsonLd`, `formatOpeningHours` + `type` w
`buildLocalBusinessJsonLd`, `sameAsUrls`, IndexNow (`indexNow: true`, `createIndexNowKeyRoute`),
`collectSiteIndex` (blog i wszystkie języki w llms.txt i MCP), URL + data w frontmatterze Markdown,
karta X/Twitter, `og:type=article`, obrazy w sitemapie, domyślny obraz udostępniania działa.
- Gotowe trasy i akcje: `createMarkdownRoute`, `createSubmitAction`, `createProxy({ markdown: true })`.
- Zgoda: wersja polityki z panelu, `equalChoice`, rejestr zgód (`consentLog`), tabela ciasteczek
(`getCookieTable`, `<CookieTable>`), skaner `cookie-scan` + import do panelu.
- noindex: `IPAL_NOINDEX=1` dla stagingu, Markdown/llms z `X-Robots-Tag: noindex` i canonical,
blokada noindex na stronie głównej i archiwach.
- Media: `mediaImageProps`, `videoProps`, `MEDIA_SIZES`, placeholdery przy uploadzie,
`buildImagesConfig`, `<YouTubeEmbed>`, `buildUploadSecurityHeaders`.
- Skalowanie: `fluid-wide.css` (do 1920 px) i zmienne zależne od wysokości ekranu.
- `safeHref` (linki z CMS bez `javascript:`), walidacja ID analityki, pełny preset CSP Google Maps.
- Agent: AGENT.md §0c (treść pod Google i AI, kiedy noindex), §6.0 (zasady komponentu), §6.11a/b
(skalowanie, Core Web Vitals), §8a (testy) + szablon `smoke.spec.ts`; seed formularza; nowe
kontrole w `ipal-audit` i `ipal-seo-check`.
## 1.9.0 ## 1.9.0
### Wymaga zmian w projekcie ### Wymaga zmian w projekcie
@@ -56,3 +164,189 @@ Zmiany ważne dla projektów na ipal-kit. Jak przejść na nową wersję: skill
przy instalacji z gita. CI w `.gitea/workflows/ci.yml`. przy instalacji z gita. CI w `.gitea/workflows/ci.yml`.
- 79 testów (vitest), w tym integracyjne na prawdziwym Payloadzie (SQLite w pamięci). - 79 testów (vitest), w tym integracyjne na prawdziwym Payloadzie (SQLite w pamięci).
- `pnpm typecheck`, `pnpm lint` (0 błędów), `pnpm test:int`. - `pnpm typecheck`, `pnpm lint` (0 błędów), `pnpm test:int`.
## 1.8.14
### Wymaga zmian w projekcie
- **2FA: w Next `twoFactor.plugin` trzeba wstrzyknąć** (`plugin: payloadTotp`).
`serverExternalPackages` nie jest obejściem — pakiet importuje własne `.css`,
którego Node nie załaduje. Usuń wpis z `next.config` i adapter z rzutowaniem.
### Poprawki
- `collection` w typie 2FA to `CollectionSlug` (wcześniej `string`) —
`plugin: payloadTotp` przechodzi typecheck bez rzutowania (`TS2322`).
- Paczka publikuje `bin` — działa `ipal-skills`.
## 1.8.13
### Nowe
- **Status wysyłki maili w panelu:** `mailAdapter()` zapisuje wynik w Site
Integrations; błąd → alert na dashboardzie i baner w zakładce SMTP. Formularz
działa dalej (zgłoszenie zapisane). Po aktualizacji: `generate:importmap`,
Postgres: `migrate:create`.
- Formularze w panelu w grupie **Forms** z etykietami (`forms.adminGroup`);
Notifications w grupie Settings — bez nadpisań w projekcie.
### Wymaga zmian w projekcie
- **`POST /api/form-submissions` zamknięty dla anonimów** (403). Front wysyła przez
server action + `submitForm` (skill `ipal-form`). Świadomie publiczny REST →
`formSubmissionOverrides.access.create`.
## 1.8.12
### Nowe
- **Turnstile: awaria po naszej stronie nie blokuje formularzy.** `checkTurnstile`
(`/server`) rozróżnia `pass` / `reject` (zły token odwiedzającego) / `degraded`
(brak lub zły sekret, Cloudflare nieosiągalny). `degraded` → zgłoszenie przyjęte,
alert na dashboardzie (`IntegrationAlerts`) i baner w Site Integrations →
Turnstile. Twardo: `submitForm({ turnstileOnConfigError: 'reject' })`.
- Sekret Turnstile z panelu albo env `TURNSTILE_SECRET_KEY`; przyczyna odrzucenia
w logu serwera. `remoteip` domyślnie nie jest wysyłany (`sendRemoteIp: true`).
- Po aktualizacji: `generate:importmap`, Postgres: `migrate:create` (`turnstileStatus`).
## 1.8.11
### Nowe
- Limit zapytań na IP: wyszukiwarka (`createSearchRoute`, 120/min) i MCP
(`createMcpRoute`, 60 wiadomości/min, batch maks. 10) → `429` z `Retry-After`.
`rateLimit: { max, windowMs }` albo `false` (limiter z przodu, np. Cloudflare WAF).
- Wspólny moduł limitera (`shared/rateLimit`) dla formularzy, wyszukiwarki i MCP.
## 1.8.10
### Zmiany
- Nagłówek stylowanej sitemapy to stałe „XML Sitemap” (bez nazwy strony z Site
Settings); usunięta opcja `siteNameField`. Własny tytuł: `sitemapStyle: { title }`.
## 1.8.9
### Nowe
- **`@intecion/ipal-kit/env`** — walidacja env bez Payload i Node, bezpieczna w
`instrumentation.ts` (root paczki wywracał Edge/Turbopack).
- **`fluid.css`** — płynna skala typografii i odstępów 360→1280 px (same zmienne,
opt-in, mapowanie w `@theme`).
- `R2_PUBLIC_URL` poza produkcją może być ścieżką (`/media`) — prefiksowana
`NEXT_PUBLIC_SERVER_URL`; CSP nie dopisuje jej do `img-src`.
- `ipal-audit`: `html-check.mjs` — inline JSON-LD bez escapowania `<` = ERROR (XSS).
### Poprawki
- `createSitemapRouteHandler` wymaga `req` — Next 16 sprawdza typ pierwszego
argumentu route handlera (`Request | undefined` wywracał build).
## 1.8.8
- Przywrócony opcjonalny `req` w handlerze sitemapy (cofnięte w 1.8.9).
## 1.8.7
- Poprawki typów `routeHandlers` (handler sitemapy).
## 1.8.6
### Poprawki
- `buildLinkField` importował `src/…` zamiast ścieżki względnej — błąd w projekcie.
## 1.8.5
### Nowe
- **`sitemapRoute`** z `createContentHelpers`: XML dla crawlerów, a w przeglądarce
wygląd serwowany przez plugin (`/sitemap.xml?style`, CSS na XML, nie XSLT).
`sitemapStyle: { accent, credit, title } | false`.
### Wymaga zmian w projekcie
- Jedna sitemapa: `app/sitemap.xml/route.ts` (`export { sitemapRoute as GET }`);
usuń `app/sitemap.ts` i `public/sitemap.css` (`ipal-audit` to zgłasza).
## 1.8.4
### Nowe
- **`rowLabel()`** (`/admin`) — wiersze tablic w panelu pokazują treść („Kontakt”)
zamiast „Item 01”. Po dodaniu: `generate:importmap`.
- **`buildOptimizeUploadHook`** — optymalizacja obrazów przy uploadzie.
- Skille agenta: `ipal-site` (strona od briefu do raportu), seed treści, `ipal-upgrade` i inne.
- Baner cookies: atrybuty `data-ipal` na przyciskach (testy), etykiety z tekstów panelu.
## 1.8.3
### Nowe
- **Moduł Links:** `buildLinkField`, `buildLinksField`, `resolveLinkHref` — link do
strony / URL / pliku, przyciski sekcji jako tablica (zamiast `cta1`, `cta2`).
- `createContentHelpers`: `generatePageMetadata` (współdzieli cache z trasą) i opcja
`robots`; jeden odczyt Site Settings na język na żądanie.
- Szablony kodu sekcji i nawigacji dla agenta (`ipal-block`, `ipal-nav`).
## 1.8.2
### Poprawki
- Brakujący eksport `LocaleView` w `/client`.
## 1.8.1
### Poprawki
- Przywrócone zmiany z 1.7.14, które wydanie 1.8.0 przypadkiem cofnęło
(`LocaleView`, 404 bez `headers()`, poprawki R2). **Nie używaj 1.8.0.**
## 1.8.0
- Wydanie wadliwe: cofało zmiany z 1.7.14 — zaktualizuj do 1.8.1 lub nowszej.
- Dokumentacja agenta przeniesiona do `docs/agent/AGENT.md` + skille.
## 1.7.14
### Wymaga zmian w projekcie
- **`not-found.tsx` bez `headers()`** — Next 16 zamieniał stronę SSG/ISR na
dynamiczną. Serwer renderuje 404 dla każdego języka, `<LocaleView>` wybiera
wersję z URL (pages.md).
### Poprawki
- `buildR2Storage`: poprawki konfiguracji R2.
- Skille dla agentów (`ipal-audit` i inne).
## 1.7.12
### Nowe
- Link do polityki prywatności w banerze cookies brany automatycznie z Site
Settings → System Pages; tekst linku w panelu (`privacyLinkLabel`, per język).
Stare `privacyPolicy.label` w kodzie — przestarzałe.
- Nowa struktura dokumentacji: `docs/dev/PROGRAMISTA.md`, AGENT.md, `vibe.md`.
## 1.7.10
### Poprawki
- White-label: branding czyta Site Settings przez `payload` przekazany przez Payload
(bez `import('@payload-config')`, którego Next nie bundlował); nazwa
zlokalizowana wg języka panelu.
## 1.7.9
### Nowe
- `<Analytics defer>` — tagi ładują się przy pierwszej interakcji albo po
`deferTimeoutMs` (domyślnie 3500 ms) od `load`; Consent Mode bez zmian.
- Eksport loaderów `loadMetaPixel`, `loadClarity`, `loadLinkedIn`, `loadTikTok`.
## 1.7.8
### Nowe
- **Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel** w Site
Integrations — ładowane dopiero po zgodzie na właściwą kategorię.
- Strona 404 z panelu (Site Settings → System Pages, `resolveNotFoundPage`).
### Wymaga zmian w projekcie
- `<Analytics>` musi być wewnątrz `<ConsentProvider>`.
## 1.7.7
### Bezpieczeństwo
- `/api/health` i MCP nie zwracają treści błędów (host bazy, schemat) — tylko
ogólny komunikat; szczegóły w logu serwera.
## 1.7.6
### Poprawki
- **noindex:** pole `buildNoindexField` jest top-level (`doc.noindex`) — wcześniejszy
zapis do `meta.noindex` był wycinany przez plugin-seo, więc strony noindex
trafiały do sitemapy. Sitemap, llms.txt, wyszukiwarka i metadata czytają `noindex`.
## 1.7.4
### Nowe
- 2FA: `twoFactor.plugin` — wstrzyknięcie `payloadTotp` zamiast dynamicznego importu.
- White-label: kredyt „Technology supported by Intecion.com” pod nawigacją i na
ekranie logowania; większe logo na logowaniu.
+279 -73
View File
@@ -23,7 +23,7 @@
3. **Next 16 = `proxy.ts`.** NIGDY `middleware.ts`. 3. **Next 16 = `proxy.ts`.** NIGDY `middleware.ts`.
4. **Bez jawnego `<head>`, z ISR i `generateStaticParams`** — inaczej metadata 4. **Bez jawnego `<head>`, z ISR i `generateStaticParams`** — inaczej metadata
ląduje w `<body>` i SEO pada. ląduje w `<body>` i SEO pada.
5. **Minimum kolekcji.** Users są wbudowane, dane firmy/nawigacja to globale, 5. **Minimum kolekcji.** Users wstrzykuje ipalKit, dane firmy/nawigacja to globale,
FAQ/hero to bloki. FAQ/hero to bloki.
6. **Sekcja = kompozycja prymitywów.** `buildLinksField()` + `<CMSLink>`, upload + 6. **Sekcja = kompozycja prymitywów.** `buildLinksField()` + `<CMSLink>`, upload +
`<Media>`, `<Section>` + `<SectionHeader>`. Zero pól `ctaLabel`/`pdfUrl`. `<Media>`, `<Section>` + `<SectionHeader>`. Zero pól `ctaLabel`/`pdfUrl`.
@@ -52,22 +52,24 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2.
| # | Obszar | Co musi być (plik) | API pluginu | Kontrola | | # | Obszar | Co musi być (plik) | API pluginu | Kontrola |
|---|---|---|---|---| |---|---|---|---|---|
| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` z ISR + `generateStaticParams`, `not-found.tsx` | `createProxy`, `createContentHelpers`, `resolveRoute`, `resolveRedirect` | A, S | | 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, {…})` | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S |
| 2 | **SEO** — meta | `generateMetadata` w każdej trasie stron; favicon i OG z Site Settings; `htmlLimitedBots` w `next.config.ts`; tab SEO + `buildNoindexField` w Pages | `generatePageMetadata`, `buildIconsMetadata`, `buildNoindexField` | A, S | | 2 | **SEO** — meta | `generateMetadata` w każdej trasie stron; favicon i OG z Site Settings; `htmlLimitedBots` w `next.config.ts`; tab SEO + `buildNoindexField` w Pages | `generatePageMetadata`, `buildIconsMetadata`, `buildNoindexField` | A, S |
| 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` (wszystkie z `force-dynamic` poza robots) | `sitemapRoute`, `robots`, `createManifestHandler` | A, S | | 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` — każdy to re-eksport z `lib/content` (`sitemapRoute`, `robots`, `manifest`) + `force-dynamic` poza robots | `sitemapRoute`, `robots`, `manifest` | A, S |
| 4 | **SEO** — dane strukturalne | `<JsonLdGraph>` w `[locale]/layout.tsx`: `WebSite` + `Organization` (lub `LocalBusiness` dla firmy lokalnej) z danych z panelu; `Breadcrumb` na podstronach; `FAQPage` przy bloku FAQ | `build*JsonLd`, `JsonLdGraph` (`/rsc`) | A, S | | 4 | **SEO** — dane strukturalne | layout: `<SiteProviders shell={…}>` daje `WebSite` + `Organization` (`sameAs`) z Site Settings; firma lokalna → `createContentHelpers({ siteJsonLd })` z `buildLocalBusinessJsonLd` (`type`, godziny → `formatOpeningHours`); nawigacja: `<SiteProviders jsonLd={[buildNavigationJsonLd(…)]}>`; strona: `createPageRoute` dokłada `getPageJsonLd` (WebPage/BlogPosting, okruszki, FAQ — `pageJsonLd: { faq }`) | `getSiteShell`, `SiteProviders`, `build*JsonLd`, `getPageJsonLd` | A, S |
| 5 | **GEO** — llms | `src/app/llms.txt/route.ts` i `src/app/llms-full.txt/route.ts` (`full: true`); pole `buildSummaryField()` w Pages, `summaryField: 'aiSummary'` w trasach AI | `createLlmsTxtRoute`, `buildSummaryField` | A, S | | 5 | **GEO** — llms | `src/app/llms.txt/route.ts` (`llmsRoute`) i `src/app/llms-full.txt/route.ts` (`llmsFullRoute`) z `lib/content`; pole `buildSummaryField()` w Pages, `summaryField: 'aiSummary'` w `createContentHelpers` | `llmsRoute`, `llmsFullRoute`, `buildSummaryField` | A, S |
| 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `createMarkdownRenderer`, `markdownResponse`, `markdownAlternate`, `createProxy({ markdown })` | A, S | | 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link w `<head>`); `createProxy(…, { NextResponse, markdown: true })` (bez tego `/md/…` dostaje redirect na język) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S |
| 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` (publiczny — AI przegląda stronę: `get_site_info`, `list_pages`, `search_content`, `get_page`) | `createMcpRoute` | A, S | | 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` = `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` (publiczny — AI przegląda stronę: `get_site_info`, `list_pages`, `search_content`, `get_page`); nazwa: `createContentHelpers({ mcp: { serverName } })` | `mcpGET`, `mcpPOST` | A, S |
| 8 | **GEO** — boty AI | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`); `'block-training'` / `'disallow'` tylko z decyzji klienta | `buildRobots` | S | | 8 | **GEO** — boty AI + IndexNow | robots **wpuszcza** boty AI (domyślne `aiBots: 'allow'`; blokada tylko z decyzji klienta); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (`indexNowKeyRoute`; publikacja → Bing/ChatGPT Search w minuty) | `buildRobots`, `indexNowKeyRoute` | A, S |
| 9 | **Media / R2** | `Media` z `normalizeFilenameHook` + `buildOptimizeUploadHook`; **zawsze** `buildR2Storage(['media'], { s3Storage })` w `payload.config.ts` + `@payloadcms/storage-s3` w zależnościach; `R2_*` w `.env.example`; `<MediaPreconnect/>` w layoutcie | `buildR2Storage`, `normalizeFilenameHook`, `MediaPreconnect` | A | | 9 | **Media / R2 / szybkość** | `Media` z `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + pole; **zawsze** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` w `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` i `buildUploadSecurityHeaders()` w `next.config.ts`; `<Media>` projektu przez `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S |
| 10 | **Formularze** | formularze w panelu (kolekcja Forms); jeden `FormRenderer` + jedna akcja `sendForm` → `submitForm`; `forms: {…}` w `ipalKit`; `email: mailAdapter()` | `submitForm`, `useForm`, `isHoneypotTripped`, `mailAdapter` | A, P | | 10 | **Formularze** | każdy formularz z **seeda** (`scripts/seed-form-*.ts`: pola, potwierdzenie, mail do firmy **i** potwierdzenie do klienta, każdy język); blok z `<RenderForm>` + `formClasses.ts` (wygląd, raz); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` w `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
| 11 | **Turnstile** | `<TurnstileProvider siteKey={…}>` w `[locale]/layout.tsx`, `siteKey` z `getTurnstileConfig(payload)`; widget w `FormRenderer` (`useTurnstile`); klucze w Site Integrations | `getTurnstileConfig`, `TurnstileProvider`, `useTurnstile` | A, P | | 11 | **Turnstile** | `<SiteProviders>` w `[locale]/layout.tsx` (wpina `TurnstileProvider` z kluczem z panelu); widget renderuje `RenderForm`; klucze w Site Integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
| 12 | Zgoda + analityka | `ConsentProvider`, `CookieBanner`, `CookieButton`, `Analytics` w layoutcie; ID narzędzi w panelu | consent.md, analytics.md | A, `ipal-consent-check` | | 12 | Zgoda + analityka | `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>` (ConsentProvider, baner, CookieButton, Analytics w dobrej kolejności); ID narzędzi w panelu; lista ciasteczek ze skanu (cookie-scan → import) + `<CookieTable>` na stronie polityki cookies | consent.md, analytics.md | A, `ipal-consent-check` |
| 13 | Bezpieczeństwo | `buildSecurityHeaders` w `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` na produkcji | security.md, forms.md | A | | 13 | Bezpieczeństwo | `buildSecurityHeaders` w `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` na produkcji | security.md, forms.md | A |
| 14 | Operacje | `src/app/api/health/route.ts`; `src/instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` | `createHealthRoute`, `assertEnv`, `ipalEnvRules` | A | | 14 | Operacje | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging z `IPAL_NOINDEX=1`; testy smoke (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
| 15 | Strony systemowe | Site Settings → System Pages: homepage, 404, polityka prywatności, cookies; linki prawne w stopce przez rolę | `getSystemPagePath`, `getNotFoundPage` | P | | 15 | Strony systemowe | Site Settings → System Pages: homepage, 404, polityka prywatności, cookies; linki prawne w stopce przez rolę | `getSystemPagePath`, `getNotFoundPage` | P |
| 16 | **Zero hardkodów** | każdy tekst, link, obraz, plik, dane firmy z panelu; domeny i klucze z `.env` (§2) | — | A, P | | 16 | **Zero hardkodów** | każdy tekst, link, obraz, plik, dane firmy z panelu; domeny i klucze z `.env` (§2) | — | A, P |
| 17 | **Treść** | jedno h1, odpowiedź na początku sekcji, fakty, linki wewnętrzne, FAQ z prawdziwych pytań, `aiSummary`, sameAs, spójne dane firmy (§0c) | — | S, P |
| 18 | **Skalowanie** | `fluid.css` / `fluid-wide.css`, hero na `--ipal-hero-min-h`, lista ekranów §6.11a (w tym 1366×768) | — | A, przeglądarka |
**Turnstile działa sam:** oba klucze w panelu (lub env) → widget się pokazuje, a **Turnstile działa sam:** oba klucze w panelu (lub env) → widget się pokazuje, a
`submitForm` **wymaga** tokenu; brak kluczy → widgetu nie ma, formularz działa. `submitForm` **wymaga** tokenu; brak kluczy → widgetu nie ma, formularz działa.
@@ -81,12 +83,13 @@ Nie warunkujesz providera ani widgetu w kodzie — wpinasz zawsze.
| Zamiast pluginu | Dlaczego nie | Użyj | | Zamiast pluginu | Dlaczego nie | Użyj |
|---|---|---| |---|---|---|
| własny formularz z polami w JSX, `react-hook-form`, `formik` | klient nie zmieni pól; brak Turnstile, rate limitu, zgody RODO | builder w panelu + `FormRenderer` + `submitForm` | | własny formularz z polami w JSX, `react-hook-form`, `formik`, własny renderer formularzy | klient nie zmieni pól; brak Turnstile, rate limitu, zgody RODO; kopia silnika przekazuje adresy z zakładki Emails do HTML | builder w panelu + `<RenderForm>` (wygląd: `formClasses`, nietypowe: `useBuilderForm`) |
| własna trasa `api/contact` / `api/send` / `api/form`, `nodemailer` / `resend` / `@sendgrid` w projekcie | omija walidację i bramki `submitForm`, drugi transport maili | server action `sendForm` → `submitForm`, maile z Forms → Emails przez `mailAdapter()` | | własna trasa `api/contact` / `api/send` / `api/form`, `nodemailer` / `resend` / `@sendgrid` w projekcie | omija walidację i bramki `submitForm`, drugi transport maili | server action `sendForm` → `submitForm`, maile z Forms → Emails przez `mailAdapter()` |
| reCAPTCHA, hCaptcha, własna captcha | drugi mechanizm, brak statusu w panelu | Turnstile z pluginu | | reCAPTCHA, hCaptcha, własna captcha | drugi mechanizm, brak statusu w panelu | Turnstile z pluginu |
| ręczny `<script type="application/ld+json">` | brak escapowania, rozjazd z panelem | `JsonLdGraph` | | ręczny `<script type="application/ld+json">` | brak escapowania, rozjazd z panelem | `JsonLdGraph` |
| własny `sitemap.ts` / tekstowy `robots.txt` w `public/` | bez hreflang, noindex i stron systemowych | `sitemapRoute`, `robots` z `lib/content` | | własny `sitemap.ts` / tekstowy `robots.txt` w `public/` | bez hreflang, noindex i stron systemowych | `sitemapRoute`, `robots` z `lib/content` |
| własny `llms.txt` w `public/` | statyczny, starzeje się | `createLlmsTxtRoute` | | własny `llms.txt` w `public/` | statyczny, starzeje się | `createLlmsTxtRoute` |
| własna funkcja linku (`resolveHref`, `getHref`…): slug strony głównej w kodzie (`=== 'home'`), `` `/${slug}` `` | brak prefiksu języka, strona główna zależy od Site Settings, `javascript:` z panelu w `href`, martwy link prowadzi na `/` | `resolveLink(link, locale)` / `resolveNav` z `lib/content` (pole: `buildLinkField`) |
| `@aws-sdk/client-s3` / własny upload do bucketa | omija hooki mediów i URL z `R2_PUBLIC_URL` | `buildR2Storage` | | `@aws-sdk/client-s3` / własny upload do bucketa | omija hooki mediów i URL z `R2_PUBLIC_URL` | `buildR2Storage` |
### Świadomy wyjątek (tylko z decyzji klienta) ### Świadomy wyjątek (tylko z decyzji klienta)
@@ -96,7 +99,63 @@ W `AGENTS.md` projektu, w „Ustaleniach”, jedna linia z kluczami pozycji i po
ipal-audit-skip: mcp, llms-full — klient nie chce udostępniać treści agentom AI (mail 2026-03-02) ipal-audit-skip: mcp, llms-full — klient nie chce udostępniać treści agentom AI (mail 2026-03-02)
``` ```
Klucze: `llms`, `llms-full`, `markdown`, `mcp`, `jsonld`, `r2`, `turnstile`, Klucze: `llms`, `llms-full`, `markdown`, `mcp`, `jsonld`, `r2`, `turnstile`,
`analytics`, `csp`, `twofactor`. Bez tej linii brak pozycji to błąd. `analytics`, `csp`, `twofactor`, `aibots`, `forms-seed`. Bez tej linii brak pozycji to błąd.
---
## 0c. TREŚĆ POD GOOGLE I AI (SEO + GEO) — jak piszesz i układasz strony
Technika z §0b sprawia, że strona *może* być dobrze widoczna. To, czy Google ją
wypozycjonuje, a asystent AI zacytuje, zależy od treści. Wpisując treść z briefu do
panelu (seed, faza 6 w ipal-site), stosujesz poniższe — nie wymyślając faktów.
### Struktura każdej strony
- **Jedno `h1`** (nagłówek hero/strony), potem `h2` sekcji, `h3` w środku — bez przeskoków
poziomów. `SectionHeader` dostaje `as="h1"` tylko w pierwszej sekcji.
- **Najpierw odpowiedź.** Pierwsze 1–2 zdania sekcji odpowiadają wprost na jej nagłówek
(„Ile kosztuje…?” → „Od 1500 zł netto za…”). AI cytuje dokładnie takie zdania.
- **Nagłówki = pytania i frazy klientów**, nie hasła („Jak przebiega montaż?”, nie „Proces”).
- **Fakty zamiast ogólników:** liczby, zakres, obszar działania, czas realizacji, ceny „od” —
tylko z briefu; brak → `[DO UZUPEŁNIENIA]`. Zero „najlepsza jakość”, „profesjonalne podejście”.
- **Treść w HTML, nie w obrazach.** Kluczowa informacja nie może być tylko na grafice ani w
wideo. `alt` opisuje, co jest na obrazie (nie „zdjęcie1”, nie słowa kluczowe).
- **Każda strona linkuje dalej:** usługa → powiązane usługi + kontakt; wpis → usługa, której
dotyczy. Żadna strona bez linków wewnętrznych (CMSLink).
- **FAQ z prawdziwych pytań** z briefu → blok FAQ + `getPageJsonLd(…, { faq })` (FAQPage).
Pytania i odpowiedzi w JSON-LD = widoczne na stronie, słowo w słowo.
- **Długość:** strona usługi ≥ ~300 słów sensownej treści; krótsza = „cienka” — połącz z inną
albo poproś o materiał.
### Wiarygodność (E-E-A-T) i encja firmy
- Strona **O nas** z ludźmi, doświadczeniem, certyfikatami (z briefu); wpisy z autorem i datą.
- **Te same dane firmy wszędzie** (nazwa, adres, telefon): stopka, kontakt, JSON-LD
(`LocalBusiness`/`Organization`), wizytówka Google. Jeden global Company jako źródło.
- **Site Settings → sameAs:** profile firmy (Google Business Profile, LinkedIn, Facebook…).
- **Site Settings → opis strony** (2–3 zdania: kto, co, gdzie) — zasila llms.txt, MCP i meta.
- **`aiSummary`** ważnych stron: popraw auto-fill, gdy streszczenie jest słabe (1–3 zdania, fakty).
### Meta w zakładce SEO
Tytuł ≤ 60 znaków, unikalny, fraza na początku; opis ≤ 155 znaków, z konkretem i zachętą;
obraz udostępniania (1200×630) na stronach z ofertą — reszta dziedziczy domyślny z Site Settings.
### noindex — kiedy TAK, kiedy NIE
| Strona | noindex? |
|---|---|
| „Dziękujemy” po formularzu, strona potwierdzenia | **tak** |
| wyniki wewnętrznej wyszukiwarki, strony filtrów/parametrów | **tak** (+ `disallowParams` w robots) |
| strona testowa, robocza, landing tylko dla kampanii płatnej | **tak** |
| staging, preview, kopia testowa całej strony | **`IPAL_NOINDEX=1` w env tego środowiska** — nie checkbox |
| strona główna, archiwa (blog, realizacje) | **nigdy** — panel zablokuje zapis |
| usługi, oferta, kontakt, o nas, wpisy | **nigdy** |
| polityka prywatności, cookies, regulamin | **nie** domyślnie (to sygnał wiarygodności, nie szkodzą); `noindex` tylko na prośbę klienta |
| 404 | nie dotyczy — plugin wyklucza ją z sitemapy i zwraca prawdziwe 404 |
noindex **nie** zastępuje przekierowania ani usunięcia: stary adres → zmiana sluga (308 z
`trackSlugHistoryHook`), strona do skasowania → usuń ją. Treść roboczą trzymasz jako **draft**
(niepublikowana nie jest dostępna publicznie), nie jako opublikowaną stronę z noindex.
Kontrole: `ipal-seo-check` (jedno h1, kolejność nagłówków, alt, obraz OG, cienkie strony,
linki wewnętrzne, noindex w sitemapie).
--- ---
@@ -223,23 +282,23 @@ src/
(frontend)/ (frontend)/
styles.css # Tailwind + @source na node_modules/@intecion/ipal-kit/dist styles.css # Tailwind + @source na node_modules/@intecion/ipal-kit/dist
[locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md) [locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md)
layout.tsx # bez <head>; JsonLdGraph, TurnstileProvider, ConsentProvider + Analytics layout.tsx # bez <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer
actions.ts # sendForm → submitForm (jedyna droga wysyłki formularzy) actions.ts # sendForm = createSubmitAction(…) (jedyna droga wysyłki formularzy)
not-found.tsx # 404 z panelu (getNotFoundPage) not-found.tsx # createNotFoundPage(content, { blocks }) — 404 z panelu
[[...slug]]/page.tsx # PODWÓJNE nawiasy; RenderBlocks [[...slug]]/page.tsx # PODWÓJNE nawiasy; createPageRoute(content, { blocks, … }) + revalidate
(payload)/ # panel (generowany) (payload)/ # panel (generowany)
manifest.ts # createManifestHandler + force-dynamic manifest.ts # export { manifest as default } from lib/content + force-dynamic
sitemap.xml/route.ts # sitemapRoute z lib/content + force-dynamic (wygląd z pluginu) sitemap.xml/route.ts # export { sitemapRoute as GET } + force-dynamic (wygląd z pluginu)
robots.ts # z lib/content (boty AI wpuszczone) robots.ts # export { robots as default } (boty AI wpuszczone)
llms.txt/route.ts # createLlmsTxtRoute (GEO) llms.txt/route.ts # export { llmsRoute as GET } (GEO)
llms-full.txt/route.ts # createLlmsTxtRoute({ full: true }) (GEO) llms-full.txt/route.ts # export { llmsFullRoute as GET } (GEO)
md/[locale]/[[...slug]]/route.ts # createMarkdownRenderer — strona jako Markdown (GEO) md/[locale]/[[...slug]]/route.ts # export { markdownRoute as GET } — strona jako Markdown (GEO)
api/mcp/route.ts # createMcpRoute — publiczny serwer MCP (GEO) api/mcp/route.ts # export { mcpGET as GET, mcpPOST as POST } — publiczny MCP (GEO)
api/health/route.ts # createHealthRoute api/health/route.ts # export { healthRoute as GET }
indexnow-key.txt/route.ts # export { indexNowKeyRoute as GET }
instrumentation.ts # assertEnv(ipalEnvRules({...})) z '@intecion/ipal-kit/env' instrumentation.ts # assertEnv(ipalEnvRules({...})) z '@intecion/ipal-kit/env'
fields/ # sectionHeader.ts, sectionSettings.ts (linki: z pluginu)
components/ components/
forms/FormRenderer.tsx # jedyny renderer formularzy z panelu (ipal-form) forms/formClasses.ts # JEDYNE miejsce wyglądu formularzy (RenderForm classNames)
ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader
layout/ # Header, Footer, MobileNav (§6.8) layout/ # Header, Footer, MobileNav (§6.8)
icons/ # names.ts + Icon.tsx (§6.10) icons/ # names.ts + Icon.tsx (§6.10)
@@ -247,13 +306,17 @@ src/
blocks/registry.ts # blockType → komponent blocks/registry.ts # blockType → komponent
collections/ # Pages.ts, Media.ts (+ treść tylko gdy wymagana) collections/ # Pages.ts, Media.ts (+ treść tylko gdy wymagana)
globals/ # Header.ts, Footer.ts, Company.ts globals/ # Header.ts, Footer.ts, Company.ts
lib/content.ts # createContentHelpers — JEDYNY dostęp do Payloada lib/content.ts # createContentHelpers — JEDYNY dostęp do Payloada, trasy, linki, nawigacja
lib/navigation.ts # resolveNav → dane dla menu
i18n.config.ts # locale — jedno źródło i18n.config.ts # locale — jedno źródło
payload.config.ts payload.config.ts
proxy.ts # NIE middleware.ts proxy.ts # NIE middleware.ts
``` ```
Trasy w `app/` to **re-eksporty** z `lib/content` — konfiguracja (domena, `summaryField`,
nazwa MCP) jest raz, w `createContentHelpers`. Pola sekcji (`buildSectionHeaderField`,
`buildSectionSettingsField`), linki (`resolveLink`) i menu (`resolveNav`) są w pluginie —
nie twórz `src/fields/sectionHeader.ts` ani `lib/navigation.ts`.
| Element | Konwencja | Przykład | | Element | Konwencja | Przykład |
|---|---|---| |---|---|---|
| Folder bloku, kolekcja, global | PascalCase | `blocks/FeatureGrid/`, `collections/Pages.ts` | | Folder bloku, kolekcja, global | PascalCase | `blocks/FeatureGrid/`, `collections/Pages.ts` |
@@ -264,7 +327,7 @@ src/
| Komponent | nazwana funkcja, typy z `@/payload-types` | `export function Hero(...)` | | Komponent | nazwana funkcja, typy z `@/payload-types` | `export function Hero(...)` |
Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`, Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`,
`lib/locales.ts` — plugin ma `resolveRoute`, `getConfiguredLocales`. `lib/locales.ts`, `lib/navigation.ts` — plugin ma `resolveRoute`, `getConfiguredLocales`, `resolveNav`.
--- ---
@@ -315,7 +378,11 @@ Domyślnie: `pages`, `media` + globale pluginu (`site-settings`,
`site-integrations`, Notifications, Cookie Settings) + globale projektu `site-integrations`, Notifications, Cookie Settings) + globale projektu
(nawigacja, stopka, firma). Nic więcej, dopóki klient jawnie nie wymaga. (nawigacja, stopka, firma). Nic więcej, dopóki klient jawnie nie wymaga.
**NIGDY:** `users` (wbudowane w Payload), druga `media`, `daneFirmy`/`settings`/ **`users`** wstrzykuje `ipalKit` (kolekcja auth z `roles` i 2FA) — nie twórz jej, chyba
że potrzebujesz dodatkowych pól (wtedy własna `Users.ts` ze slugiem z `access.authCollection`;
plugin doda do niej role i 2FA).
**NIGDY:** druga `media`, `daneFirmy`/`settings`/
`navigation`/`footer` jako kolekcje (to globale), FAQ/hero/features jako kolekcje `navigation`/`footer` jako kolekcje (to globale), FAQ/hero/features jako kolekcje
(to bloki), kolekcja dla jednej rzeczy (to strona albo global). (to bloki), kolekcja dla jednej rzeczy (to strona albo global).
@@ -352,10 +419,27 @@ Trzy problemy, których nie wolno powtarzać: **zoo pól CTA** (`ctaLabel`,
`cta2Text`, `buttonUrl`…), **pliki jako tekst** (`pdfUrl: '/files/x.pdf'`), `cta2Text`, `buttonUrl`…), **pliki jako tekst** (`pdfUrl: '/files/x.pdf'`),
**sekcja-monolit** (200–400 linii z kartami, ikonami SVG i stylami przycisków). **sekcja-monolit** (200–400 linii z kartami, ikonami SVG i stylami przycisków).
### 6.0 Dziesięć zasad komponentu (skrót — szczegóły niżej)
1. **Mały:** `Component.tsx` sekcji ≤ ~80 linii JSX; element listy > 5 linii → własny `XxxCard.tsx`.
2. **Jedna rzecz = jeden komponent, stylowany RAZ.** Przycisk to `Button` (wygląd) + `CMSLink`
(cel z panelu) — w sekcjach nigdy własne klasy przycisku. Zmiana wyglądu wszystkich
przycisków = jedna zmiana w `Button.tsx`. To samo: obraz → `Media`, nagłówek → `SectionHeader`.
3. **Powtarzalne = tablica „+ Add …”**, nigdy numerowane pola. Przyciski: `buildLinksField()` →
redaktor klika „Add Button” tyle razy, ile potrzebuje (`maxRows` = ile mieści projekt).
`cta1`/`cta2`/`cta3`, `feature1Title`…, `image2` = błąd audytu.
4. **Panel czytelny bez znajomości kodu:** etykiety EN 1–3 słowa, zwinięte wiersze z treścią
(`rowLabel`), ≤ 6 pozycji widocznych po dodaniu bloku, ustawienia techniczne w sidebarze.
5. **Wariant zamiast kopii:** inny wygląd tej samej sekcji = `variant` (select), nie drugi blok.
6. **Zero tekstu, linku i obrazu w JSX** — wszystko z panelu, w każdym języku.
7. **Puste pole = element się nie renderuje** (nie „Lorem”, nie pusty `<div>`).
8. **Serwer domyślnie;** interakcja w osobnym, małym pliku `'use client'` z prostymi propsami.
9. **Typy z `@/payload-types`**, eksport nazwany, import z `@/…`, bez barreli.
10. **Każdy nowy blok:** test pustego bloku w panelu (§6.5a) + `ipal-audit --quick`.
### 6.1 Trzy warstwy ### 6.1 Trzy warstwy
``` ```
WARSTWA 1 — wspólne pola: linki z pluginu (buildLinkField, buildLinksField) WARSTWA 1 — wspólne pola: z pluginu (buildLinkField, buildLinksField,
+ src/fields/ projektu (sectionHeader, sectionSettings) buildSectionHeaderField, buildSectionSettingsField)
src/components/ui/ WARSTWA 2 — prymitywy UI (CMSLink, Button, Media, Section, SectionHeader) src/components/ui/ WARSTWA 2 — prymitywy UI (CMSLink, Button, Media, Section, SectionHeader)
src/blocks/X/ WARSTWA 3 — sekcja = kompozycja warstw 1 i 2 src/blocks/X/ WARSTWA 3 — sekcja = kompozycja warstw 1 i 2
``` ```
@@ -381,10 +465,11 @@ pobrania = link typu `file`, nigdy pole `pdfUrl`. W `payload-types.ts`: `CmsLink
pliki `buildOptimizeUploadHook` + `buildOptimizeUploadField` (storage.md). Pliki przygotowujesz pliki `buildOptimizeUploadHook` + `buildOptimizeUploadField` (storage.md). Pliki przygotowujesz
przed wgraniem — hook tylko łapie wpadki i pyta o zgodę. przed wgraniem — hook tylko łapie wpadki i pyta o zgodę.
**W projekcie (`src/fields/`)** — dwa małe helpery, kod w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md): **Nagłówek i ustawienia sekcji — z pluginu** ([blocks.md](../blocks.md)):
- `sectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized), - `buildSectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized),
- `sectionSettingsField()` → grupa `settings` (sidebar): `anchor`, `background`. - `buildSectionSettingsField()` → grupa `settings` (sidebar): `anchor`, `background`
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `sectionId` per blok. (tła projektu: `buildSectionSettingsField({ backgrounds: [{ label, value }] })`, dodatkowe pola: `fields`).
Każda sekcja ma `buildSectionSettingsField()` — żadnych `bgColor`, `sectionId` per blok.
Etykiety pól po angielsku (panel jest EN). Etykiety pól po angielsku (panel jest EN).
### 6.3 Warstwa 2 — prymitywy UI ### 6.3 Warstwa 2 — prymitywy UI
@@ -393,16 +478,16 @@ Kod 1:1: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). Każdy ma
| Prymityw | Robi | Zamiast | | Prymityw | Robi | Zamiast |
|---|---|---| |---|---|---|
| `CMSLink` (async, serwer) | każdy link z panelu: `resolveLinkHref` z pluginu + styl z `Button` + `newTab`/plik | `<a href>`, `<Link href>` w sekcjach | | `CMSLink` (async, serwer) | każdy link z panelu: `resolveLink(link, locale)` z `lib/content` (href, `internal`, `targetProps`, `appearance`) + klasy z `Button` | `<a href>`, `<Link href>` w sekcjach |
| `Button.tsx` | `Record<LinkAppearance, string>` z klasami wariantów | łańcuchy ternary, style przycisków w sekcjach | | `Button.tsx` | `Record<LinkAppearance, string>` z klasami wariantów | łańcuchy ternary, style przycisków w sekcjach |
| `Media` | każdy obraz/wideo z panelu (`next/image`, alt z dokumentu) | `<img src={x.url}>` | | `Media` | każdy obraz/wideo z panelu (`next/image`, alt z dokumentu) | `<img src={x.url}>` |
| `Section` | `id` z anchora, tło z mapy, kontener | ręczne `<section className=…>` | | `Section` | `id` z anchora, tło z mapy, kontener | ręczne `<section className=…>` |
| `SectionHeader` | eyebrow + nagłówek (`h1`/`h2`) + intro | luźne nagłówki w każdej sekcji | | `SectionHeader` | eyebrow + nagłówek (`h1`/`h2`) + intro | luźne nagłówki w każdej sekcji |
**`locale` dla bloków — raz, w trasie strony** (nigdy `headers()` w komponentach): **`locale` dla bloków — raz, w trasie strony** (nigdy `headers()` w komponentach):
```tsx `createPageRoute` podaje każdemu blokowi `locale` + to, co zwróci `blockProps`
const enhanceProps = () => ({ locale }) // Turnstile: <TurnstileProvider> w layoucie, nie props (np. `{ formTexts, sendForm }`). Własna strona: `enhanceProps={() => ({ locale })}`.
``` Turnstile i zgoda są w `<SiteProviders>` w layoucie, nie w propsach.
### 6.4 Warstwa 3 — sekcja = kompozycja ### 6.4 Warstwa 3 — sekcja = kompozycja
@@ -449,11 +534,11 @@ Podkomponent jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/c
| Pojedynczy link (karta, element) | `link` (`buildLinkField()`) | `href`, `url`, `target`, `linkTo`, `readMoreUrl` | | Pojedynczy link (karta, element) | `link` (`buildLinkField()`) | `href`, `url`, `target`, `linkTo`, `readMoreUrl` |
| Obraz / wideo | `media` | `image`, `img`, `imageUrl`, `photo`, `bgImage`, `heroImage` | | Obraz / wideo | `media` | `image`, `img`, `imageUrl`, `photo`, `bgImage`, `heroImage` |
| Plik do pobrania | `link` typu `file` | osobne `pdf`, `pdfUrl`, `file`, `download`, `attachment` | | Plik do pobrania | `link` typu `file` | osobne `pdf`, `pdfUrl`, `file`, `download`, `attachment` |
| Nagłówek sekcji | `header` (`sectionHeaderField()`) | luźne `title`, `headline`, `sectionTitle`, `subheading`, `subtitle` | | Nagłówek sekcji | `header` (`buildSectionHeaderField()`) | luźne `title`, `headline`, `sectionTitle`, `subheading`, `subtitle` |
| Tekst elementu | `heading` + `text` | `title`/`desc`/`description` naprzemiennie | | Tekst elementu | `heading` + `text` | `title`/`desc`/`description` naprzemiennie |
| Tekst sformatowany | `content` (richText) | `body`, `html`, `richText` | | Tekst sformatowany | `content` (richText) | `body`, `html`, `richText` |
| Lista elementów | `items` | `cards`, `features`, `list`, `boxes` | | Lista elementów | `items` | `cards`, `features`, `list`, `boxes` |
| Anchor / tło | `settings` (`sectionSettingsField()`) | `sectionId`, `bgColor`, `dark`, `theme` per blok | | Anchor / tło | `settings` (`buildSectionSettingsField()`) | `sectionId`, `bgColor`, `dark`, `theme` per blok |
| Zgoda RODO w formularzu | `consent` (checkbox) | — | | Zgoda RODO w formularzu | `consent` (checkbox) | — |
Wyjątek tylko przy dwóch rzeczach tego samego rodzaju o różnej roli Wyjątek tylko przy dwóch rzeczach tego samego rodzaju o różnej roli
@@ -505,12 +590,12 @@ pustych pól, bez zgadywania, bez numerowanych slotów. Schemat projektujesz dla
{ name: 'bgColor', type: 'text', admin: { description: 'Kolor tła sekcji w hex, używany w className komponentu' } }, { name: 'bgColor', type: 'text', admin: { description: 'Kolor tła sekcji w hex, używany w className komponentu' } },
// DOBRZE — 4 pozycje w panelu, rośnie przyciskiem „+ Add …” // DOBRZE — 4 pozycje w panelu, rośnie przyciskiem „+ Add …”
sectionHeaderField(), // Eyebrow / Heading / Intro buildSectionHeaderField(), // Eyebrow / Heading / Intro
{ name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' }, maxRows: 6, { name: 'items', type: 'array', labels: { singular: 'Feature', plural: 'Features' }, maxRows: 6,
admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') }, admin: { initCollapsed: true, components: rowLabel('heading', 'Feature') },
fields: [{ name: 'heading', type: 'text', localized: true, required: true }, { name: 'text', type: 'textarea', localized: true }] }, fields: [{ name: 'heading', type: 'text', localized: true, required: true }, { name: 'text', type: 'textarea', localized: true }] },
buildLinksField(), // „+ Add Button” buildLinksField(), // „+ Add Button”
sectionSettingsField(), // sidebar: anchor, background buildSectionSettingsField(), // sidebar: anchor, background
``` ```
**Test pustego bloku** (po każdym nowym bloku, w panelu): dodaj blok na stronie → **Test pustego bloku** (po każdym nowym bloku, w panelu): dodaj blok na stronie →
@@ -555,7 +640,7 @@ className={v === 'a' ? 'x' : v === 'b' ? 'y' : 'z'}
### 6.8 Header i Footer (globale nawigacji) ### 6.8 Header i Footer (globale nawigacji)
Kod (globale, `resolveNav`, `Header`, `Footer`, `MobileNav`): [kod-nawigacji.md](./skills/ipal-nav/resources/kod-nawigacji.md). Kod (globale, `Header`, `Footer`, `MobileNav`; `resolveNav` z pluginu): [kod-nawigacji.md](./skills/ipal-nav/resources/kod-nawigacji.md).
Skill: **ipal-nav**. Skill: **ipal-nav**.
- Nawigacja, stopka, dane firmy = **globale projektu** (`header`, `footer`, `company`), - Nawigacja, stopka, dane firmy = **globale projektu** (`header`, `footer`, `company`),
@@ -563,8 +648,9 @@ Skill: **ipal-nav**.
- Menu: jeden poziom podmenu, nie głębiej. CTA w nagłówku = `links`. - Menu: jeden poziom podmenu, nie głębiej. CTA w nagłówku = `links`.
- Logo i nazwa z Site Settings — nie duplikuj pól w Header. - Logo i nazwa z Site Settings — nie duplikuj pól w Header.
- **Linki prawne w stopce** z ról System Pages (`getSystemPagePath`), nie ręcznie. - **Linki prawne w stopce** z ról System Pages (`getSystemPagePath`), nie ręcznie.
- Linki rozwiązuj **na serwerze** (`resolveNav` → `{ href, label, newTab }`); do - Linki rozwiązuj **na serwerze**: `await resolveNav(header.navItems, locale)` z `lib/content`
komponentu klienckiego idą tylko proste dane — `CMSLink` jest serwerowy. → `{ href, label, internal, newTab, targetProps, children }[]` (martwe linki pominięte); do
komponentu klienckiego (MobileNav) idą tylko te dane — `CMSLink` jest serwerowy.
- Etykiety a11y (przycisk menu) — pola w panelu. - Etykiety a11y (przycisk menu) — pola w panelu.
- Global zmieniany na każdej stronie → `afterChange` z `revalidatePath('/', 'layout')`. - Global zmieniany na każdej stronie → `afterChange` z `revalidatePath('/', 'layout')`.
- Globale pobiera tylko `[locale]/layout.tsx` i podaje jako props. - Globale pobiera tylko `[locale]/layout.tsx` i podaje jako props.
@@ -613,6 +699,43 @@ bloku nie importował Reacta). Kod: [kod-sekcji.md](./skills/ipal-block/resource
- Warianty → `Record<Variant, string>`, nie łańcuchy ternary. - Warianty → `Record<Variant, string>`, nie łańcuchy ternary.
Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md).
### 6.11a Skalowanie (fluid / responsive) — od 360 px do 1920 px
- **Skala z pluginu:** `fluid.css` (rośnie do 1280 px) albo `fluid-wide.css` (rośnie do 1920 px —
wybierz, gdy projekt ma wyglądać inaczej na 13″ laptopie i 27″ monitorze). Zero `clamp()` w
komponentach; liczby z `DESIGN.md` → nadpisz `--ipal-*` w `:root`.
- **Wysokość ekranu:** zamiast `h-screen` / `100vh` → `min-h-[var(--ipal-hero-min-h)]` (svh, z
limitem). Nagłówek hero `--ipal-fs-display-fit`, odstępy hero `--ipal-space-section-fit` — na
1366×768 CTA hero musi być widoczne bez przewijania.
- **Szerokości:** kontener `max-w-[var(--ipal-container)]` + `px-gutter`; tekst ciągły
`max-w-[var(--ipal-measure)]` (~68 znaków w linii). Żadnych stałych `w-[640px]`, `h-[500px]`
w sekcjach — `min()`, `%`, `aspect-*`, `max-w-*`.
- **Siatki:** `grid-cols-[repeat(auto-fit,minmax(min(100%,18rem),1fr))]` albo breakpointy;
karta reaguje na swoją kolumnę: container queries (`@container` + `@md:`), nie tylko na ekran.
- **Obrazy kadrowane** (`object-cover`) mają punkt ostrości z panelu (`focalPoint: true` w
Media → `object-position` z `mediaImageProps`).
- **Ekrany testowe** (każda strona, przeglądarka / Playwright): 360×740, 390×844, 768×1024,
1024×768, **1280×800, 1366×768, 1440×900** (laptopy 13–15″), 1536×864, 1920×1080, plus
zoom 125 % i 150 % na 1366 (częsty na Windows). Zero poziomego scrolla, tekst bez ucięć,
menu działa, CTA hero widoczne.
### 6.11b Szybkość (Core Web Vitals)
| Co | Jak | Zakaz |
|---|---|---|
| obraz LCP (pierwszy widoczny, zwykle hero) | `<Media priority>` — dokładnie jeden na stronę | `priority` na wielu obrazach, hero jako CSS `background-image` |
| każdy inny obraz | `<Media sizes={MEDIA_SIZES.third}>` — `sizes` = szerokość na ekranie | brak `sizes` (pobiera pełną szerokość), `<img>` |
| placeholder | `buildMediaPlaceholderHook` + pole w Media (blur + kolor) | puste pudełka „wskakujące” przy ładowaniu |
| wideo w tle | `videoMode="background"`, MP4 H.264 ≤ 20 MB, bez dźwięku, z plakatem | wideo jako hero bez plakatu, `autoplay` z dźwiękiem |
| wideo z treścią | `videoMode="player"` (ładuje się po kliknięciu) | `preload="auto"` |
| YouTube | `<YouTubeEmbed>` z `/client` (iframe dopiero po kliknięciu) | gołe `<iframe src="youtube.com/embed…">` |
| next.config | `images: { ...buildImagesConfig() }` (AVIF/WebP, R2) | brak `remotePatterns` → obrazy z R2 bez optymalizacji |
| fonty | `next/font`, maks. 2 rodziny × 2–3 grubości, `subsets: ['latin', 'latin-ext']` (PL), `display: 'swap'` | `<link>` do Google Fonts, 6 grubości „na zapas” |
| skrypty firm trzecich | `Analytics`/`ConsentScript` z pluginu (po zgodzie, `defer`) | widgety czatu/map ładowane na starcie |
| komponenty klienckie | małe, tylko interakcja (§6.9) | cała sekcja `'use client'` |
Cel na zbudowanej stronie (mobile, Lighthouse/PageSpeed): LCP < 2,5 s, CLS < 0,1, INP < 200 ms.
Kontrole: `ipal-audit` (img/video poza Media, wiele `priority`, `h-screen`, stałe szerokości,
`<iframe>` YouTube) i `ipal-seo-check` (obrazy bez wymiarów, obraz LCP bez priorytetu).
### 6.12 Eksporty i importy ### 6.12 Eksporty i importy
- **Eksporty nazwane** (`export function Hero`). `export default` tylko tam, - **Eksporty nazwane** (`export function Hero`). `export default` tylko tam,
@@ -632,36 +755,93 @@ Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sek
## 7. WZORCE PLUGINU — UŻYWAJ, NIE PISZ OD NOWA ## 7. WZORCE PLUGINU — UŻYWAJ, NIE PISZ OD NOWA
Katalog: **potrzeba → import**. Zanim napiszesz helper, hook, komponent logiki albo trasę —
znajdź ją tutaj. Wejścia: `@intecion/ipal-kit` (serwer/config), `/client` (`'use client'`),
`/rsc` (komponenty serwerowe), `/server` (server actions), `/admin` (panel), `/env`
(`instrumentation.ts`). Plugin daje **logikę i szkielet**; wygląd zostaje w projekcie
(klasy, `classNames`, własny markup na hooku). Nie ma czegoś, co powtórzy się w innym
projekcie → **ipal-plugin-gap**, nie kopia.
**Strona i dane** (`lib/content.ts` = `createContentHelpers`, PROGRAMISTA §2.7)
| Potrzeba | Użyj | Doc | | Potrzeba | Użyj | Doc |
|---|---|---| |---|---|---|
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField`, `resolveLinkHref` | links.md | | Payload, ustawienia, języki (cache na żądanie) | `getCachedPayload`, `getSettings`, `getConfiguredLocales` | content.md |
| Strona catch-all (route, 308, 404, meta, static params, JSON-LD, bloki) | `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })` (`/rsc`) | pages.md |
| 404 z panelu w każdym języku | `createNotFoundPage(content, { blocks, fallback })` (`/rsc`) | pages.md |
| Layout: zgoda, baner, Turnstile, analityka, JSON-LD strony, preconnect | `getSiteShell(locale)` + `<SiteProviders shell>` (`/rsc`) | consent.md |
| Własna strona / archiwum | `resolveRoute`, `getEntries`, `resolvePageRedirect`, `generatePageMetadata`, `getPageJsonLd`, `generateStaticParams` | content.md, pages.md |
| Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md | | Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md |
| Rich text | `RenderRichText` (`/rsc`), styl przez `converters` | richtext.md | | Rich text / Lexical → Markdown | `RenderRichText` (`/rsc`, styl przez `converters`), `lexicalToMarkdown` | richtext.md |
| Wartość zlokalizowana | `resolveLocalized(value, locale)` (nie `getSafeString`) | forms.md | | Wartość zlokalizowana | `resolveLocalized(value, locale)` (nie `getSafeString`) | i18n.md |
| Formularz | builder w panelu + `FormRenderer` + akcja `sendForm` → `submitForm`; logika `useForm`; IP: `clientIp(await headers())` | forms.md |
| Turnstile | `TurnstileProvider siteKey={(await getTurnstileConfig(payload)).siteKey}` w layoutcie + `useTurnstile()` — przy obu kluczach token jest wymagany | turnstile.md | **Pola i panel**
| Slug | `buildSlugField({ from: 'title' })` | slug.md | | Potrzeba | Użyj | Doc |
| noindex | `buildNoindexField()` | seo.md | |---|---|---|
| Ścieżki językowe | `getLocalizedSlugs`, `switchLocalePath`, `LanguageSwitcher` | i18n.md | | Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField` | links.md |
| Strony systemowe, 404 | `getSystemPagePath`, `getNotFoundPage` | pages.md | | Nagłówek i ustawienia sekcji | `buildSectionHeaderField`, `buildSectionSettingsField({ backgrounds })` | blocks.md |
| Routing, archiwa | `resolveRoute`, `getEntries`, `resolveRedirect` | content.md | | Czytelne wiersze tablic | `rowLabel(['heading'], 'Feature')` (+ `generate:importmap`) | links.md |
| ISR po zapisie | `buildRevalidateHook` (wstrzyknięty `revalidatePath`) | hooks.md | | Slug / noindex / opis dla AI | `buildSlugField`, `buildNoindexField`, `buildSummaryField` | slug.md, seo.md |
| Stary slug → 308 | `trackSlugHistoryHook` + `resolveRedirect` | hooks.md | | Strony systemowe i ich ochrona | `getSystemPagePath`, `buildPreventDeleteSystemPage`, `buildValidateUniqueRole` | pages.md, hooks.md |
| Obrazy między językami | `buildCrossLocaleFieldSync` (języki z configu) | hooks.md | | ISR po zapisie, stary slug → 308, obrazy między językami | `buildRevalidateHook`, `trackSlugHistoryHook`, `buildCrossLocaleFieldSync` | hooks.md |
| Ochrona stron systemowych | `buildPreventDeleteSystemPage`, `buildValidateUniqueRole` | hooks.md | | Role i dostęp | `adminOnly`, `adminOrEditor`, `adminOrSelf`, `authenticated`, `requireRole`, `hasMinimumRole` (+ `…Field`) | access.md |
| Metadata, sitemap, JSON-LD | `generatePageMetadata` (z `createContentHelpers`), `sitemapRoute`, `build*JsonLd` + `JsonLdGraph` | seo.md | | Dane z globali | `getGlobal`, `getSiteSettings`, `getSiteIntegrations` | payload-helpers.md |
| GEO (AI) | `createLlmsTxtRoute` (+ `full: true`), `createMarkdownRenderer` + `markdownResponse`, `markdownAlternate: true`, `createProxy({ markdown: true })`, `createMcpRoute`, `buildSummaryField` | seo.md, content.md, mcp.md |
| Consent, analytics, pixele | `ConsentProvider`, `CookieBanner`, `Analytics` (wewnątrz providera) | consent.md, analytics.md | **Linki i nawigacja**
| Nagłówki, CSP, 2FA | `buildSecurityHeaders`, `buildCsp`, `twoFactor` (wstrzyknięty `payloadTotp`) | security.md | | Potrzeba | Użyj | Doc |
| Media, R2 | `buildR2Storage(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField`, `MediaPreconnect` | storage.md | |---|---|---|
| Email | `email: mailAdapter()` | email.md | | href + nowa karta + rel + internal dla linku z panelu | `resolveLink(link, locale)` (`lib/content`) / `resolveLink(link, opts)` | links.md |
| Walidacja env | `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` z `@intecion/ipal-kit/env` | env.md | | Menu z globala (dowolna głębokość, martwe linki pominięte) | `resolveNav(items, locale)` | links.md |
| Ścieżki językowe, przełącznik, hreflang | `getLocalizedSlugs`, `switchLocalePath`, `LanguageSwitcher`, `buildLocalizedPath` | i18n.md |
| Bezpieczny URL (bez `javascript:`) | `safeHref` | links.md |
**Formularze**
| Potrzeba | Użyj | Doc |
|---|---|---|
| Formularz z panelu w bloku (kroki, radio, listy, daty) | `<RenderForm form action locale texts classNames>` (`/rsc`) | forms.md |
| Wygląd formularzy | `formClasses.ts` (`BuilderFormClassNames`) — raz na projekt | forms.md |
| Nietypowy markup formularza | `BuilderForm renderField` / `useBuilderForm` (`/client`) | forms.md |
| Wysyłka | `createSubmitAction({ getCachedPayload, headers })` (`/server`) | forms.md |
| Teksty komunikatów i przycisków kroków | Notifications → `getFormTexts(locale)` | notifications.md |
| Formularz w bazie | seed `ipal-form/resources/seed-form.template.ts` | forms.md |
| Antyspam / limit / IP | honeypot w `BuilderForm`, Turnstile z `SiteProviders`, `clientIp`, `setRateLimitStore` | forms.md, turnstile.md |
| Zdarzenie GTM po wysłaniu | `buildFormAnalyticsFields` (panel) — `RenderForm` wysyła je sam | forms.md |
| Formularz spoza buildera (np. filtry) | `useForm` + `buildValidator`, `required`, `email`… | forms.md |
**SEO i GEO** (trasy = re-eksport z `lib/content`)
| Potrzeba | Użyj | Doc |
|---|---|---|
| Metadata, kanoniczne, hreflang, OG, X | `generatePageMetadata` (`createPageRoute` robi to sam) | seo.md |
| sitemap / robots / manifest | `sitemapRoute`, `robots`, `manifest` | seo.md |
| JSON-LD | `getSiteShell().jsonLd`, `getPageJsonLd`, `build*JsonLd`, `formatOpeningHours`, `sameAsUrls`, `<JsonLdGraph>` | seo.md |
| llms.txt / llms-full / Markdown / MCP | `llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`; `markdownAlternate: true`; `createProxy({ markdown: true })` | seo.md, content.md, mcp.md |
| IndexNow | `ipalKit({ indexNow: true })` + `indexNowKeyRoute` | seo.md |
| Wyszukiwarka | `createSearchRoute` | content.md |
**Media, wygląd, szybkość**
| Potrzeba | Użyj | Doc |
|---|---|---|
| R2, nazwy plików, optymalizacja, podgląd | `buildR2Storage`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` | storage.md |
| Obraz / wideo w `<Media>` | `mediaImageProps`, `videoProps`, `MEDIA_SIZES` | storage.md |
| YouTube bez ciasteczek przed kliknięciem | `<YouTubeEmbed>` (`/client`) | storage.md |
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders`, `buildCsp`, `buildUploadSecurityHeaders` | storage.md, security.md |
| Płynna typografia i odstępy | `fluid.css` / `fluid-wide.css` (zmienne `--ipal-*`) | PROGRAMISTA §2.5 |
**Zgoda, analityka, operacje**
| Potrzeba | Użyj | Doc |
|---|---|---|
| Baner, ustawienia, przycisk cookies | `<SiteProviders banner={<CookieBanner …/>}>`, `CookieButton`, `useConsent` | consent.md |
| Skrypt zależny od zgody | `ConsentScript` | consent.md |
| Tabela ciasteczek na polityce | `<CookieTable>` (`/rsc`), `getCookieTable` | consent.md |
| GA4, GTM, Pixel, Clarity, LinkedIn, TikTok | ID w panelu — `SiteProviders` ładuje `Analytics` (`analytics={{ defer: true }}`) | analytics.md |
| Mail | `email: mailAdapter()`, `sendEmail` | email.md |
| Walidacja env, health | `assertEnv(ipalEnvRules({…}))` (`/env`), `healthRoute` | env.md |
| 2FA, white-label, nagłówki | `twoFactor: { issuer, plugin: payloadTotp }`, `whiteLabel`, `buildSecurityHeaders` | security.md, white-label.md |
| Rate limit (formularze, MCP, wyszukiwarka) | wbudowany; IP z `IPAL_IP_HEADER`; kilka instancji → `setRateLimitStore` | forms.md | | Rate limit (formularze, MCP, wyszukiwarka) | wbudowany; IP z `IPAL_IP_HEADER`; kilka instancji → `setRateLimitStore` | forms.md |
**Compliance (PL/EU) — mechanizm z pluginu, treść od klienta:** strony polityk **Compliance (PL/EU) — mechanizm z pluginu, treść od klienta:** strony polityk
jako System Pages, `CookieBanner` + `CookieButton`, checkbox `consent` w jako System Pages, `CookieBanner` + `CookieButton`, checkbox `consent` w
formularzach (enforcement server-side), dane administratora w globalu, polityki z formularzach (enforcement server-side), dane administratora w globalu, tabela
`noindex`. Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient ciasteczek z panelu (`<CookieTable>`, skan: ipal-consent-check). Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
wymaga (accessibility.md). wymaga (accessibility.md).
**Bezpieczeństwo:** 2FA wymuszone (`ipalKit({ twoFactor: { issuer, plugin: **Bezpieczeństwo:** 2FA wymuszone (`ipalKit({ twoFactor: { issuer, plugin:
@@ -670,6 +850,32 @@ payloadTotp } })`, nigdy `twoFactor: false` bez decyzji klienta). CSP: najpierw
--- ---
## 8a. TESTY — co sprawdzasz i jak
Testujesz **zachowanie, które klient i Google widzą**, nie implementację pluginu (ten ma
własne testy). Kolejność od najtańszych:
| Poziom | Co | Kiedy |
|---|---|---|
| Typy | `pnpm generate:types && pnpm tsc --noEmit` | po każdej zmianie schematu |
| Reguły | `ipal-audit --quick` (hardkody, komplet §0b, panel) | po każdym bloku / kolekcji |
| Build | `pnpm build` — trasy stron `●` (SSG), nie `ƒ` | przed każdym „gotowe” |
| Smoke (Playwright) | `ipal-audit/resources/smoke.spec.template.ts` → `tests/smoke.spec.ts`: wszystkie URL-e z sitemapy 200 + tytuł + jedno h1, 404, trasy GEO, baner, formularz end-to-end | przed oddaniem i po każdej aktualizacji ipal-kit |
| Strona w przeglądarce | `ipal-seo-check`, `ipal-consent-check`, `cookie-scan` | przed oddaniem, po deployu |
| Logika projektu | vitest dla własnych funkcji (mapowanie danych firmy na JSON-LD, helpery, hooki, skrypty migracji z `--dry-run`) | gdy piszesz logikę, której plugin nie ma |
| Panel | test redaktora (§11) i test pustego bloku (§6.5a) | każdy nowy blok / global |
Zasady:
- **Test niezależny od treści** — szuka elementów po rolach i `data-ipal`, URL-i z sitemapy, nie po
tekstach, które redaktor zmieni jutro.
- **Każdy naprawiony błąd = test**, który by go złapał (smoke albo vitest), żeby nie wrócił.
- **Formularz testujesz naprawdę**: wysyłka → rekord w Form Submissions → mail do firmy **i**
potwierdzenie do klienta (lokalnie: Site Integrations → Send test + logi adaptera).
- **Nie testujesz pluginu w projekcie** (np. czy `submitForm` waliduje) — to robi ipal-kit. Gdy
zachowanie pluginu jest złe: ipal-plugin-gap.
- Testy w CI projektu: typy + audit `--quick` + build na każdy push; smoke na stagingu
(`IPAL_NOINDEX=1`) przed wdrożeniem produkcji.
## 8. STANDARDY KODU ## 8. STANDARDY KODU
**Typy** **Typy**
@@ -0,0 +1,78 @@
/**
* Smoke tests of a client site (Playwright) — the few things that must never
* break: every language's homepage, a real 404, the form end to end, the
* language switch, the GEO routes. Copy to tests/smoke.spec.ts and run against
* a production build:
*
* pnpm add -D @playwright/test && pnpm exec playwright install chromium
* pnpm build && pnpm start &
* BASE_URL=http://localhost:3000 pnpm exec playwright test tests/smoke.spec.ts
*
* Content-agnostic on purpose: it reads locales from the sitemap and finds the
* form by its renderer, so it survives editors changing texts in the panel.
* Turnstile: run with the test keys in Site Integrations (1x00000000000000000000AA /
* 1x0000000000000000000000000000000AA) or without keys.
*/
import { expect, test } from '@playwright/test'
const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '')
async function sitemapUrls(): Promise<string[]> {
const xml = await (await fetch(`${BASE}/sitemap.xml`)).text()
return [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/^https?:\/\/[^/]+/, BASE))
}
test('every sitemap URL answers 200 with a title and one h1', async ({ page }) => {
const urls = (await sitemapUrls()).slice(0, 30)
expect(urls.length).toBeGreaterThan(0)
for (const url of urls) {
const res = await page.goto(url)
expect(res?.status(), url).toBe(200)
await expect(page, url).toHaveTitle(/\S/)
expect(await page.locator('h1').count(), `${url}: exactly one h1`).toBe(1)
}
})
test('unknown URL is a real 404', async ({ request }) => {
const res = await request.get(`${BASE}/this-page-does-not-exist-${Date.now()}`, { maxRedirects: 5 })
expect(res.status()).toBe(404)
})
test('GEO routes answer', async ({ request }) => {
for (const path of ['/robots.txt', '/sitemap.xml', '/llms.txt', '/llms-full.txt', '/api/health']) {
expect((await request.get(`${BASE}${path}`)).status(), path).toBe(200)
}
const mcp = await request.post(`${BASE}/api/mcp`, { data: { id: 1, jsonrpc: '2.0', method: 'tools/list' } })
expect(((await mcp.json()) as { result: { tools: unknown[] } }).result.tools.length).toBeGreaterThan(0)
})
test('cookie banner: reject hides it and survives a reload', async ({ page }) => {
await page.goto(BASE)
await page.locator('[data-ipal="reject"]').click()
await expect(page.locator('[data-ipal="banner"]')).toBeHidden()
await page.reload()
await expect(page.locator('[data-ipal="banner"]')).toBeHidden()
})
test('the first form on the site submits and shows the confirmation', async ({ page }) => {
const urls = await sitemapUrls()
let found = false
for (const url of urls) {
await page.goto(url)
const form = page.locator('form').filter({ has: page.locator('[type="submit"]') }).first()
if (!(await form.count())) {continue}
found = true
await page.locator('[data-ipal="reject"]').click().catch(() => {})
for (const input of await form.locator('input:not([type=hidden]):not([type=checkbox]), textarea').all()) {
const type = await input.getAttribute('type')
if (await input.getAttribute('name') === 'company_url') {continue} // honeypot stays empty
await input.fill(type === 'email' ? '[email protected]' : type === 'number' ? '1' : 'Smoke test')
}
for (const box of await form.locator('input[type=checkbox]').all()) {await box.check()}
for (const select of await form.locator('select').all()) {await select.selectOption({ index: 1 }).catch(() => {})}
await form.locator('[type="submit"]').click()
await expect(page.locator('[role="status"], [role="alert"]').first()).toBeVisible({ timeout: 15_000 })
break
}
test.skip(!found, 'no form on the site')
})
+70 -19
View File
@@ -41,7 +41,8 @@ report() {
g() { grep -rnE "$@" 2>/dev/null || true; } g() { grep -rnE "$@" 2>/dev/null || true; }
# drop matches that sit inside a // or /* comment (keeps http:// URLs) # drop matches that sit inside a // or /* comment (keeps http:// URLs)
nc() { grep -vE "(^|[^:])//.*$1|/\*.*$1" || true; } # (also a whole-line comment right after grep's "file:line:" prefix)
nc() { grep -vE "^[^:]+:[0-9]+:[[:space:]]*(//|/?\*)|(^|[^:])//.*$1|/\*.*$1" || true; }
dirs() { for d in "$@"; do [ -d "$d" ] && printf '%s ' "$d"; done; } dirs() { for d in "$@"; do [ -d "$d" ] && printf '%s ' "$d"; done; }
BLOCKS=$(dirs src/blocks) BLOCKS=$(dirs src/blocks)
@@ -105,12 +106,27 @@ if [ -n "$BLOCKS" ]; then
report ERROR "hardcoded href/src/file paths in blocks" "§2, §6 use CMSLink / Media" \ report ERROR "hardcoded href/src/file paths in blocks" "§2, §6 use CMSLink / Media" \
"$(g 'href=\{?["`]/|<img |/files/|/images/|\.pdf' $BLOCKS --include=*.tsx | nc '(href|<img|/files/|/images/|\.pdf)')" "$(g 'href=\{?["`]/|<img |/files/|/images/|\.pdf' $BLOCKS --include=*.tsx | nc '(href|<img|/files/|/images/|\.pdf)')"
report WARNING "button styled inside a section" "§6.0 style buttons once in Button.tsx — sections render <CMSLink> (appearance from the panel)" \
"$(g '<button[^>]*className=[^>]*(bg-|rounded|px-[0-9])' $BLOCKS --include=*.tsx)"
report ERROR "raw <a>/<Link> in blocks" "§6.3 links from the panel render via CMSLink" \ report ERROR "raw <a>/<Link> in blocks" "§6.3 links from the panel render via CMSLink" \
"$(g '<(a|Link)[ >]' $BLOCKS --include=*.tsx)" "$(g '<(a|Link)[ >]' $BLOCKS --include=*.tsx)"
report ERROR "hardcoded text in blocks" "§2 every visible text comes from the panel (localized field)" \ report ERROR "hardcoded text in blocks" "§2 every visible text comes from the panel (localized field)" \
"$(node "$(dirname "$0")/jsx-text.mjs" $BLOCKS 2>/dev/null)" "$(node "$(dirname "$0")/jsx-text.mjs" $BLOCKS 2>/dev/null)"
report WARNING "<video> outside <Media>" "§6.11b videoMode background|player via Media (videoProps)" \
"$(g '<video[ >]' $BLOCKS --include=*.tsx)"
report WARNING "priority outside the hero" "§6.11b exactly one LCP image per page — priority only in the first section" \
"$(g '<Media[^>]*\bpriority\b' $BLOCKS --include=*.tsx | grep -viE '/hero')"
report WARNING "<Media> without sizes" "§6.11b sizes = width on screen (MEDIA_SIZES.*) — without it the full-width file downloads" \
"$(g '<Media[^>]*/>' $BLOCKS --include=*.tsx | grep -v 'sizes=')"
report WARNING "raw YouTube iframe" "§6.11b <YouTubeEmbed> (iframe only after click, no cookies before)" \
"$(g '<iframe[^>]*youtube' src --include=*.tsx)"
report WARNING "inline <svg> in blocks" "§6.10 icons via media upload or Icon map" \ report WARNING "inline <svg> in blocks" "§6.10 icons via media upload or Icon map" \
"$(g '<svg[ >]' $BLOCKS --include=*.tsx)" "$(g '<svg[ >]' $BLOCKS --include=*.tsx)"
@@ -127,6 +143,12 @@ if [ -d src/components ]; then
fi fi
if [ -n "$UI" ]; then if [ -n "$UI" ]; then
report WARNING "100vh / h-screen" "§6.11a use min-h-[var(--ipal-hero-min-h)] (svh, capped) — 100vh overflows on laptops and mobile bars" \
"$(g '\b(h-screen|min-h-screen|h-\[100vh\]|min-h-\[100vh\])' $UI --include=*.tsx)"
report WARNING "fixed pixel widths/heights" "§6.11a no w-[640px]/h-[500px] in sections — max-w-*, %, aspect-*, min()" \
"$(g '\b(w|h|min-w|min-h)-\[[0-9]{3,}px\]' $UI --include=*.tsx)"
report ERROR "hex colors in classes" "§6.11 use design tokens (bg-primary…)" \ report ERROR "hex colors in classes" "§6.11 use design tokens (bg-primary…)" \
"$(g '(bg|text|border|from|to|via|fill|stroke)-\[#' $UI --include=*.tsx)" "$(g '(bg|text|border|from|to|via|fill|stroke)-\[#' $UI --include=*.tsx)"
@@ -142,8 +164,10 @@ fi
# --- Collections (§5.3) --- # --- Collections (§5.3) ---
if [ -d src/collections ]; then if [ -d src/collections ]; then
report ERROR "forbidden collection" "§5.3 users are built in; settings/nav/footer are globals; FAQ/hero are blocks" \ report ERROR "forbidden collection" "§5.3 settings/nav/footer are globals; FAQ/hero are blocks" \
"$(ls src/collections | grep -iE '^(users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')" "$(ls src/collections | grep -iE '^(settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
report WARNING "own users collection" "§5.3 ipalKit injects the auth collection — keep your own only to add fields (roles + 2FA still attach)" \
"$(ls src/collections | grep -iE '^(users|user)\.ts$')"
report WARNING "collections present — confirm each passed the §5.3 test" "minimum: Pages, Media" \ report WARNING "collections present — confirm each passed the §5.3 test" "minimum: Pages, Media" \
"$(ls src/collections | grep -viE '^(pages|media|users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')" "$(ls src/collections | grep -viE '^(pages|media|users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
fi fi
@@ -166,6 +190,15 @@ report WARNING "files that usually duplicate the plugin" "§3 plugin has resolve
"$(ls src/lib/pages.ts src/lib/locales.ts 2>/dev/null)" "$(ls src/lib/pages.ts src/lib/locales.ts 2>/dev/null)"
report ERROR "project copy of link fields" "links.md — use buildLinkField / buildLinksField / resolveLinkHref from the plugin" \ report ERROR "project copy of link fields" "links.md — use buildLinkField / buildLinksField / resolveLinkHref from the plugin" \
"$(ls src/fields/link.ts src/lib/links.ts 2>/dev/null; g "from '@/fields/link'|from '@/lib/links'" src --include=*.ts --include=*.tsx)" "$(ls src/fields/link.ts src/lib/links.ts 2>/dev/null; g "from '@/fields/link'|from '@/lib/links'" src --include=*.ts --include=*.tsx)"
# Hand-rolled link resolution under another name (resolveHref, getHref…): the plugin knows the
# homepage from Site Settings, adds the locale prefix, drops unsafe URLs and dead links.
FRONT=$(dirs src/app src/blocks src/components src/lib src/globals src/collections)
if [ -n "$FRONT" ]; then
report ERROR "hardcoded homepage slug" "links.md — the homepage comes from Site Settings: resolveLink(link, locale) / getHomeSlug(locale), never a slug name in code" \
"$(g "(===|!==|==|!=) *['\"](home|homepage|strona-glowna|glowna|start|index)['\"]|['\"](home|homepage|strona-glowna|glowna|start|index)['\"] *(===|!==|==|!=)" $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | grep -vE "[Tt]ype *[!=]==? *['\"]home|['\"]home['\"] *[!=]==? *[A-Za-z_.]*[Tt]ype" | nc '=')"
report ERROR "URL built from a slug by hand" "links.md — resolveLink / resolveNav (lib/content) or buildLocalizedPath: locale prefix, homepage, unsafe and dead links" \
"$(g '`/\$\{[^}]*[Ss]lug|['"'"'"]/['"'"'"] *\+ *[A-Za-z_.?]*[Ss]lug' $FRONT --include=*.ts --include=*.tsx | grep -v '/(payload)/' | nc '[Ss]lug')"
fi
report ERROR "manual Lexical rendering" "§7 use RenderRichText" \ report ERROR "manual Lexical rendering" "§7 use RenderRichText" \
"$(g 'node\.type *===' src --include=*.tsx | nc 'node')" "$(g 'node\.type *===' src --include=*.tsx | nc 'node')"
HTML=$(node "$(dirname "$0")/html-check.mjs" src) HTML=$(node "$(dirname "$0")/html-check.mjs" src)
@@ -193,32 +226,35 @@ APP=$(dirs src/app)
if [ -n "$APP" ]; then if [ -n "$APP" ]; then
# SEO # SEO
need ERROR '' "page metadata" "generatePageMetadata (lib/content) in generateMetadata of the page routes" 'generatePageMetadata|createPageMetadata|createMetadataGenerator' src/app need ERROR '' "page metadata" "generatePageMetadata (lib/content) in generateMetadata of the page routes" 'generatePageMetadata|createPageMetadata|createMetadataGenerator|createPageRoute' src/app
need ERROR '' "sitemap.xml route" "src/app/sitemap.xml/route.ts → sitemapRoute" 'sitemapRoute|createSitemapRouteHandler|buildSitemapEntries|sitemap' src/app/sitemap.xml src/app/sitemap.ts need ERROR '' "sitemap.xml route" "src/app/sitemap.xml/route.ts → sitemapRoute" 'sitemapRoute|createSitemapRouteHandler|buildSitemapEntries|sitemap' src/app/sitemap.xml src/app/sitemap.ts
need ERROR '' "robots" "src/app/robots.ts → robots from lib/content" 'robots|buildRobots' src/app/robots.ts need ERROR '' "robots" "src/app/robots.ts → robots from lib/content" 'robots|buildRobots' src/app/robots.ts
need ERROR '' "manifest" "src/app/manifest.ts → createManifestHandler" 'createManifestHandler|buildManifest' src/app/manifest.ts need ERROR '' "manifest" "src/app/manifest.ts → export { manifest as default } from '@/lib/content'" 'manifest|createManifestHandler|buildManifest' src/app/manifest.ts
need ERROR '' "htmlLimitedBots" "next.config.ts — metadata must reach crawlers in <head>" 'htmlLimitedBots' next.config.ts next.config.mjs next.config.js need ERROR '' "htmlLimitedBots" "next.config.ts — metadata must reach crawlers in <head>" 'htmlLimitedBots' next.config.ts next.config.mjs next.config.js
need ERROR jsonld "structured data" "<JsonLdGraph> with WebSite + Organization/LocalBusiness in [locale]/layout.tsx" 'JsonLdGraph' src need ERROR jsonld "structured data" "<SiteProviders shell={await getSiteShell(locale)}> (WebSite + Organization) or <JsonLdGraph> in [locale]/layout.tsx" 'JsonLdGraph|SiteProviders' src
# GEO # GEO
need ERROR llms "llms.txt" "src/app/llms.txt/route.ts → createLlmsTxtRoute" 'createLlmsTxtRoute|buildLlmsTxt' src/app need ERROR llms "llms.txt" "src/app/llms.txt/route.ts → export { llmsRoute as GET } from '@/lib/content'" 'llmsRoute|createLlmsTxtRoute|buildLlmsTxt' src/app
need ERROR llms-full "llms-full.txt" "src/app/llms-full.txt/route.ts → createLlmsTxtRoute({ full: true })" 'full: *true' src/app/llms-full.txt need ERROR llms-full "llms-full.txt" "src/app/llms-full.txt/route.ts → export { llmsFullRoute as GET } from '@/lib/content'" 'llmsFullRoute|full: *true' src/app/llms-full.txt
need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts → createMarkdownRenderer + markdownResponse" 'createMarkdownRenderer' src/app need ERROR markdown "Markdown route" "src/app/md/[locale]/[[...slug]]/route.ts → export { markdownRoute as GET } from '@/lib/content'" 'markdownRoute|createMarkdownRoute|createMarkdownRenderer' src/app
need WARNING jsonld "page structured data" "[[...slug]]/page.tsx → createPageRoute (adds getPageJsonLd) or <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />" 'createPageRoute|getPageJsonLd|buildWebPageJsonLd|buildBreadcrumbJsonLd' src/app
need ERROR markdown "Markdown in proxy" "proxy.ts → createProxy(i18nConfig, { NextResponse, markdown: true }) — without it /md/… is redirected to /<locale>/md/…" 'markdown: *(true|['"'"'"])|prefersMarkdown' src/proxy.ts proxy.ts need ERROR markdown "Markdown in proxy" "proxy.ts → createProxy(i18nConfig, { NextResponse, markdown: true }) — without it /md/… is redirected to /<locale>/md/…" 'markdown: *(true|['"'"'"])|prefersMarkdown' src/proxy.ts proxy.ts
need WARNING markdown "Markdown alternate link" "createContentHelpers({ markdownAlternate: true }) or markdownHref in metadata" 'markdownAlternate|markdownHref' src need WARNING markdown "Markdown alternate link" "createContentHelpers({ markdownAlternate: true }) or markdownHref in metadata" 'markdownAlternate|markdownHref' src
need ERROR mcp "MCP server" "src/app/api/mcp/route.ts → createMcpRoute (public: AI browses the site)" 'createMcpRoute' src/app need ERROR mcp "MCP server" "src/app/api/mcp/route.ts → export { mcpGET as GET, mcpPOST as POST } from '@/lib/content' (public: AI browses the site)" 'mcpPOST|createMcpRoute' src/app
need WARNING '' "AI summary field" "buildSummaryField() in Pages + summaryField: 'aiSummary' in llms/MCP routes" 'buildSummaryField' src need WARNING '' "AI summary field" "buildSummaryField() in Pages + createContentHelpers({ summaryField: 'aiSummary' })" 'buildSummaryField' src
# Ops # Ops
need ERROR '' "health route" "src/app/api/health/route.ts → createHealthRoute" 'createHealthRoute' src/app need ERROR '' "health route" "src/app/api/health/route.ts → export { healthRoute as GET } from '@/lib/content'" 'healthRoute|createHealthRoute' src/app
need ERROR '' "env validation" "src/instrumentation.ts → assertEnv(ipalEnvRules({...})) from @intecion/ipal-kit/env" 'assertEnv' src/instrumentation.ts instrumentation.ts need ERROR '' "env validation" "src/instrumentation.ts → assertEnv(ipalEnvRules({...})) from @intecion/ipal-kit/env" 'assertEnv' src/instrumentation.ts instrumentation.ts
need ERROR '' "security headers" "next.config.ts → buildSecurityHeaders" 'buildSecurityHeaders' next.config.ts next.config.mjs next.config.js need ERROR '' "security headers" "next.config.ts → buildSecurityHeaders" 'buildSecurityHeaders' next.config.ts next.config.mjs next.config.js
# Consent, analytics, Turnstile (layout) # Consent, analytics, Turnstile (layout)
need ERROR '' "cookie consent" "ConsentProvider + CookieBanner + CookieButton in [locale]/layout.tsx" 'CookieBanner' src/app need ERROR '' "cookie consent" "<SiteProviders> (or ConsentProvider + CookieBanner + CookieButton) in [locale]/layout.tsx" 'SiteProviders|CookieBanner' src/app
need ERROR analytics "analytics" "<Analytics> inside ConsentProvider (IDs from the panel)" '<Analytics' src/app need ERROR analytics "analytics" "<SiteProviders> (loads Analytics) or <Analytics> inside ConsentProvider" 'SiteProviders|<Analytics' src/app
need ERROR turnstile "Turnstile provider" "<TurnstileProvider siteKey> in [locale]/layout.tsx — always, it hides itself without keys" 'TurnstileProvider' src need ERROR turnstile "Turnstile provider" "<SiteProviders> or <TurnstileProvider siteKey> in [locale]/layout.tsx — always, it hides itself without keys" 'SiteProviders|TurnstileProvider' src
need WARNING turnstile "getTurnstileConfig" "siteKey from getTurnstileConfig(payload) — off unless BOTH keys are set" 'getTurnstileConfig' src need WARNING turnstile "Turnstile site key" "getSiteShell(locale) (or getTurnstileConfig(payload)) — off unless BOTH keys are set" 'getSiteShell|getTurnstileConfig' src
need WARNING '' "MediaPreconnect" "<MediaPreconnect/> in the layout (R2 CDN preconnect from env)" 'MediaPreconnect' src/app need WARNING '' "MediaPreconnect" "<SiteProviders> (adds it) or <MediaPreconnect/> in the layout" 'SiteProviders|MediaPreconnect' src/app
# Forms # Forms
need ERROR '' "form submission via the plugin" "server action sendForm → submitForm (ipal-form)" 'submitForm' src need ERROR '' "form submission via the plugin" "actions.ts → export const sendForm = createSubmitAction({ getCachedPayload, headers }) (ipal-form)" 'createSubmitAction|submitForm' src
need WARNING '' "upload sandbox headers" "next.config.ts → ...buildUploadSecurityHeaders() (uploaded SVG can't run script)" 'buildUploadSecurityHeaders' next.config.ts next.config.mjs next.config.js
need WARNING '' "images preset" "next.config.ts → images: { ...buildImagesConfig() } (AVIF/WebP, R2 domain)" 'buildImagesConfig' next.config.ts next.config.mjs next.config.js
fi fi
if [ -n "$CFG" ]; then if [ -n "$CFG" ]; then
@@ -230,6 +266,9 @@ if [ -n "$CFG" ]; then
report WARNING "robots blocks AI bots" "§0b.8 — only with the client's decision in AGENTS.md" \ report WARNING "robots blocks AI bots" "§0b.8 — only with the client's decision in AGENTS.md" \
"$(skipped aibots || g "aiBots: *'(disallow|block-training)'" src --include=*.ts)" "$(skipped aibots || g "aiBots: *'(disallow|block-training)'" src --include=*.ts)"
fi fi
if [ -n "$CFG" ] && grep -qE 'forms *:' "$CFG" 2>/dev/null && ! ls scripts/seed-form* >/dev/null 2>&1 && ! skipped forms-seed; then
report WARNING "no form seed" "ipal-form §5 — every form from scripts/seed-form-*.ts (notification + sender confirmation, all languages)" "scripts/seed-form-*.ts"
fi
need WARNING r2 "R2 env in .env.example" ".env.example lists R2_BUCKET, R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_PUBLIC_URL" 'R2_BUCKET' .env.example need WARNING r2 "R2 env in .env.example" ".env.example lists R2_BUCKET, R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_PUBLIC_URL" 'R2_BUCKET' .env.example
need WARNING '' "IPAL_IP_HEADER in .env.example" "header the rate limit trusts, e.g. cf-connecting-ip (forms.md)" 'IPAL_IP_HEADER' .env.example need WARNING '' "IPAL_IP_HEADER in .env.example" "header the rate limit trusts, e.g. cf-connecting-ip (forms.md)" 'IPAL_IP_HEADER' .env.example
@@ -242,9 +281,21 @@ report ERROR "hand-written JSON-LD script" "§0b — <JsonLdGraph> escapes and w
"$(g 'application/ld\+json' src --include=*.tsx | grep -v 'JsonLdGraph')" "$(g 'application/ld\+json' src --include=*.tsx | grep -v 'JsonLdGraph')"
report ERROR "static SEO files in public/" "§0b — sitemap, robots and llms are generated from the panel" \ report ERROR "static SEO files in public/" "§0b — sitemap, robots and llms are generated from the panel" \
"$(ls public/sitemap.xml public/robots.txt public/llms.txt public/llms-full.txt 2>/dev/null)" "$(ls public/sitemap.xml public/robots.txt public/llms.txt public/llms-full.txt 2>/dev/null)"
report WARNING "<form> outside the form renderer" "§0b — forms render from the panel via FormRenderer (a search box is fine)" \ report WARNING "<form> outside the form renderer" "§0b — panel forms render via <RenderForm> (a search box is fine)" \
"$(g '<form[ >]' src --include=*.tsx | grep -v 'components/forms/')" "$(g '<form[ >]' src --include=*.tsx | grep -v 'components/forms/')"
# Project copies of what the plugin now ships (import instead of code)
report WARNING "own form engine" "ipal-form §3 — <RenderForm> / useBuilderForm (steps, choices, Turnstile, honeypot; Emails tab never reaches the browser)" \
"$(g 'buildValidator|useForm\(' src --include=*.tsx | grep -v 'useBuilderForm')"
report WARNING "project copy of section fields / navigation" "blocks.md, links.md — buildSectionHeaderField, buildSectionSettingsField, resolveNav (lib/content)" \
"$(ls src/fields/sectionHeader.ts src/fields/sectionSettings.ts src/lib/navigation.ts 2>/dev/null)"
if [ -n "$UI" ]; then
for c in $(grep -rlE "^['\"]use client['\"]" $UI 2>/dev/null); do
report ERROR "server entry in client component" "§6.9 '@intecion/ipal-kit' (root), '/rsc', '/server' pull Payload into the browser — client code imports '/client' (types: import type)" \
"$(grep -nE "from '@intecion/ipal-kit(/rsc|/server)?'" "$c" | grep -v 'import type' | sed "s|^|$c:|")"
done
fi
# --- Compile & build --- # --- Compile & build ---
if [ "$QUICK" -eq 0 ]; then if [ "$QUICK" -eq 0 ]; then
echo echo
+5 -5
View File
@@ -1,6 +1,6 @@
--- ---
name: ipal-block name: ipal-block
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short English labels, no empty spare fields), shared fields (sectionHeaderField, buildLinksField, buildLinkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component. description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — a clean editor panel (repeatable things as "+ Add …" arrays with rowLabel, never cta1/cta2 slots, short English labels, no empty spare fields), shared fields from the plugin (buildSectionHeaderField, buildLinksField, buildLinkField, buildSectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
--- ---
# ipal-block # ipal-block
@@ -9,9 +9,9 @@ Jedna sekcja na jedno użycie skilla. Szczegóły i gotowy kod:
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6. `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.
## 0. Warunki wstępne ## 0. Warunki wstępne
Sprawdź, czy istnieją: `src/fields/sectionHeader.ts`, Sprawdź, czy istnieją: `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
`sectionSettings.ts`, `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`. Stare `src/fields/sectionHeader.ts` / `sectionSettings.ts` → zamień na import z pluginu i usuń (blocks.md, bez migracji).
Linki (`buildLinkField`, `buildLinksField`, `resolveLinkHref`) są w pluginie — nie twórz ich w projekcie. Linki (`buildLinkField`, `buildLinksField`, `resolveLink`) i pola sekcji (`buildSectionHeaderField`, `buildSectionSettingsField`) są w pluginie — nie twórz ich w projekcie.
Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill) Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
(i powiedz o tym użytkownikowi). Nie pisz własnych wersji. (i powiedz o tym użytkownikowi). Nie pisz własnych wersji.
@@ -27,7 +27,7 @@ Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`. Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`.
1. `src/blocks/<Nazwa>/config.ts` — `interfaceName: '<Nazwa>Block'`, pola z planu, 1. `src/blocks/<Nazwa>/config.ts` — `interfaceName: '<Nazwa>Block'`, pola z planu,
zawsze `sectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`. zawsze `buildSectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`.
Plik do pobrania = link typu `file`. **Panel wg AGENT.md §6.5a:** Plik do pobrania = link typu `file`. **Panel wg AGENT.md §6.5a:**
- powtarzalne → tablica z `labels: { singular, plural }` + `admin: { initCollapsed: true, components: rowLabel('heading', '<Singular>') }`, `maxRows` z designu; - powtarzalne → tablica z `labels: { singular, plural }` + `admin: { initCollapsed: true, components: rowLabel('heading', '<Singular>') }`, `maxRows` z designu;
- zero numerowanych pól (`cta1`, `feature2Title`, `image3`) i pól „na zapas”; - zero numerowanych pól (`cta1`, `feature2Title`, `image3`) i pól „na zapas”;
@@ -3,7 +3,8 @@
> Zasoby skilla **ipal-block**. Reguły (dlaczego tak, czego nie robić) są w > Zasoby skilla **ipal-block**. Reguły (dlaczego tak, czego nie robić) są w
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6 — ten plik to tylko kod > `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6 — ten plik to tylko kod
> do utworzenia w projekcie **1:1**. Linki (`buildLinkField`, `buildLinksField`, > do utworzenia w projekcie **1:1**. Linki (`buildLinkField`, `buildLinksField`,
> `resolveLinkHref`) są w pluginie — nie twórz ich kopii. > `resolveLink`), pola sekcji (`buildSectionHeaderField`, `buildSectionSettingsField`) i menu
> (`resolveNav`) są w pluginie — nie twórz ich kopii.
## Warstwa 1 — wspólne pola ## Warstwa 1 — wspólne pola
@@ -29,53 +30,17 @@ Kolekcja `media` dopuszcza PDF (`upload.mimeTypes: ['image/*', 'application/pdf'
'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`. 'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`.
„Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`. „Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`.
`src/fields/sectionHeader.ts` i `src/fields/sectionSettings.ts`: **Nagłówek i ustawienia sekcji — z pluginu, nie kopiuj kodu** (`docs/blocks.md`):
```ts ```ts
import type { GroupField } from 'payload' import { buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
export function sectionHeaderField(name = 'header'): GroupField { buildSectionHeaderField() // grupa `header`: eyebrow, heading, intro (localized) — typ SectionHeaderData
return { buildSectionSettingsField() // sidebar `settings`: anchor, background (default/muted/inverted) — typ SectionSettings
name, buildSectionSettingsField({ backgrounds: [{ label: 'Default', value: 'default' }, { label: 'Brand', value: 'brand' }] })
type: 'group',
interfaceName: 'SectionHeaderData',
fields: [
{ name: 'eyebrow', type: 'text', localized: true, admin: { description: 'Small line above the heading. Optional.' } },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', localized: true, admin: { rows: 3 } },
],
}
}
export function sectionSettingsField(): GroupField {
return {
name: 'settings',
type: 'group',
label: 'Section settings',
interfaceName: 'SectionSettings',
admin: { position: 'sidebar' },
fields: [
{
name: 'anchor',
type: 'text',
admin: { description: 'Section id for #links and section nav, e.g. "pricing".' },
},
{
name: 'background',
type: 'select',
defaultValue: 'default',
options: [
{ label: 'Default', value: 'default' },
{ label: 'Muted', value: 'muted' },
{ label: 'Inverted (dark)', value: 'inverted' },
],
},
],
}
}
``` ```
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`, Każda sekcja ma `buildSectionSettingsField()` — żadnych `bgColor`, `darkMode`,
`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN). `sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN).
## Warstwa 2 — prymitywy UI ## Warstwa 2 — prymitywy UI
@@ -85,11 +50,10 @@ Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
```tsx ```tsx
import Link from 'next/link' import Link from 'next/link'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { resolveLinkHref } from '@intecion/ipal-kit'
import type { CmsLink } from '@/payload-types' import type { CmsLink } from '@/payload-types'
import { i18nConfig } from '@/i18n.config' import { resolveLink } from '@/lib/content'
import { getSettings } from '@/lib/content'
import { buttonClass } from './Button' import { buttonClass } from './Button'
import type { LinkAppearance } from '@intecion/ipal-kit'
type Props = { type Props = {
link: CmsLink | null | undefined link: CmsLink | null | undefined
@@ -99,25 +63,15 @@ type Props = {
children?: ReactNode children?: ReactNode
} }
// href, new tab, rel, internal/external — from the plugin. Here: the element and the classes.
export async function CMSLink({ link, locale, className, children }: Props) { export async function CMSLink({ link, locale, className, children }: Props) {
const settings = await getSettings(locale) // react cache → one query per request const l = await resolveLink(link, locale)
const home = settings?.homepage const content = children ?? l?.label
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined if (!l || !content) return null
const cls = [l.appearance ? buttonClass(l.appearance as LinkAppearance) : '', className].filter(Boolean).join(' ') || undefined
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug }) return l.internal
const content = children ?? link?.label ? <Link href={l.href} className={cls} {...l.targetProps}>{content}</Link>
if (!link || !href || !content) return null : <a href={l.href} className={cls} {...l.targetProps}>{content}</a>
const cls = [link.appearance ? buttonClass(link.appearance) : '', className]
.filter(Boolean)
.join(' ')
const newTab = link.newTab || link.type === 'file'
const targetProps = newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {}
if (link.type === 'internal') {
return <Link href={href} className={cls} {...targetProps}>{content}</Link>
}
return <a href={href} className={cls} {...targetProps}>{content}</a>
} }
``` ```
@@ -137,40 +91,40 @@ export function buttonClass(appearance: LinkAppearance): string {
} }
``` ```
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu: `src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu. Szybkość liczy plugin
(`mediaImageProps`, `videoProps`), wygląd zostaje tutaj:
```tsx ```tsx
import Image from 'next/image' import Image from 'next/image'
import { mediaImageProps, MEDIA_SIZES, videoProps, type VideoMode } from '@intecion/ipal-kit'
import type { Media as MediaDoc } from '@/payload-types' import type { Media as MediaDoc } from '@/payload-types'
type Props = { type Props = {
resource: MediaDoc | string | number | null | undefined resource: MediaDoc | string | number | null | undefined
/** Szerokość NA EKRANIE — MEDIA_SIZES.half / .third / własny string. Bez tego pobiera się pełna szerokość. */
sizes?: string sizes?: string
/** Tylko pierwszy widoczny obraz strony (hero, LCP). Reszta ładuje się leniwie. */
priority?: boolean priority?: boolean
className?: string className?: string
/** Poster image URL for videos (shown before playback). */ /** Wideo: 'background' (pętla bez dźwięku) albo 'player' (kontrolki, ładowanie po kliknięciu). */
poster?: string videoMode?: VideoMode
/** Plakat wideo — upload z panelu. */
poster?: MediaDoc | string | number | null
} }
export function Media({ resource, sizes = '100vw', priority = false, className, poster }: Props) { export function Media({ resource, sizes = MEDIA_SIZES.full, priority = false, className, videoMode = 'player', poster }: Props) {
if (!resource || typeof resource !== 'object' || !resource.url) return null const video = videoProps(resource, { mode: videoMode, poster })
const { url, alt, width, height, mimeType } = resource if (video) return <video {...video} className={className} />
const img = mediaImageProps(resource, { priority, sizes })
if (mimeType?.startsWith('video/')) { if (!img) return null // PDF / plik — link typu 'file' (CMSLink), nie <Media>
// preload="metadata": the browser fetches only headers until playback, not the whole file return <Image {...img} className={className} />
return (
<video src={url} className={className} poster={poster} preload="metadata" autoPlay muted loop playsInline />
)
}
if (!width || !height) return null // non-image file (PDF) — use CMSLink type 'file'
return (
<Image src={url} alt={alt ?? ''} width={width} height={height}
sizes={sizes} priority={priority} className={className} />
)
} }
``` ```
Media w kolekcji: `upload: { focalPoint: true, … }` (punkt ostrości → `object-position`) oraz
placeholder z pluginu: `hooks.beforeOperation: [buildOptimizeUploadHook(), buildMediaPlaceholderHook()]`,
pole `buildMediaPlaceholderField()` (rozmyty podgląd + kolor podczas ładowania).
`Section.tsx` i `SectionHeader.tsx`: `Section.tsx` i `SectionHeader.tsx`:
```tsx ```tsx
@@ -225,18 +179,17 @@ const enhanceProps = () => ({ locale }) // Turnstile: <TurnstileProvider> w la
// src/blocks/Hero/config.ts // src/blocks/Hero/config.ts
import type { Block } from 'payload' import type { Block } from 'payload'
import { buildLinksField } from '@intecion/ipal-kit' import { buildLinksField } from '@intecion/ipal-kit'
import { sectionHeaderField } from '@/fields/sectionHeader' import { buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
import { sectionSettingsField } from '@/fields/sectionSettings'
export const HeroBlock: Block = { export const HeroBlock: Block = {
slug: 'hero', slug: 'hero',
interfaceName: 'HeroBlock', interfaceName: 'HeroBlock',
labels: { singular: 'Hero', plural: 'Heroes' }, labels: { singular: 'Hero', plural: 'Heroes' },
fields: [ fields: [
sectionHeaderField(), buildSectionHeaderField(),
{ name: 'media', type: 'upload', relationTo: 'media' }, { name: 'media', type: 'upload', relationTo: 'media' },
buildLinksField(), buildLinksField(),
sectionSettingsField(), buildSectionSettingsField(),
], ],
} }
``` ```
@@ -272,7 +225,7 @@ Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
```ts ```ts
// src/blocks/FeatureGrid/config.ts (fields) — import { buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit' // src/blocks/FeatureGrid/config.ts (fields) — import { buildLinkField, buildLinksField, rowLabel } from '@intecion/ipal-kit'
sectionHeaderField(), buildSectionHeaderField(),
{ {
name: 'items', name: 'items',
type: 'array', type: 'array',
@@ -289,7 +242,7 @@ sectionHeaderField(),
], ],
}, },
buildLinksField({ maxRows: 1 }), buildLinksField({ maxRows: 1 }),
sectionSettingsField(), buildSectionSettingsField(),
``` ```
```tsx ```tsx
+32 -1
View File
@@ -26,7 +26,7 @@ się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ci
|---|---| |---|---|
| piksel loaded without consent | skrypt wpięty ręcznie / skopiowany `Analytics` → ID w Site Integrations, `<Analytics>` z pluginu (analytics.md) | | piksel loaded without consent | skrypt wpięty ręcznie / skopiowany `Analytics` → ID w Site Integrations, `<Analytics>` z pluginu (analytics.md) |
| tracking cookie set without consent | to samo; albo GTM odpala tag bez warunku `ad_storage` (analytics.md → GTM) | | tracking cookie set without consent | to samo; albo GTM odpala tag bez warunku `ad_storage` (analytics.md → GTM) |
| GA hit with consent GRANTED | `setDefaultConsent` nie przed tagiem — `<Analytics>` musi być wewnątrz `<ConsentProvider>` | | GA hit with consent GRANTED | `setDefaultConsent` nie przed tagiem — `<Analytics>` musi być wewnątrz `<ConsentProvider>` (`SiteProviders` robi to sam) |
| YouTube / Maps before consent (warning) | `ConsentScript` (consent.md), `youtube-nocookie.com` albo „kliknij, aby załadować” | | YouTube / Maps before consent (warning) | `ConsentScript` (consent.md), `youtube-nocookie.com` albo „kliknij, aby załadować” |
4. Sekcja „after accept” mówi, co startuje po zgodzie — porównaj z ID w Site 4. Sekcja „after accept” mówi, co startuje po zgodzie — porównaj z ID w Site
@@ -37,3 +37,34 @@ się załadować wcześniej tylko z sygnałem Consent Mode „denied” i bez ci
Skrypt wymaga przycisków z `data-ipal="accept"` / `"reject"` — ma je Skrypt wymaga przycisków z `data-ipal="accept"` / `"reject"` — ma je
`CookieBanner` z pluginu. Własny baner w projekcie to naruszenie AGENT.md §7. `CookieBanner` z pluginu. Własny baner w projekcie to naruszenie AGENT.md §7.
## Lista ciasteczek do polityki cookies (cookie-scan)
Po każdej zmianie narzędzi (nowy piksel, czat, mapa, wideo) i przed oddaniem strony:
1. Skan działającej strony (bez zgody i po „Akceptuj wszystko”, strona główna + do 10 stron z sitemapy):
```bash
node .agents/skills/ipal-consent-check/scripts/cookie-scan.mjs http://localhost:3000 --lang pl
```
Wynik: `cookie-scan/cookies.json` i `cookie-scan/cookies.md` (tabela). `[ERROR]` = ciasteczko
**nie-niezbędne ustawione przed zgodą** — napraw jak w tabeli wyżej. `[WARNING] unknown` —
ustal dostawcę i cel, wpisz `category` (`necessary|functional|analytics|marketing`) i `purpose`
w `cookies.json`. Nie zgaduj — zapytaj, jeśli nie wiesz.
2. Import do panelu (Cookie Settings → Cookies), każdy język osobno (skan z `--lang en` dla angielskiego):
```bash
LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
```
Łączy po nazwie, nie nadpisuje zmian redaktora (`OVERWRITE=1` wymusza). Nie usuwa ciasteczek,
których skan nie widział — to robi redaktor w panelu.
3. Strona polityki cookies pokazuje tabelę z panelu — **nie wklejaj listy do treści polityki**:
```tsx
import { getCookieTable, getConsentTexts } from '@intecion/ipal-kit'
import { CookieTable } from '@intecion/ipal-kit/rsc'
const rows = await getCookieTable({ payload, locale })
<CookieTable rows={rows} categories={texts.categories} labels={/* nagłówki kolumn z panelu */} />
```
Tabela bez stylów (`classNames` per element). Blok w panelu typu „Cookie table” na stronie
polityki to dobre miejsce — wtedy redaktor decyduje, gdzie się pojawi.
Czas życia: Chrome skraca każde ciasteczko do maks. 400 dni (13 mies.) — skan pokazuje to, co
realnie zostaje w przeglądarce. `ipal-a11y` i inne klucze localStorage są wymienione osobno.
@@ -0,0 +1,176 @@
#!/usr/bin/env node
// ipal cookie-scan — lists every cookie (and localStorage key) a running site sets, for the cookie policy.
// node cookie-scan.mjs <baseUrl> [--pages 10] [--lang pl|en] [--out cookie-scan] [--wait 3000]
// Two fresh browser profiles: before any decision, and after "Accept all" (data-ipal="accept").
// Pages: the base URL + up to --pages URLs from /sitemap.xml.
// Writes <out>/cookies.json (import into the panel: import-cookies.ts) and <out>/cookies.md (table).
// Needs Playwright: pnpm add -D playwright && pnpm exec playwright install chromium
// Exit code: 0 = ok, 1 = non-necessary cookies set BEFORE consent, 2 = setup problem.
import { mkdirSync, writeFileSync } from 'node:fs'
import path from 'node:path'
const args = process.argv.slice(2)
if (!args[0] || args.includes('--help') || args.includes('-h')) {
console.log('Usage: cookie-scan.mjs <baseUrl> [--pages N] [--lang pl|en] [--out dir] [--wait ms]')
process.exit(args[0] ? 0 : 2)
}
const opt = (name, def) => {
const i = args.indexOf(`--${name}`)
return i >= 0 ? args[i + 1] : def
}
const base = args[0].replace(/\/$/, '')
const MAX = Number(opt('pages', 10)) || 10
const LANG = opt('lang', 'pl') === 'en' ? 'en' : 'pl'
const OUT = opt('out', 'cookie-scan')
const WAIT = Number(opt('wait', 3000)) || 3000
let pw
for (const mod of ['playwright', 'playwright-core', '@playwright/test']) {
try { pw = await import(mod); break } catch { /* next */ }
}
if (!pw) {
console.error('cookie-scan: Playwright not found. Install: pnpm add -D playwright && pnpm exec playwright install chromium')
process.exit(2)
}
const { chromium } = pw.default ?? pw
// Known cookies → provider, consent category, purpose. `*` = prefix.
const T = (pl, en) => ({ en, pl })
const CATALOG = [
['cookie-consent', 'this site', 'necessary', T('Zapamiętuje Twoją decyzję w sprawie plików cookies.', 'Stores your cookie consent decision.')],
['NEXT_LOCALE', 'this site', 'functional', T('Zapamiętuje wybrany język strony.', 'Remembers the selected site language.')],
['payload-token', 'this site', 'necessary', T('Sesja zalogowanego redaktora (panel administracyjny).', 'Logged-in editor session (admin panel).')],
['__cf_bm', 'Cloudflare', 'necessary', T('Ochrona przed botami.', 'Bot protection.')],
['_cfuvid', 'Cloudflare', 'necessary', T('Ochrona przed nadużyciami i limit zapytań.', 'Abuse protection and rate limiting.')],
['cf_clearance', 'Cloudflare', 'necessary', T('Potwierdzenie przejścia weryfikacji Cloudflare.', 'Proof of passing a Cloudflare challenge.')],
['_ga', 'Google', 'analytics', T('Google Analytics: rozróżnia użytkowników w statystykach.', 'Google Analytics: distinguishes users in statistics.')],
['_ga_*', 'Google', 'analytics', T('Google Analytics: stan sesji w statystykach.', 'Google Analytics: session state for statistics.')],
['_gid', 'Google', 'analytics', T('Google Analytics: rozróżnia użytkowników (24 h).', 'Google Analytics: distinguishes users (24 h).')],
['_gat*', 'Google', 'analytics', T('Google Analytics: ogranicza liczbę zapytań.', 'Google Analytics: throttles request rate.')],
['_gcl_*', 'Google', 'marketing', T('Google Ads: przypisanie konwersji do reklam.', 'Google Ads: attributes conversions to ads.')],
['_fbp', 'Meta', 'marketing', T('Meta Pixel: pomiar i dopasowanie reklam.', 'Meta Pixel: ad measurement and targeting.')],
['_fbc', 'Meta', 'marketing', T('Meta Pixel: zapamiętuje kliknięcie w reklamę.', 'Meta Pixel: stores the ad click.')],
['_clck', 'Microsoft Clarity', 'analytics', T('Clarity: identyfikator użytkownika w analizie zachowań.', 'Clarity: user id for behaviour analytics.')],
['_clsk', 'Microsoft Clarity', 'analytics', T('Clarity: łączy odsłony w jedną sesję.', 'Clarity: joins page views into a session.')],
['CLID', 'Microsoft Clarity', 'analytics', T('Clarity: identyfikator użytkownika.', 'Clarity: user id.')],
['MUID', 'Microsoft', 'marketing', T('Microsoft: identyfikator przeglądarki dla reklam.', 'Microsoft: browser id for advertising.')],
['_uetsid', 'Microsoft Ads', 'marketing', T('Microsoft Ads: pomiar konwersji (sesja).', 'Microsoft Ads: conversion tracking (session).')],
['_uetvid', 'Microsoft Ads', 'marketing', T('Microsoft Ads: pomiar konwersji (użytkownik).', 'Microsoft Ads: conversion tracking (user).')],
['li_fat_id', 'LinkedIn', 'marketing', T('LinkedIn Insight: przypisanie konwersji.', 'LinkedIn Insight: conversion attribution.')],
['lidc', 'LinkedIn', 'marketing', T('LinkedIn: wybór centrum danych.', 'LinkedIn: data-center routing.')],
['bcookie', 'LinkedIn', 'marketing', T('LinkedIn: identyfikator przeglądarki.', 'LinkedIn: browser id.')],
['bscookie', 'LinkedIn', 'marketing', T('LinkedIn: bezpieczny identyfikator przeglądarki.', 'LinkedIn: secure browser id.')],
['UserMatchHistory', 'LinkedIn', 'marketing', T('LinkedIn Ads: synchronizacja identyfikatorów.', 'LinkedIn Ads: id sync.')],
['AnalyticsSyncHistory', 'LinkedIn', 'marketing', T('LinkedIn: synchronizacja z analityką.', 'LinkedIn: analytics sync.')],
['_ttp', 'TikTok', 'marketing', T('TikTok Pixel: pomiar reklam.', 'TikTok Pixel: ad measurement.')],
['_tt_enable_cookie', 'TikTok', 'marketing', T('TikTok Pixel: sprawdza obsługę cookies.', 'TikTok Pixel: cookie support check.')],
['_hj*', 'Hotjar', 'analytics', T('Hotjar: analiza zachowań użytkowników.', 'Hotjar: behaviour analytics.')],
['YSC', 'YouTube', 'marketing', T('YouTube: statystyki odtworzeń osadzonych filmów.', 'YouTube: embedded video statistics.')],
['VISITOR_INFO1_LIVE', 'YouTube', 'marketing', T('YouTube: szacuje przepustowość, preferencje odtwarzacza.', 'YouTube: bandwidth estimate, player preferences.')],
['VISITOR_PRIVACY_METADATA', 'YouTube', 'marketing', T('YouTube: stan zgody użytkownika.', 'YouTube: user consent state.')],
]
const match = (name) =>
CATALOG.find(([pattern]) => (pattern.endsWith('*') ? name.startsWith(pattern.slice(0, -1)) : name === pattern))
const human = (expires) => {
if (!expires || expires < 0) {return LANG === 'pl' ? 'sesja' : 'session'}
const days = Math.round((expires * 1000 - Date.now()) / 86_400_000)
if (days < 1) {
const h = Math.max(1, Math.round((expires * 1000 - Date.now()) / 3_600_000))
return LANG === 'pl' ? `${h} godz.` : `${h} h`
}
if (days < 60) {return LANG === 'pl' ? `${days} dni` : `${days} days`}
const months = Math.round(days / 30)
if (months < 24) {return LANG === 'pl' ? `${months} mies.` : `${months} months`}
const years = Math.round(days / 365)
return LANG === 'pl' ? `${years} ${years < 5 ? 'lata' : 'lat'}` : `${years} years`
}
// Pages to visit
const pages = [base]
try {
const xml = await (await fetch(`${base}/sitemap.xml`)).text()
for (const m of xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)) {
if (pages.length > MAX) {break}
if (!pages.includes(m[1])) {pages.push(m[1])}
}
} catch { /* no sitemap — base only */ }
let browser
try {
browser = await chromium.launch()
} catch (err) {
console.error(`cookie-scan: cannot start Chromium — run: pnpm exec playwright install chromium\n${err.message?.split('\n')[0] ?? err}`)
process.exit(2)
}
const host = new URL(base).hostname.replace(/^www\./, '')
async function visit(accept) {
const ctx = await browser.newContext()
const page = await ctx.newPage()
const storage = new Set()
try {
for (const [i, url] of pages.entries()) {
await page.goto(url, { waitUntil: 'networkidle', timeout: 30_000 }).catch(() => {})
if (accept && i === 0) {
const btn = page.locator('[data-ipal="accept"]')
if (await btn.count()) {await btn.first().click().catch(() => {})}
}
await page.waitForTimeout(WAIT)
for (const k of await page.evaluate(() => Object.keys(localStorage)).catch(() => [])) {storage.add(k)}
}
return { cookies: await ctx.cookies(), storage: [...storage] }
} finally {
await ctx.close()
}
}
const before = await visit(false)
const after = await visit(true)
await browser.close()
const beforeNames = new Set(before.cookies.map((c) => c.name))
const seen = new Map()
for (const c of [...before.cookies, ...after.cookies]) {
if (seen.has(c.name)) {continue}
const known = match(c.name)
const firstParty = c.domain.replace(/^\./, '').endsWith(host)
seen.set(c.name, {
category: known?.[2] ?? 'unknown',
domain: c.domain.replace(/^\./, ''),
duration: human(c.expires),
firstParty,
name: c.name,
provider: known ? (known[1] === 'this site' ? (LANG === 'pl' ? 'ta strona' : 'this site') : known[1]) : firstParty ? (LANG === 'pl' ? 'ta strona' : 'this site') : c.domain.replace(/^\./, ''),
purpose: known?.[3][LANG] ?? '',
setBeforeConsent: beforeNames.has(c.name),
})
}
const ORDER = ['necessary', 'functional', 'analytics', 'marketing', 'unknown']
const cookies = [...seen.values()].sort((a, b) => ORDER.indexOf(a.category) - ORDER.indexOf(b.category) || a.name.localeCompare(b.name))
mkdirSync(OUT, { recursive: true })
writeFileSync(path.join(OUT, 'cookies.json'), JSON.stringify({ base, cookies, lang: LANG, localStorage: after.storage, pages, scannedAt: new Date().toISOString() }, null, 2))
const head = LANG === 'pl'
? '| Nazwa | Dostawca | Kategoria | Cel | Czas przechowywania |\n|---|---|---|---|---|'
: '| Name | Provider | Category | Purpose | Duration |\n|---|---|---|---|---|'
const rows = cookies.map((c) => `| \`${c.name}\` | ${c.provider} | ${c.category} | ${c.purpose || '—'} | ${c.duration} |`)
writeFileSync(path.join(OUT, 'cookies.md'), `${head}\n${rows.join('\n')}\n`)
let errors = 0
console.log(`cookie-scan — ${base} (${pages.length} page(s))`)
const early = cookies.filter((c) => c.setBeforeConsent && c.category !== 'necessary')
if (early.length) {
errors += early.length
console.log(`\n[ERROR] set BEFORE consent and not necessary (${early.length}) — GDPR: gate it (ConsentScript / Analytics) or classify it as necessary if it truly is`)
for (const c of early) {console.log(` ${c.name} (${c.domain}, ${c.category})`)}
}
const unknown = cookies.filter((c) => c.category === 'unknown')
if (unknown.length) {
console.log(`\n[WARNING] unknown cookies (${unknown.length}) — find the provider and purpose, set the category in cookies.json before importing`)
for (const c of unknown) {console.log(` ${c.name} (${c.domain})`)}
}
if (after.storage.length) {console.log(`\nlocalStorage keys (mention in the policy if they hold personal data): ${after.storage.join(', ')}`)}
console.log(`\n${cookies.length} cookie(s) → ${path.join(OUT, 'cookies.json')}, ${path.join(OUT, 'cookies.md')}`)
console.log(`Import into the panel: LOCALE=${LANG} pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts ${path.join(OUT, 'cookies.json')}`)
process.exit(errors ? 1 : 0)
@@ -0,0 +1,59 @@
/**
* Imports a cookie-scan result into Cookie Settings → Cookies (panel), so the
* cookie policy page (<CookieTable>) lists what the site really sets.
*
* LOCALE=pl pnpm payload run .agents/skills/ipal-consent-check/scripts/import-cookies.ts cookie-scan/cookies.json
* # second language: scan again with --lang en, then import with LOCALE=en
* # (rows are matched by cookie name; only purpose/duration are localized)
*
* Merges by cookie name: an editor's own purpose/duration/provider are kept
* unless OVERWRITE=1. Cookies no longer seen are kept too (remove them in the
* panel) — a scan of a few pages can miss cookies set elsewhere. `unknown`
* category rows are skipped: classify them in cookies.json first.
*/
import config from '@payload-config'
import { readFileSync } from 'node:fs'
import { getPayload } from 'payload'
type Scanned = { category: string; duration?: string; name: string; provider?: string; purpose?: string }
type Row = { category?: string; duration?: null | string; id?: string; name?: string; provider?: null | string; purpose?: null | string }
// `payload run` forwards positional args but not --flags — options come from env.
const file = process.argv.slice(2).find((a) => a.endsWith('.json'))
const locale = process.env.LOCALE
const overwrite = process.env.OVERWRITE === '1'
if (!file || !locale) {
console.error('Usage: LOCALE=<code> [OVERWRITE=1] pnpm payload run import-cookies.ts <cookies.json>')
process.exit(2)
}
const scan = JSON.parse(readFileSync(file, 'utf8')) as { cookies: Scanned[] }
const payload = await getPayload({ config })
const current = (await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, locale: locale as never })) as { cookies?: Row[] }
const rows: Row[] = [...(current.cookies ?? [])]
let added = 0
let updated = 0
let skipped = 0
for (const c of scan.cookies) {
if (c.category === 'unknown') {
skipped++
continue
}
const existing = rows.find((r) => r.name === c.name)
if (!existing) {
rows.push({ category: c.category, duration: c.duration, name: c.name, provider: c.provider, purpose: c.purpose })
added++
continue
}
const pick = (mine: null | string | undefined, theirs?: string) => (overwrite || !mine ? (theirs ?? mine) : mine)
existing.provider = pick(existing.provider, c.provider)
existing.purpose = pick(existing.purpose, c.purpose)
existing.duration = pick(existing.duration, c.duration)
if (overwrite) {existing.category = c.category}
updated++
}
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: rows } as never, locale: locale as never })
console.log(`Cookie Settings (${locale}): ${added} added, ${updated} updated, ${skipped} unknown skipped. Review them in the panel.`)
process.exit(0)
+71 -37
View File
@@ -5,8 +5,8 @@ description: Wires forms the ipal-kit way — forms built by the editor in the p
# ipal-form # ipal-form
**Formularz buduje redaktor w panelu. Ty piszesz raz: renderer + akcję.** Każdy **Formularz buduje redaktor w panelu. Projekt ma akcję, blok z `<RenderForm>` i klasy.** Każdy
kolejny formularz to tylko panel. Ręcznie wpisane pola/etykiety w JSX = błąd kolejny formularz — także krokowy, z listami wyboru — to tylko panel. Ręcznie wpisane pola/etykiety w JSX = błąd
(ipal-audit to złapie). Szczegóły API: `docs/forms.md`, `turnstile.md`, `notifications.md`, `email.md`. (ipal-audit to złapie). Szczegóły API: `docs/forms.md`, `turnstile.md`, `notifications.md`, `email.md`.
## 1. Config (raz na projekt) ## 1. Config (raz na projekt)
@@ -29,58 +29,95 @@ export default buildConfig({
`generate:importmap`, restart. `generate:importmap`, restart.
## 2. Layout — Turnstile raz ## 2. Layout — Turnstile raz
`<TurnstileProvider siteKey={(await getTurnstileConfig(payload)).siteKey}>` w `<SiteProviders shell={await getSiteShell(locale)}>` w `[locale]/layout.tsx` (PROGRAMISTA §2.8)
`[locale]/layout.tsx` (turnstile.md) — **zawsze**, nie warunkuj providera ani widgetu. wpina `TurnstileProvider` z kluczem z panelu — **zawsze**, nie warunkuj providera ani widgetu.
Własny layout bez SiteProviders: `<TurnstileProvider siteKey={shell.turnstileSiteKey}>` (turnstile.md).
Zachowanie z pluginu: **oba klucze** (panel lub env) → widget widoczny, a `submitForm` Zachowanie z pluginu: **oba klucze** (panel lub env) → widget widoczny, a `submitForm`
**wymaga** tokenu (bot nie ominie, nie wysyłając go); brak kluczy → widgetu nie ma, **wymaga** tokenu (bot nie ominie, nie wysyłając go); brak kluczy → widgetu nie ma,
weryfikacji nie ma, formularz działa; jeden klucz → wyłączony + alert na dashboardzie. weryfikacji nie ma, formularz działa; jeden klucz → wyłączony + alert na dashboardzie.
## 3. Kod (skopiuj z `resources/`, dostosuj tylko klasy) ## 3. Kod — import, nie kopia
Renderer, kroki, walidacja, Turnstile, honeypot, przekierowanie i zdarzenie GTM są w
pluginie. W projekcie zostają **trzy krótkie pliki**:
| Plik | Do projektu | Rola | | Plik | Do projektu | Rola |
|---|---|---| |---|---|---|
| `actions.ts` | `src/app/(frontend)/[locale]/actions.ts` | jedna akcja `sendForm`: honeypot → IP (`clientIp`, `IPAL_IP_HEADER`) → `submitForm` → tekst z Notifications | | `resources/actions.ts` | `src/app/(frontend)/[locale]/actions.ts` | `export const sendForm = createSubmitAction({ getCachedPayload, headers })` |
| `FormBlock.tsx` | `src/blocks/FormBlock/Component.tsx` | serwer: RichText (potwierdzenie, pola „message”), bind akcji | | `resources/FormBlock.tsx` | `src/blocks/FormBlock/Component.tsx` | `<RenderForm>` z `/rsc` + klasy projektu, w `<Section>`/`<SectionHeader>` |
| `FormRenderer.tsx` | `src/components/forms/FormRenderer.tsx` | klient: dowolny formularz z panelu przez `useForm` | | `resources/formClasses.ts` | `src/components/forms/formClasses.ts` | **jedyne** miejsce wyglądu formularzy (klasy z DESIGN.md) |
| `resources/seed-form.template.ts` | `scripts/seed-form-<nazwa>.ts` | formularz w bazie: pola, potwierdzenie, mail do firmy + do klienta, każdy język |
Renderer obsługuje typy buildera `text, email, textarea, number, select, checkbox, `RenderForm` (serwer) renderuje bloki „message” i potwierdzenie przez `RenderRichText`,
message` (`country/state` jako tekst), `width` ≤ 50 → pół szerokości, `required`, wiąże akcję z formularzem i językiem, rozwiązuje redirect i **wysyła do przeglądarki tylko
potwierdzenie albo redirect, a11y (`label for`, `aria-invalid`, `role="alert"`), publiczną część formularza** (zakładka Emails z adresami firmy nigdy nie trafia do HTML).
honeypot, Turnstile, zdarzenie GTM z panelu. Nie dopisuj własnej walidacji Pod spodem `BuilderForm` (klient) — czysty, dostępny HTML **bez stylów**: wygląd = `classNames`
„na sztywno” — reguły wynikają z definicji pola. (+ atrybuty `data-ipal`, `data-type`, `data-width`, `data-step`).
## 4. Strona — dane do bloku przez enhanceProps (bloki nie importują `lib/*`) **Typy pól w panelu:** text, email, textarea, number, **date**, select, **radio** (jeden wybór),
checkbox, **Checkbox group** (wiele wyborów, min/max), message, **Step** (podział na kroki).
- **Formularz krokowy:** redaktor wstawia blok **Step** (tytuł, opis) — pola pod nim to jeden
ekran. Przyciski Dalej/Wstecz i „Krok 1 z 3” z **Notifications → Form messages** (next, back,
stepOf). Dalej waliduje tylko bieżący krok; błąd z serwera wraca na krok z polem; fokus
przechodzi na nowy krok. Bez Step = jeden ekran.
- `width` ≤ 50 → klasa `fieldHalf`, inaczej `fieldFull`.
**Formularz nietypowy** (karty do wyboru zamiast radio, podsumowanie przed wysłaniem,
własny typ pola, suwak): nie kopiuj silnika — w kolejności:
1. `renderField` w `BuilderForm` (plik `'use client'`): podmieniasz wybrane pola, reszta domyślna
(`defaultRender()` daje oryginał do owinięcia);
2. własny komponent na `useBuilderForm` — pełna kontrola nad markupem, ta sama logika
(`resources/CustomForm.example.tsx`): `steps`, `step`, `next/back/goTo`, `submit`,
`getInputProps / getTextareaProps / getSelectProps / getOptionProps`, `errors`, `TurnstileWidget`.
Własny typ pola w panelu: `forms.fields: { mojTyp: { slug, fields } }` (blok form-buildera)
+ `renderField`; serwer przyjmie go jako tekst — potrzebujesz innej walidacji → **ipal-plugin-gap**.
## 4. Strona — dane do bloku raz (bloki nie importują `lib/*`)
Z `createPageRoute` (PROGRAMISTA §2.8):
```tsx ```tsx
// [locale]/[[...slug]]/page.tsx const route = createPageRoute(content, {
import { getNotificationTexts } from '@intecion/ipal-kit' blocks: blockRegistry, notFound, permanentRedirect,
import { sendForm } from '../actions' blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
const formTexts = doc.layout?.some((b) => b.blockType === 'formBlock')
? (await getNotificationTexts({ payload: await getCachedPayload(), locale })).form
: undefined
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
locale,
...(block.blockType === 'formBlock' ? { formTexts, sendForm } : {}),
}) })
``` ```
Własna strona: to samo w `enhanceProps` (`formTexts` z `getFormTexts(locale)`, `sendForm` z `actions.ts`).
Zapytanie strony: `depth` ≥ 1 (relacja `form` jako obiekt). Rejestr bloków: Zapytanie strony: `depth` ≥ 1 (relacja `form` jako obiekt). Rejestr bloków:
`formBlock: FormBlock`. Formularz poza blokiem (stopka, modal) = ten sam `formBlock: FormBlock`. Formularz poza blokiem (stopka, modal) = ten sam `<RenderForm>`
`FormRenderer` z formularzem pobranym po ID z globalu (relacja w Footer), nigdy kopia. z formularzem z relacji w globalu, nigdy kopia.
## 5. Panel (zrób sam albo seedem, potem opisz w raporcie) ## 5. Formularz w bazie — ZAWSZE seedem (`resources/seed-form.template.ts`)
1. **Forms → nowy formularz**: pola z briefu, `name` po angielsku, małe litery Każdy formularz z briefu powstaje skryptem, nie ręcznie: wtedy jest powtarzalny (dev → produkcja),
ma wszystkie języki i **oba maile**, o których łatwo zapomnieć:
- **powiadomienie do firmy**: `emailTo` = adres z panelu (global firmy), `replyTo: {{email}}`, treść `{{*:table}}`;
- **potwierdzenie do klienta**: `emailTo: {{email}}`, `replyTo` = adres firmy, temat i treść per język.
```bash
cp .agents/skills/ipal-form/resources/seed-form.template.ts scripts/seed-form-contact.ts
# uzupełnij FORM z briefu (pola, etykiety, komunikaty, tematy maili — każdy język), NOTIFY = global/pole z adresem firmy
pnpm payload run scripts/seed-form-contact.ts
```
Bez adresu powiadomień skrypt **zatrzymuje się** — zapytaj klienta, na jaką skrzynkę mają przychodzić
zgłoszenia (pytanie z listy w ipal-site), wpisz go w panelu i uruchom ponownie. Nie wpisuj adresu w kod.
Skrypt commitujesz — na produkcji uruchamiasz go po migracji. Zmiana formularza: popraw FORM,
`SEED_UPDATE=1 pnpm payload run …` (nadpisuje zmiany redaktora — tylko przed oddaniem).
Szczegóły, które seed już spełnia, a które sprawdzasz po każdej ręcznej zmianie w panelu:
1. **Forms → formularz**: pola z briefu, `name` po angielsku, małe litery
(`name`, `email`, `phone`, `message`, `consent`); etykiety per język. (`name`, `email`, `phone`, `message`, `consent`); etykiety per język.
2. **Zgoda RODO**: checkbox `consent`, etykieta z linkiem do polityki, **nie** 2. **Zgoda RODO**: checkbox `consent`, etykieta z linkiem do polityki, **nie**
zaznaczony domyślnie (plugin i tak wymusza server-side → `reason: 'consent'`). zaznaczony domyślnie (plugin i tak wymusza server-side → `reason: 'consent'`).
3. **Confirmation**: komunikat (per język) albo redirect na stronę „Dziękujemy” 3. **Confirmation**: komunikat (per język) albo redirect na stronę „Dziękujemy”
(wtedy ta strona `noindex`). (wtedy ta strona `noindex`).
4. **Emails**: powiadomienie do firmy (`emailTo` z globalu firmy/panelu, `replyTo: {{email}}`, 4. **Emails**: powiadomienie do firmy (`emailTo` z globalu firmy/panelu, `replyTo: {{email}}`,
treść `{{*:table}}`) + opcjonalne potwierdzenie do wysyłającego (`emailTo: {{email}}`). treść `{{*:table}}`) **i** potwierdzenie do wysyłającego (`emailTo: {{email}}`) — oba obowiązkowe.
Pole e-mail musi mieć `name: 'email'` (plugin przyjmuje w nim dokładnie jeden adres).
5. **Analytics (GTM / dataLayer)**: Event name `generate_lead` / `form_submit`, parametry `form_name`. 5. **Analytics (GTM / dataLayer)**: Event name `generate_lead` / `form_submit`, parametry `form_name`.
6. **Site Integrations**: transport maila (SMTP/Graph) + **Send test**; klucze Turnstile. 6. **Site Integrations**: transport maila (SMTP/Graph) + **Send test**; klucze Turnstile.
7. **Notifications → form.\***: teksty w każdym języku. 7. **Notifications → form.\***: teksty w każdym języku.
## 6. Sprawdź sam, zanim powiesz „gotowe” ## 6. Sprawdź sam, zanim powiesz „gotowe”
- [ ] wysyłka z pustymi wymaganymi polami → błędy przy polach, bez requestu; - [ ] wysyłka z pustymi wymaganymi polami → błędy przy polach, bez requestu;
- [ ] poprawna wysyłka → potwierdzenie, rekord w **Form Submissions**, mail doszedł - [ ] poprawna wysyłka → potwierdzenie, rekord w **Form Submissions**, mail do firmy doszedł
**i** potwierdzenie doszło na adres wpisany w formularzu
(Send test w panelu działa = transport OK; brak maila mimo to → zakładka Emails formularza); (Send test w panelu działa = transport OK; brak maila mimo to → zakładka Emails formularza);
- [ ] niezaznaczona zgoda → komunikat z Notifications (nie angielski fallback); - [ ] niezaznaczona zgoda → komunikat z Notifications (nie angielski fallback);
- [ ] 6 szybkich wysyłek → `rate_limited`; - [ ] 6 szybkich wysyłek → `rate_limited`;
@@ -89,7 +126,8 @@ Zapytanie strony: `depth` ≥ 1 (relacja `form` jako obiekt). Rejestr bloków:
- [ ] Turnstile bez kluczy → brak widgetu, formularz przechodzi; - [ ] Turnstile bez kluczy → brak widgetu, formularz przechodzi;
- [ ] drugi język → etykiety i komunikaty w tym języku; - [ ] drugi język → etykiety i komunikaty w tym języku;
- [ ] GTM Preview → zdarzenie z nazwą z panelu po sukcesie; - [ ] GTM Preview → zdarzenie z nazwą z panelu po sukcesie;
- [ ] `ipal-audit --quick` → zero hardkodów w FormRenderer/FormBlock; - [ ] formularz krokowy: Dalej z pustym krokiem → błędy, krok zostaje; Wstecz zachowuje wpisane wartości;
- [ ] `ipal-audit --quick` → zero hardkodów w FormBlock, brak kopii silnika formularza;
- [ ] `ipal-consent-check` → nadal 0 naruszeń (Turnstile to niezbędny, nie śledzący). - [ ] `ipal-consent-check` → nadal 0 naruszeń (Turnstile to niezbędny, nie śledzący).
## Diagnostyka ## Diagnostyka
@@ -97,14 +135,10 @@ Zapytanie strony: `depth` ≥ 1 (relacja `form` jako obiekt). Rejestr bloków:
|---|---| |---|---|
| brak kolekcji Forms w panelu | rozjazd wersji form-buildera vs payload → ta sama wersja, `pnpm.overrides` | | brak kolekcji Forms w panelu | rozjazd wersji form-buildera vs payload → ta sama wersja, `pnpm.overrides` |
| blok renderuje nic | `form` to ID (za małe `depth`) albo brak `formTexts`/`sendForm` w enhanceProps | | blok renderuje nic | `form` to ID (za małe `depth`) albo brak `formTexts`/`sendForm` w enhanceProps |
| `reason: 'validation'`, `kind: 'unknown_fields'` | front wysyła pole, którego formularz nie ma (honeypot nieusunięty w akcji, literówka w `name`) | | `reason: 'validation'`, `kind: 'unknown_fields'` | front wysyła pole, którego formularz nie ma (własny renderer z dodatkowym polem, literówka w `name`) |
| przyciski „Next/Back” po angielsku | puste Notifications → Form messages → next / back / stepOf w tym języku |
| `reason: 'not_found'` | `formId` z innej bazy (seed na dev, prod inny ID) — relacja z panelu, nie stałe ID w kodzie | | `reason: 'not_found'` | `formId` z innej bazy (seed na dev, prod inny ID) — relacja z panelu, nie stałe ID w kodzie |
| zgłoszenie jest, maila brak | brak `email: mailAdapter()`, pusta zakładka Emails, transport w panelu; logi serwera | | zgłoszenie jest, maila brak | brak `email: mailAdapter()`, pusta zakładka Emails, transport w panelu; logi serwera |
| zawsze `turnstile` | token jednorazowy — `ts.reset()` po błędzie (jest w rendererze); zła para kluczy / domena w Cloudflare | | zawsze `turnstile` | zła para kluczy / domena w Cloudflare (reset tokenu po błędzie robi BuilderForm) |
| strona stała się dynamiczna (`ƒ`) | `headers()` w komponencie zamiast w akcji | | strona stała się dynamiczna (`ƒ`) | `headers()` w komponencie zamiast w akcji |
| komunikaty po angielsku | puste Notifications w tym języku | | komunikaty po angielsku | puste Notifications w tym języku |
## Znane ograniczenie pluginu
`useForm` trzyma własny stan tokenu, `useTurnstile` swój — renderer synchronizuje je
`useEffect`em. Jeśli w kolejnym projekcie to przeszkadza, zgłoś przez **ipal-plugin-gap**
(propozycja: `useForm` czyta token z `TurnstileProvider`, gdy jest w drzewie).
@@ -0,0 +1,50 @@
// Only for a form that looks or behaves unlike the default (option cards, a
// summary step, a custom field type). Same engine as BuilderForm — you write the
// markup only. Ordinary forms: RenderForm in FormBlock, no file like this.
//
// Lighter option first: <BuilderForm renderField={…}> replaces chosen fields only.
'use client'
import { honeypotInputProps, useBuilderForm, type UseBuilderFormOptions } from '@intecion/ipal-kit/client'
export function QuoteCardsForm(props: UseBuilderFormOptions) {
const f = useBuilderForm(props)
if (f.isSuccess) return <div role="status">{f.resultMessage}</div>
return (
<form onSubmit={f.submit} noValidate>
<input {...honeypotInputProps()} />
{f.total > 1 && <p aria-live="polite">{props.texts.stepOf?.replace('{current}', String(f.stepIndex + 1)).replace('{total}', String(f.total))}</p>}
{f.step.fields.map(({ field }) => {
if (!field.name) return null
if (field.blockType === 'radio') {
// options as clickable cards — still a real radio group (keyboard, screen readers)
return (
<fieldset key={field.name} id={f.fieldId(field)} aria-invalid={f.getFieldProps(field)['aria-invalid']} aria-describedby={f.getFieldProps(field)['aria-describedby']}>
<legend>{field.label}</legend>
{(field.options ?? []).map((o, i) => (
<label key={o.value} className="card">
<input {...f.getOptionProps(field, o, i)} className="sr-only" />
{o.label}
</label>
))}
{f.errors[field.name] && <p id={f.errorId(field)}>{f.errors[field.name]}</p>}
</fieldset>
)
}
return (
<div key={field.name}>
<label htmlFor={f.fieldId(field)}>{field.label}</label>
{field.blockType === 'textarea' ? <textarea {...f.getTextareaProps(field)} /> : <input {...f.getInputProps(field)} />}
{f.errors[field.name] && <p id={f.errorId(field)}>{f.errors[field.name]}</p>}
</div>
)
})}
{f.isLast && <f.TurnstileWidget />}
{f.errorMessage && <p role="alert">{f.errorMessage}</p>}
{!f.isFirst && <button type="button" onClick={f.back}>{props.texts.back}</button>}
<button type="submit" disabled={f.isSubmitting}>{f.isLast ? props.form.submitButtonLabel : props.texts.next}</button>
</form>
)
}
@@ -1,39 +1,26 @@
// src/blocks/FormBlock/Component.tsx — SERVER part: rich text from the panel + bound action. // src/blocks/FormBlock/Component.tsx — a panel form inside a section. Logic, steps,
// validation, Turnstile, honeypot and rich text come from ipal-kit; the look is
// formClasses (one file for every form on the site).
// Block config (src/blocks/FormBlock/config.ts): slug 'formBlock', fields // Block config (src/blocks/FormBlock/config.ts): slug 'formBlock', fields
// { name: 'form', type: 'relationship', relationTo: 'forms', required: true } + the // buildSectionHeaderField(), { name: 'form', type: 'relationship', relationTo: 'forms', required: true },
// shared section fields (eyebrow/heading/intro, anchor, background) — ipal-block. // buildSectionSettingsField()
// Page query depth ≥ 1, otherwise `form` is just an ID. Wrap the output in the // Page query depth ≥ 1, otherwise `form` is just an ID (RenderForm renders nothing).
// project's <Section>/<SectionHeader> like every other block. // `formTexts` and `sendForm` arrive via createPageRoute blockProps (ipal-form SKILL §4).
// Blocks never import lib/* or app/* (AGENT.md §4.10) — texts and the server action
// come in through enhanceProps from the page route (SKILL.md, step 4).
import type { ReactNode } from 'react'
import type { FormNotificationTexts } from '@intecion/ipal-kit' import type { FormNotificationTexts } from '@intecion/ipal-kit'
import { RichText } from '@/components/RichText' import { RenderForm, type SendFormAction } from '@intecion/ipal-kit/rsc'
import { FormRenderer, type BuilderForm, type FormAction } from '@/components/forms/FormRenderer' import type { FormBlock as FormBlockData } from '@/payload-types'
import { formClasses } from '@/components/forms/formClasses'
import { Section } from '@/components/ui/Section'
import { SectionHeader } from '@/components/ui/SectionHeader'
type Props = { type Props = FormBlockData & { locale: string; formTexts?: FormNotificationTexts; sendForm?: SendFormAction }
form?: BuilderForm | string | number | null
locale: string
formTexts?: FormNotificationTexts
sendForm?: (formId: string, locale: string, values: Record<string, unknown>, token?: string) => ReturnType<FormAction>
}
export function FormBlock({ form, locale, formTexts, sendForm }: Props) {
if (!form || typeof form !== 'object' || !formTexts || !sendForm) return null // never a fake/hardcoded form
const messages: Record<number, ReactNode> = {}
form.fields?.forEach((f, i) => {
if (f.blockType === 'message' && f.message) messages[i] = <RichText data={f.message as never} />
})
const confirmation = form.confirmationMessage ? <RichText data={form.confirmationMessage as never} /> : null
export function FormBlock({ form, header, settings, locale, formTexts, sendForm }: Props) {
if (!formTexts || !sendForm) return null // never a fake/hardcoded form
return ( return (
<FormRenderer <Section settings={settings}>
form={form} <SectionHeader header={header} />
messages={messages} <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
confirmation={confirmation} </Section>
validationText={formTexts.validation}
action={sendForm.bind(null, String(form.id), locale)}
/>
) )
} }
@@ -1,138 +0,0 @@
// src/components/forms/FormRenderer.tsx — CLIENT part: renders ANY form built in the panel.
// Logic from ipal-kit, markup + classes are the project's (restyle freely, keep the wiring).
'use client'
import { useEffect, useMemo, type ReactNode } from 'react'
import { useRouter } from 'next/navigation'
import {
useForm, buildValidator, required, email, checked, honeypotInputProps,
useTurnstile, formAnalyticsOnSuccess, type FormAnalyticsConfig,
} from '@intecion/ipal-kit/client'
type Option = { label?: string | null; value: string }
export type BuilderField = {
blockType: 'text' | 'textarea' | 'email' | 'number' | 'select' | 'checkbox' | 'country' | 'state' | 'message' | string
name?: string | null
label?: string | null
required?: boolean | null
width?: number | null
defaultValue?: unknown
options?: Option[] | null
message?: unknown
}
export type BuilderForm = {
id: string | number
fields?: BuilderField[] | null
submitButtonLabel?: string | null
confirmationType?: 'message' | 'redirect' | null
confirmationMessage?: unknown
redirect?: { url?: string | null } | null
analytics?: FormAnalyticsConfig
}
export type FormAction = (values: Record<string, unknown>, turnstileToken?: string) => Promise<{ success: boolean; message?: string }>
type Props = {
form: BuilderForm
action: FormAction
messages: Record<number, ReactNode>
confirmation: ReactNode
/** Notifications → form.validation, may contain {field}. */
validationText: string
}
export function FormRenderer({ form, action, messages, confirmation, validationText }: Props) {
const router = useRouter()
const ts = useTurnstile() // needs <TurnstileProvider> in the layout (siteKey may be empty → disabled)
const fields = (form.fields ?? []).filter((f) => f.blockType !== 'message' && f.name)
const msg = (f: BuilderField) => validationText.replace('{field}', f.label || f.name || '')
const initialValues = useMemo(
() => Object.fromEntries(fields.map((f) => [f.name as string, f.blockType === 'checkbox' ? Boolean(f.defaultValue) : (f.defaultValue as string) ?? ''])),
// eslint-disable-next-line react-hooks/exhaustive-deps
[form.id],
)
const validate = useMemo(
() =>
buildValidator<Record<string, unknown>>(
Object.fromEntries(
fields.map((f) => {
const rules = []
if (f.required) rules.push(f.blockType === 'checkbox' ? checked(msg(f)) : required(msg(f)))
if (f.blockType === 'email') rules.push(email(msg(f)))
return [f.name as string, rules]
}),
),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[form.id, validationText],
)
const f = useForm({
initialValues,
validate,
submitAction: action,
requireTurnstile: ts.enabled,
onSuccess: (result, values) => {
formAnalyticsOnSuccess(form.analytics)(result, values)
if (form.confirmationType === 'redirect' && form.redirect?.url) router.push(form.redirect.url)
},
})
// Turnstile token lives in the provider; the form engine needs it too.
useEffect(() => f.setTurnstileToken(ts.token), [ts.token]) // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => { if (f.errorMessage) ts.reset() }, [f.errorMessage]) // eslint-disable-line react-hooks/exhaustive-deps
if (f.isSuccess && form.confirmationType !== 'redirect') return <div role="status">{confirmation}</div>
return (
<form onSubmit={f.handleSubmit} noValidate className="grid grid-cols-12 gap-4">
<input {...honeypotInputProps()} />
{(form.fields ?? []).map((field, i) => {
if (field.blockType === 'message') return <div key={i} className="col-span-12">{messages[i]}</div>
const name = field.name as string
const id = `f-${String(form.id)}-${name}`
const error = f.errors[name]
const span = field.width && field.width <= 50 ? 'col-span-12 md:col-span-6' : 'col-span-12'
const common = {
id, name, required: Boolean(field.required),
'aria-invalid': Boolean(error) || undefined,
'aria-describedby': error ? `${id}-err` : undefined,
}
const value = f.values[name]
return (
<div key={name} className={span}>
{field.blockType === 'checkbox' ? (
<label htmlFor={id} className="flex items-start gap-2">
<input type="checkbox" {...common} checked={Boolean(value)} onChange={(e) => f.setField(name, e.target.checked)} />
<span>{field.label}</span>
</label>
) : (
<>
<label htmlFor={id} className="mb-1 block">{field.label}</label>
{field.blockType === 'textarea' ? (
<textarea {...common} rows={5} value={String(value ?? '')} onChange={(e) => f.setField(name, e.target.value)} />
) : field.blockType === 'select' ? (
<select {...common} value={String(value ?? '')} onChange={(e) => f.setField(name, e.target.value)}>
<option value="" />
{(field.options ?? []).map((o) => <option key={o.value} value={o.value}>{o.label ?? o.value}</option>)}
</select>
) : (
<input
{...common}
type={field.blockType === 'email' ? 'email' : field.blockType === 'number' ? 'number' : 'text'}
autoComplete={field.blockType === 'email' ? 'email' : undefined}
value={String(value ?? '')}
onChange={(e) => f.setField(name, e.target.value)}
/>
)}
</>
)}
{error && <p id={`${id}-err`} className="mt-1 text-sm text-red-600">{error}</p>}
</div>
)
})}
<div className="col-span-12"><ts.TurnstileWidget /></div>
{f.errorMessage && <p role="alert" className="col-span-12 text-red-600">{f.errorMessage}</p>}
<div className="col-span-12">
<button type="submit" disabled={f.isSubmitting}>{form.submitButtonLabel}</button>
</div>
</form>
)
}
@@ -1,21 +1,9 @@
// src/app/(frontend)/[locale]/actions.ts — ONE server action for every builder form. // src/app/(frontend)/[locale]/actions.ts — ONE server action for every builder form.
// honeypot → client IP (IPAL_IP_HEADER) → submitForm (rate limit, Turnstile,
// validation, GDPR consent, storage) → visitor message from Notifications.
'use server' 'use server'
import { headers } from 'next/headers' import { headers } from 'next/headers'
import { submitForm } from '@intecion/ipal-kit/server' import { createSubmitAction } from '@intecion/ipal-kit/server'
import { clientIp, isHoneypotTripped, HONEYPOT_FIELD, getNotificationTexts, resolveFormMessage } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content' import { getCachedPayload } from '@/lib/content'
export async function sendForm( export const sendForm = createSubmitAction({ getCachedPayload, headers })
formId: string,
locale: string,
values: Record<string, unknown>,
turnstileToken?: string,
): Promise<{ success: boolean; message: string }> {
const payload = await getCachedPayload()
const texts = (await getNotificationTexts({ payload, locale })).form
if (isHoneypotTripped(values)) return { success: true, message: texts.success } // bot: fake success, nothing stored
const { [HONEYPOT_FIELD]: _hp, ...data } = values
const ip = clientIp(await headers()) || undefined // headers(): fine in a server action — never in the page tree (breaks SSG)
const result = await submitForm({ payload, formId, data, turnstileToken, ip })
return { success: result.success, message: resolveFormMessage(result, texts) }
}
@@ -0,0 +1,29 @@
// src/components/forms/formClasses.ts — the ONLY place forms are styled. Every
// panel form (RenderForm / BuilderForm) uses it. Values = the project's design
// tokens (DESIGN.md); the plugin ships no styles. Delete keys you don't need.
import type { BuilderFormClassNames } from '@intecion/ipal-kit/client'
export const formClasses: BuilderFormClassNames = {
form: 'grid gap-6',
progress: 'text-sm text-muted', // "Krok 1 z 3"
step: 'grid gap-4',
stepTitle: 'text-h3 font-semibold',
stepDescription: 'text-muted',
fields: 'grid grid-cols-12 gap-4',
field: 'col-span-12',
fieldHalf: 'md:col-span-6', // width ≤ 50 in the panel
label: 'mb-1 block font-medium',
input: 'w-full rounded-md border border-border px-3 py-2',
textarea: 'w-full rounded-md border border-border px-3 py-2',
select: 'w-full rounded-md border border-border px-3 py-2',
checkboxLabel: 'flex items-start gap-2',
choices: 'grid gap-2', // radio / checkbox group <fieldset>
legend: 'mb-1 font-medium',
choice: 'flex items-center gap-2',
error: 'mt-1 text-sm text-danger',
formError: 'text-danger',
actions: 'flex gap-3',
back: 'btn btn-secondary', // same classes as Button.tsx variants
submit: 'btn btn-primary',
success: 'rounded-md bg-surface p-6',
}
@@ -0,0 +1,203 @@
/**
* Seed of ONE form in the database — fields, confirmation, and the two e-mails
* every site needs: a notification to the company and a confirmation to the
* person who sent it. Copy to scripts/seed-form-<name>.ts, fill FORM from the
* brief (every language), run:
*
* pnpm payload run scripts/seed-form-contact.ts # creates the form if missing
* SEED_UPDATE=1 pnpm payload run scripts/seed-form-contact.ts # also overwrites an existing one
*
* Nothing about the company lives in this file. The notification address comes
* from the panel — NOTIFY.global / NOTIFY.field below (the project's company
* global) — or SEED_NOTIFY_EMAIL for a first run. Without an address the script
* stops: a form whose submissions reach nobody is a bug, not a default.
*
* Safe to send to {{email}}: submitForm accepts exactly one address in an
* `email` field (no extra recipients, no header injection).
*/
import config from '@payload-config'
import { getPayload } from 'payload'
// ─── fill from the brief ────────────────────────────────────────────────────
const FORM = {
/** Unique, not shown to visitors — the seed finds the form by it. */
title: 'Contact form',
fields: [
{ blockType: 'text', name: 'name', required: true, width: 50, label: { pl: 'Imię i nazwisko', en: 'Full name' } },
{ blockType: 'email', name: 'email', required: true, width: 50, label: { pl: 'E-mail', en: 'E-mail' } },
{ blockType: 'text', name: 'phone', required: false, width: 50, label: { pl: 'Telefon', en: 'Phone' } },
{ blockType: 'textarea', name: 'message', required: true, width: 100, label: { pl: 'Wiadomość', en: 'Message' } },
// Step-by-step form: a `step` block starts a new screen (title/description per language).
// { blockType: 'step', title: { pl: 'Projekt', en: 'Project' } },
// Choice lists (option labels per language, values stay the same):
// { blockType: 'radio', name: 'budget', required: true, label: { pl: 'Budżet', en: 'Budget' },
// options: [{ value: 's', label: { pl: 'do 10 tys.', en: 'up to 10k' } }, …] },
// { blockType: 'checkboxGroup', name: 'services', maxSelected: 3, label: {…}, options: [ …same shape… ] },
// { blockType: 'date', name: 'deadline', label: { pl: 'Termin', en: 'Deadline' } },
// GDPR consent — name MUST stay `consent`; never pre-ticked (the plugin enforces it server-side).
{
blockType: 'checkbox',
name: 'consent',
required: true,
width: 100,
label: {
pl: 'Zgadzam się na przetwarzanie moich danych w celu odpowiedzi na wiadomość.',
en: 'I agree to the processing of my data to answer this message.',
},
},
],
submitButtonLabel: { pl: 'Wyślij', en: 'Send' },
confirmation: {
pl: 'Dziękujemy! Odpowiemy najszybciej, jak to możliwe.',
en: 'Thank you! We will get back to you as soon as possible.',
},
/** E-mail to the company. {{*:table}} = every field as a table. */
notification: {
subject: { pl: 'Nowa wiadomość ze strony od {{name}}', en: 'New website message from {{name}}' },
message: { pl: 'Nowe zgłoszenie z formularza:\n\n{{*:table}}', en: 'New form submission:\n\n{{*:table}}' },
},
/** E-mail to the sender. */
confirmationEmail: {
subject: { pl: 'Otrzymaliśmy Twoją wiadomość', en: 'We received your message' },
message: {
pl: 'Dzień dobry {{name}},\n\ndziękujemy za wiadomość — odpowiemy wkrótce.\n\nTwoje zgłoszenie:\n{{*:table}}',
en: 'Hello {{name}},\n\nthank you for your message — we will reply shortly.\n\nYour submission:\n{{*:table}}',
},
},
} as const
/** Where the company's address lives in the panel (project global + field). */
const NOTIFY = { global: 'company', field: 'email' }
// ────────────────────────────────────────────────────────────────────────────
type Localized = Readonly<Record<string, string>>
/** Plain text (with blank-line paragraphs) → Lexical rich text, as form-builder messages expect. */
function richText(text: string) {
return {
root: {
children: text.split(/\n{2,}/).map((para) => ({
children: para.split('\n').flatMap((line, i) => [
...(i ? [{ type: 'linebreak', version: 1 }] : []),
{ detail: 0, format: 0, mode: 'normal', style: '', text: line, type: 'text', version: 1 },
]),
direction: 'ltr',
format: '',
indent: 0,
type: 'paragraph',
version: 1,
})),
direction: 'ltr',
format: '',
indent: 0,
type: 'root',
version: 1,
},
}
}
const payload = await getPayload({ config })
const locales = (payload.config.localization ? payload.config.localization.localeCodes : ['pl']) as string[]
const defaultLocale = (payload.config.localization ? payload.config.localization.defaultLocale : locales[0]) as string
const pick = (value: Localized, locale: string) => value[locale] ?? value[defaultLocale] ?? Object.values(value)[0]
// Notification address — from the panel, never from this file.
let notifyTo = process.env.SEED_NOTIFY_EMAIL?.trim() ?? ''
if (!notifyTo) {
try {
const g = (await payload.findGlobal({ slug: NOTIFY.global as never, depth: 0 })) as Record<string, unknown>
notifyTo = typeof g[NOTIFY.field] === 'string' ? (g[NOTIFY.field] as string).trim() : ''
} catch {
// no such global — handled below
}
}
if (!/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/.test(notifyTo)) {
console.error(
`[seed-form] No notification address. Fill ${NOTIFY.global} → ${NOTIFY.field} in the panel ` +
'(or run with SEED_NOTIFY_EMAIL=…). Ask the client which inbox gets the submissions — do not guess.',
)
process.exit(1)
}
/** A field with every per-language text ({ pl, en }) resolved: label, step title/description, option labels. */
function localizeField(field: Record<string, unknown>, locale: string): Record<string, unknown> {
const text = (v: unknown) => (v && typeof v === 'object' ? pick(v as Localized, locale) : v)
return {
...field,
...('label' in field ? { label: text(field.label) } : {}),
...('title' in field ? { title: text(field.title) } : {}),
...('description' in field ? { description: text(field.description) } : {}),
...(Array.isArray(field.options)
? { options: (field.options as Record<string, unknown>[]).map((o) => ({ ...o, label: text(o.label) })) }
: {}),
}
}
/** Form data in one locale (localized fields resolved for it). */
function dataFor(locale: string) {
return {
confirmationMessage: richText(pick(FORM.confirmation, locale)),
confirmationType: 'message',
emails: [
{
emailTo: notifyTo,
replyTo: '{{email}}',
message: richText(pick(FORM.notification.message, locale)),
subject: pick(FORM.notification.subject, locale),
},
{
emailTo: '{{email}}',
replyTo: notifyTo,
message: richText(pick(FORM.confirmationEmail.message, locale)),
subject: pick(FORM.confirmationEmail.subject, locale),
},
],
fields: FORM.fields.map((field) => localizeField(field as Record<string, unknown>, locale)),
submitButtonLabel: pick(FORM.submitButtonLabel, locale),
title: FORM.title,
}
}
const existing = await payload.find({ collection: 'forms' as never, limit: 1, where: { title: { equals: FORM.title } } })
let id = existing.docs[0]?.id as number | string | undefined
if (id && process.env.SEED_UPDATE !== '1') {
console.log(`[seed-form] "${FORM.title}" exists (id ${id}) — unchanged. SEED_UPDATE=1 overwrites it.`)
process.exit(0)
}
if (!id) {
const created = await payload.create({ collection: 'forms' as never, data: dataFor(defaultLocale) as never, locale: defaultLocale as never })
id = created.id
} else {
await payload.update({ collection: 'forms' as never, data: dataFor(defaultLocale) as never, id, locale: defaultLocale as never })
}
// Other languages: same rows (ids kept), localized texts per locale.
for (const locale of locales.filter((l) => l !== defaultLocale)) {
const doc = (await payload.findByID({ collection: 'forms' as never, depth: 0, id, locale: locale as never })) as {
emails?: { id?: string }[]
fields?: { id?: string; options?: { id?: string }[] }[]
}
const d = dataFor(locale)
await payload.update({
collection: 'forms' as never,
data: {
...d,
emails: d.emails.map((e, i) => ({ ...e, id: doc.emails?.[i]?.id })),
// Keep row ids (fields and their options) — new ids would wipe the other languages' texts.
fields: d.fields.map((f, i) => ({
...f,
id: doc.fields?.[i]?.id,
...(Array.isArray(f.options)
? { options: (f.options as Record<string, unknown>[]).map((o, j) => ({ ...o, id: doc.fields?.[i]?.options?.[j]?.id })) }
: {}),
})),
} as never,
id,
locale: locale as never,
})
}
console.log(`[seed-form] "${FORM.title}" ready (id ${id}) in ${locales.join(', ')} — notifications to ${notifyTo}, confirmation to the sender.`)
console.log('Next: place the form in a Form block on the contact page, then Site Integrations → Send test.')
process.exit(0)
+5 -4
View File
@@ -1,6 +1,6 @@
--- ---
name: ipal-nav name: ipal-nav
description: Builds the site header, footer, mobile menu and company data in an ipal-kit project — Header/Footer/Company globals with buildLinkField from the plugin, server-side link resolution (resolveNav), a small client MobileNav, legal links from System Pages, revalidation on change. Use when creating or changing navigation, menu, header, footer, contact details, social links or the company global. description: Builds the site header, footer, mobile menu and company data in an ipal-kit project — Header/Footer/Company globals with buildLinkField from the plugin, server-side link resolution (resolveNav from the plugin), a small client MobileNav, legal links from System Pages, revalidation on change. Use when creating or changing navigation, menu, header, footer, contact details, social links or the company global.
--- ---
# ipal-nav # ipal-nav
@@ -19,10 +19,11 @@ Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (jak skill ipal-blo
(teksty localized), `access.read: () => true`. (teksty localized), `access.read: () => true`.
2. Hook `afterChange` na każdym globalu: `revalidatePath('/', 'layout')` 2. Hook `afterChange` na każdym globalu: `revalidatePath('/', 'layout')`
(wstrzyknięty z `next/cache`, hooks.md). (wstrzyknięty z `next/cache`, hooks.md).
3. `src/lib/navigation.ts` (`resolveNav`) — linki rozwiązane na serwerze do 3. Menu: `await resolveNav(header.navItems, locale)` z `lib/content` (plugin) — linki
`{ href, label, newTab, subItems }`. rozwiązane na serwerze do `{ href, label, internal, newTab, targetProps, children }`.
Nie twórz `lib/navigation.ts`.
4. `src/components/layout/Header.tsx`, `Footer.tsx` (serwer), `MobileNav.tsx` 4. `src/components/layout/Header.tsx`, `Footer.tsx` (serwer), `MobileNav.tsx`
(`'use client'`, tylko stan otwarcia, dane przez props, `import type` z lib). (`'use client'`, tylko stan otwarcia, dane przez props, `import type { NavItem } from '@intecion/ipal-kit'`).
5. **Linki prawne w stopce** z ról System Pages (`getSystemPagePath` + tytuł 5. **Linki prawne w stopce** z ról System Pages (`getSystemPagePath` + tytuł
strony) — nie jako ręczne pozycje. Rok w copyright z kodu, nazwa z `Company`. strony) — nie jako ręczne pozycje. Rok w copyright z kodu, nazwa z `Company`.
6. Logo z Site Settings przez `<Media>` — nie duplikuj pola w Header. 6. Logo z Site Settings przez `<Media>` — nie duplikuj pola w Header.
@@ -86,49 +86,16 @@ export const Footer: GlobalConfig = {
- **Odświeżanie:** global zmienia się na każdej stronie → hook `afterChange` - **Odświeżanie:** global zmienia się na każdej stronie → hook `afterChange`
z `revalidatePath('/', 'layout')` (hooks.md). z `revalidatePath('/', 'layout')` (hooks.md).
Linki rozwiązuj **na serwerze** do zwykłych danych, a do klienta (menu mobilne) Menu z globala rozwiązuje plugin: `await resolveNav(header.navItems, locale)` z `lib/content`
przekazuj tylko `{ href, label, newTab }` — komponent kliencki nie może wołać → `{ href, label, internal, newTab, targetProps, children }[]` (martwe linki pominięte, dowolna
`CMSLink` (to async server component). głębokość). To zwykłe dane — idą wprost do klienckiego `MobileNav`. Nie twórz `lib/navigation.ts`.
```ts
// src/lib/navigation.ts
import { resolveLinkHref } from '@intecion/ipal-kit'
import type { CmsLink } from '@/payload-types'
import { i18nConfig } from '@/i18n.config'
import { getSettings } from '@/lib/content'
export type NavItem = { href: string; label: string; newTab: boolean; subItems: NavItem[] }
type NavSource = { link?: CmsLink | null; subItems?: { link?: CmsLink | null }[] | null }
function toNavItem(link: CmsLink | null | undefined, locale: string, homeSlug?: string): NavItem | null {
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
if (!link || !href || !link.label) return null
return { href, label: link.label, newTab: Boolean(link.newTab), subItems: [] }
}
export async function resolveNav(items: NavSource[] | null | undefined, locale: string): Promise<NavItem[]> {
const settings = await getSettings(locale)
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
return (items ?? []).flatMap((item) => {
const node = toNavItem(item.link, locale, homeSlug)
if (!node) return []
node.subItems = (item.subItems ?? []).flatMap((sub) => {
const child = toNavItem(sub.link, locale, homeSlug)
return child ? [child] : []
})
return [node]
})
}
```
```tsx ```tsx
// src/components/layout/Header.tsx — serwer // src/components/layout/Header.tsx — serwer
import Link from 'next/link' import Link from 'next/link'
import type { Header as HeaderData } from '@/payload-types' import type { Header as HeaderData } from '@/payload-types'
import { resolveNav } from '@/lib/navigation' import { resolveNav } from '@/lib/content'
import { CMSLink } from '@/components/ui/CMSLink' import { CMSLink } from '@/components/ui/CMSLink'
import { MobileNav } from './MobileNav' import { MobileNav } from './MobileNav'
@@ -141,9 +108,7 @@ export async function Header({ header, locale }: { header: HeaderData; locale: s
<ul className="hidden gap-6 md:flex"> <ul className="hidden gap-6 md:flex">
{items.map((item) => ( {items.map((item) => (
<li key={item.href}> <li key={item.href}>
<Link href={item.href} {...(item.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})}> <Link href={item.href} {...item.targetProps}>{item.label}</Link>
{item.label}
</Link>
</li> </li>
))} ))}
</ul> </ul>
@@ -160,7 +125,7 @@ export async function Header({ header, locale }: { header: HeaderData; locale: s
'use client' 'use client'
import { useState } from 'react' import { useState } from 'react'
import Link from 'next/link' import Link from 'next/link'
import type { NavItem } from '@/lib/navigation' // import TYPU — nie ciągnie kodu serwera import type { NavItem } from '@intecion/ipal-kit' // import TYPU — nie ciągnie kodu serwera
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) { export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
+2 -2
View File
@@ -28,8 +28,8 @@ Sprawdza **działającą** aplikację, nie kod — dokładnie to, co dostaje Goo
| unknown URL returns 200 | brak `notFound()` w catch-all | | unknown URL returns 200 | brak `notFound()` w catch-all |
| sitemap URLs not 200 | w sitemapie adresy z przekierowaniem (stare slugi) | | sitemap URLs not 200 | w sitemapie adresy z przekierowaniem (stare slugi) |
| robots.txt points to localhost | `NEXT_PUBLIC_SERVER_URL` nieustawione w buildzie | | robots.txt points to localhost | `NEXT_PUBLIC_SERVER_URL` nieustawione w buildzie |
| no JSON-LD structured data | brak `<JsonLdGraph>` w `[locale]/layout.tsx` albo pusta nazwa w Site Settings | | no JSON-LD structured data | brak `<SiteProviders>` / `<JsonLdGraph>` w `[locale]/layout.tsx` albo pusta nazwa w Site Settings |
| `/llms.txt` / `/llms-full.txt` → 404 | brak trasy `createLlmsTxtRoute` (drugiej z `full: true`) | | `/llms.txt` / `/llms-full.txt` → 404 | brak trasy (`export { llmsRoute as GET }` / `llmsFullRoute` z `lib/content`) |
| Markdown version `/md/…` → 404 | brak `src/app/md/[locale]/[[...slug]]/route.ts`; strona noindex/draft | | Markdown version `/md/…` → 404 | brak `src/app/md/[locale]/[[...slug]]/route.ts`; strona noindex/draft |
| MCP not answering initialize | brak `src/app/api/mcp/route.ts` albo Cloudflare Access bez Bypass (mcp.md) | | MCP not answering initialize | brak `src/app/api/mcp/route.ts` albo Cloudflare Access bez Bypass (mcp.md) |
@@ -98,7 +98,7 @@ for (let i = 0; sample.length < Math.min(MAX, urls.length); i++) {
const multiLocale = hasAlternates || byLocale.size > 1 const multiLocale = hasAlternates || byLocale.size > 1
const urlSet = new Set(urls.map(norm)) const urlSet = new Set(urls.map(norm))
const titles = new Map() const titles = new Map()
const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [], jsonLd: [], mdAlt: [] } const issues = { status: [], noHead: [], body: [], title: [], longTitle: [], desc: [], canonical: [], canonSelf: [], noindex: [], hreflang: [], xdefault: [], reciprocal: [], favicon: [], jsonLd: [], mdAlt: [], h1: [], headingSkip: [], alt: [], imgSize: [], lcp: [], ogImage: [], thin: [], noLinks: [], xRobots: [] }
const checkedPaths = [] const checkedPaths = []
for (const url of sample) { for (const url of sample) {
@@ -135,6 +135,33 @@ for (const url of sample) {
if (!/<link[^>]+type="text\/markdown"/i.test(head)) issues.mdAlt.push(url) if (!/<link[^>]+type="text\/markdown"/i.test(head)) issues.mdAlt.push(url)
checkedPaths.push(new URL(url).pathname) checkedPaths.push(new URL(url).pathname)
// --- content & performance (AGENT.md §0c, §6.11b) ---
if (/noindex/i.test(page.res.headers.get('x-robots-tag') ?? '')) issues.xRobots.push(url)
const main = body.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<template[\s\S]*?<\/template>/gi, '')
const h1s = (main.match(/<h1[\s>]/gi) ?? []).length
if (h1s !== 1) issues.h1.push(`${url} (${h1s} h1)`)
let prev = 0
for (const m of main.matchAll(/<h([1-6])[\s>]/gi)) {
const level = Number(m[1])
if (prev && level > prev + 1) { issues.headingSkip.push(`${url} (h${prev} → h${level})`); break }
prev = level
}
const imgs = tags(main, /<img\b[^>]*>/gi)
const noAlt = imgs.filter((t) => !/\salt\s*=/.test(t))
if (noAlt.length) issues.alt.push(`${url} (${noAlt.length} img)`)
const noSize = imgs.filter((t) => !/\swidth\s*=/.test(t) || !/\sheight\s*=/.test(t)).filter((t) => !/data-nimg="fill"/.test(t))
if (noSize.length) issues.imgSize.push(`${url} (${noSize.length} img)`)
if (imgs.length && !/fetchpriority="high"/i.test(imgs[0]) && !/<link[^>]+rel="preload"[^>]+as="image"/i.test(head)) issues.lcp.push(url)
if (!/<meta[^>]+property="og:image"/i.test(head)) issues.ogImage.push(url)
const words = main.replace(/<[^>]+>/g, ' ').replace(/&[a-z#0-9]+;/gi, ' ').split(/\s+/).filter((w) => /\p{L}{2,}/u.test(w)).length
if (words < 150) issues.thin.push(`${url} (${words} words)`)
const own = new URL(url).host
const internal = tags(main, /<a\b[^>]*href="([^"#]+)"[^>]*>/gi).filter((t) => {
const href = attr(t, 'href') ?? ''
try { const u = new URL(href, url); return u.host === own && norm(u.pathname) !== norm(new URL(url).pathname) } catch { return false }
})
if (internal.length === 0) issues.noLinks.push(url)
if (multiLocale) { if (multiLocale) {
const alts = tags(head, /<link[^>]+hreflang="[^"]+"[^>]*>/gi).map((t) => ({ lang: attr(t, 'hreflang'), href: attr(t, 'href') })) const alts = tags(head, /<link[^>]+hreflang="[^"]+"[^>]*>/gi).map((t) => ({ lang: attr(t, 'hreflang'), href: attr(t, 'href') }))
if (alts.length === 0) issues.hreflang.push(url) if (alts.length === 0) issues.hreflang.push(url)
@@ -161,6 +188,15 @@ if (issues.desc.length) report('WARNING', 'missing meta description', 'fill SEO
if (dupTitles.length) report('WARNING', 'duplicate titles', 'unique meta titles per page', dupTitles) if (dupTitles.length) report('WARNING', 'duplicate titles', 'unique meta titles per page', dupTitles)
if (issues.longTitle.length) report('WARNING', 'titles over 65 chars (truncated in results)', 'shorten in the SEO tab', issues.longTitle) if (issues.longTitle.length) report('WARNING', 'titles over 65 chars (truncated in results)', 'shorten in the SEO tab', issues.longTitle)
if (issues.favicon.length) report('WARNING', 'no favicon link in head', 'buildIconsMetadata(settings.favicon) in root generateMetadata', issues.favicon.slice(0, 3)) if (issues.favicon.length) report('WARNING', 'no favicon link in head', 'buildIconsMetadata(settings.favicon) in root generateMetadata', issues.favicon.slice(0, 3))
if (issues.xRobots.length) report('ERROR', 'X-Robots-Tag: noindex on pages', 'IPAL_NOINDEX is set in this environment — remove it in production', issues.xRobots.slice(0, 3))
if (issues.h1.length) report('ERROR', 'not exactly one h1', 'one h1 per page — SectionHeader as="h1" only in the first section (AGENT.md §0c)', issues.h1)
if (issues.alt.length) report('ERROR', 'images without alt', 'alt from the Media document; decorative: alt=""', issues.alt)
if (issues.headingSkip.length) report('WARNING', 'heading levels skipped', 'h1 → h2 → h3, no jumps (AGENT.md §0c)', issues.headingSkip)
if (issues.imgSize.length) report('WARNING', 'images without width/height (layout shift)', '<Media> via mediaImageProps (AGENT.md §6.11b)', issues.imgSize)
if (issues.lcp.length) report('WARNING', 'first image not prioritised (LCP)', '<Media priority> on the hero image (AGENT.md §6.11b)', issues.lcp)
if (issues.ogImage.length) report('WARNING', 'no og:image', 'share image in the SEO tab or Site Settings → Default share image', issues.ogImage.slice(0, 5))
if (issues.thin.length) report('WARNING', 'thin pages (< 150 words)', 'add real content from the brief or merge pages (AGENT.md §0c)', issues.thin)
if (issues.noLinks.length) report('WARNING', 'pages without internal links', 'link related pages and contact (AGENT.md §0c)', issues.noLinks)
if (!skipped('jsonld') && issues.jsonLd.length) report('ERROR', 'no JSON-LD structured data', '<JsonLdGraph> WebSite + Organization in [locale]/layout.tsx (AGENT.md §0b.4)', issues.jsonLd.slice(0, 5)) if (!skipped('jsonld') && issues.jsonLd.length) report('ERROR', 'no JSON-LD structured data', '<JsonLdGraph> WebSite + Organization in [locale]/layout.tsx (AGENT.md §0b.4)', issues.jsonLd.slice(0, 5))
if (!skipped('markdown') && issues.mdAlt.length) report('WARNING', 'no text/markdown alternate link in head', 'createContentHelpers({ markdownAlternate: true }) (AGENT.md §0b.6)', issues.mdAlt.slice(0, 3)) if (!skipped('markdown') && issues.mdAlt.length) report('WARNING', 'no text/markdown alternate link in head', 'createContentHelpers({ markdownAlternate: true }) (AGENT.md §0b.6)', issues.mdAlt.slice(0, 3))
+22 -13
View File
@@ -5,7 +5,7 @@ description: Sets up a new client project on Payload 3 + Next 16 + @intecion/ipa
# ipal-setup # ipal-setup
**Cel: OBOWIĄZKOWY KOMPLET z AGENT.md §0b — wszystkie 16 pozycji.** Wszystko **Cel: OBOWIĄZKOWY KOMPLET z AGENT.md §0b — wszystkie 18 pozycji.** Wszystko
sprawdza etap 11; nie kończysz z brakami (chyba że `ipal-audit-skip` z decyzji klienta). sprawdza etap 11; nie kończysz z brakami (chyba że `ipal-audit-skip` z decyzji klienta).
Kod i szczegóły: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md` §1–2 Kod i szczegóły: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md` §1–2
@@ -27,23 +27,32 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**.
3. **Konfiguracja** — `src/i18n.config.ts` (`as const satisfies I18nConfig`), 3. **Konfiguracja** — `src/i18n.config.ts` (`as const satisfies I18nConfig`),
`payload.config.ts` wg PROGRAMISTA §2.3: `twoFactor` z **wstrzykniętym** `payload.config.ts` wg PROGRAMISTA §2.3: `twoFactor` z **wstrzykniętym**
`payloadTotp`, `whiteLabel: true`, `email: mailAdapter()`, `forms: {…}`, `payloadTotp`, `whiteLabel: true`, `email: mailAdapter()`, `forms: {…}`,
**`buildR2Storage(['media'], { s3Storage })` zawsze** (bez `R2_*` w dev = dysk lokalny). **`buildR2Storage(['media'], { s3Storage })` zawsze** (bez `R2_*` w dev = dysk lokalny),
`.env.example` z `R2_*`, `IPAL_IP_HEADER`, `NEXT_PUBLIC_SERVER_URL`. `indexNow: true`, `consentLog: true`.
`.env.example` z `R2_*`, `IPAL_IP_HEADER`, `NEXT_PUBLIC_SERVER_URL`, `IPAL_NOINDEX` (puste; `1` na stagingu).
4. **Rdzeń** — wspólne pola i prymitywy (`../ipal-block/resources/kod-sekcji.md`), `Pages` (z `buildSummaryField()` — GEO), `Media` 4. **Rdzeń** — wspólne pola i prymitywy (`../ipal-block/resources/kod-sekcji.md`), `Pages` (z `buildSummaryField()` — GEO), `Media`
z `normalizeFilenameHook` + `buildOptimizeUploadHook`/`buildOptimizeUploadField` (PROGRAMISTA §2.4, storage.md). Żadnych innych kolekcji. z `focalPoint: true`, `normalizeFilenameHook`, `buildOptimizeUploadHook`/`buildOptimizeUploadField`,
`buildMediaPlaceholderHook`/`buildMediaPlaceholderField`; prymityw `Media` przez `mediaImageProps`/`videoProps`
(PROGRAMISTA §2.4, storage.md). Żadnych innych kolekcji (`users` wstrzykuje plugin).
5. **Style** — `styles.css` z `@theme` z `DESIGN.md` (jeśli brak — zapytaj o 5. **Style** — `styles.css` z `@theme` z `DESIGN.md` (jeśli brak — zapytaj o
Impeccable albo załóż neutralne tokeny), `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`). Impeccable albo załóż neutralne tokeny), `fluid.css` lub `fluid-wide.css` (AGENT §6.11a), fonty
przez `next/font` z `latin-ext`, `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`).
6. **Routing** — `proxy.ts` (`createProxy(i18nConfig, { NextResponse, markdown: true })`), `lib/content.ts` 6. **Routing** — `proxy.ts` (`createProxy(i18nConfig, { NextResponse, markdown: true })`), `lib/content.ts`
(`markdownAlternate: true`), layout bez `<head>` z `JsonLdGraph`, `TurnstileProvider` (`createContentHelpers` z `markdownAlternate: true`, `summaryField`, `mcp` — PROGRAMISTA §2.7),
(`getTurnstileConfig`), consent i `Analytics` (PROGRAMISTA §2.8), catch-all z ISR + `generateStaticParams` + `resolveRedirect`, layout bez `<head>`: `<SiteProviders shell={await getSiteShell(locale)} logEndpoint banner={<CookieBanner equalChoice />}>`,
`not-found.tsx` z `LocaleView` — bez `headers()`, wersja na każdy język (PROGRAMISTA §2.6–2.8, pages.md). catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`,
7. **SEO i bezpieczeństwo** — sitemap (`sitemap.xml/route.ts` = `sitemapRoute`, bez CSS w `public/`), robots, manifest, health `not-found.tsx`: `createNotFoundPage(content, { blocks })` (PROGRAMISTA §2.6–2.8, pages.md).
(z `force-dynamic`), `htmlLimitedBots`, `buildSecurityHeaders`, 7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, health jako re-eksporty z `lib/content`
(`sitemapRoute`, `robots`, `manifest`, `healthRoute`; z `force-dynamic` poza robots; bez CSS w `public/`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`,
`images: buildImagesConfig()`,
`instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` z `@intecion/ipal-kit/env` (PROGRAMISTA §2.8–2.9, env.md). `instrumentation.ts` z `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))` z `@intecion/ipal-kit/env` (PROGRAMISTA §2.8–2.9, env.md).
8. **GEO (obowiązkowe)** — `llms.txt`, `llms-full.txt` (`full: true`), `md/[locale]/[[...slug]]/route.ts`, 8. **GEO (obowiązkowe)** — re-eksporty z `lib/content`: `llms.txt` (`llmsRoute`), `llms-full.txt`
`api/mcp/route.ts` (publiczny), `summaryField: 'aiSummary'` w trasach AI; robots (`llmsFullRoute`), `md/[locale]/[[...slug]]/route.ts` (`markdownRoute`), `api/mcp/route.ts`
(`mcpGET`/`mcpPOST`, publiczny), `indexnow-key.txt/route.ts` (`indexNowKeyRoute`); robots
wpuszcza boty AI (PROGRAMISTA §2.8, AGENT.md §0b.5–8). wpuszcza boty AI (PROGRAMISTA §2.8, AGENT.md §0b.5–8).
9. **Formularze** — skill **ipal-form** (renderer + akcja raz; formularze w panelu). 9. **Formularze** — skill **ipal-form**: blok z `<RenderForm>`, `formClasses.ts`, `createSubmitAction` raz, każdy formularz z seeda
(mail do firmy + potwierdzenie do klienta). Cookies: skan + import (ipal-consent-check), `<CookieTable>`
na stronie polityki cookies.
10. **Nawigacja** — skill **ipal-nav**. 10. **Nawigacja** — skill **ipal-nav**.
11. **Kontrola kompletu** — `pnpm generate:types`, `pnpm payload generate:importmap`, 11. **Kontrola kompletu** — `pnpm generate:types`, `pnpm payload generate:importmap`,
**ipal-audit** (pełny) = 0 błędów, w tym sekcja „missing: …” (§0b); po **ipal-audit** (pełny) = 0 błędów, w tym sekcja „missing: …” (§0b); po
+3 -2
View File
@@ -25,7 +25,7 @@ między fazami. Przed fazą przejdź tabelę „Przewidujesz” z AGENT.md §0a.
1. Języki strony? (pl + en — jak w briefie) 1. Języki strony? (pl + en — jak w briefie)
2. Domena produkcyjna? (placeholder w .env, canonical ustawię po wdrożeniu) 2. Domena produkcyjna? (placeholder w .env, canonical ustawię po wdrożeniu)
3. Dane firmy: NIP, adres, telefon? ([DO UZUPEŁNIENIA] w panelu) 3. Dane firmy: NIP, adres, telefon? ([DO UZUPEŁNIENIA] w panelu)
4. Na jaki adres wysyłać zgłoszenia z formularza? ([DO UZUPEŁNIENIA] w Forms → Emails) 4. Na jaki adres wysyłać zgłoszenia z formularza? (bez tego seed formularza się nie uruchomi — to jedyne pytanie, bez którego nie oddam formularzy)
5. Analityka: ID GA4/GTM/pikseli? (wyłączona do czasu wpisania ID w panelu) 5. Analityka: ID GA4/GTM/pikseli? (wyłączona do czasu wpisania ID w panelu)
6. Dane R2: bucket, endpoint, klucze, domena mediów? (R2 jest wpięty zawsze; do czasu kluczy media lokalnie w dev) 6. Dane R2: bucket, endpoint, klucze, domena mediów? (R2 jest wpięty zawsze; do czasu kluczy media lokalnie w dev)
7. Klucze Turnstile? (testowe w dev; produkcyjne wpiszesz w Site Integrations) 7. Klucze Turnstile? (testowe w dev; produkcyjne wpiszesz w Site Integrations)
@@ -57,7 +57,8 @@ Każdy blok: schemat ze słownika pól, kompozycja prymitywów, zero tekstu w JS
(`ipal-audit --quick` po każdym bloku — błędy naprawiasz od razu). (`ipal-audit --quick` po każdym bloku — błędy naprawiasz od razu).
## Faza 5 — Formularze → **ipal-form** ## Faza 5 — Formularze → **ipal-form**
Formularze tworzysz w panelu (albo seedem) — kod piszesz raz. **Nigdy** własny Każdy formularz = seed z `ipal-form/resources/seed-form.template.ts` (pola, potwierdzenie, mail do
firmy **i** potwierdzenie do klienta, każdy język) — kod renderera i akcji piszesz raz. **Nigdy** własny
formularz z polami w JSX, trasa `api/contact`, `nodemailer`, reCAPTCHA (AGENT.md §0b). formularz z polami w JSX, trasa `api/contact`, `nodemailer`, reCAPTCHA (AGENT.md §0b).
## Faza 6 — Treść w panelu, każdy język ## Faza 6 — Treść w panelu, każdy język
+8
View File
@@ -30,6 +30,14 @@ nie dodatek. Pomijasz tylko z decyzją klienta w `AGENTS.md` (`ipal-audit-skip:`
wymagany — sprawdź, że każdy formularz ma widget); `clientIp(await headers())` w wymagany — sprawdź, że każdy formularz ma widget); `clientIp(await headers())` w
akcji formularza + `IPAL_IP_HEADER` w env produkcji; `buildR2Storage` wpięty. akcji formularza + `IPAL_IP_HEADER` w env produkcji; `buildR2Storage` wpięty.
**→ 1.9.2 (PROGRAMISTA §6, poz. 28–33) — import zamiast kodu, zacznij od poz. 28 (bezpieczeństwo):**
własny `FormRenderer` przekazywał do HTML zakładkę Emails (adresy firmy) → blok z `<RenderForm>` +
`formClasses.ts`, usuń renderer. Potem: layout → `SiteProviders`, strona i 404 → `createPageRoute` /
`createNotFoundPage`, trasy GEO → re-eksporty z `lib/content`, `src/fields/section*.ts` i
`lib/navigation.ts` → `buildSection*Field`, `resolveNav`, `resolveLink`. Każdą pozycję sprawdź w
przeglądarce (formularz: wysyłka + mail; strona: 200, 404, metadata). Postgres: `migrate:create`
(nowe typy pól formularza i teksty w Notifications).
## 2. Inwentaryzacja (bez zmian w kodzie) ## 2. Inwentaryzacja (bez zmian w kodzie)
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik. dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
+17
View File
@@ -74,6 +74,23 @@ const enhanceProps = ({ block, allBlocks }) => {
<RenderBlocks blocks={page.layout} components={registry} enhanceProps={enhanceProps} /> <RenderBlocks blocks={page.layout} components={registry} enhanceProps={enhanceProps} />
``` ```
## Wspólne pola sekcji — `buildSectionHeaderField`, `buildSectionSettingsField`
```ts
import { buildLinksField, buildSectionHeaderField, buildSectionSettingsField } from '@intecion/ipal-kit'
fields: [
buildSectionHeaderField(), // grupa `header`: eyebrow, heading, intro (localized) — typ SectionHeaderData
…pola bloku…,
buildLinksField(),
buildSectionSettingsField(), // sidebar `settings`: anchor, background — typ SectionSettings
]
```
Wszystko do zmiany: `buildSectionSettingsField({ backgrounds: [{ label: 'Brand', value: 'brand' }], anchor: false,
fields: [{ name: 'spacing', … }] })`, `backgrounds: false` (bez wyboru tła), `buildSectionHeaderField({ name, fields,
interfaceName })`. Wartości tła mapuje na klasy `<Section>` projektu. Kształt danych taki jak dawne
`src/fields/sectionHeader.ts` / `sectionSettings.ts` z kod-sekcji.md — zamiana importu nie wymaga migracji.
## Komponent bloku ## Komponent bloku
Każdy komponent dostaje dane bloku jako propsy (plus `_components`, plus to co Każdy komponent dostaje dane bloku jako propsy (plus `_components`, plus to co
+30
View File
@@ -36,6 +36,14 @@ okazji aktualizacji.
## Front — Provider + banner ## Front — Provider + banner
Zwykle jedną linią w layoutcie (PROGRAMISTA §2.8) — `SiteProviders` (`/rsc`) wpina provider,
baner, przycisk i `Analytics` w dobrej kolejności, z tekstami z `getSiteShell(locale).consent`:
```tsx
<SiteProviders shell={await getSiteShell(locale)} logEndpoint="/api/ipal/consent"
banner={<CookieBanner equalChoice classNames={…} />}>{children}</SiteProviders>
```
Ręcznie (własny układ) — to samo z pojedynczych części:
Provider owija aplikację, banner i button renderują się same. Import z Provider owija aplikację, banner i button renderują się same. Import z
`@intecion/ipal-kit/client`: `@intecion/ipal-kit/client`:
@@ -204,3 +212,25 @@ chcesz zachować sprzątanie locale (albo zaimportuj `LOCALE_COOKIE_NAME` i doda
> Mechanizm zgody dla locale jest opisany też od strony i18n: > Mechanizm zgody dla locale jest opisany też od strony i18n:
> [i18n.md](./i18n.md#cookie-locale-a-zgoda-rodo). > [i18n.md](./i18n.md#cookie-locale-a-zgoda-rodo).
## Wersja polityki, wycofanie zgody, rejestr zgód, tabela ciasteczek (1.9.1)
- **Ponowna zgoda po zmianie polityki:** Cookie Settings → *Policy version* (sidebar). Podnieś o 1
po dodaniu narzędzia albo zmianie polityki — każdy odwiedzający zobaczy baner ponownie.
`getConsentTexts` przekazuje wersję do `<ConsentProvider texts>` automatycznie.
- **Wycofanie zgody kasuje ciasteczka narzędzi** (`_ga`, `_ga_*`, `_gid`, `_fbp`, `_gcl_*`, Clarity,
LinkedIn, TikTok, Hotjar…) — także na domenie nadrzędnej (`.klient.pl`), gdzie zapisuje je GA.
Własne ciasteczka projektu: `<ConsentProvider cookieMap={{ marketing: ['_my*'] }}>` (dopisywane do
listy domyślnej, `*` = prefiks).
- **Równy wybór:** `<CookieBanner equalChoice />` — „Odrzuć” wygląda jak „Akceptuj wszystko”
(wymóg UODO/EDPB: odmowa równie łatwa jak zgoda). Domyślnie wyłączone, żeby nie zmieniać wyglądu
istniejących stron; **w nowych projektach włączaj**.
- **Rejestr zgód (dowód zgody, art. 7 ust. 1 RODO):** `ipalKit({ consentLog: true })` +
`<ConsentProvider logEndpoint="/api/ipal/consent">`. Zapisuje losowy identyfikator (ten sam co w
ciasteczku), wybory, wersję polityki i czas — **bez IP i user-agenta**. Kolekcja *Consent records*
(tylko admin), automatyczne czyszczenie po `retentionDays` (domyślnie 1095). Postgres: `migrate:create`.
- **Tabela ciasteczek** dla strony polityki: Cookie Settings → *Cookies* (wypełniana skanem,
skill `ipal-consent-check` → cookie-scan) + `getCookieTable` + `<CookieTable>` z `/rsc`.
- Ciasteczko zgody ma `Secure` na HTTPS.
- Global Privacy Control nie jest potrzebny: w UE wszystko poza niezbędnymi i tak jest domyślnie
wyłączone do czasu zgody.
+1 -1
View File
@@ -224,7 +224,7 @@ round-trip do bazy i zwraca 200/503, więc Coolify/Docker odróżni „proces ż
od „app gotowa, baza dostępna": od „app gotowa, baza dostępna":
```ts ```ts
// app/api/health/route.ts // app/api/health/route.ts — zwykle: export { healthRoute as GET } from '@/lib/content'
import { createHealthRoute } from '@intecion/ipal-kit' import { createHealthRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content' import { getCachedPayload } from '@/lib/content'
export const dynamic = 'force-dynamic' // nigdy nie prerenderuj/cache'uj health export const dynamic = 'force-dynamic' // nigdy nie prerenderuj/cache'uj health
+118 -97
View File
@@ -120,7 +120,7 @@ import { Pages } from '@/collections/Pages'
import { Media } from '@/collections/Media' import { Media } from '@/collections/Media'
export default buildConfig({ export default buildConfig({
collections: [Pages, Media], // users wbudowane — nie twórz collections: [Pages, Media], // users wstrzykuje ipalKit (własna tylko dla dodatkowych pól)
email: mailAdapter(), // bez tego maile form-buildera nie wyjdą email: mailAdapter(), // bez tego maile form-buildera nie wyjdą
plugins: [ plugins: [
ipalKit({ ipalKit({
@@ -132,6 +132,8 @@ export default buildConfig({
forms: { redirectRelationships: ['pages'] }, forms: { redirectRelationships: ['pages'] },
twoFactor: { issuer: 'Nazwa Klienta', plugin: payloadTotp }, twoFactor: { issuer: 'Nazwa Klienta', plugin: payloadTotp },
whiteLabel: true, // logo/nazwa z Site Settings w panelu whiteLabel: true, // logo/nazwa z Site Settings w panelu
indexNow: true, // publikacja → Bing / ChatGPT Search (produkcja)
consentLog: true, // dowód zgody (RODO art. 7 ust. 1), bez danych osobowych
// adminRoute: '/its', // + przenieś app/(payload)/admin → its // adminRoute: '/its', // + przenieś app/(payload)/admin → its
}), }),
buildR2Storage(['media'], { s3Storage }), // ZAWSZE — R2 przy komplecie R2_* w env, dysk lokalny bez nich buildR2Storage(['media'], { s3Storage }), // ZAWSZE — R2 przy komplecie R2_* w env, dysk lokalny bez nich
@@ -148,10 +150,11 @@ sprawdzić: **AGENT.md §0b**. Kod wszystkich tras niżej (§2.7–2.9).
- `Media`: upload z `mimeTypes` (obrazy + PDF), `alt` (required, localized), - `Media`: upload z `mimeTypes` (obrazy + PDF), `alt` (required, localized),
`normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField` (za duże pliki, za zgodą); R2 przez `buildR2Storage(['media'], { s3Storage })` — `normalizeFilenameHook`, `buildOptimizeUploadHook` + `buildOptimizeUploadField` (za duże pliki, za zgodą); R2 przez `buildR2Storage(['media'], { s3Storage })` —
`s3Storage` z `@payloadcms/storage-s3`, wstrzykiwany (storage.md). `s3Storage` z `@payloadcms/storage-s3`, wstrzykiwany (storage.md).
- Linki z pluginu (`buildLinkField`, `buildLinksField`, `resolveLinkHref` — links.md), - Pola z pluginu: linki (`buildLinkField`, `buildLinksField` — links.md), nagłówek i ustawienia
`src/fields/` (sectionHeader, sectionSettings) i `src/components/ui/` sekcji (`buildSectionHeaderField`, `buildSectionSettingsField` — blocks.md). W projekcie tylko
(CMSLink, Button, Media, Section, SectionHeader) — gotowy kod w prymitywy wyglądu `src/components/ui/` (CMSLink na `resolveLink`, Button, Media, Section,
`agent/skills/ipal-block/resources/kod-sekcji.md`, reguły w AGENT.md §6. SectionHeader) i `src/components/forms/formClasses.ts` — gotowy kod w
`agent/skills/ipal-block/resources/kod-sekcji.md` i `ipal-form/resources/`, reguły w AGENT.md §6.
Załóż je **przed** pierwszym blokiem. Załóż je **przed** pierwszym blokiem.
### 2.5 Tailwind ### 2.5 Tailwind
@@ -177,7 +180,10 @@ export default { plugins: { '@tailwindcss/postcss': {} } }
} }
``` ```
`fluid.css` to same zmienne `clamp()` (360 → 1280 px, w `rem`) — klasy `text-h1`, `fluid.css` to same zmienne `clamp()` (360 → 1280 px, w `rem`) — klasy `text-h1`,
`py-section`, `px-gutter`. Liczby z `DESIGN.md` nadpisujesz w `:root` projektu `py-section`, `px-gutter`. `fluid-wide.css` — te same zmienne, skala do 1920 px (13″ ≠ 27″);
importujesz jeden z dwóch. Oba mają też zmienne wysokości i szerokości: `--ipal-hero-min-h`,
`--ipal-fs-display-fit`, `--ipal-space-section-fit`, `--ipal-measure`, `--ipal-container`
(AGENT.md §6.11a). Liczby z `DESIGN.md` nadpisujesz w `:root` projektu
(`--ipal-fs-h1: clamp(…)`); formuł nie piszesz od zera. (`--ipal-fs-h1: clamp(…)`); formuł nie piszesz od zera.
Bez `@source` komponenty pluginu (baner cookies, Turnstile) są bez stylów. Bez `@source` komponenty pluginu (baner cookies, Turnstile) są bez stylów.
Kolory komponentów pluginu: `--ipal-primary`, `--ipal-radius` (consent.md). Kolory komponentów pluginu: `--ipal-primary`, `--ipal-radius` (consent.md).
@@ -202,35 +208,44 @@ layoutach i `not-found.tsx` **nie czytaj `headers()`** (AGENT.md §4.6).
### 2.7 Warstwa danych — jedno źródło ### 2.7 Warstwa danych — jedno źródło
```ts ```ts
// src/lib/content.ts // src/lib/content.ts — JEDYNE miejsce konfiguracji: dane, trasy, linki, layout
import { createContentHelpers } from '@intecion/ipal-kit' import { createContentHelpers } from '@intecion/ipal-kit'
import config from '@/payload.config' import config from '@/payload.config'
import { i18nConfig } from '@/i18n.config' import { i18nConfig } from '@/i18n.config'
import { contentConfig } from '@/content.config' import { contentConfig } from '@/content.config'
export const { export const {
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, // dane
generatePageMetadata, getNotFoundPage, generateStaticParams, sitemap, robots, getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries, getNotFoundPage,
generatePageMetadata, generateStaticParams, getPageJsonLd, resolvePageRedirect, i18n,
// layout, formularze, linki
getSiteShell, getFormTexts, getLinkOptions, getHomeSlug, resolveLink, resolveNav,
// trasy (re-eksport w app/)
sitemap, sitemapRoute, robots, manifest, llmsRoute, llmsFullRoute, markdownRoute,
mcpGET, mcpPOST, healthRoute, indexNowKeyRoute,
} = createContentHelpers({ } = createContentHelpers({
config, config,
content: contentConfig, content: contentConfig,
i18n: i18nConfig, i18n: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
markdownAlternate: true, // GEO: <link rel="alternate" type="text/markdown"> w każdej stronie markdownAlternate: true, // GEO: <link rel="alternate" type="text/markdown"> w każdej stronie
summaryField: 'aiSummary', // llms.txt i MCP biorą opis dla AI z buildSummaryField
mcp: { serverName: '<klient>-site' },
// pageJsonLd: { faq: (doc) => …mapowanie bloku FAQ na { question, answer }… },
// siteJsonLd: async ({ settings, baseUrl, locale }) => [buildLocalBusinessJsonLd({…})], // firma lokalna
}) })
``` ```
Wszystko liczy się dopiero przy pierwszym użyciu i jest w cache na żądanie. Każdą
funkcję można pominąć i złożyć stronę z niższych klocków (`createPageMetadata`,
`createLlmsTxtRoute`, `createMcpRoute`… — seo.md, mcp.md) — plugin niczego nie wymusza.
### 2.8 Trasy ### 2.8 Trasy
```tsx ```tsx
// src/app/(frontend)/[locale]/layout.tsx // src/app/(frontend)/[locale]/layout.tsx
import { notFound } from 'next/navigation' import { notFound } from 'next/navigation'
import { import { CookieBanner } from '@intecion/ipal-kit/client'
buildOrganizationJsonLd, buildWebSiteJsonLd, getAnalyticsConfig, getConsentTexts, getTurnstileConfig, import { SiteProviders } from '@intecion/ipal-kit/rsc'
} from '@intecion/ipal-kit' import { getConfiguredLocales, getSiteShell } from '@/lib/content'
import { Analytics, ConsentProvider, CookieBanner, CookieButton, TurnstileProvider } from '@intecion/ipal-kit/client'
import { JsonLdGraph, MediaPreconnect } from '@intecion/ipal-kit/rsc'
import { i18nConfig } from '@/i18n.config'
import { getCachedPayload, getConfiguredLocales, getSettings } from '@/lib/content'
import '../styles.css' import '../styles.css'
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> } type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
@@ -238,80 +253,64 @@ type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
export default async function LocaleLayout({ children, params }: Props) { export default async function LocaleLayout({ children, params }: Props) {
const { locale } = await params const { locale } = await params
if (!(await getConfiguredLocales()).includes(locale)) notFound() if (!(await getConfiguredLocales()).includes(locale)) notFound()
const shell = await getSiteShell(locale) // zgoda, analityka, Turnstile, JSON-LD strony, Site Settings
const payload = await getCachedPayload()
const [texts, analytics, turnstile, settings] = await Promise.all([
getConsentTexts({ config: i18nConfig, locale, payload }), // link do polityki — automatycznie (consent.md)
getAnalyticsConfig(payload),
getTurnstileConfig(payload), // siteKey tylko przy obu kluczach — inaczej widget i weryfikacja wyłączone
getSettings(locale),
])
const url = process.env.NEXT_PUBLIC_SERVER_URL
const name = typeof settings?.siteName === 'string' ? settings.siteName : undefined
// Dane z panelu; brak → węzeł pominięty (nigdy fallback z nazwą klienta). Firma lokalna: buildLocalBusinessJsonLd z globalu Company.
const schemas = name && url ? [buildWebSiteJsonLd({ name, url }), buildOrganizationJsonLd({ name, url })] : []
return ( return (
<html lang={locale}> <html lang={locale}>
{/* BEZ <head> — Next zarządza nim sam */} {/* BEZ <head> — Next zarządza nim sam */}
<body> <body>
<MediaPreconnect /> <SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>
<JsonLdGraph schemas={schemas} /> {/* <Header …/> */}
<ConsentProvider texts={texts}> <main>{children}</main>
<TurnstileProvider siteKey={turnstile.siteKey}> {/* zawsze — sam się wyłącza bez kluczy */} {/* <Footer …/> */}
<main>{children}</main> </SiteProviders>
</TurnstileProvider>
<CookieBanner />
<CookieButton />
<Analytics {...analytics} /> {/* wewnątrz providera; opcja defer — analytics.md */}
</ConsentProvider>
</body> </body>
</html> </html>
) )
} }
``` ```
`SiteProviders` wpina w dobrej kolejności: `MediaPreconnect`, `JsonLdGraph` (WebSite + Organization
z Site Settings), `ConsentProvider` → `TurnstileProvider` (zawsze — sam się wyłącza bez kluczy) →
baner, `CookieButton`, `Analytics` (wewnątrz zgody). Nie dodaje żadnego markupu. Każdą część
zmienisz albo wyłączysz: `banner={<CookieBanner classNames={…} />}` / `false`, `cookieButton`,
`analytics={{ defer: true }}` / `false`, `jsonLd={[buildNavigationJsonLd(…)]}`, `cookieMap`,
`preconnect={false}`. Zupełnie własny układ: te same dane z `shell` do providerów (consent.md).
```tsx ```tsx
// src/app/(frontend)/[locale]/[[...slug]]/page.tsx — PODWÓJNE nawiasy // src/app/(frontend)/[locale]/[[...slug]]/page.tsx — PODWÓJNE nawiasy
import { notFound, permanentRedirect } from 'next/navigation' import { notFound, permanentRedirect } from 'next/navigation'
import type { Metadata } from 'next' import { createPageRoute } from '@intecion/ipal-kit/rsc'
import { RenderBlocks } from '@intecion/ipal-kit/rsc' import * as content from '@/lib/content'
import { resolveRedirect } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
import { blockRegistry } from '@/blocks/registry' import { blockRegistry } from '@/blocks/registry'
import { generatePageMetadata, getCachedPayload, resolveRoute } from '@/lib/content' import { sendForm } from '../actions'
export { generateStaticParams } from '@/lib/content' // SSG → <head> synchroniczny export const revalidate = 3600 // ISR — literał w pliku (Next czyta go statycznie)
export const revalidate = 3600 // ISR
type Args = { params: Promise<{ locale: string; slug?: string[] }> } // bez searchParams! const route = createPageRoute(content, {
blocks: blockRegistry,
// Ten sam cache co strona: jedno odczytanie ustawień i jedno resolveRoute na żądanie notFound, permanentRedirect, // wstrzyknięte z next/navigation
export async function generateMetadata({ params }: Args): Promise<Metadata> { blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
const { locale, slug } = await params // render: ({ route, blocks }) => route.type === 'archive' ? <Archive … /> : undefined,
return generatePageMetadata(locale, slug) })
} export default route.Page
export const generateMetadata = route.generateMetadata
export default async function Page({ params }: Args) { export const generateStaticParams = route.generateStaticParams // SSG → <head> synchroniczny
const { locale, slug } = await params
const route = await resolveRoute(locale, slug ?? [], 1)
if (!route) {
const target = await resolveRedirect({ payload: await getCachedPayload(), locale, segments: slug, config: i18nConfig })
if (target) permanentRedirect(target)
notFound()
}
const enhanceProps = () => ({ locale }) // locale dla CMSLink w blokach
const doc = route.doc as { layout?: unknown[] }
return <RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
}
``` ```
Opcje `resolveRedirect` (`collections`, `homeSlug`): content.md. `createPageRoute`: trasa (`resolveRoute`), stary slug → 308 (`resolvePageRedirect`), 404, metadata,
Archiwum z paginacją (`?page=`) — osobna trasa albo świadomie dynamiczna (pages.md). `generateStaticParams`, JSON-LD strony (`getPageJsonLd`, wyłączenie: `jsonLd: false`) i bloki z
`locale` + `blockProps`. Bez `searchParams` — archiwum z paginacją (`?page=`) to osobna trasa albo
świadomie dynamiczna (pages.md). Własna strona: te same helpery ręcznie (pages.md).
404 z panelu: `src/app/(frontend)/[locale]/not-found.tsx` z `getNotFoundPage` ```tsx
(przykład w pages.md). // src/app/(frontend)/[locale]/not-found.tsx — 404 z panelu, w języku z URL, bez headers()
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
export default createNotFoundPage(content, { blocks: blockRegistry /*, fallback: <h1>404</h1> */ })
```
```ts ```ts
// Trasy SEO / GEO / ops — każda to re-eksport, konfiguracja jest w lib/content.ts
// src/app/sitemap.xml/route.ts — XML dla Google, wygląd dla ludzi z pluginu (nic w /public) // src/app/sitemap.xml/route.ts — XML dla Google, wygląd dla ludzi z pluginu (nic w /public)
export { sitemapRoute as GET } from '@/lib/content' export { sitemapRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
@@ -320,41 +319,29 @@ export const dynamic = 'force-dynamic'
export { robots as default } from '@/lib/content' export { robots as default } from '@/lib/content'
// src/app/manifest.ts // src/app/manifest.ts
import { createManifestHandler } from '@intecion/ipal-kit' export { manifest as default } from '@/lib/content'
import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config'
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
export default createManifestHandler({ getCachedPayload, config: i18nConfig })
// ---- GEO: wszystkie poniżej są obowiązkowe (AGENT.md §0b.5–7) ---- // ---- GEO: wszystkie poniżej są obowiązkowe (AGENT.md §0b.5–8) ----
// src/app/llms.txt/route.ts (+ llms-full.txt/route.ts: to samo z `full: true`) // src/app/llms.txt/route.ts (+ llms-full.txt/route.ts: llmsFullRoute)
import { createLlmsTxtRoute } from '@intecion/ipal-kit' export { llmsRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, summaryField: 'aiSummary' })
// src/app/md/[locale]/[[...slug]]/route.ts — każda strona jako Markdown // src/app/md/[locale]/[[...slug]]/route.ts — każda strona jako Markdown (noindex + canonical do HTML)
import { createMarkdownRenderer, markdownResponse } from '@intecion/ipal-kit' export { markdownRoute as GET } from '@/lib/content'
import { contentConfig } from '@/content.config' export const dynamic = 'force-dynamic'
const render = createMarkdownRenderer({ content: contentConfig })
// src/app/indexnow-key.txt/route.ts — klucz IndexNow (z Site Integrations albo INDEXNOW_KEY)
export { indexNowKeyRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
export async function GET(_req: Request, { params }: { params: Promise<{ locale: string; slug?: string[] }> }) {
const { locale, slug } = await params
return markdownResponse(await render({ payload: await getCachedPayload(), locale, slug }))
}
// src/app/api/mcp/route.ts — publiczny serwer MCP (AI przegląda stronę) // src/app/api/mcp/route.ts — publiczny serwer MCP (AI przegląda stronę)
import { createMcpRoute } from '@intecion/ipal-kit' export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
const mcp = createMcpRoute({ getCachedPayload, config: i18nConfig, content: contentConfig,
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!, serverName: '<klient>-site', summaryField: 'aiSummary' })
export const POST = mcp.POST
export const GET = mcp.GET
// src/app/api/health/route.ts // src/app/api/health/route.ts
import { createHealthRoute } from '@intecion/ipal-kit' export { healthRoute as GET } from '@/lib/content'
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
export const GET = createHealthRoute({ getCachedPayload })
``` ```
Jeden sitemap: `sitemap.xml/route.ts` **albo** `sitemap.ts` — nigdy oba. Nagłówek Jeden sitemap: `sitemap.xml/route.ts` **albo** `sitemap.ts` — nigdy oba. Nagłówek
sitemapy = „XML Sitemap”, pod nim „Technology by Intecion.com”; zmiana sitemapy = „XML Sitemap”, pod nim „Technology by Intecion.com”; zmiana
@@ -364,15 +351,16 @@ przez `createContentHelpers({ sitemapStyle })` (seo.md).
```ts ```ts
// next.config.ts // next.config.ts
import { withPayload } from '@payloadcms/next/withPayload' import { withPayload } from '@payloadcms/next/withPayload'
import { buildSecurityHeaders } from '@intecion/ipal-kit' import { buildImagesConfig, buildSecurityHeaders, buildUploadSecurityHeaders } from '@intecion/ipal-kit'
const securityHeaders = buildSecurityHeaders({ hsts: process.env.NODE_ENV === 'production' }) const securityHeaders = buildSecurityHeaders({ hsts: process.env.NODE_ENV === 'production' })
export default withPayload({ export default withPayload({
images: { ...buildImagesConfig() }, // AVIF/WebP, domena R2 (R2_PUBLIC_URL), cache 31 dni
htmlLimitedBots: htmlLimitedBots:
/Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i, /Googlebot|Google-InspectionTool|Storebot-Google|Bingbot|Yandex|DuckDuckBot|Baiduspider|Screaming Frog|AhrefsBot|SemrushBot/i,
async headers() { async headers() {
return [{ source: '/:path*', headers: securityHeaders }] return [{ source: '/:path*', headers: securityHeaders }, ...buildUploadSecurityHeaders()]
}, },
}) })
``` ```
@@ -411,6 +399,8 @@ pnpm dev
| `NEXT_PUBLIC_SERVER_URL` | ✅ | publiczny URL (canonical, hreflang, OG); bez niego linki względne | | `NEXT_PUBLIC_SERVER_URL` | ✅ | publiczny URL (canonical, hreflang, OG); bez niego linki względne |
| `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | ⬜ | email przez Microsoft Graph | | `GRAPH_TENANT_ID`, `GRAPH_CLIENT_ID`, `GRAPH_CLIENT_SECRET`, `GRAPH_SENDER` | ⬜ | email przez Microsoft Graph |
| `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL` | ✅ prod | media w Cloudflare R2 — na produkcji zawsze (brak → dysk kontenera, pliki znikają przy redeployu); w dev mogą być puste | | `R2_BUCKET`, `R2_ENDPOINT`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_PUBLIC_URL` | ✅ prod | media w Cloudflare R2 — na produkcji zawsze (brak → dysk kontenera, pliki znikają przy redeployu); w dev mogą być puste |
| `IPAL_NOINDEX` | ⬜ | `1` **tylko na stagingu / preview** — cała strona poza Google (robots, meta, nagłówek) |
| `INDEXNOW_KEY` | ⬜ | klucz IndexNow, gdy nie z panelu (Site Integrations → IndexNow generuje sam) |
| `IPAL_IP_HEADER` | ✅ prod | nagłówek z prawdziwym IP dla rate limitu: `cf-connecting-ip` za Cloudflare, `x-forwarded-for` za samym Traefikiem/nginx (forms.md) | | `IPAL_IP_HEADER` | ✅ prod | nagłówek z prawdziwym IP dla rate limitu: `cf-connecting-ip` za Cloudflare, `x-forwarded-for` za samym Traefikiem/nginx (forms.md) |
| `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | fallback, gdy kluczy Turnstile nie ma w panelu | | `NEXT_PUBLIC_TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | ⬜ | fallback, gdy kluczy Turnstile nie ma w panelu |
@@ -542,6 +532,18 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
| 19 | **1.9.0** — `twoFactor: { issuer }` bez `plugin` | dopisz `plugin: payloadTotp` (fallback z dynamicznym importem usunięty — start kończy się błędem) | security.md | | 19 | **1.9.0** — `twoFactor: { issuer }` bez `plugin` | dopisz `plugin: payloadTotp` (fallback z dynamicznym importem usunięty — start kończy się błędem) | security.md |
| 20 | **1.9.0** — IP w akcji formularza liczone ręcznie z `x-forwarded-for` | `clientIp(await headers())` + `IPAL_IP_HEADER` w env produkcji | forms.md | | 20 | **1.9.0** — IP w akcji formularza liczone ręcznie z `x-forwarded-for` | `clientIp(await headers())` + `IPAL_IP_HEADER` w env produkcji | forms.md |
| 21 | **1.9.0** — media bez R2 na produkcji / brak `buildR2Storage` | wpnij `buildR2Storage(['media'], { s3Storage })`, ustaw `R2_*` | storage.md | | 21 | **1.9.0** — media bez R2 na produkcji / brak `buildR2Storage` | wpnij `buildR2Storage(['media'], { s3Storage })`, ustaw `R2_*` | storage.md |
| 22 | **1.9.1** — ręczny `actions.ts` / trasa `md` / brak seeda formularza | `createSubmitAction`, `createMarkdownRoute`, seed z `ipal-form` (mail do firmy + do klienta) | forms.md, content.md |
| 23 | **1.9.1** — `createProxy` bez `markdown: true` | dopisz — inaczej `/md/…` przekierowuje na `/pl/md/…` | content.md |
| 24 | **1.9.1** — JSON-LD strony składany ręcznie | `getPageJsonLd`, `buildNavigationJsonLd`, `sameAsUrls`, `formatOpeningHours` | seo.md |
| 25 | **1.9.1** — zgoda: wersja, rejestr, tabela | Cookie Settings → Policy version; `consentLog: true` + `logEndpoint`; `<CookieBanner equalChoice>`; skan + `<CookieTable>`; Postgres: `migrate:create` | consent.md |
| 26 | **1.9.1** — media: `priority`, brak placeholderów, `images` w next.config | `<Media>` przez `mediaImageProps`/`videoProps`, `buildMediaPlaceholderHook`, `buildImagesConfig`, `buildUploadSecurityHeaders` | storage.md |
| 27 | **1.9.1** — staging indeksowany | `IPAL_NOINDEX=1` w env stagingu | seo.md |
| 28 | **1.9.2** — własny `FormRenderer` (kopia silnika na `useForm`) | **bezpieczeństwo:** przekazywał do przeglądarki cały dokument formularza z zakładką Emails (adresy firmy w HTML). Blok → `<RenderForm form action locale texts classNames>`, wygląd do `formClasses.ts`, usuń `FormRenderer.tsx`; nietypowy formularz → `useBuilderForm` | forms.md |
| 29 | **1.9.2** — formularze krokowe / listy wyboru robione w kodzie | panel: bloki **Step**, **Radio**, **Checkbox group**, **Date**; Notifications → next / back / stepOf; Postgres: `migrate:create` | forms.md |
| 30 | **1.9.2** — layout składany ręcznie (ConsentProvider, TurnstileProvider, Analytics, JsonLdGraph, MediaPreconnect) | `<SiteProviders shell={await getSiteShell(locale)} …>` — te same opcje (banner, analytics, jsonLd, logEndpoint) | PROGRAMISTA §2.8 |
| 31 | **1.9.2** — strona catch-all i `not-found.tsx` pisane ręcznie | `createPageRoute(content, {…})` / `createNotFoundPage(content, {…})` z `/rsc`; `revalidate` zostaje literałem | pages.md |
| 32 | **1.9.2** — trasy llms/md/mcp/health/indexnow/manifest z konfiguracją w każdym pliku | re-eksport z `lib/content` (`llmsRoute`, `llmsFullRoute`, `markdownRoute`, `mcpGET`/`mcpPOST`, `healthRoute`, `indexNowKeyRoute`, `manifest`); `summaryField`, `mcp` raz w `createContentHelpers` | PROGRAMISTA §2.7 |
| 33 | **1.9.2** — `src/fields/sectionHeader.ts`, `sectionSettings.ts`, `lib/navigation.ts`, ręczne `resolveLinkHref` w `CMSLink` | `buildSectionHeaderField`, `buildSectionSettingsField` (ten sam kształt danych — bez migracji), `resolveNav`, `resolveLink` z `lib/content` | blocks.md, links.md |
Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep nowego symbolu w Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep nowego symbolu w
`node_modules/@intecion/ipal-kit/dist`. `node_modules/@intecion/ipal-kit/dist`.
@@ -594,6 +596,7 @@ grep -c "<symbol>" src/<ścieżka> # >0 — zmiana zapisana
# docs/: zmiana API/zachowania → zaktualizuj plik modułu W TYM SAMYM commicie # docs/: zmiana API/zachowania → zaktualizuj plik modułu W TYM SAMYM commicie
pnpm clean && pnpm build pnpm clean && pnpm build
grep -c "<symbol>" dist/<ścieżka> # >0 — build ją złapał (eksport w index.ts!) grep -c "<symbol>" dist/<ścieżka> # >0 — build ją złapał (eksport w index.ts!)
# docs/CHANGELOG.md: nowa sekcja ## <wersja> na górze (zostaje min. 20 ostatnich wersji)
git add -A && git commit -m "opis" # PRZED version (dist/ i tak jest ignorowany) git add -A && git commit -m "opis" # PRZED version (dist/ i tak jest ignorowany)
npm version <wersja> # numer podaje człowiek; minor = nowe API, major = łamiące npm version <wersja> # numer podaje człowiek; minor = nowe API, major = łamiące
npm publish npm publish
@@ -615,6 +618,24 @@ wersji z czerwonymi testami. `prepare` buduje paczkę przy instalacji z gita.
Przed commitem: `pnpm typecheck && pnpm lint && pnpm test:int` (to samo puszcza CI Przed commitem: `pnpm typecheck && pnpm lint && pnpm test:int` (to samo puszcza CI
w `.gitea/workflows/ci.yml` na każdy push i PR). w `.gitea/workflows/ci.yml` na każdy push i PR).
### 8.1a Testy pluginu
`test/` (poza `src`, nie trafia do `dist`), vitest: `pnpm test:int` (raz), `pnpm test:watch`.
| Rodzaj | Gdzie | Dla czego |
|---|---|---|
| jednostkowe | `test/<moduł>.test.ts` | czyste funkcje: ścieżki, metadata, robots, CSP, parsery (godziny, Markdown), walidacja |
| z atrapą Payloada | `test/helpers.ts` → `fakePayload()` | logika na Local API bez bazy: `submitForm`, Turnstile, MCP, IndexNow |
| integracyjne | `test/integration.test.ts`, `test/drafts.test.ts` — **prawdziwy Payload + SQLite w pamięci** | dostęp (access), hooki, schemat pól, drafty, globale — wszystko, czego atrapa nie odda |
| kontrakt pakietu | `test/exports.test.ts` | każda ścieżka `@intecion/ipal-kit/…` z docs istnieje w `exports` |
Zasady: **każdy naprawiony błąd = test regresyjny** (sprawdź, że na starym kodzie pada);
zero sieci (`vi.spyOn(globalThis, 'fetch')`); env przez `vi.stubEnv` + `unstubAllEnvs`;
`server-only` mockowane (`vi.mock('server-only', () => ({}))`); test zmiany zachowania
widocznej dla projektów → wpis w `docs/CHANGELOG.md`. Skrypty skilli (`audit.sh`,
`seo-check.mjs`, `cookie-scan.mjs`) testujesz na atrapie strony/projektu w scratchpadzie:
pusty projekt (same błędy) i kompletny (0 błędów). CI (`.gitea/workflows/ci.yml`) puszcza
typecheck, lint, testy i build na każdy push.
### 8.2 package.json pluginu ### 8.2 package.json pluginu
- `"files": ["dist", "docs", "bin"]` — **docs i komenda `ipal-skills` jadą w pakiecie**; agenci w projektach - `"files": ["dist", "docs", "bin"]` — **docs i komenda `ipal-skills` jadą w pakiecie**; agenci w projektach
czytają `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`. Bez `docs` nie mają nic. czytają `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`. Bez `docs` nie mają nic.
+19 -20
View File
@@ -127,14 +127,13 @@ Sprawdź: lista języków istnieje tylko w `i18n.config.ts` (grep `'pl'` w `src`
``` ```
Zrób zgodnie z AGENT.md §5.3 i §6.2: Zrób zgodnie z AGENT.md §5.3 i §6.2:
1. src/fields/sectionHeader.ts, sectionSettings.ts — kod 1:1 z 1. Wspólne pola sekcji i linki są w pluginie: buildSectionHeaderField, buildSectionSettingsField,
node_modules/@intecion/ipal-kit/docs/agent/skills/ipal-block/resources/kod-sekcji.md buildLinkField, buildLinksField z @intecion/ipal-kit — nie kopiuj, nie twórz src/fields/.
(linki: buildLinkField/buildLinksField z @intecion/ipal-kit — nie kopiuj).
2. collections/Media.ts: upload (mimeTypes obrazy + PDF + mp4), alt required localized, 2. collections/Media.ts: upload (mimeTypes obrazy + PDF + mp4), alt required localized,
normalizeFilenameHook, buildOptimizeUploadHook + buildOptimizeUploadField (storage.md); jeśli R2 — buildR2Storage(['media'], { s3Storage }) z env, s3Storage normalizeFilenameHook, buildOptimizeUploadHook + buildOptimizeUploadField (storage.md); jeśli R2 — buildR2Storage(['media'], { s3Storage }) z env, s3Storage
wstrzyknięty z @payloadcms/storage-s3 (storage.md). wstrzyknięty z @payloadcms/storage-s3 (storage.md).
3. collections/Pages.ts: title localized, buildSlugField, buildNoindexField, 3. collections/Pages.ts: title localized, buildSlugField, buildNoindexField,
layout typu blocks (na razie jeden blok Content: sectionHeaderField + content richText), layout typu blocks (na razie jeden blok Content: buildSectionHeaderField + content richText),
trackSlugHistoryHook, buildRevalidateHook (hooks.md). trackSlugHistoryHook, buildRevalidateHook (hooks.md).
NIE twórz kolekcji users, settings, navigation ani żadnych innych. NIE twórz kolekcji users, settings, navigation ani żadnych innych.
Potem pnpm generate:types i payload generate:importmap. Potem pnpm generate:types i payload generate:importmap.
@@ -167,12 +166,12 @@ Plan najpierw.
``` ```
Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4: Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4:
- src/proxy.ts z createProxy, matcher jako literał inline, - src/proxy.ts z createProxy, matcher jako literał inline,
- src/lib/content.ts z createContentHelpers (w tym getNotFoundPage, generateStaticParams), - src/lib/content.ts z createContentHelpers (PROGRAMISTA §2.7 — eksportuje też trasy, getSiteShell, resolveNav),
- app/(frontend)/[locale]/layout.tsx: BEZ <head>, MediaPreconnect w body, - app/(frontend)/[locale]/layout.tsx: BEZ <head>, <SiteProviders shell={await getSiteShell(locale)} …>
ConsentProvider + CookieBanner + CookieButton + Analytics wewnątrz providera, (zgoda, baner equalChoice, Turnstile, Analytics, JSON-LD, preconnect — w dobrej kolejności),
- [locale]/[[...slug]]/page.tsx: revalidate, generateStaticParams, BEZ searchParams, - [locale]/[[...slug]]/page.tsx: createPageRoute(content, { blocks, notFound, permanentRedirect }) +
resolveRedirect przed notFound, enhanceProps wstrzykuje locale do bloków, export const revalidate (literał), BEZ searchParams,
- [locale]/not-found.tsx z getNotFoundPage dla każdego języka + LocaleView, BEZ headers() (pages.md). - [locale]/not-found.tsx: createNotFoundPage(content, { blocks }) — BEZ headers() (pages.md).
Plan najpierw. Plan najpierw.
``` ```
Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`; Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`;
@@ -184,11 +183,11 @@ Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`
``` ```
Zrób wg PROGRAMISTA.md §2.8–2.9 i seo.md: Zrób wg PROGRAMISTA.md §2.8–2.9 i seo.md:
- app/sitemap.xml/route.ts (sitemapRoute z lib/content), robots.ts, manifest.ts (createManifestHandler), llms.txt/route.ts, - re-eksporty z lib/content: app/sitemap.xml/route.ts (sitemapRoute), robots.ts (robots), manifest.ts (manifest), llms.txt/route.ts (llmsRoute),
api/health/route.ts — każda trasa czytająca bazę z export const dynamic = 'force-dynamic', api/health/route.ts — każda trasa czytająca bazę z export const dynamic = 'force-dynamic',
- next.config.ts: htmlLimitedBots, buildSecurityHeaders, - next.config.ts: htmlLimitedBots, buildSecurityHeaders,
- metadata strony przez generatePageMetadata z lib/content (wspólny cache), favicon przez buildIconsMetadata, - metadata strony przez generatePageMetadata z lib/content (wspólny cache), favicon przez buildIconsMetadata,
- JSON-LD w root layoucie: Organization + WebSite (seo.md) z danych z panelu, - JSON-LD: Organization + WebSite daje SiteProviders z Site Settings; firma lokalna → siteJsonLd w createContentHelpers (seo.md),
- src/instrumentation.ts z assertEnv(ipalEnvRules(...)) importowanym z @intecion/ipal-kit/env (env.md). - src/instrumentation.ts z assertEnv(ipalEnvRules(...)) importowanym z @intecion/ipal-kit/env (env.md).
CSP jeszcze nie — będzie w kroku 14. CSP jeszcze nie — będzie w kroku 14.
Plan najpierw. Plan najpierw.
@@ -207,7 +206,7 @@ Zrób wg AGENT.md §6.8, kod z node_modules/@intecion/ipal-kit/docs/agent/skills
- globals/Header.ts, Footer.ts (kod z §6.8), - globals/Header.ts, Footer.ts (kod z §6.8),
- globals/Company.ts dla rynku <PL/AU/…>: nazwa, adres, <NIP/ABN/…>, telefon, email — - globals/Company.ts dla rynku <PL/AU/…>: nazwa, adres, <NIP/ABN/…>, telefon, email —
wszystko localized tam, gdzie tekst, wszystko localized tam, gdzie tekst,
- lib/navigation.ts (resolveNav), components/layout/Header.tsx, Footer.tsx, MobileNav.tsx, - menu przez resolveNav z lib/content (plugin, NIE lib/navigation.ts), components/layout/Header.tsx, Footer.tsx, MobileNav.tsx,
- linki prawne w stopce z ról System Pages, NIE ręcznie, - linki prawne w stopce z ról System Pages, NIE ręcznie,
- hook afterChange na globalach z revalidatePath('/', 'layout'). - hook afterChange na globalach z revalidatePath('/', 'layout').
Podepnij w [locale]/layout.tsx. Etykiety a11y z panelu. Podepnij w [locale]/layout.tsx. Etykiety a11y z panelu.
@@ -234,8 +233,8 @@ Skrót: `/ipal-block <Nazwa> — <pola z 9a>, <opis wyglądu / zrzut>`.
``` ```
Zbuduj blok <nazwa> wg AGENT.md §6 (warstwa 3): Zbuduj blok <nazwa> wg AGENT.md §6 (warstwa 3):
- src/blocks/<Nazwa>/config.ts: sectionHeaderField, buildLinksField, media, items, - src/blocks/<Nazwa>/config.ts: buildSectionHeaderField, buildLinksField, media, items,
sectionSettingsField — tylko pola z listy z kroku 9a, nazwy z §6.5, buildSectionSettingsField — tylko pola z listy z kroku 9a, nazwy z §6.5,
- Component.tsx: Section + SectionHeader + Media + CMSLink, max ~80 linii JSX, - Component.tsx: Section + SectionHeader + Media + CMSLink, max ~80 linii JSX,
powtarzalne elementy w <Nazwa>Card.tsx, interakcja w osobnym pliku 'use client' (§6.9), powtarzalne elementy w <Nazwa>Card.tsx, interakcja w osobnym pliku 'use client' (§6.9),
- dodaj do Pages.layout i do blocks/registry.ts, - dodaj do Pages.layout i do blocks/registry.ts,
@@ -253,11 +252,11 @@ Skrót: `/ipal-form <formularz, odbiorca zgłoszeń>`.
``` ```
Zrób wg forms.md, turnstile.md, email.md: Zrób wg forms.md, turnstile.md, email.md:
- blok formularza korzystający z form-buildera pluginu (pola i teksty z panelu), - blok formularza: <RenderForm> z @intecion/ipal-kit/rsc + formClasses.ts (skill ipal-form) — pola, kroki,
- logika przez useForm/useContactForm z @intecion/ipal-kit/client — bez ręcznego useState, listy wyboru i teksty z panelu, żadnego własnego renderera,
- checkbox consent (zgoda RODO) z linkiem do polityki przez getSystemPagePath, - checkbox consent (zgoda RODO) z linkiem do polityki przez getSystemPagePath,
- TurnstileProvider w layoucie (siteKey z getSiteIntegrations) — bez przekazywania siteKey do bloku, - Turnstile z SiteProviders w layoucie — bez przekazywania siteKey do bloku,
- honeypot, zdarzenie form_submit (formAnalyticsOnSuccess). - honeypot i zdarzenie GTM z panelu robi RenderForm sam (forms.md).
Plan najpierw. Plan najpierw.
``` ```
Sprawdź: panel → Site Integrations → Send test; wysłanie formularza bez zgody → odrzucone. Sprawdź: panel → Site Integrations → Send test; wysłanie formularza bez zgody → odrzucone.
@@ -268,7 +267,7 @@ Sprawdź: panel → Site Integrations → Send test; wysłanie formularza bez zg
``` ```
Zweryfikuj i dokończ wg consent.md i analytics.md: Zweryfikuj i dokończ wg consent.md i analytics.md:
- Analytics wewnątrz ConsentProvider, ID tylko z Site Integrations, - Analytics przez SiteProviders (wewnątrz zgody), ID tylko z Site Integrations,
- czy włączyć defer (Core Web Vitals) — <tak/nie>, - czy włączyć defer (Core Web Vitals) — <tak/nie>,
- Meta Pixel: <w panelu | w GTM> (nigdy oba), - Meta Pixel: <w panelu | w GTM> (nigdy oba),
- link do polityki w banerze: automatyczny (bez parametru privacyPolicy w kodzie). - link do polityki w banerze: automatyczny (bez parametru privacyPolicy w kodzie).
+78 -4
View File
@@ -23,8 +23,8 @@ consent RODO, powiadomienia).
| własna walidacja/wysyłka | `submitForm` (Turnstile+consent+mail) | | własna walidacja/wysyłka | `submitForm` (Turnstile+consent+mail) |
| klient nie zmieni formularza | klient edytuje pola w panelu | | klient nie zmieni formularza | klient edytuje pola w panelu |
**Jak poprawnie:** redaktor tworzy formularz w kolekcji Forms → front pobiera **Jak poprawnie:** redaktor tworzy formularz w kolekcji Forms → blok renderuje go
jego definicję → renderuje pola dynamicznie → wysyła przez `submitForm`. Pola, przez `<RenderForm>` → wysyłka przez `sendForm` (`createSubmitAction` → `submitForm`). Pola,
etykiety, komunikaty, odbiorca — wszystko z panelu. etykiety, komunikaty, odbiorca — wszystko z panelu.
Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigurację Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigurację
@@ -42,7 +42,8 @@ Jeśli formularz wymaga pola, którego builder nie ma — dodaj je przez konfigu
ipalKit({ ipalKit({
forms: { forms: {
redirectRelationships: ['pages'], // formularz może przekierować na Page redirectRelationships: ['pages'], // formularz może przekierować na Page
// fields: { text: true, textarea: true, email: true, ... }, // domyślnie włączone sensowne // fields: { date: false, payment: true, … }, // domyślnie: text, textarea, email, number, date,
// // select, radio, checkbox, checkboxGroup, message, step
}, },
}) })
``` ```
@@ -53,6 +54,61 @@ Dodaje kolekcje **Forms** (edytor buduje formularze) i **Form Submissions**
`forms: { adminGroup: 'Content' }`; domyślna Payloada: `adminGroup: false`. Maile po zgłoszeniu wysyła form-builder według zakładki **Emails** `forms: { adminGroup: 'Content' }`; domyślna Payloada: `adminGroup: false`. Maile po zgłoszeniu wysyła form-builder według zakładki **Emails**
formularza — przez adapter z `email:` w configu (sekcja „Maile” niżej). formularza — przez adapter z `email:` w configu (sekcja „Maile” niżej).
## Front — RenderForm (zalecane, jedna linia)
Cały front formularza z panelu jest w pluginie. Projekt ma blok i klasy:
```tsx
// src/blocks/FormBlock/Component.tsx
import { RenderForm } from '@intecion/ipal-kit/rsc'
<RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
```
- `form` — relacja z bloku (depth ≥ 1; ID albo null → nic się nie renderuje),
- `action` — `sendForm` z `createSubmitAction` (niżej), `texts` — `getFormTexts(locale)` z `lib/content`
(Notifications → Form messages),
- `classNames` — **jedyne** miejsce wyglądu (`src/components/forms/formClasses.ts`, szablon w ipal-form);
plugin nie ma żadnych stylów. Klucze: `form, progress, step, stepTitle, stepDescription, fields,
field, fieldHalf, fieldFull, label, input, textarea, select, checkbox, checkboxLabel, choices,
legend, choice, choiceInput, choiceLabel, message, error, formError, turnstile, actions, back,
next, submit, success, required`. Do CSS są też `data-ipal="form"`, `data-type`, `data-width`, `data-step`.
- opcje: `requiredMark` (np. `" *"`), `converters` / `richTextClassName` (wygląd rich text),
`linkOptions` (`await getLinkOptions(locale)` — redirect na stronę z panelu), `turnstileTheme`.
`RenderForm` (serwer) renderuje bloki **message** i potwierdzenie przez `RenderRichText`, wiąże
akcję z formularzem i językiem, rozwiązuje redirect i podaje przeglądarce **tylko publiczną część
formularza** — Local API czyta z `overrideAccess`, więc dokument ma zakładkę Emails (adresy firmy);
ręczne `<FormRenderer form={form}>` wysyłało je w HTML. Pod spodem `BuilderForm` (klient).
### Typy pól w panelu
text, email, textarea, number, **date**, select, **radio**, checkbox, **Checkbox group**,
message, **Step** (+ country/state jako tekst). Wyłączenie typu: `forms.fields: { date: false }`.
| Typ | Wartość | Serwer sprawdza |
|---|---|---|
| radio, select | jedna wartość | tylko wartości z panelu |
| Checkbox group | `string[]` (zapis: „www, seo”) | tylko wartości z panelu, bez duplikatów, `minSelected`/`maxSelected` |
| date | `YYYY-MM-DD` | prawdziwa data |
| Step | — (podział) | nie jest polem |
### Formularz krokowy
Blok **Step** (tytuł, opis, per język) zaczyna nowy ekran; pola nad pierwszym Step to ekran 1.
`BuilderForm`: „Krok 1 z 3” (`stepOf`), Dalej waliduje tylko bieżący krok, Wstecz zachowuje
wartości, fokus przechodzi na nowy krok, Turnstile na ostatnim kroku, błąd pola z serwera wraca
na krok z tym polem. Teksty przycisków: Notifications → Form messages → `next`, `back`, `stepOf`.
### Formularz nietypowy — bez kopiowania silnika
1. `renderField` (BuilderForm w pliku `'use client'`) — podmienia wybrane pola:
`renderField={({ field, defaultRender }) => field.name === 'budget' ? <Cards …/> : undefined}`.
2. `useBuilderForm({ form, action, texts })` — cała logika, markup Twój: `steps`, `step`,
`stepIndex`, `total`, `isFirst/isLast`, `next()`, `back()`, `goTo(i)`, `submit`, `values`,
`errors`, `errorMessage`, `isSubmitting`, `isSuccess`, `resultMessage`, `getFieldProps`,
`getInputProps`, `getTextareaProps`, `getSelectProps`, `getOptionProps`, `fieldId`, `errorId`,
`TurnstileWidget`. Przykład: `ipal-form/resources/CustomForm.example.tsx`.
3. Czysta logika (też na serwerze / w testach): `splitSteps`, `initialBuilderValues`,
`validateBuilderFields`, `stepOfField`, `inputFields`, `autoCompleteFor` (podpowiedź autouzupełniania z typu i nazwy pola).
`useOptionalTurnstile()` — jak `useTurnstile`, ale bez providera zwraca `enabled: false` zamiast rzucać.
## Front — submitForm (server) ## Front — submitForm (server)
Wołasz w Server Action. Kształt pasuje 1:1 do `useForm` / `useContactForm` Wołasz w Server Action. Kształt pasuje 1:1 do `useForm` / `useContactForm`
@@ -283,7 +339,11 @@ To obsługuje WSZYSTKIE kody (w tym `consent`, `rate_limited`, `validation` z
`{field}`) tekstami z panelu. Ręczny switch (wyżej) zostaw tylko, jeśli nie `{field}`) tekstami z panelu. Ręczny switch (wyżej) zostaw tylko, jeśli nie
używasz modułu notifications. Szczegóły: [notifications.md](./notifications.md). używasz modułu notifications. Szczegóły: [notifications.md](./notifications.md).
## Logika klienta — useForm / useContactForm (bez markupu) ## Logika klienta — useForm / useContactForm (niższy poziom)
Dla formularzy z panelu używaj `RenderForm` / `useBuilderForm` (wyżej) — mają kroki, listy
wyboru i walidację z definicji pola. `useForm` to silnik pod spodem: dla formularza **spoza
buildera** (np. wyszukiwarka z filtrami), nie dla formularzy kontaktowych.
`submitForm` to serwer. Po stronie klienta powtarzała się ta sama hydraulika w `submitForm` to serwer. Po stronie klienta powtarzała się ta sama hydraulika w
każdym projekcie: `useState` na pola, regex e-maila, token Turnstile, submit, każdym projekcie: `useState` na pola, regex e-maila, token Turnstile, submit,
@@ -436,3 +496,17 @@ const label = resolveLocalized(topic.label, locale)
Turnstile wstrzykuje ukryte pole `cf-turnstile-response`. Plugin je toleruje Turnstile wstrzykuje ukryte pole `cf-turnstile-response`. Plugin je toleruje
(nie odrzuca jako `unknown_fields`) — bo sam obsługuje Turnstile. Nie musisz go (nie odrzuca jako `unknown_fields`) — bo sam obsługuje Turnstile. Nie musisz go
filtrować w kliencie. filtrować w kliencie.
## 1.9.1 — gotowa akcja, seed formularza, walidacja typów
- **`createSubmitAction({ getCachedPayload, headers })`** z `/server` zastępuje ręczny `actions.ts`:
`export const sendForm = createSubmitAction({ getCachedPayload, headers })` (`headers` z
`next/headers`, wstrzyknięty). Honeypot → `clientIp` → `submitForm` → tekst z Notifications;
wynik `{ success, message, reason?, field? }`.
- **Seed formularza** (`ipal-form/resources/seed-form.template.ts`): pola, potwierdzenie, mail do firmy
(adres z panelu) i potwierdzenie do klienta (`{{email}}`), każdy język, idempotentny. Obowiązkowy.
- **Walidacja po typie pola z panelu:** email = jeden adres (bez `a@x, b@y`, bez CR/LF), select/radio
tylko wartości z panelu, liczby, checkbox `true/false`, obiekty i tablice odrzucane, znaki
sterujące i bidi usuwane. Błąd: `reason: 'validation'`, `kind: 'invalid_format'`, `field`.
- **Dostęp:** zgłoszenia czytają tylko `editor`/`admin` (wcześniej każde konto), usuwa `admin`;
zakładka Emails formularza (adresy odbiorców) ukryta w publicznym `GET /api/forms`.
+4
View File
@@ -307,6 +307,10 @@ fallback na root `/{code}`.
> i przekaż do AlternateLinksUpdater. To eliminuje własny AlternateLinksContext > i przekaż do AlternateLinksUpdater. To eliminuje własny AlternateLinksContext
> (~150 linii) kopiowany w projektach. > (~150 linii) kopiowany w projektach.
Własny przełącznik (inny markup niż `LanguageSwitcher`): `useAlternateLinks()` (`/client`) zwraca
`{ [locale]: url }` bieżącej strony; `useSetAlternateLinks()` to setter, którego używa
`AlternateLinksUpdater` (zwykle niepotrzebny w projekcie).
## Next matcher — MUSI być literałem inline ## Next matcher — MUSI być literałem inline
Next.js analizuje `config.matcher` STATYCZNIE (AST) — musi być literałem tablicy Next.js analizuje `config.matcher` STATYCZNIE (AST) — musi być literałem tablicy
+53 -4
View File
@@ -69,11 +69,58 @@ Linki wewnętrzne wymagają **zpopulowanej** strony (`depth ≥ 2` w bloku).
`homeSlug` — slug strony głównej (string albo mapa per język, np. z `homeSlug` — slug strony głównej (string albo mapa per język, np. z
`SiteSettings.homepage`), żeby zwinąć ją do `/{locale}`. `SiteSettings.homepage`), żeby zwinąć ją do `/{locale}`.
## Render w projekcie ## Link gotowy do renderu — `resolveLink`
Komponent `CMSLink` jest w projekcie (wygląd przycisków to sprawa projektu) — ```ts
gotowy kod: [kod-sekcji.md](./agent/skills/ipal-block/resources/kod-sekcji.md). Menu: `resolveNav` w // w komponencie serwerowym, z lib/content (locale → homeSlug i i18n same):
`lib/navigation.ts` ([kod-nawigacji.md](./agent/skills/ipal-nav/resources/kod-nawigacji.md)) korzysta z tego samego `resolveLinkHref`. const l = await resolveLink(link, locale)
// bez lib/content: resolveLink(link, { locale, config: i18nConfig, homeSlug })
// → { href, label, internal, newTab, targetProps, appearance } | null
```
- `internal` → `next/link`, inaczej `<a>` (URL, plik, mailto, tel),
- `targetProps` → `{ target: '_blank', rel: 'noopener noreferrer' }` przy nowej karcie (plik zawsze),
- `appearance` → klucz wariantu w `Button.tsx` projektu,
- `null` → link prowadzi donikąd w tym języku (brak strony, pliku, niebezpieczny URL) — nic nie renderuj.
`CMSLink` zostaje w projekcie (element i klasy to wygląd), ale nie liczy niczego sam:
```tsx
// src/components/ui/CMSLink.tsx
import Link from 'next/link'
import type { ReactNode } from 'react'
import type { CmsLink } from '@/payload-types'
import { resolveLink } from '@/lib/content'
import { buttonClass } from './Button'
export async function CMSLink({ link, locale, className, children }: { link: CmsLink | null | undefined; locale: string; className?: string; children?: ReactNode }) {
const l = await resolveLink(link, locale)
const content = children ?? l?.label
if (!l || !content) return null
const cls = [l.appearance ? buttonClass(l.appearance as never) : '', className].filter(Boolean).join(' ') || undefined
return l.internal
? <Link href={l.href} className={cls} {...l.targetProps}>{content}</Link>
: <a href={l.href} className={cls} {...l.targetProps}>{content}</a>
}
```
**Nie pisz własnej wersji** (`resolveHref`, `getHref`, `` `/${slug}` ``, `slug === 'home'`): gubi prefiks
języka, stronę główną z Site Settings, filtr `javascript:` i martwe linki. `ipal-audit` zgłasza to jako
ERROR. Pole w innym kształcie (np. `page` + `url`) mapujesz na kształt pluginu zamiast liczyć href:
`resolveLink(url?.trim() ? { type: 'external', url } : { type: 'internal', page }, locale)`.
## Menu — `resolveNav`
```ts
const items = await resolveNav(header.navItems, locale) // z lib/content
// resolveNav(items, { locale, config: i18nConfig, homeSlug, linkField: 'link', childrenField: 'subItems' })
// → NavItem[]: { href, label, internal, newTab, targetProps, appearance?, children: NavItem[] }
```
Dowolna głębokość, kształt pozycji konfigurowalny (`linkField`, `childrenField`), pozycje z martwym
linkiem albo bez etykiety pominięte (zamiast `href="#"`). Wynik to zwykłe dane — idzie wprost do
klienckiego `MobileNav`. Markup menu (Header, Footer, MobileNav) zostaje w projekcie:
[kod-nawigacji.md](./agent/skills/ipal-nav/resources/kod-nawigacji.md).
`homeSlugFrom(settings)` — slug strony głównej z `SiteSettings.homepage` (lib/content: `getHomeSlug(locale)`,
a komplet opcji linków: `getLinkOptions(locale)` — też dla `RenderForm linkOptions`).
## Migracja z `src/fields/link.ts` ## Migracja z `src/fields/link.ts`
@@ -85,3 +132,5 @@ bazy nie jest potrzebna**:
2. `resolveLinkHref(link, locale, homeSlug)` z `@/lib/links` → 2. `resolveLinkHref(link, locale, homeSlug)` z `@/lib/links` →
`resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })` z pluginu, `resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })` z pluginu,
3. usuń `src/fields/link.ts` i `src/lib/links.ts`, `pnpm generate:types`. 3. usuń `src/fields/link.ts` i `src/lib/links.ts`, `pnpm generate:types`.
4. `lib/navigation.ts` z własnym `resolveNav` → `resolveNav` z `lib/content` (te same dane +
`internal`, `targetProps`; `subItems` nazywa się teraz `children`).
+3
View File
@@ -35,6 +35,9 @@ odfiltrowane — ta sama zasada co sitemap/llms).
```ts ```ts
// app/api/mcp/route.ts // app/api/mcp/route.ts
// Zwykle jedna linia (konfiguracja w createContentHelpers({ mcp: { serverName }, summaryField })):
// export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'
// Niżej pełny wariant — gdy trasa potrzebuje opcji spoza lib/content.
import { createMcpRoute } from '@intecion/ipal-kit' import { createMcpRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content' import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config' import { i18nConfig } from '@/i18n.config'
+4 -2
View File
@@ -16,7 +16,9 @@ Dzięki temu żaden komunikat nie jest zaszyty w kodzie — wszystko przez panel
Brak opcji — global **Notifications** jest zawsze budowany. Edytor zarządza Brak opcji — global **Notifications** jest zawsze budowany. Edytor zarządza
tekstami w panelu (karta Notifications), grupowane per kontekst. Grupa `form`: tekstami w panelu (karta Notifications), grupowane per kontekst. Grupa `form`:
`success`, `error`, `rateLimited`, `turnstile`, `validation`, `consent`, `success`, `error`, `rateLimited`, `turnstile`, `validation`, `consent`,
`notFound`. Każde pole puste → fallback (NOTIFICATION_FALLBACK). `notFound` oraz przyciski formularzy krokowych: `next` („Dalej”), `back` („Wstecz”),
`stepOf` („Krok {current} z {total}”). Każde pole puste → fallback (NOTIFICATION_FALLBACK, EN).
Dla formularzy: `getFormTexts(locale)` z `lib/content` = grupa `form` w danym języku.
## Helper — getNotificationTexts ## Helper — getNotificationTexts
@@ -25,7 +27,7 @@ Pobiera teksty z globala per język, fallback per pole. Analog `getConsentTexts`
```ts ```ts
import { getNotificationTexts } from '@intecion/ipal-kit' import { getNotificationTexts } from '@intecion/ipal-kit'
const notifications = await getNotificationTexts({ payload, locale }) const notifications = await getNotificationTexts({ payload, locale }) // w lib/content: getFormTexts(locale) = .form
// notifications.form.error, notifications.form.success, ... // notifications.form.error, notifications.form.success, ...
``` ```
+20 -1
View File
@@ -62,7 +62,26 @@ Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
- stronę główną (część klientów tak woli), **albo** - stronę główną (część klientów tak woli), **albo**
- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`. - nic → projekt pokazuje wbudowany fallback z `not-found.tsx`.
Projekt — `app/(frontend)/[locale]/not-found.tsx` (pełny plik): Projekt — `app/(frontend)/[locale]/not-found.tsx`, jedna linia (od 1.9.2):
```tsx
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import * as content from '@/lib/content'
import { blockRegistry } from '@/blocks/registry'
export default createNotFoundPage(content, {
blocks: blockRegistry,
fallback: <h1>404</h1>, // gdy w panelu nie wybrano strony 404 (albo per język: (locale) => …)
// blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
})
```
Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `LocaleView`, bez `headers()`).
Strona catch-all z tymi samymi helperami: `createPageRoute(content, { blocks, notFound, permanentRedirect,
blockProps, render, jsonLd })` — PROGRAMISTA §2.8. `render` daje własny widok dla archiwum lub wpisu
(`route.type`: `page | home | archive | entry`), reszta zostaje domyślna.
Ręcznie (pełny plik — gdy potrzebujesz czegoś, czego `createNotFoundPage` nie ma):
```tsx ```tsx
import React from 'react' import React from 'react'
+11
View File
@@ -322,3 +322,14 @@ Wybrany, bo wrapuje ACCESS CONTROL (TOTP przed dostępem do danych) + forceSetup
(wymuszenie dla wszystkich). Inne pluginy 2FA dla Payload gatują tylko nawigację (wymuszenie dla wszystkich). Inne pluginy 2FA dla Payload gatują tylko nawigację
/admin — user z hasłem może omijać przez REST/GraphQL/Bearer. @clocklimited chroni /admin — user z hasłem może omijać przez REST/GraphQL/Bearer. @clocklimited chroni
dostęp do danych, nie tylko UI. dostęp do danych, nie tylko UI.
## 1.9.1 — wyniki przeglądu bezpieczeństwa
- Drafty nigdy nieopublikowane nie są już dostępne publicznie (`resolveRoute`, Markdown, MCP,
metadata) ani na listach archiwów (`getArchiveEntries`). Podgląd: `resolveRoute({ draft: true })`,
`getArchiveEntries({ draft: true })` w trybie `draftMode()`.
- Linki z CMS: tylko `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` i `data:` odrzucane.
- ID analityki walidowane (panel i przed wysłaniem do przeglądarki).
- Zgłoszenia formularzy: odczyt `editor+`; adresy z zakładki Emails niewidoczne publicznie.
- Uploady: `buildUploadSecurityHeaders()` w `next.config.ts` (SVG nie uruchomi skryptu na domenie strony).
- `users`: plugin wstrzykuje kolekcję auth, gdy projekt jej nie ma (role i 2FA zawsze się wpinają).
+41 -2
View File
@@ -415,7 +415,7 @@ klienta w fallbacku. Fallback z nazwą/kolorem klienta to ukryty hardkod.
> **Zalecane (aktualne): `createManifestHandler`** — to samo bez ręcznego kodu, > **Zalecane (aktualne): `createManifestHandler`** — to samo bez ręcznego kodu,
> z try/catch na brak bazy w buildzie: > z try/catch na brak bazy w buildzie:
> ```ts > ```ts
> // app/manifest.ts > // app/manifest.ts — zwykle: export { manifest as default } from '@/lib/content'
> import { createManifestHandler } from '@intecion/ipal-kit' > import { createManifestHandler } from '@intecion/ipal-kit'
> import { getCachedPayload } from '@/lib/content' > import { getCachedPayload } from '@/lib/content'
> import { i18nConfig } from '@/i18n.config' > import { i18nConfig } from '@/i18n.config'
@@ -1004,6 +1004,7 @@ fields: [ /* … */ buildSummaryField() ]
Potem wskaż je jako źródło opisu dla AI (preferowane nad meta.description): Potem wskaż je jako źródło opisu dla AI (preferowane nad meta.description):
```ts ```ts
createContentHelpers({ …, summaryField: 'aiSummary' }) // llmsRoute, llmsFullRoute, mcpGET/POST — raz
buildLlmsTxt({ …, summaryField: 'aiSummary' }) buildLlmsTxt({ …, summaryField: 'aiSummary' })
createLlmsTxtRoute({ …, summaryField: 'aiSummary' }) createLlmsTxtRoute({ …, summaryField: 'aiSummary' })
createSearchRoute({ …, summaryField: 'aiSummary' }) createSearchRoute({ …, summaryField: 'aiSummary' })
@@ -1021,7 +1022,7 @@ llmstxt.org) — agent dostaje całą stronę jednym żądaniem. Dołóż drugi
`full: true`: `full: true`:
```ts ```ts
// app/llms-full.txt/route.ts // app/llms-full.txt/route.ts — zwykle: export { llmsFullRoute as GET } from '@/lib/content'
import { createLlmsTxtRoute } from '@intecion/ipal-kit' import { createLlmsTxtRoute } from '@intecion/ipal-kit'
import { getCachedPayload } from '@/lib/content' import { getCachedPayload } from '@/lib/content'
import { i18nConfig } from '@/i18n.config' import { i18nConfig } from '@/i18n.config'
@@ -1168,3 +1169,41 @@ W markupie projektu oznacz pasujące elementy (np. `className="speakable"` albo
sekcja `.lead` ze streszczeniem). Selektory nietrafiające w nic są ignorowane — sekcja `.lead` ze streszczeniem). Selektory nietrafiające w nic są ignorowane —
nie wskazuj nawigacji ani boilerplate'u, tylko samodzielny, czytelny tekst. nie wskazuj nawigacji ani boilerplate'u, tylko samodzielny, czytelny tekst.
Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony. Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
## 1.9.1 — dane strukturalne strony, IndexNow, sameAs, godziny otwarcia
- **`getPageJsonLd(locale, slug, { faq, pageType, entryType, breadcrumbs })`** z `createContentHelpers`
(węzeł strony składa `buildWebPageJsonLd` — dostępny też osobno dla własnych tras):
WebPage / CollectionPage / BlogPosting (język, `dateModified`, obraz), BreadcrumbList z prawdziwej
trasy (tytuły stron z panelu), FAQPage, gdy projekt zmapuje swój blok FAQ. W `[[...slug]]/page.tsx`:
`<JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />`.
- **`buildNavigationJsonLd({ items: header.navItems, baseUrl, locale, config, homeSlug })`** — nawigacja z
globala nagłówka (linki stron per język, tylko własna domena, bez duplikatów). Inny kształt globala:
`getLink` / `getChildren`.
- **`buildLocalBusinessJsonLd({ type: 'Dentist', openingHours: company.hours, … })`** — `type` dowolny
schema.org; godziny jako tekst redaktora (PL/EN/DE: „Pn-Pt: 8-17, Sob: 9-13, Nd nieczynne”) →
`formatOpeningHours` → `['Mo-Fr 08:00-17:00', 'Sa 09:00-13:00']`. Nieczytelny tekst jest pomijany.
- **Site Settings → sameAs** (profile firmy) → `sameAsUrls(settings)` do Organization/LocalBusiness.
- **Site Settings → Default share image** działa jako obraz OG stron bez własnego (wcześniej ignorowany).
Metadata ma kartę X/Twitter, wymiary i alt obrazu, a wpisy `og:type=article` z datami.
- **Sitemap z obrazami** (`<image:image>`): domyślnie obraz SEO strony; własne źródło:
`createContentHelpers({ sitemapImages: (doc) => [...] })`.
- **IndexNow:** `ipalKit({ indexNow: true })` + trasa `src/app/indexnow-key.txt/route.ts`
(`createIndexNowKeyRoute`). Po publikacji strony/wpisu adresy we wszystkich językach idą do Bing &
co. (ChatGPT Search, Copilot korzystają z indeksu Binga). Tylko produkcja z publicznym https.
Klucz: Site Integrations → IndexNow (generuje się przy zapisie) albo `INDEXNOW_KEY`. Google nie
obsługuje IndexNow — dla niego sitemap.
Trasa klucza z `lib/content`: `export { indexNowKeyRoute as GET } from '@/lib/content'`.
Ręcznie (np. import treści skryptem): `submitToIndexNow({ payload, urls })` (klucz: `getIndexNowKey(payload)`)
— nigdy nie rzuca, tylko loguje.
- **llms.txt / llms-full.txt** obejmują wpisy kolekcji treści (`content`) i wszystkie języki; MCP
`list_pages` też. Wspólne źródło: `collectSiteIndex`.
## noindex — staging, Markdown, ochrona (1.9.1)
- **`IPAL_NOINDEX=1`** w env stagingu/preview: robots `Disallow: /`, `noindex, nofollow` w meta,
`X-Robots-Tag` w `buildSecurityHeaders`. Nigdy na produkcji (`ipal-seo-check` zgłasza).
- Wersje Markdown (`/md/…`) i pliki llms mają `X-Robots-Tag: noindex`; Markdown dodatkowo
`Link: <html-url>; rel="canonical"` — AI czyta, Google nie widzi duplikatów.
- `buildNoindexField` nie pozwala zaznaczyć noindex na stronie głównej i stronach-archiwach.
- Kiedy noindex: tabela w AGENT.md §0c. Polityki prawne zostają indeksowane domyślnie.
+12
View File
@@ -309,3 +309,15 @@ env, komponent podąża automatycznie.
> NIE hardkoduj `<link rel="preconnect" href="https://media.klient.pl">` ręcznie > NIE hardkoduj `<link rel="preconnect" href="https://media.klient.pl">` ręcznie
> w layoutcie — to zaszywa domenę klienta w kodzie. Użyj MediaPreconnect, który > w layoutcie — to zaszywa domenę klienta w kodzie. Użyj MediaPreconnect, który
> bierze ją z env. > bierze ją z env.
## 1.9.1 — szybkość mediów (narzędzia do własnego `<Media>`)
- `mediaImageProps(resource, { sizes, priority, alt })` → propsy `next/image`: wymiary z dokumentu,
`lazy` domyślnie, obraz LCP `preload` + `fetchPriority="high"` + `eager` (Next 16), focal point →
`object-position`, placeholder blur + kolor. `MEDIA_SIZES` — podpowiedzi `sizes`.
- `videoProps(resource, { mode: 'background' | 'player', poster, reducedMotion })`.
- `buildMediaPlaceholderHook()` + `buildMediaPlaceholderField()` w Media — podgląd liczony przy
uploadzie przez `sharp` z configu. Postgres: `migrate:create`.
- `buildImagesConfig()` → `next.config.ts images` (AVIF/WebP, `remotePatterns` z `R2_PUBLIC_URL`).
- `<YouTubeEmbed videoId title playLabel note poster>` z `/client` — iframe po kliknięciu.
- `buildUploadSecurityHeaders()` → sandbox CSP dla `/api/media/file/*` (SVG z uploadu bez skryptów).
+3
View File
@@ -116,6 +116,9 @@ przekazywania siteKey do każdego formularza.
### 1. Provider w layoutcie (raz, siteKey z serwera) ### 1. Provider w layoutcie (raz, siteKey z serwera)
Z `SiteProviders` (PROGRAMISTA §2.8) provider jest już wpięty — klucz z `getSiteShell(locale).turnstileSiteKey`,
widget renderuje `RenderForm` na ostatnim kroku formularza. Ręcznie:
```tsx ```tsx
// app/(frontend)/[locale]/layout.tsx (server) // app/(frontend)/[locale]/layout.tsx (server)
import { getTurnstileConfig } from '@intecion/ipal-kit' import { getTurnstileConfig } from '@intecion/ipal-kit'
+10 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "@intecion/ipal-kit", "name": "@intecion/ipal-kit",
"version": "1.9.0", "version": "1.9.3",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.", "description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT", "license": "MIT",
"repository": { "repository": {
@@ -38,12 +38,19 @@
"import": "./dist/exports/admin.js", "import": "./dist/exports/admin.js",
"types": "./dist/exports/admin.d.ts", "types": "./dist/exports/admin.d.ts",
"default": "./dist/exports/admin.js" "default": "./dist/exports/admin.js"
} },
"./env": {
"import": "./dist/exports/env.js",
"types": "./dist/exports/env.d.ts",
"default": "./dist/exports/env.js"
},
"./fluid.css": "./dist/styles/fluid.css",
"./fluid-wide.css": "./dist/styles/fluid-wide.css"
}, },
"main": "./dist/index.js", "main": "./dist/index.js",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"bin": { "bin": {
"ipal-skills": "./bin/ipal-skills.mjs" "ipal-skills": "bin/ipal-skills.mjs"
}, },
"files": [ "files": [
"dist", "dist",
+15 -1
View File
@@ -24,9 +24,22 @@ export {
useConsentContext, useConsentContext,
} from '../modules/consent/client.js' } from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js' export type { CookieBannerClassNames } from '../modules/consent/client.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from '../modules/forms/builderLogic.js'
export type {
BuilderField,
BuilderFormAction,
BuilderFormDoc,
BuilderFormTexts,
BuilderOption,
BuilderStep,
} from '../modules/forms/builderTypes.js'
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js' export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js' export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js' export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export { useBuilderForm } from '../modules/forms/useBuilderForm.js'
export type { BuilderFormApi, UseBuilderFormOptions } from '../modules/forms/useBuilderForm.js'
export { useContactForm } from '../modules/forms/useContactForm.js' export { useContactForm } from '../modules/forms/useContactForm.js'
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js' export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'
export { useForm } from '../modules/forms/useForm.js' export { useForm } from '../modules/forms/useForm.js'
@@ -62,6 +75,7 @@ export {
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js' export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js' export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { LocaleView } from '../modules/pages/LocaleView.js' export { LocaleView } from '../modules/pages/LocaleView.js'
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
export { Turnstile } from '../modules/turnstile/client.js' export { Turnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js' export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from '../modules/turnstile/client.js'
export type { TurnstileProps } from '../modules/turnstile/client.js' export type { TurnstileProps } from '../modules/turnstile/client.js'
+10
View File
@@ -12,6 +12,16 @@ export type {
EnhanceProps, EnhanceProps,
RenderBlocksProps, RenderBlocksProps,
} from '../modules/blocks/index.js' } from '../modules/blocks/index.js'
export { CookieTable } from '../modules/consent/CookieTable.js'
export type { CookieTableLabels } from '../modules/consent/CookieTable.js'
export { RenderForm } from '../modules/forms/RenderForm.js'
export type { RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js'
// Layout wiring + catch-all page + 404 from lib/content helpers (optional — the
// pieces stay available for a project that composes them itself).
export { createNotFoundPage, createPageRoute } from '../modules/frontend/pageRoute.js'
export type { NotFoundPageOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js'
export { SiteProviders } from '../modules/frontend/SiteProviders.js'
export type { SiteProvidersProps } from '../modules/frontend/SiteProviders.js'
export { RenderRichText } from '../modules/richtext/index.js' export { RenderRichText } from '../modules/richtext/index.js'
export type { RenderRichTextProps } from '../modules/richtext/index.js' export type { RenderRichTextProps } from '../modules/richtext/index.js'
export { JsonLdGraph } from '../modules/seo/index.js' export { JsonLdGraph } from '../modules/seo/index.js'
+2
View File
@@ -1,5 +1,7 @@
export { sendEmail } from '../modules/email/index.js' export { sendEmail } from '../modules/email/index.js'
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js' export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
export { createSubmitAction } from '../modules/forms/createSubmitAction.js'
export type { SubmitActionResult } from '../modules/forms/createSubmitAction.js'
export { submitForm } from '../modules/forms/index.js' export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js' export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
/** /**
+42
View File
@@ -9,6 +9,19 @@ import { CONSENT_CATEGORIES } from '../../modules/consent/categories.js'
* truth. Only the link's visible text lives here (privacyLinkLabel). * truth. Only the link's visible text lives here (privacyLinkLabel).
*/ */
export const cookieSettingsFields: Field[] = [ export const cookieSettingsFields: Field[] = [
{
name: 'policyVersion',
type: 'number',
admin: {
description:
'Raise by 1 when you add a tool or change the cookie policy — every visitor is asked for consent again.',
position: 'sidebar',
step: 1,
},
defaultValue: 1,
min: 1,
required: true,
},
{ {
name: 'message', name: 'message',
type: 'textarea', type: 'textarea',
@@ -65,4 +78,33 @@ export const cookieSettingsFields: Field[] = [
{ name: 'description', type: 'textarea', localized: true }, { name: 'description', type: 'textarea', localized: true },
], ],
}, },
{
name: 'cookies',
type: 'array',
admin: {
description:
'Cookies the site uses — shown on the cookie policy page (<CookieTable>). Fill it from a scan: ipal-consent-check → cookie-scan.',
initCollapsed: true,
},
fields: [
{
type: 'row',
fields: [
{ name: 'name', type: 'text', admin: { width: '40%' }, required: true },
{ name: 'provider', type: 'text', admin: { description: 'e.g. Google, this site', width: '30%' } },
{
name: 'category',
type: 'select',
admin: { width: '30%' },
defaultValue: 'necessary',
options: CONSENT_CATEGORIES.map((c) => ({ label: c, value: c })),
required: true,
},
],
},
{ name: 'purpose', type: 'textarea', localized: true },
{ name: 'duration', type: 'text', admin: { description: 'e.g. "2 years", "session"' }, localized: true },
],
labels: { plural: 'Cookies', singular: 'Cookie' },
},
] ]
+23
View File
@@ -69,6 +69,29 @@ export const notificationsFields: Field[] = [
admin: { placeholder: 'This form is no longer available.' }, admin: { placeholder: 'This form is no longer available.' },
localized: true, localized: true,
}, },
{
type: 'row',
fields: [
{
name: 'next',
type: 'text',
admin: { description: 'Step-by-step forms: button to the next step.', placeholder: 'Next', width: '33%' },
localized: true,
},
{
name: 'back',
type: 'text',
admin: { description: 'Step-by-step forms: button to the previous step.', placeholder: 'Back', width: '33%' },
localized: true,
},
{
name: 'stepOf',
type: 'text',
admin: { description: 'Progress — {current} and {total} are replaced.', placeholder: 'Step {current} of {total}', width: '34%' },
localized: true,
},
],
},
], ],
label: 'Form messages', label: 'Form messages',
}, },
@@ -1,5 +1,7 @@
import type { Field } from 'payload' import type { Field } from 'payload'
import { validateAnalyticsId } from '../../../modules/analytics/idFormats.js'
/** /**
* Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no * Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no
* read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only * read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only
@@ -13,6 +15,7 @@ export const analyticsFields: Field[] = [
description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)', description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',
placeholder: 'G-XXXXXXXXXX', placeholder: 'G-XXXXXXXXXX',
}, },
validate: validateAnalyticsId('ga4MeasurementId', 'G-XXXXXXXXXX'),
}, },
{ {
name: 'gtmContainerId', name: 'gtmContainerId',
@@ -21,6 +24,7 @@ export const analyticsFields: Field[] = [
description: 'Google Tag Manager container ID. (Google — Consent Mode)', description: 'Google Tag Manager container ID. (Google — Consent Mode)',
placeholder: 'GTM-XXXXXXX', placeholder: 'GTM-XXXXXXX',
}, },
validate: validateAnalyticsId('gtmContainerId', 'GTM-XXXXXXX'),
}, },
{ {
name: 'metaPixelId', name: 'metaPixelId',
@@ -29,6 +33,7 @@ export const analyticsFields: Field[] = [
description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.', description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',
placeholder: '1234567890123456', placeholder: '1234567890123456',
}, },
validate: validateAnalyticsId('metaPixelId', '1234567890123456'),
}, },
{ {
name: 'clarityProjectId', name: 'clarityProjectId',
@@ -37,6 +42,7 @@ export const analyticsFields: Field[] = [
description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.', description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',
placeholder: 'abcdefghij', placeholder: 'abcdefghij',
}, },
validate: validateAnalyticsId('clarityProjectId', 'abcdefghij'),
}, },
{ {
name: 'linkedInPartnerId', name: 'linkedInPartnerId',
@@ -45,6 +51,7 @@ export const analyticsFields: Field[] = [
description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.', description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',
placeholder: '1234567', placeholder: '1234567',
}, },
validate: validateAnalyticsId('linkedInPartnerId', '1234567'),
}, },
{ {
name: 'tiktokPixelId', name: 'tiktokPixelId',
@@ -53,5 +60,6 @@ export const analyticsFields: Field[] = [
description: 'TikTok Pixel ID. Loads only after MARKETING consent.', description: 'TikTok Pixel ID. Loads only after MARKETING consent.',
placeholder: 'CXXXXXXXXXXXXXXXXXXX', placeholder: 'CXXXXXXXXXXXXXXXXXXX',
}, },
validate: validateAnalyticsId('tiktokPixelId', 'CXXXXXXXXXXXXXXXXXXX'),
}, },
] ]
+2
View File
@@ -1,6 +1,7 @@
import type { Field, GlobalConfig } from 'payload' import type { Field, GlobalConfig } from 'payload'
import { isAdmin } from '../../modules/access/index.js' import { isAdmin } from '../../modules/access/index.js'
import { indexNowFields } from '../../modules/seo/indexNow.js'
import { analyticsFields } from './fields/analytics.js' import { analyticsFields } from './fields/analytics.js'
import { smtpFields } from './fields/smtp.js' import { smtpFields } from './fields/smtp.js'
import { turnstileFields } from './fields/turnstile.js' import { turnstileFields } from './fields/turnstile.js'
@@ -43,6 +44,7 @@ export function buildSiteIntegrations({
{ fields: analyticsFields, label: 'Analytics' }, { fields: analyticsFields, label: 'Analytics' },
{ fields: turnstileFields, label: 'Turnstile' }, { fields: turnstileFields, label: 'Turnstile' },
{ fields: smtpFields, label: 'SMTP' }, { fields: smtpFields, label: 'SMTP' },
{ fields: indexNowFields, label: 'IndexNow' },
...(additionalFields?.length ...(additionalFields?.length
? [{ fields: additionalFields, label: 'Custom' }] ? [{ fields: additionalFields, label: 'Custom' }]
: []), : []),
@@ -68,6 +68,17 @@ export const generalFields: Field[] = [
}, },
relationTo: 'media', relationTo: 'media',
}, },
{
name: 'sameAs',
type: 'array',
admin: {
description:
'Official profiles of this business (Google Business Profile, LinkedIn, Facebook, Wikipedia…). Tells search engines and AI which entity the site belongs to.',
initCollapsed: true,
},
fields: [{ name: 'url', type: 'text', required: true, validate: (v: unknown) => (typeof v === 'string' && /^https?:\/\/\S+$/.test(v)) || 'Full URL, e.g. https://www.linkedin.com/company/acme' }],
labels: { plural: 'Profiles', singular: 'Profile' },
},
{ {
name: 'favicon', name: 'favicon',
type: 'upload', type: 'upload',
+43 -6
View File
@@ -19,21 +19,29 @@ export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js' export type { RowLabelProps } from './modules/admin-ui/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js' export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js' export { getAnalyticsConfig } from './modules/analytics/index.js'
// Shared section fields (header: eyebrow/heading/intro, settings: anchor/background).
export { buildSectionHeaderField, buildSectionSettingsField } from './modules/blocks/sectionFields.js'
export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './modules/blocks/sectionFields.js'
export { export {
ACCEPT_ALL_CONSENT, ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
buildConsentLogEndpoint,
CONSENT_CATEGORIES, CONSENT_CATEGORIES,
CONSENT_COOKIE, CONSENT_COOKIE,
CONSENT_LOG_SLUG,
CONSENT_MAX_AGE, CONSENT_MAX_AGE,
CONSENT_VERSION, CONSENT_VERSION,
DEFAULT_CONSENT, DEFAULT_CONSENT,
getConsentTexts, getConsentTexts,
getCookieTable,
parseConsent, parseConsent,
readConsentRecord,
REJECT_ALL_CONSENT, REJECT_ALL_CONSENT,
serializeConsent, serializeConsent,
setDefaultConsent, setDefaultConsent,
updateConsent, updateConsent,
} from './modules/consent/index.js' } from './modules/consent/index.js'
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js' export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js' export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
export { export {
archiveFieldName, archiveFieldName,
@@ -41,6 +49,7 @@ export {
buildArchivePath, buildArchivePath,
buildEntryPath, buildEntryPath,
createMarkdownRenderer, createMarkdownRenderer,
createMarkdownRoute,
createSearchRoute, createSearchRoute,
getArchiveEntries, getArchiveEntries,
listContent, listContent,
@@ -68,6 +77,9 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys). // Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js' export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js' export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
export { checkboxGroupBlock, stepBlock } from './modules/forms/builderBlocks.js'
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './modules/forms/builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './modules/forms/builderTypes.js'
// Panel-managed form analytics (config-time field builder). // Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js' export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js' export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
@@ -93,6 +105,7 @@ export {
required, required,
} from './modules/forms/validators.js' } from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js' export type { Rule } from './modules/forms/validators.js'
export type { ContentHelpers, PageJsonLdOptions, SiteShell } from './modules/frontend/createContentHelpers.js'
export { createContentHelpers } from './modules/frontend/index.js' export { createContentHelpers } from './modules/frontend/index.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip). // Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js' export { createHealthRoute } from './modules/health/index.js'
@@ -119,18 +132,29 @@ export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js' export { resolveLocalized } from './modules/i18n/index.js'
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js' export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js' export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js' export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, safeHref } from './modules/links/index.js'
export type { export type {
BuildLinkFieldOptions, BuildLinkFieldOptions,
BuildLinksFieldOptions, BuildLinksFieldOptions,
LinkAppearance, LinkAppearance,
LinkValue, LinkValue,
NavItem,
ResolvedLink,
ResolveLinkHrefOptions, ResolveLinkHrefOptions,
ResolveNavOptions,
} from './modules/links/index.js' } from './modules/links/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it). // Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js' export { createMcpRoute } from './modules/mcp/index.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js' export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
export type { OptimizeUploadOptions } from './modules/media/index.js' export type { OptimizeUploadOptions } from './modules/media/index.js'
export {
buildMediaPlaceholderField,
buildMediaPlaceholderHook,
MEDIA_SIZES,
mediaImageProps,
videoProps,
} from './modules/media/index.js'
export type { MediaImageOptions, MediaImageProps, VideoMode, VideoProps } from './modules/media/index.js'
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js' export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js'
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js' export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js' export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
@@ -145,11 +169,12 @@ export {
} from './modules/payload/index.js' } from './modules/payload/index.js'
// Lexical → Markdown (pure, no React) — for AI-readable output. // Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js' export { lexicalToMarkdown } from './modules/richtext/index.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
export { buildSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js' export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js' export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js' export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
export { export {
buildHreflangAlternates, buildHreflangAlternates,
@@ -159,6 +184,16 @@ export {
slugsAcrossLocales, slugsAcrossLocales,
} from './modules/seo/index.js' } from './modules/seo/index.js'
export type { SiteMetaConfig } from './modules/seo/index.js' export type { SiteMetaConfig } from './modules/seo/index.js'
export { collectSiteIndex } from './modules/seo/index.js'
export {
buildIndexNowHook,
createIndexNowKeyRoute,
getIndexNowKey,
INDEXNOW_KEY_ENV,
INDEXNOW_KEY_PATH,
submitToIndexNow,
} from './modules/seo/index.js'
export type { CollectSiteIndexArgs, SiteIndexEntry } from './modules/seo/index.js'
export type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry } from './modules/seo/index.js' export type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry } from './modules/seo/index.js'
export { export {
AI_ASSISTANT_BOTS, AI_ASSISTANT_BOTS,
@@ -171,20 +206,22 @@ export {
injectAutoFillMeta, injectAutoFillMeta,
} from './modules/seo/index.js' } from './modules/seo/index.js'
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js' export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js'
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js' export { buildIconsMetadata, buildOrganizationJsonLd, sameAsUrls, validateFaviconField } from './modules/seo/index.js'
export { buildNoindexField } from './modules/seo/index.js' export { buildNoindexField } from './modules/seo/index.js'
export { buildSpeakableJsonLd } from './modules/seo/index.js' export { buildSpeakableJsonLd } from './modules/seo/index.js'
export { buildSummaryField } from './modules/seo/index.js' export { buildSummaryField } from './modules/seo/index.js'
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js' export { buildBreadcrumbJsonLd, buildNavigationJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage. // Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js' export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd } from './modules/seo/index.js' export { buildArticleJsonLd, buildWebPageJsonLd, formatOpeningHours } from './modules/seo/index.js'
export { buildLlmsTxt } from './modules/seo/index.js' export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js' export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js' export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js' export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js' export { buildSlugField, toSlug } from './modules/slug/index.js'
export { buildImagesConfig } from './modules/storage/buildImagesConfig.js'
export type { ImagesConfig } from './modules/storage/buildImagesConfig.js'
export { buildR2Storage } from './modules/storage/index.js' export { buildR2Storage } from './modules/storage/index.js'
// Imported from the file, not the turnstile barrel — that one re-exports verify, // Imported from the file, not the turnstile barrel — that one re-exports verify,
// which imports 'server-only'. // which imports 'server-only'.
+7 -6
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { AnalyticsConfig } from './types.js' import type { AnalyticsConfig } from './types.js'
import { getSiteIntegrations } from '../payload/index.js' import { getSiteIntegrations } from '../payload/index.js'
import { validAnalyticsId } from './idFormats.js'
/** /**
* Reads the public analytics / marketing tag IDs from SiteIntegrations, * Reads the public analytics / marketing tag IDs from SiteIntegrations,
@@ -12,11 +13,11 @@ import { getSiteIntegrations } from '../payload/index.js'
export async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> { export async function getAnalyticsConfig(payload: BasePayload): Promise<AnalyticsConfig> {
const integrations = await getSiteIntegrations<AnalyticsConfig>(payload) const integrations = await getSiteIntegrations<AnalyticsConfig>(payload)
return { return {
clarityProjectId: integrations.clarityProjectId ?? null, clarityProjectId: validAnalyticsId('clarityProjectId', integrations.clarityProjectId),
ga4MeasurementId: integrations.ga4MeasurementId ?? null, ga4MeasurementId: validAnalyticsId('ga4MeasurementId', integrations.ga4MeasurementId),
gtmContainerId: integrations.gtmContainerId ?? null, gtmContainerId: validAnalyticsId('gtmContainerId', integrations.gtmContainerId),
linkedInPartnerId: integrations.linkedInPartnerId ?? null, linkedInPartnerId: validAnalyticsId('linkedInPartnerId', integrations.linkedInPartnerId),
metaPixelId: integrations.metaPixelId ?? null, metaPixelId: validAnalyticsId('metaPixelId', integrations.metaPixelId),
tiktokPixelId: integrations.tiktokPixelId ?? null, tiktokPixelId: validAnalyticsId('tiktokPixelId', integrations.tiktokPixelId),
} }
} }
+28
View File
@@ -0,0 +1,28 @@
/**
* Formats of the tag IDs typed into Site Integrations. Used twice: as field
* validation in the panel (typos caught on save) and when the IDs are handed to
* the browser (getAnalyticsConfig) — a malformed value from an import or an old
* version is dropped instead of being put into a script URL.
*/
export const ANALYTICS_ID_FORMATS = {
clarityProjectId: /^[a-z0-9]{5,20}$/i,
ga4MeasurementId: /^G-[A-Z0-9]{4,20}$/,
gtmContainerId: /^GTM-[A-Z0-9]{4,12}$/,
linkedInPartnerId: /^\d{3,12}$/,
metaPixelId: /^\d{5,20}$/,
tiktokPixelId: /^[A-Z0-9]{10,30}$/i,
} as const
export type AnalyticsIdField = keyof typeof ANALYTICS_ID_FORMATS
/** The trimmed ID when it matches its format, else null. */
export function validAnalyticsId(field: AnalyticsIdField, value: unknown): null | string {
const v = typeof value === 'string' ? value.trim() : ''
return v && ANALYTICS_ID_FORMATS[field].test(v) ? v : null
}
/** Payload field `validate` for an ID field. */
export const validateAnalyticsId =
(field: AnalyticsIdField, example: string) =>
(value: null | string | undefined): string | true =>
!value?.trim() || validAnalyticsId(field, value) !== null || `Unexpected format — expected something like ${example}`
+2
View File
@@ -1,3 +1,5 @@
export { RenderBlocks } from './RenderBlocks.js' export { RenderBlocks } from './RenderBlocks.js'
export type { RenderBlocksProps } from './RenderBlocks.js' export type { RenderBlocksProps } from './RenderBlocks.js'
export { buildSectionHeaderField, buildSectionSettingsField } from './sectionFields.js'
export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './sectionFields.js'
export type { BlockComponentMap, BlockData, EnhanceProps } from './types.js' export type { BlockComponentMap, BlockData, EnhanceProps } from './types.js'
+82
View File
@@ -0,0 +1,82 @@
import type { Field, GroupField } from 'payload'
/**
* The two field groups every section block shares — same panel, same data
* shape in every project, so the shared <Section>/<SectionHeader> components
* work on every block. Everything is overridable: names, options, extra fields.
*
* fields: [buildSectionHeaderField(), …the block's own fields…, buildSectionSettingsField()]
* fields: [buildSectionSettingsField({ backgrounds: [{ label: 'Brand', value: 'brand' }] })]
*/
export type SectionHeaderFieldOptions = {
/** Extra fields inside the group (e.g. a heading level select). */
fields?: Field[]
/** Generated TS type name. Default 'SectionHeaderData'. */
interfaceName?: string
/** Default 'header'. */
name?: string
}
/** eyebrow + heading + intro, localized — rendered by the project's <SectionHeader>. */
export function buildSectionHeaderField({ name = 'header', fields = [], interfaceName = 'SectionHeaderData' }: SectionHeaderFieldOptions = {}): GroupField {
return {
name,
type: 'group',
fields: [
{ name: 'eyebrow', type: 'text', admin: { description: 'Small line above the heading. Optional.' }, localized: true },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', admin: { rows: 3 }, localized: true },
...fields,
],
interfaceName,
}
}
export type SectionSettingsFieldOptions = {
/** Section #id for anchor links and a section nav. Default true. */
anchor?: boolean
/**
* Background choices — values map to the project's own classes in <Section>.
* Default Default / Muted / Inverted (dark). `false` → no background select.
*/
backgrounds?: { label: string; value: string }[] | false
/** Extra settings (e.g. spacing, width). */
fields?: Field[]
/** Generated TS type name. Default 'SectionSettings'. */
interfaceName?: string
/** Default 'settings'. */
name?: string
}
const DEFAULT_BACKGROUNDS = [
{ label: 'Default', value: 'default' },
{ label: 'Muted', value: 'muted' },
{ label: 'Inverted (dark)', value: 'inverted' },
]
/** Sidebar group: anchor + background (+ your own) — instead of bgColor / sectionId per block. */
export function buildSectionSettingsField({
name = 'settings',
anchor = true,
backgrounds = DEFAULT_BACKGROUNDS,
fields = [],
interfaceName = 'SectionSettings',
}: SectionSettingsFieldOptions = {}): GroupField {
return {
name,
type: 'group',
admin: { position: 'sidebar' },
fields: [
...(anchor
? [{ name: 'anchor', type: 'text', admin: { description: 'Section id for #links and section nav, e.g. "pricing".' } } as Field]
: []),
...(backgrounds && backgrounds.length
? [{ name: 'background', type: 'select', defaultValue: backgrounds[0].value, options: backgrounds } as Field]
: []),
...fields,
],
interfaceName,
label: 'Section settings',
}
}
+29 -2
View File
@@ -2,6 +2,7 @@
import { createContext, type ReactNode, use } from 'react' import { createContext, type ReactNode, use } from 'react'
import type { ConsentTexts } from './texts.js' import type { ConsentTexts } from './texts.js'
import type { ConsentCookieMap } from './useConsent.js'
import { useConsent } from './useConsent.js' import { useConsent } from './useConsent.js'
@@ -9,8 +10,34 @@ type ConsentContextValue = { texts: ConsentTexts } & ReturnType<typeof useConsen
const ConsentContext = createContext<ConsentContextValue | null>(null) const ConsentContext = createContext<ConsentContextValue | null>(null)
export function ConsentProvider({ children, texts }: { children: ReactNode; texts: ConsentTexts }) { type ConsentProviderProps = {
const consent = useConsent() children: ReactNode
/** Extra cookies per category to delete when consent is withdrawn — merged with the built-in list. */
cookieMap?: ConsentCookieMap
/**
* Consent log endpoint (createConsentLogEndpoint, e.g. '/api/ipal/consent'):
* every decision is POSTed — random id, choices, policy version, no personal
* data — so the site can demonstrate consent (GDPR Art. 7(1)). Off when omitted.
*/
logEndpoint?: string
texts: ConsentTexts
}
export function ConsentProvider({ children, cookieMap, logEndpoint, texts }: ConsentProviderProps) {
const consent = useConsent({
cookieMap,
onDecision: logEndpoint
? (record) => {
void fetch(logEndpoint, {
body: JSON.stringify(record),
headers: { 'content-type': 'application/json' },
keepalive: true,
method: 'POST',
}).catch(() => {})
}
: undefined,
version: texts.version,
})
return <ConsentContext value={{ ...consent, texts }}>{children}</ConsentContext> return <ConsentContext value={{ ...consent, texts }}>{children}</ConsentContext>
} }
+12 -2
View File
@@ -53,7 +53,17 @@ const strongText =
const mutedText = const mutedText =
'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]' 'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNames } = {}) { type CookieBannerProps = {
classNames?: CookieBannerClassNames
/**
* Style "Reject" like "Accept all" (primary). Polish and EU regulators (UODO,
* EDPB) expect refusing to be as easy and visible as accepting. Default false
* keeps the existing look; recommended true.
*/
equalChoice?: boolean
}
export function CookieBanner({ classNames, equalChoice = false }: CookieBannerProps = {}) {
const isMounted = useIsMounted() const isMounted = useIsMounted()
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext() const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
const [showSettings, setShowSettings] = useState(false) const [showSettings, setShowSettings] = useState(false)
@@ -104,7 +114,7 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button"> <button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button">
{texts.buttons.settings} {texts.buttons.settings}
</button> </button>
<button className={secondaryClass} data-ipal="reject" onClick={rejectAll} type="button"> <button className={equalChoice ? primaryClass : secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
{texts.buttons.reject} {texts.buttons.reject}
</button> </button>
<button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button"> <button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button">
+61
View File
@@ -0,0 +1,61 @@
import type { CookieTableRow } from './getConsentTexts.js'
import type { ConsentTexts } from './texts.js'
export type CookieTableLabels = {
category: string
duration: string
name: string
provider: string
purpose: string
}
type CookieTableProps = {
/** Optional caption above the table. */
caption?: string
/** Category names — pass `texts.categories` from getConsentTexts so they match the banner. */
categories?: ConsentTexts['categories']
/** Classes per element; nothing is styled by default. */
classNames?: Partial<Record<'caption' | 'table' | 'td' | 'th' | 'tr', string>>
/** Column headings in the page's language — from the project (panel field or page content). */
labels: CookieTableLabels
/** From getCookieTable({ payload, locale }) — Cookie Settings → Cookies. */
rows: CookieTableRow[]
}
/**
* The cookie list for the cookie-policy page, straight from the panel — no copy
* pasted into the policy text, so it can't go stale. Plain semantic <table>,
* unstyled: classNames per element, or style it from the page's CSS. Server
* component (no state).
*
* const rows = await getCookieTable({ payload, locale })
* <CookieTable rows={rows} labels={…from the panel…} categories={texts.categories} />
*/
export function CookieTable({ caption, categories, classNames = {}, labels, rows }: CookieTableProps) {
if (rows.length === 0) {return null}
return (
<table className={classNames.table}>
{caption ? <caption className={classNames.caption}>{caption}</caption> : null}
<thead>
<tr className={classNames.tr}>
<th className={classNames.th} scope="col">{labels.name}</th>
<th className={classNames.th} scope="col">{labels.provider}</th>
<th className={classNames.th} scope="col">{labels.category}</th>
<th className={classNames.th} scope="col">{labels.purpose}</th>
<th className={classNames.th} scope="col">{labels.duration}</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr className={classNames.tr} key={`${row.category}:${row.name}`}>
<td className={classNames.td}><code>{row.name}</code></td>
<td className={classNames.td}>{row.provider ?? ''}</td>
<td className={classNames.td}>{categories?.[row.category]?.title ?? row.category}</td>
<td className={classNames.td}>{row.purpose ?? ''}</td>
<td className={classNames.td}>{row.duration ?? ''}</td>
</tr>
))}
</tbody>
</table>
)
}
+2 -1
View File
@@ -5,4 +5,5 @@ export { CookieBanner } from './CookieBanner.js'
export type { CookieBannerClassNames } from './CookieBanner.js' export type { CookieBannerClassNames } from './CookieBanner.js'
export { CookieButton } from './CookieButton.js' export { CookieButton } from './CookieButton.js'
// Client-only consent exports — hook, provider, and UI components. // Client-only consent exports — hook, provider, and UI components.
export { useConsent } from './useConsent.js' export { DEFAULT_COOKIE_MAP, useConsent } from './useConsent.js'
export type { ConsentCookieMap } from './useConsent.js'
+110
View File
@@ -0,0 +1,110 @@
import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
import { isAdmin } from '../access/predicates.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
import { CONSENT_CATEGORIES } from './categories.js'
/**
* Consent log — proof of consent (GDPR Art. 7(1): the controller must be able
* to demonstrate it). Each banner decision is stored as: random consent id (the
* same one kept in the visitor's cookie), the choices, the policy version and
* the time. NO IP address, user agent or other personal data — the id alone
* links a record to the browser that holds the cookie.
*
* Opt-in: `ipalKit({ consentLog: true })` adds the collection and the endpoint
* POST /api/ipal/consent; the layout passes `<ConsentProvider logEndpoint="/api/ipal/consent">`.
* Records older than `retentionDays` (default 3 years) are purged automatically.
*/
export const CONSENT_LOG_SLUG = 'consent-records'
export type ConsentLogOptions = {
/** Days a record is kept. Default 1095 (3 years). */
retentionDays?: number
}
export function buildConsentLogCollection(): CollectionConfig {
return {
slug: CONSENT_LOG_SLUG,
access: {
// Written only by the endpoint (Local API); read and pruned by admins.
create: () => false,
delete: ({ req: { user } }) => isAdmin(user),
read: ({ req: { user } }) => isAdmin(user),
update: () => false,
},
admin: {
defaultColumns: ['consentId', 'version', 'createdAt'],
description: 'Proof of cookie consent: random id (also in the visitor cookie), choices, policy version, time. No personal data.',
group: 'Settings',
useAsTitle: 'consentId',
},
fields: [
{ name: 'consentId', type: 'text', index: true, required: true },
{ name: 'version', type: 'number', required: true },
{
name: 'choices',
type: 'group',
fields: CONSENT_CATEGORIES.map((c) => ({ name: c, type: 'checkbox' as const })),
},
],
labels: { plural: 'Consent records', singular: 'Consent record' },
timestamps: true,
}
}
let lastPurge = 0
export function buildConsentLogEndpoint({ retentionDays = 1095 }: ConsentLogOptions = {}): Endpoint {
return {
handler: async (req: PayloadRequest) => {
const limit = await consumeRateLimit({ key: clientIp(req as unknown as Request), max: 20, scope: 'consent' })
if (!limit.ok) {return Response.json({ ok: false }, { status: 429 })}
let body: unknown
try {
body = await (req as unknown as Request).json()
} catch {
return Response.json({ ok: false }, { status: 400 })
}
const b = body as { id?: unknown; state?: Record<string, unknown>; version?: unknown }
const valid =
typeof b.id === 'string' &&
/^[0-9a-f]{16,64}$/.test(b.id) &&
typeof b.version === 'number' &&
Number.isInteger(b.version) &&
b.version >= 1 &&
b.state !== null &&
typeof b.state === 'object' &&
CONSENT_CATEGORIES.every((c) => typeof b.state![c] === 'boolean')
if (!valid) {return Response.json({ ok: false }, { status: 400 })}
try {
await req.payload.create({
collection: CONSENT_LOG_SLUG as never,
data: {
choices: Object.fromEntries(CONSENT_CATEGORIES.map((c) => [c, b.state![c] === true])),
consentId: b.id,
version: b.version,
} as never,
overrideAccess: true,
})
const now = Date.now()
if (now - lastPurge > 24 * 60 * 60 * 1000) {
lastPurge = now
await req.payload.delete({
collection: CONSENT_LOG_SLUG as never,
overrideAccess: true,
where: { createdAt: { less_than: new Date(now - retentionDays * 86_400_000).toISOString() } },
})
}
return Response.json({ ok: true }, { status: 201 })
} catch (err) {
req.payload.logger.error(`[ipal] consent log write failed: ${err instanceof Error ? err.message : String(err)}`)
return Response.json({ ok: false }, { status: 500 })
}
},
method: 'post',
path: '/ipal/consent',
}
}
+33 -1
View File
@@ -6,7 +6,7 @@ import type { ConsentTexts } from './texts.js'
import { resolveLocalized } from '../i18n/resolveLocalized.js' import { resolveLocalized } from '../i18n/resolveLocalized.js'
import { getSystemPagePath } from '../pages/index.js' import { getSystemPagePath } from '../pages/index.js'
import { getGlobal } from '../payload/index.js' import { getGlobal } from '../payload/index.js'
import { CONSENT_CATEGORIES } from './categories.js' import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
/** English fallback used when the global has no value for a field. */ /** English fallback used when the global has no value for a field. */
const FALLBACK: ConsentTexts = { const FALLBACK: ConsentTexts = {
@@ -39,7 +39,9 @@ const FALLBACK_PRIVACY_LABEL = 'Privacy policy'
type CookieSettingsData = { type CookieSettingsData = {
buttons?: null | Partial<ConsentTexts['buttons']> buttons?: null | Partial<ConsentTexts['buttons']>
categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null
cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null
message?: null | string message?: null | string
policyVersion?: null | number
privacyLinkLabel?: null | string privacyLinkLabel?: null | string
settingsTitle?: null | string settingsTitle?: null | string
} }
@@ -141,5 +143,35 @@ export async function getConsentTexts({
message: g.message || FALLBACK.message, message: g.message || FALLBACK.message,
privacyLink, privacyLink,
settingsTitle: g.settingsTitle || FALLBACK.settingsTitle, settingsTitle: g.settingsTitle || FALLBACK.settingsTitle,
...(typeof g.policyVersion === 'number' && g.policyVersion >= 1 ? { version: Math.trunc(g.policyVersion) } : {}),
}
}
export type CookieTableRow = {
category: ConsentCategory
duration?: string
name: string
provider?: string
purpose?: string
}
/**
* Rows of Cookie Settings → Cookies in one language, for the cookie policy page
* (<CookieTable rows={…}>). Server-side; never throws (empty list).
*/
export async function getCookieTable({ locale, payload }: { locale?: string; payload: BasePayload }): Promise<CookieTableRow[]> {
try {
const g = await getGlobal<CookieSettingsData>(payload, 'cookie-settings', { locale })
return (g.cookies ?? [])
.filter((c) => typeof c.name === 'string' && c.name.trim())
.map((c) => ({
name: c.name!.trim(),
category: (CONSENT_CATEGORIES as readonly string[]).includes(c.category ?? '') ? (c.category as ConsentCategory) : 'necessary',
...(c.provider?.trim() ? { provider: c.provider.trim() } : {}),
...(c.purpose?.trim() ? { purpose: c.purpose.trim() } : {}),
...(c.duration?.trim() ? { duration: c.duration.trim() } : {}),
}))
} catch {
return []
} }
} }
+6 -1
View File
@@ -8,13 +8,18 @@ export {
REJECT_ALL_CONSENT, REJECT_ALL_CONSENT,
} from './categories.js' } from './categories.js'
export type { ConsentCategory, ConsentState } from './categories.js' export type { ConsentCategory, ConsentState } from './categories.js'
export { getConsentTexts } from './getConsentTexts.js' export { buildConsentLogCollection, buildConsentLogEndpoint, CONSENT_LOG_SLUG } from './consentLog.js'
export type { ConsentLogOptions } from './consentLog.js'
export { getConsentTexts, getCookieTable } from './getConsentTexts.js'
export type { CookieTableRow } from './getConsentTexts.js'
export { setDefaultConsent, updateConsent } from './googleConsent.js' export { setDefaultConsent, updateConsent } from './googleConsent.js'
export { export {
CONSENT_COOKIE, CONSENT_COOKIE,
CONSENT_MAX_AGE, CONSENT_MAX_AGE,
CONSENT_VERSION, CONSENT_VERSION,
newConsentId,
parseConsent, parseConsent,
readConsentRecord,
serializeConsent, serializeConsent,
} from './storage.js' } from './storage.js'
export type { ConsentTexts } from './texts.js' export type { ConsentTexts } from './texts.js'
+26 -8
View File
@@ -3,41 +3,59 @@ import type { ConsentState } from './categories.js'
import { CONSENT_CATEGORIES, DEFAULT_CONSENT } from './categories.js' import { CONSENT_CATEGORIES, DEFAULT_CONSENT } from './categories.js'
/** /**
* Consent persistence in a cookie. Stored with a version so we can invalidate * Consent persistence in a cookie. Stored with a version so old consents can be
* old consents when the policy changes, and a timestamp (GDPR: consent must be * invalidated when the policy changes (Cookie Settings → Policy version in the
* dated). Readable both client-side (banner) and server-side (script gating). * panel), a timestamp (GDPR: consent must be dated) and a random id that links
* the visitor's choice to the optional server-side consent record. Readable both
* client-side (banner) and server-side (script gating, proxy).
*/ */
export const CONSENT_COOKIE = 'cookie-consent' export const CONSENT_COOKIE = 'cookie-consent'
/** Default policy version — the panel's Cookie Settings → Policy version overrides it. */
export const CONSENT_VERSION = 1 export const CONSENT_VERSION = 1
export const CONSENT_MAX_AGE = 60 * 60 * 24 * 180 // 180 days export const CONSENT_MAX_AGE = 60 * 60 * 24 * 180 // 180 days
type StoredConsent = { type StoredConsent = {
/** Random id of this decision (no personal data) — matches the consent record. */
id?: string
state: ConsentState state: ConsentState
timestamp: string timestamp: string
version: number version: number
} }
export function serializeConsent(state: ConsentState): string { /** Random id for a consent decision. */
export function newConsentId(): string {
const bytes = new Uint8Array(12)
globalThis.crypto.getRandomValues(bytes)
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
}
export function serializeConsent(state: ConsentState, version: number = CONSENT_VERSION, id?: string): string {
const payload: StoredConsent = { const payload: StoredConsent = {
...(id ? { id } : {}),
state, state,
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
version: CONSENT_VERSION, version,
} }
return encodeURIComponent(JSON.stringify(payload)) return encodeURIComponent(JSON.stringify(payload))
} }
export function parseConsent(raw: string | undefined): ConsentState | null { /** Full stored record (id, timestamp, version) — null when missing, unreadable or from another policy version. */
export function readConsentRecord(raw: string | undefined, version: number = CONSENT_VERSION): ({ state: ConsentState } & StoredConsent) | null {
if (!raw) {return null} if (!raw) {return null}
try { try {
const parsed = JSON.parse(decodeURIComponent(raw)) as StoredConsent const parsed = JSON.parse(decodeURIComponent(raw)) as StoredConsent
if (parsed.version !== CONSENT_VERSION) {return null} if (parsed.version !== version) {return null}
const state = { ...DEFAULT_CONSENT } const state = { ...DEFAULT_CONSENT }
for (const cat of CONSENT_CATEGORIES) { for (const cat of CONSENT_CATEGORIES) {
if (typeof parsed.state?.[cat] === 'boolean') {state[cat] = parsed.state[cat]} if (typeof parsed.state?.[cat] === 'boolean') {state[cat] = parsed.state[cat]}
} }
state.necessary = true state.necessary = true
return state return { ...parsed, state }
} catch { } catch {
return null return null
} }
} }
export function parseConsent(raw: string | undefined, version: number = CONSENT_VERSION): ConsentState | null {
return readConsentRecord(raw, version)?.state ?? null
}
+2
View File
@@ -13,4 +13,6 @@ export type ConsentTexts = {
/** null = no privacy-policy link shown */ /** null = no privacy-policy link shown */
privacyLink: { href: string; label: string } | null privacyLink: { href: string; label: string } | null
settingsTitle: string settingsTitle: string
/** Policy version from the panel — a stored consent from another version asks again. */
version?: number
} }
+81 -25
View File
@@ -1,69 +1,125 @@
'use client' 'use client'
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useMemo, useState } from 'react'
import type { ConsentCategory, ConsentState } from './categories.js' import type { ConsentCategory, ConsentState } from './categories.js'
import { LOCALE_COOKIE_NAME } from '../i18n/index.js' import { LOCALE_COOKIE_NAME } from '../i18n/index.js'
import { ACCEPT_ALL_CONSENT, DEFAULT_CONSENT, REJECT_ALL_CONSENT } from './categories.js' import { ACCEPT_ALL_CONSENT, DEFAULT_CONSENT, REJECT_ALL_CONSENT } from './categories.js'
import { updateConsent } from './googleConsent.js' import { updateConsent } from './googleConsent.js'
import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent, serializeConsent } from './storage.js' import { CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, newConsentId, readConsentRecord, serializeConsent } from './storage.js'
export type ConsentCookieMap = Partial<Record<ConsentCategory, string[]>>
/** /**
* Cookies to delete when consent for a category is withdrawn. Keyed by * Cookies deleted when consent for a category is withdrawn (GDPR: withdrawing
* category. The plugin knows about its own functional cookie (locale); clients * must stop the processing). `name*` matches a prefix (`_ga_*` → _ga_ABC123).
* can extend this via the `cookieMap` arg to useConsent if they set their own. * Covers the plugin's own functional cookie and the tools Analytics can load;
* projects add theirs through <ConsentProvider cookieMap> (merged, not replaced).
*/ */
const DEFAULT_COOKIE_MAP: Partial<Record<ConsentCategory, string[]>> = { export const DEFAULT_COOKIE_MAP: ConsentCookieMap = {
analytics: ['_ga', '_ga_*', '_gid', '_gat*', '_clck', '_clsk', 'CLID', '_hj*'],
functional: [LOCALE_COOKIE_NAME], functional: [LOCALE_COOKIE_NAME],
marketing: ['_fbp', '_fbc', '_gcl_*', '_ttp', 'li_fat_id', '_uetsid', '_uetvid'],
} }
/** Expire a cookie now, across the whole site. */ function mergeCookieMaps(extra?: ConsentCookieMap): ConsentCookieMap {
if (!extra) {return DEFAULT_COOKIE_MAP}
const out: ConsentCookieMap = { ...DEFAULT_COOKIE_MAP }
for (const [cat, names] of Object.entries(extra) as [ConsentCategory, string[]][]) {
out[cat] = [...new Set([...(out[cat] ?? []), ...names])]
}
return out
}
/** Names of cookies currently set that match a pattern (`name` or prefix `name*`). */
function matchingCookies(pattern: string): string[] {
const names = document.cookie.split('; ').map((c) => c.split('=')[0]).filter(Boolean)
return pattern.endsWith('*') ? names.filter((n) => n.startsWith(pattern.slice(0, -1))) : names.filter((n) => n === pattern)
}
/**
* Expire a cookie on this host AND every parent domain — GA, Meta and others
* set theirs on the registrable domain (.acme.pl), which a host-only delete
* leaves behind.
*/
function deleteCookie(name: string) { function deleteCookie(name: string) {
document.cookie = `${name}=;path=/;max-age=0;samesite=lax` const parts = location.hostname.split('.')
const domains = [''] // host-only
for (let i = 0; i < parts.length - 1; i++) {domains.push(`;domain=.${parts.slice(i).join('.')}`)}
for (const domain of domains) {document.cookie = `${name}=;path=/;max-age=0;samesite=lax${domain}`}
} }
export function useConsent( type UseConsentOptions = {
cookieMap: Partial<Record<ConsentCategory, string[]>> = DEFAULT_COOKIE_MAP, /** Extra cookies per category to delete on withdrawal — merged with DEFAULT_COOKIE_MAP. */
) { cookieMap?: ConsentCookieMap
/**
* Called after every decision with the consent id and choices — e.g. POST to
* the consent log (createConsentLogEndpoint). Never blocks the banner.
*/
onDecision?: (record: { id: string; state: ConsentState; version: number }) => void
/** Policy version from the panel (Cookie Settings). A stored consent from another version asks again. */
version?: number
}
export function useConsent(options: ConsentCookieMap | UseConsentOptions = {}) {
// Backwards compatible: the old signature took the cookie map directly.
const opts: UseConsentOptions =
'cookieMap' in options || 'version' in options || 'onDecision' in options
? (options)
: { cookieMap: options as ConsentCookieMap }
const version = opts.version ?? CONSENT_VERSION
// Merge once per distinct map (props may pass a new object each render).
const cookieMapKey = JSON.stringify(opts.cookieMap ?? null)
const cookieMap = useMemo(() => mergeCookieMaps(opts.cookieMap), [cookieMapKey])
const { onDecision } = opts
const [state, setState] = useState<ConsentState>(DEFAULT_CONSENT) const [state, setState] = useState<ConsentState>(DEFAULT_CONSENT)
const [decided, setDecided] = useState(false) const [decided, setDecided] = useState(false)
const [consentId, setConsentId] = useState<string | undefined>(undefined)
useEffect(() => { useEffect(() => {
const raw = document.cookie const raw = document.cookie
.split('; ') .split('; ')
.find((c) => c.startsWith(`${CONSENT_COOKIE}=`)) .find((c) => c.startsWith(`${CONSENT_COOKIE}=`))
?.split('=')[1] ?.split('=')[1]
const parsed = parseConsent(raw) const record = readConsentRecord(raw, version)
if (parsed) { if (record) {
setState(parsed) setState(record.state)
setDecided(true) setDecided(true)
setConsentId(record.id)
} }
}, []) }, [version])
const persist = useCallback( const persist = useCallback(
(next: ConsentState) => { (next: ConsentState) => {
// Withdrawal cleanup: for any category flipping true → false, delete the // Withdrawal cleanup: for any category flipping true → false, delete the
// cookies tied to it. GDPR: withdrawing consent must stop the processing, // cookies tied to it. GDPR: withdrawing consent must stop the processing.
// so a functional cookie (e.g. locale) written under consent has to go when
// that consent is revoked. Uses the current `state` as the previous value.
for (const cat of Object.keys(cookieMap) as ConsentCategory[]) { for (const cat of Object.keys(cookieMap) as ConsentCategory[]) {
const wasGranted = state[cat] === true if (state[cat] === true && next[cat] !== true) {
const nowDenied = next[cat] !== true for (const pattern of cookieMap[cat] ?? []) {
if (wasGranted && nowDenied) { for (const name of matchingCookies(pattern)) {deleteCookie(name)}
for (const name of cookieMap[cat] ?? []) {deleteCookie(name)} }
} }
} }
document.cookie = `${CONSENT_COOKIE}=${serializeConsent(next)};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax` const id = consentId ?? newConsentId()
const secure = location.protocol === 'https:' ? ';secure' : ''
document.cookie = `${CONSENT_COOKIE}=${serializeConsent(next, version, id)};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}`
setState(next) setState(next)
setDecided(true) setDecided(true)
setConsentId(id)
// Tell Google right away. Tags are already on the page holding whatever // Tell Google right away. Tags are already on the page holding whatever
// defaults Analytics set at load; without this update they keep them for // defaults Analytics set at load; without this update they keep them for
// the rest of the session and never write their cookies — the banner would // the rest of the session and never write their cookies — the banner would
// look like it worked while nothing changed. // look like it worked while nothing changed.
updateConsent(next) updateConsent(next)
try {
onDecision?.({ id, state: next, version })
} catch {
// a logging hook must never break the banner
}
}, },
[state, cookieMap], [state, consentId, version, onDecision, cookieMap],
) )
const acceptAll = useCallback(() => persist(ACCEPT_ALL_CONSENT), [persist]) const acceptAll = useCallback(() => persist(ACCEPT_ALL_CONSENT), [persist])
@@ -75,5 +131,5 @@ export function useConsent(
) )
const reopen = useCallback(() => setDecided(false), []) const reopen = useCallback(() => setDecided(false), [])
return { acceptAll, decided, rejectAll, reopen, savePreferences, state } return { acceptAll, consentId, decided, rejectAll, reopen, savePreferences, state }
} }
+66 -2
View File
@@ -6,11 +6,21 @@ import { blocksToMarkdown } from './blocksToMarkdown.js'
import { resolveRoute } from './resolveRoute.js' import { resolveRoute } from './resolveRoute.js'
type CreateMarkdownRendererArgs = { type CreateMarkdownRendererArgs = {
/**
* Absolute origin. With it the frontmatter carries `url:` — the canonical page
* address an assistant should cite (instead of the /md/… mirror).
*/
baseUrl?: string
/** Pages collection. Default 'pages'. */ /** Pages collection. Default 'pages'. */
collection?: string collection?: string
/**
* i18n config — only to know a single-locale site has no /{locale} prefix in
* its URLs (for `url:`). Omit on multilingual sites if you like.
*/
config?: { locales: readonly unknown[] }
/** Archive-backed collections, same value as the plugin option (optional). */ /** Archive-backed collections, same value as the plugin option (optional). */
content?: ContentOption content?: ContentOption
/** Prepend a YAML frontmatter block (title/description/locale). Default true. */ /** Prepend a YAML frontmatter block (title, description, url, updated, locale). Default true. */
frontmatter?: boolean frontmatter?: boolean
/** Field holding the block layout. Default 'layout'. */ /** Field holding the block layout. Default 'layout'. */
layoutField?: string layoutField?: string
@@ -31,6 +41,7 @@ type DocShape = {
[key: string]: unknown [key: string]: unknown
meta?: { description?: null | string } | null meta?: { description?: null | string } | null
title?: null | string title?: null | string
updatedAt?: string
} }
function yamlEscape(v: string): string { function yamlEscape(v: string): string {
@@ -62,7 +73,9 @@ function yamlEscape(v: string): string {
*/ */
export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) { export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
const { const {
baseUrl,
collection = 'pages', collection = 'pages',
config,
content, content,
frontmatter = true, frontmatter = true,
layoutField = 'layout', layoutField = 'layout',
@@ -92,6 +105,9 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
const fm = ['---', `locale: ${locale}`] const fm = ['---', `locale: ${locale}`]
if (title) {fm.push(`title: ${yamlEscape(title)}`)} if (title) {fm.push(`title: ${yamlEscape(title)}`)}
if (description) {fm.push(`description: ${yamlEscape(description)}`)} if (description) {fm.push(`description: ${yamlEscape(description)}`)}
const url = canonicalOf(baseUrl, config, locale, slug)
if (url) {fm.push(`url: ${url}`)}
if (typeof doc.updatedAt === 'string') {fm.push(`updated: ${doc.updatedAt.slice(0, 10)}`)}
fm.push('---') fm.push('---')
parts.push(fm.join('\n')) parts.push(fm.join('\n'))
} }
@@ -109,7 +125,7 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null. * Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
* Uses the global Response — no next/server import. * Uses the global Response — no next/server import.
*/ */
export function markdownResponse(md: null | string): Response { export function markdownResponse(md: null | string, options: { canonical?: string } = {}): Response {
if (md == null) { if (md == null) {
return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 }) return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 })
} }
@@ -117,7 +133,55 @@ export function markdownResponse(md: null | string): Response {
headers: { headers: {
'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400', 'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400',
'content-type': 'text/markdown; charset=utf-8', 'content-type': 'text/markdown; charset=utf-8',
// A mirror of an HTML page: AI agents read it, search engines must not
// index it as a duplicate — and should credit the HTML page instead.
'x-robots-tag': 'noindex',
...(options.canonical ? { link: `<${options.canonical}>; rel="canonical"` } : {}),
}, },
status: 200, status: 200,
}) })
} }
/** Canonical HTML URL of a Markdown page — same rule as the frontmatter `url:`. */
function canonicalOf(baseUrl: string | undefined, config: { locales: readonly unknown[] } | undefined, locale: string, slug?: string[]) {
if (!baseUrl) {return undefined}
const segments = config?.locales.length === 1 ? (slug ?? []) : [locale, ...(slug ?? [])]
return `${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, '')
}
type MarkdownRouteContext = { params: Promise<{ locale: string; slug?: string[] }> }
/**
* The whole Markdown route in one call — same options as createMarkdownRenderer
* plus `getCachedPayload`:
*
* // src/app/md/[locale]/[[...slug]]/route.ts
* import { createMarkdownRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { contentConfig } from '@/content.config'
* import { i18nConfig } from '@/i18n.config'
* export const dynamic = 'force-dynamic'
* export const { GET } = createMarkdownRoute({ getCachedPayload, content: contentConfig,
* config: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL })
*
* 404 for unknown/unpublished pages; a database error returns a generic 503
* (details only in the server log).
*/
export function createMarkdownRoute(
args: { getCachedPayload: () => Promise<BasePayload> } & CreateMarkdownRendererArgs,
): { GET: (req: Request, ctx: MarkdownRouteContext) => Promise<Response> } {
const { getCachedPayload, ...rendererArgs } = args
const render = createMarkdownRenderer(rendererArgs)
return {
GET: async (_req, { params }) => {
try {
const { slug, locale } = await params
const md = await render({ slug, locale, payload: await getCachedPayload() })
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
} catch (err) {
console.warn('[ipal] createMarkdownRoute: render failed:', err)
return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 })
}
},
}
}
+14 -4
View File
@@ -15,6 +15,8 @@ type GetArchiveEntriesArgs = {
collection: string collection: string
/** Relationship depth. Defaults to 1 — enough for a cover image. */ /** Relationship depth. Defaults to 1 — enough for a cover image. */
depth?: number depth?: number
/** Preview (draftMode): include unpublished entries and latest drafts. Default false. */
draft?: boolean
locale: string locale: string
/** 1-based. Values below 1 are clamped. */ /** 1-based. Values below 1 are clamped. */
page?: number page?: number
@@ -30,9 +32,10 @@ type GetArchiveEntriesArgs = {
/** /**
* Fetches one page of a collection's entries for an archive listing. * Fetches one page of a collection's entries for an archive listing.
* *
* Only published documents are returned when the collection has drafts enabled; * Only published documents are returned when the collection has drafts enabled
* Payload's `where` on `_status` is left to the caller, since a collection * (the `_status` filter is added automatically — only then, since a collection
* without drafts has no such field. * without drafts has no such field and querying it would throw). Pass
* `draft: true` for a preview.
* *
* Returns pagination facts rather than markup — the listing itself belongs to * Returns pagination facts rather than markup — the listing itself belongs to
* the client (as a block on the archive page, most likely), because how a list * the client (as a block on the archive page, most likely), because how a list
@@ -41,6 +44,7 @@ type GetArchiveEntriesArgs = {
export async function getArchiveEntries<T = Record<string, unknown>>({ export async function getArchiveEntries<T = Record<string, unknown>>({
collection, collection,
depth = 1, depth = 1,
draft = false,
locale, locale,
page = 1, page = 1,
payload, payload,
@@ -48,14 +52,20 @@ export async function getArchiveEntries<T = Record<string, unknown>>({
sort = '-createdAt', sort = '-createdAt',
where, where,
}: GetArchiveEntriesArgs): Promise<ArchiveEntries<T>> { }: GetArchiveEntriesArgs): Promise<ArchiveEntries<T>> {
const versions = payload.collections?.[collection as never]?.config?.versions as { drafts?: unknown } | false | undefined
const hasDrafts = Boolean(versions && versions.drafts)
const published = !draft && hasDrafts ? { _status: { equals: 'published' } } : undefined
const fullWhere = published && where ? { and: [published, where] } : (published ?? where)
const result = await payload.find({ const result = await payload.find({
collection: collection as never, collection: collection as never,
depth, depth,
draft,
limit: perPage, limit: perPage,
locale: locale as never, locale: locale as never,
page: Math.max(1, page), page: Math.max(1, page),
sort, sort,
...(where ? { where: where as never } : {}), ...(fullWhere ? { where: fullWhere as never } : {}),
}) })
return { return {
+1 -1
View File
@@ -1,6 +1,6 @@
export { buildArchiveFields } from './archiveFields.js' export { buildArchiveFields } from './archiveFields.js'
export { blocksToMarkdown } from './blocksToMarkdown.js' export { blocksToMarkdown } from './blocksToMarkdown.js'
export { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js' export { createMarkdownRenderer, createMarkdownRoute, markdownResponse } from './createMarkdownRenderer.js'
export { createSearchRoute } from './createSearchRoute.js' export { createSearchRoute } from './createSearchRoute.js'
export { getArchiveEntries } from './getArchiveEntries.js' export { getArchiveEntries } from './getArchiveEntries.js'
export type { ArchiveEntries } from './getArchiveEntries.js' export type { ArchiveEntries } from './getArchiveEntries.js'
+25 -3
View File
@@ -31,6 +31,12 @@ export type ResolvedRoute =
type ResolveRouteArgs = { type ResolveRouteArgs = {
content?: ContentOption content?: ContentOption
/**
* Preview (Next draftMode): return the latest draft instead of the published
* version, and resolve never-published pages. Default false — public
* requests only ever see published content.
*/
draft?: boolean
locale: string locale: string
/** Page number from the query string (?page=2). Defaults to 1. */ /** Page number from the query string (?page=2). Defaults to 1. */
page?: number page?: number
@@ -72,8 +78,20 @@ type ResolveRouteArgs = {
* make canonical and hreflang ambiguous (the same entry reachable under several * make canonical and hreflang ambiguous (the same entry reachable under several
* URLs). * URLs).
*/ */
/**
* Payload's `find` returns never-published documents from the main collection
* (with `_status: 'draft'`) unless asked otherwise — public routing must drop
* them, or an unpublished page is reachable by its URL.
*/
function isPublic(doc: unknown, draft: boolean): boolean {
if (draft || !doc || typeof doc !== 'object') {return Boolean(doc)}
const status = (doc as { _status?: unknown })._status
return status === undefined || status === null || status === 'published'
}
export async function resolveRoute({ export async function resolveRoute({
content, content,
draft = false,
locale, locale,
page = 1, page = 1,
pagesSlug = 'pages', pagesSlug = 'pages',
@@ -107,10 +125,11 @@ export async function resolveRoute({
id: homepageId, id: homepageId,
collection: pagesSlug, collection: pagesSlug,
depth: 2, depth: 2,
draft,
locale: locale as never, locale: locale as never,
}) })
return doc ? { type: 'home', doc: doc as Record<string, unknown> } : null return doc && isPublic(doc, draft) ? { type: 'home', doc: doc as Record<string, unknown> } : null
} }
const [first, ...rest] = segments const [first, ...rest] = segments
@@ -122,6 +141,7 @@ export async function resolveRoute({
const archiveDoc = archive as ArchivePage const archiveDoc = archive as ArchivePage
if (archiveDoc.slug !== first) {continue} if (archiveDoc.slug !== first) {continue}
if (!isPublic(archiveDoc, draft)) {return null}
// /pl/artykuly → the archive page itself. // /pl/artykuly → the archive page itself.
if (rest.length === 0) { if (rest.length === 0) {
@@ -139,12 +159,13 @@ export async function resolveRoute({
const found = await payload.find({ const found = await payload.find({
collection: collection.slug as never, collection: collection.slug as never,
depth: 2, depth: 2,
draft,
limit: 1, limit: 1,
locale: locale as never, locale: locale as never,
where: { slug: { equals: rest[0] } }, where: { slug: { equals: rest[0] } },
}) })
const entry = found.docs[0] const entry = found.docs[0]
if (!entry) {return null} if (!entry || !isPublic(entry, draft)) {return null}
return { return {
type: 'entry', type: 'entry',
@@ -162,12 +183,13 @@ export async function resolveRoute({
const found = await payload.find({ const found = await payload.find({
collection: pagesSlug as never, collection: pagesSlug as never,
depth: 2, depth: 2,
draft,
limit: 1, limit: 1,
locale: locale as never, locale: locale as never,
where: { slug: { equals: segments.join('/') } }, where: { slug: { equals: segments.join('/') } },
}) })
const doc = found.docs[0] const doc = found.docs[0]
if (!doc) {return null} if (!doc || !isPublic(doc, draft)) {return null}
// The page assigned as 404 in System Pages must not be reachable as a normal // The page assigned as 404 in System Pages must not be reachable as a normal
// 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat // 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat
+219
View File
@@ -0,0 +1,219 @@
'use client'
import type { ReactNode } from 'react'
import { useEffect, useRef } from 'react'
import type { BuilderField } from './builderTypes.js'
import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js'
import { honeypotInputProps } from './honeypot.js'
import { useBuilderForm } from './useBuilderForm.js'
/**
* Class names for every element — the plugin ships none. Set them once in the
* project (e.g. src/components/forms/formClasses.ts) and every panel form looks
* the same. Plain strings, so a server component can pass them.
*/
export type BuilderFormClassNames = Partial<
Record<
| 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices'
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'form' | 'formError' | 'input' | 'label'
| 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription'
| 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile',
string
>
>
export type BuilderFieldRenderArgs = {
/** The default markup for this field — return it to keep it, or wrap it. */
defaultRender: () => ReactNode
field: BuilderField
form: BuilderFormApi
/** Position in the panel's field list (key of `messages`). */
index: number
}
export type BuilderFormProps = {
classNames?: BuilderFormClassNames
/** Shown after success instead of the form (the form's confirmation message, rendered by RenderForm). */
confirmation?: ReactNode
/** Rendered `message` blocks, keyed by their index in form.fields (RenderForm fills it). */
messages?: Record<number, ReactNode>
/**
* Client-side only (use BuilderForm from a 'use client' file): replace the
* markup of chosen fields — a project's own field type, option cards, a
* slider. Return undefined to keep the default.
*/
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
/** Appended to required labels, e.g. "*". Default: nothing. */
requiredMark?: ReactNode
turnstileTheme?: 'auto' | 'dark' | 'light'
} & UseBuilderFormOptions
const cx = (...c: (false | null | string | undefined)[]) => c.filter(Boolean).join(' ') || undefined
/**
* Renders ANY panel form — single screen or step-by-step, text, e-mail, number,
* date, select, radio, checkbox, checkbox group, message blocks — with plain,
* accessible HTML and no styles. Look: `classNames` (+ `data-*` hooks:
* data-ipal="form", data-type, data-width, data-step). Different markup:
* `renderField`, or your own component on useBuilderForm.
*
* In a block, use RenderForm (/rsc) — it renders the rich text, binds the
* action and passes only the public part of the form to the browser.
*/
export function BuilderForm({
classNames: cn = {},
confirmation,
messages = {},
renderField,
requiredMark,
turnstileTheme,
...options
}: BuilderFormProps) {
const f = useBuilderForm(options)
const stepRef = useRef<HTMLDivElement>(null)
const firstRender = useRef(true)
// Moving between steps: focus the new step, so keyboard and screen-reader users land on it.
useEffect(() => {
if (firstRender.current) {
firstRender.current = false
return
}
const el = stepRef.current
const target = el?.querySelector<HTMLElement>('[aria-invalid="true"], input, select, textarea') ?? el
target?.focus()
}, [f.stepIndex])
if (f.isSuccess && options.form.confirmationType !== 'redirect') {
return (
<div className={cn.success} data-ipal="form-success" role="status">
{confirmation ?? f.resultMessage ?? options.texts.success}
</div>
)
}
const label = (field: BuilderField) => (
<>
{field.label}
{field.required && requiredMark ? <span aria-hidden className={cn.required}>{requiredMark}</span> : null}
</>
)
const errorOf = (field: BuilderField) => {
const error = field.name ? f.errors[field.name] : undefined
return error ? <p className={cn.error} id={f.errorId(field)}>{error}</p> : null
}
const defaultField = (field: BuilderField, index: number): ReactNode => {
if (field.blockType === 'message') {return <div className={cn.message}>{messages[index]}</div>}
switch (field.blockType) {
case 'checkbox': {
const props = f.getInputProps(field)
return (
<>
<label className={cn.checkboxLabel} htmlFor={props.id}>
<input {...props} className={cn.checkbox} />
<span>{label(field)}</span>
</label>
{errorOf(field)}
</>
)
}
case 'checkboxGroup':
case 'radio':
return (
<fieldset
aria-describedby={f.getFieldProps(field)['aria-describedby']}
aria-invalid={f.getFieldProps(field)['aria-invalid']}
className={cn.choices}
id={f.fieldId(field)}
>
<legend className={cn.legend}>{label(field)}</legend>
{(field.options ?? []).map((option, i) => {
const o = f.getOptionProps(field, option, i)
return (
<label className={cn.choice} htmlFor={o.id} key={option.value}>
<input {...o} className={cn.choiceInput} />
<span className={cn.choiceLabel}>{option.label ?? option.value}</span>
</label>
)
})}
{errorOf(field)}
</fieldset>
)
case 'select': {
const props = f.getSelectProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<select {...props} className={cn.select}>
<option value="">{field.placeholder ?? ''}</option>
{(field.options ?? []).map((o) => <option key={o.value} value={o.value}>{o.label ?? o.value}</option>)}
</select>
{errorOf(field)}
</>
)
}
case 'textarea': {
const props = f.getTextareaProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<textarea {...props} className={cn.textarea} rows={5} />
{errorOf(field)}
</>
)
}
default: {
const props = f.getInputProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<input {...props} className={cn.input} />
{errorOf(field)}
</>
)
}
}
}
const { step } = f
const progress = options.texts.stepOf?.replace('{current}', String(f.stepIndex + 1)).replace('{total}', String(f.total))
return (
<form className={cn.form} data-ipal="form" data-step={f.stepIndex + 1} noValidate onSubmit={f.submit}>
<input {...honeypotInputProps()} />
{f.total > 1 && progress ? <p aria-live="polite" className={cn.progress}>{progress}</p> : null}
<div className={cn.step} data-ipal="form-step" ref={stepRef} tabIndex={-1}>
{step.title ? <p className={cn.stepTitle}>{step.title}</p> : null}
{step.description ? <p className={cn.stepDescription}>{step.description}</p> : null}
<div className={cn.fields}>
{step.fields.map(({ field, index }) => {
const half = typeof field.width === 'number' && field.width <= 50
const content = renderField?.({ defaultRender: () => defaultField(field, index), field, form: f, index }) ?? defaultField(field, index)
return (
<div
className={cx(cn.field, half ? cn.fieldHalf : cn.fieldFull)}
data-type={field.blockType}
data-width={field.width ?? 100}
key={field.id ?? `${field.blockType}-${index}`}
>
{content}
</div>
)
})}
</div>
</div>
{f.isLast ? <div className={cn.turnstile}><f.TurnstileWidget theme={turnstileTheme} /></div> : null}
{f.errorMessage ? <p className={cn.formError} role="alert">{f.errorMessage}</p> : null}
<div className={cn.actions}>
{!f.isFirst ? <button className={cn.back} onClick={f.back} type="button">{options.texts.back ?? 'Back'}</button> : null}
<button className={f.isLast ? cn.submit : (cn.next ?? cn.submit)} disabled={f.isSubmitting} type="submit">
{f.isLast ? options.form.submitButtonLabel || 'Send' : options.texts.next ?? 'Next'}
</button>
</div>
</form>
)
}
+109
View File
@@ -0,0 +1,109 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import type { ReactNode } from 'react'
import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js'
import type { BuilderFormClassNames } from './BuilderForm.js'
import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js'
import type { SubmitActionResult } from './createSubmitAction.js'
import { resolveLinkHref, safeHref } from '../links/resolveLinkHref.js'
import { RenderRichText } from '../richtext/RenderRichText.js'
import { BuilderForm } from './BuilderForm.js'
/** The action from createSubmitAction — `sendForm(formId, locale, values, token?)`. */
export type SendFormAction = (
formId: string,
locale: string,
values: Record<string, unknown>,
turnstileToken?: string,
) => Promise<SubmitActionResult>
export type RenderFormProps = {
/** The project's `sendForm` server action (createSubmitAction). */
action: SendFormAction
classNames?: BuilderFormClassNames
/** Rich text styling for message blocks and the confirmation (same as RenderRichText). */
converters?: JSXConvertersFunction
/** The `form` relationship of the block, populated (page query depth ≥ 1). An id or null renders nothing. */
form: BuilderFormDoc | null | number | string | undefined
/**
* For redirect forms pointing at a page: `{ config: i18nConfig, homeSlug }`
* (locale is added). Without it only a custom URL redirect works.
*/
linkOptions?: Omit<ResolveLinkHrefOptions, 'locale'>
locale: string
requiredMark?: ReactNode
richTextClassName?: string
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
texts: BuilderFormTexts
turnstileTheme?: 'auto' | 'dark' | 'light'
}
/** Only what the browser needs. The Local API reads with overrideAccess, so the
* document still carries Emails (recipient addresses) — those never leave the server. */
function publicForm(form: BuilderFormDoc): BuilderFormDoc {
return {
id: form.id,
analytics: form.analytics,
confirmationType: form.confirmationType,
fields: (form.fields ?? []).map(({ message: _message, ...field }: BuilderField) => field),
redirect: form.redirect?.type === 'custom' || form.redirect?.url ? { url: safeHref(form.redirect?.url) } : null,
submitButtonLabel: form.submitButtonLabel,
title: form.title,
}
}
/**
* A panel form inside a block, in one line — server part of BuilderForm:
*
* <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
*
* Renders `message` blocks and the confirmation with RenderRichText, binds the
* action to the form and locale, resolves the redirect target, and passes the
* client only the public part of the form (never the Emails tab).
*/
export function RenderForm({
action,
classNames,
converters,
form,
linkOptions,
locale,
requiredMark,
richTextClassName,
texts,
turnstileTheme,
}: RenderFormProps) {
if (!form || typeof form !== 'object') {return null} // never a placeholder form
const rich = (data: unknown) =>
data ? <RenderRichText className={richTextClassName} converters={converters} data={data as SerializedEditorState} /> : null
const messages: Record<number, ReactNode> = {}
form.fields?.forEach((field, i) => {
if (field.blockType === 'message' && field.message) {messages[i] = rich(field.message)}
})
const page = form.redirect?.type === 'reference' ? (form.redirect.reference as { value?: unknown } | null)?.value : undefined
const redirectHref =
form.confirmationType === 'redirect'
? page && linkOptions
? resolveLinkHref({ type: 'internal', page }, { ...linkOptions, locale })
: safeHref(form.redirect?.url)
: null
return (
<BuilderForm
action={action.bind(null, String(form.id), locale)}
classNames={classNames}
confirmation={rich(form.confirmationMessage)}
form={publicForm(form)}
messages={messages}
redirectHref={redirectHref}
requiredMark={requiredMark}
texts={texts}
turnstileTheme={turnstileTheme}
/>
)
}
+74
View File
@@ -0,0 +1,74 @@
import type { Block, Field } from 'payload'
/**
* Extra form-builder field types — what the built-in set can't express:
*
* - `step` — a divider: fields below it (until the next Step) are one
* screen of a step-by-step form, with Next / Back buttons.
* Carries no value.
* - `checkboxGroup` — a list of options where the visitor ticks several
* ("Services you're interested in"). Value: string[].
*
* Plain English labels (the panel is EN). Rendered by BuilderForm /
* useBuilderForm, validated by submitForm like every other field.
*/
const name: Field = {
name: 'name',
type: 'text',
admin: { description: 'Technical name, e.g. "services" — no spaces.', width: '50%' },
label: 'Name (lowercase, no special characters)',
required: true,
}
const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true }
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' }
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' }
export const stepBlock: Block = {
slug: 'step',
fields: [
{
name: 'title',
type: 'text',
admin: {
description:
'Starts a new step: the fields below it (until the next Step) are shown together, with Next / Back buttons. Leave the form without Steps for a single-screen form.',
},
label: 'Step title',
localized: true,
},
{ name: 'description', type: 'textarea', admin: { rows: 2 }, label: 'Step description', localized: true },
],
labels: { plural: 'Steps', singular: 'Step' },
}
export const checkboxGroupBlock: Block = {
slug: 'checkboxGroup',
fields: [
{ type: 'row', fields: [name, label] },
{ type: 'row', fields: [width, required] },
{
name: 'options',
type: 'array',
fields: [
{
type: 'row',
fields: [
{ name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true, required: true },
{ name: 'value', type: 'text', admin: { width: '50%' }, label: 'Value', required: true },
],
},
],
labels: { plural: 'Options', singular: 'Option' },
minRows: 1,
},
{
type: 'row',
fields: [
{ name: 'minSelected', type: 'number', admin: { description: 'Empty = no minimum (Required = at least one).', width: '50%' }, label: 'Minimum selected', min: 0 },
{ name: 'maxSelected', type: 'number', admin: { description: 'Empty = no limit.', width: '50%' }, label: 'Maximum selected', min: 1 },
],
},
],
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
}
+96
View File
@@ -0,0 +1,96 @@
import type { BuilderField, BuilderFormTexts, BuilderStep } from './builderTypes.js'
import { NON_INPUT_TYPES } from './builderTypes.js'
import { isEmail } from './validators.js'
/**
* Pure logic of a panel form — steps, initial values, validation. No React, so
* it's shared by useBuilderForm and tested on its own. The server re-checks
* everything (validateSubmission); this is only for instant feedback.
*/
/** Fields that hold a value (have a name and aren't message/step). */
export function inputFields(fields: BuilderField[] | null | undefined): ({ name: string } & BuilderField)[] {
return (fields ?? []).filter(
(f): f is { name: string } & BuilderField => typeof f.name === 'string' && f.name !== '' && !NON_INPUT_TYPES.has(f.blockType),
)
}
/**
* Splits the field list at `step` blocks. Fields before the first Step form
* the first screen; a form without Steps is one screen.
*/
export function splitSteps(fields: BuilderField[] | null | undefined): BuilderStep[] {
const steps: BuilderStep[] = []
let current: BuilderStep | null = null
;(fields ?? []).forEach((field, index) => {
if (field.blockType === 'step') {
current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined }
steps.push(current)
return
}
if (!current) {
current = { fields: [], index: 0 }
steps.push(current)
}
current.fields.push({ field, index })
})
// Drop screens a trailing / doubled Step left empty.
const kept = steps.filter((s) => s.fields.length > 0)
return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i }))
}
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
return Object.fromEntries(
inputFields(fields).map((f) => {
if (f.blockType === 'checkbox') {return [f.name, f.defaultValue === true]}
if (f.blockType === 'checkboxGroup') {return [f.name, Array.isArray(f.defaultValue) ? f.defaultValue : []]}
const v = f.defaultValue
return [f.name, typeof v === 'string' || typeof v === 'number' ? String(v) : '']
}),
)
}
const isBlank = (v: unknown) =>
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
/** Errors for the given fields (one message per field), empty object = valid. */
export function validateBuilderFields(
fields: BuilderField[],
values: Record<string, unknown>,
texts: Pick<BuilderFormTexts, 'validation'>,
): Record<string, string> {
const errors: Record<string, string> = {}
for (const f of inputFields(fields)) {
const v = values[f.name]
const msg = texts.validation.replace('{field}', f.label || f.name)
if (isBlank(v)) {
if (f.required) {errors[f.name] = msg}
continue
}
if (f.blockType === 'email' && !isEmail(v)) {errors[f.name] = msg}
else if (f.blockType === 'number' && !Number.isFinite(Number(v))) {errors[f.name] = msg}
else if (f.blockType === 'checkboxGroup' && Array.isArray(v)) {
if ((f.minSelected && v.length < f.minSelected) || (f.maxSelected && v.length > f.maxSelected)) {errors[f.name] = msg}
}
}
return errors
}
/** Index of the step holding a field — to jump back to it after a failed submit. */
export function stepOfField(steps: BuilderStep[], name: string): number {
const i = steps.findIndex((s) => s.fields.some(({ field }) => field.name === name))
return i < 0 ? 0 : i
}
/** Browser autofill hint from the field type / a conventional name. */
export function autoCompleteFor(field: BuilderField): string | undefined {
if (field.blockType === 'email') {return 'email'}
if (field.blockType === 'country') {return 'country-name'}
const n = (field.name ?? '').toLowerCase()
if (/^(?:full_?)?name$|^imie/.test(n)) {return 'name'}
if (/phone|tel/.test(n)) {return 'tel'}
if (/company|organi[sz]ation|firma/.test(n)) {return 'organization'}
return undefined
}
+69
View File
@@ -0,0 +1,69 @@
import type { FormAnalyticsConfig } from './formAnalytics.js'
/**
* Shapes of a panel form as the frontend receives it (form-builder + ipal's
* step / checkboxGroup). Loose on purpose — the project's generated types fit.
*/
export type BuilderOption = { label?: null | string; value: string }
export type BuilderField = {
blockName?: null | string
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
blockType: string
defaultValue?: unknown
/** step */
description?: null | string
id?: null | string
label?: null | string
maxSelected?: null | number
/** message — rich text, rendered on the server (RenderForm) */
message?: unknown
minSelected?: null | number
name?: null | string
options?: BuilderOption[] | null
placeholder?: null | string
required?: boolean | null
/** step */
title?: null | string
width?: null | number
}
export type BuilderFormDoc = {
analytics?: FormAnalyticsConfig
confirmationMessage?: unknown
confirmationType?: 'message' | 'redirect' | null
fields?: BuilderField[] | null
id: number | string
redirect?: { reference?: unknown; type?: 'custom' | 'reference' | null; url?: null | string } | null
submitButtonLabel?: null | string
title?: null | string
}
/** Texts the form needs — Notifications → form (getNotificationTexts) fits. */
export type BuilderFormTexts = {
back?: string
error?: string
next?: string
/** "Step {current} of {total}" */
stepOf?: string
success?: string
/** "Please check the {field} field" */
validation: string
}
/** The bound server action: createSubmitAction(...) bound to formId + locale (RenderForm does it). */
export type BuilderFormAction = (
values: Record<string, unknown>,
turnstileToken?: string,
) => Promise<{ field?: string; message?: string; reason?: string; success: boolean }>
export type BuilderStep = {
description?: string
/** Every field of the step, `message` blocks included, in panel order. */
fields: { field: BuilderField; index: number }[]
index: number
title?: string
}
/** Field types that carry no value. */
export const NON_INPUT_TYPES = new Set(['message', 'step'])
+92
View File
@@ -0,0 +1,92 @@
import 'server-only'
import type { BasePayload } from 'payload'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'
import { getNotificationTexts } from '../notifications/getNotificationTexts.js'
import { resolveFormMessage } from '../notifications/resolveFormMessage.js'
import { clientIp } from '../shared/rateLimit.js'
import { HONEYPOT_FIELD, isHoneypotTripped } from './honeypot.js'
import { submitForm } from './submitForm.js'
type CreateSubmitActionArgs = {
/** Optional: IP options (default IPAL_IP_HEADER env / clientIp defaults). */
clientIp?: ClientIpOptions
getCachedPayload: () => Promise<BasePayload>
/**
* `headers` from 'next/headers', INJECTED (the plugin never imports next/*,
* same pattern as NextResponse in createProxy). Called inside the action only.
*/
headers: () => Headers | Promise<Headers>
/** Honeypot field name. Default HONEYPOT_FIELD. */
honeypotField?: string
} & Pick<SubmitFormArgs, 'consentFieldName' | 'maxPerMinute' | 'turnstileOnConfigError'>
export type SubmitActionResult = {
field?: string
/** Text for the visitor, from Notifications in this locale. */
message: string
/** Why it failed — for the renderer to mark a field (`field`) or reset Turnstile. */
reason?: Exclude<SubmitFormResult, { success: true }>['reason']
success: boolean
}
/**
* The one server action every panel form posts to — honeypot → client IP →
* submitForm (rate limit, Turnstile, schema validation, GDPR consent, storage)
* → the visitor message from Notifications in the page's locale.
*
* // src/app/(frontend)/[locale]/actions.ts
* 'use server'
* import { headers } from 'next/headers'
* import { createSubmitAction } from '@intecion/ipal-kit/server'
* import { getCachedPayload } from '@/lib/content'
* export const sendForm = createSubmitAction({ getCachedPayload, headers })
*
* Signature matches the ipal-form FormRenderer: `sendForm(formId, locale, values,
* turnstileToken?)` — bind formId and locale in the block (`sendForm.bind(null, id, locale)`).
* A tripped honeypot gets a fake success and stores nothing.
*/
export function createSubmitAction({
clientIp: ipOptions,
consentFieldName,
getCachedPayload,
headers,
honeypotField = HONEYPOT_FIELD,
maxPerMinute,
turnstileOnConfigError,
}: CreateSubmitActionArgs) {
return async function sendForm(
formId: string,
locale: string,
values: Record<string, unknown>,
turnstileToken?: string,
): Promise<SubmitActionResult> {
const payload = await getCachedPayload()
const texts = (await getNotificationTexts({ locale, payload })).form
const data = values && typeof values === 'object' ? values : {}
if (isHoneypotTripped(data, honeypotField)) {return { message: texts.success, success: true }}
const { [honeypotField]: _honeypot, ...fields } = data
const ip = clientIp(await headers(), ipOptions) || undefined
const result = await submitForm({
consentFieldName,
data: fields,
formId: String(formId),
ip,
maxPerMinute,
payload,
turnstileOnConfigError,
turnstileToken: typeof turnstileToken === 'string' ? turnstileToken.trim() || undefined : undefined,
})
const message = resolveFormMessage(result, texts)
if (result.success) {return { message, success: true }}
return {
message,
reason: result.reason,
success: false,
...('field' in result && result.field ? { field: result.field } : {}),
}
}
}
+44 -3
View File
@@ -1,11 +1,39 @@
import type { Plugin } from 'payload' import type { Field, Plugin } from 'payload'
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder' import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { FormsOption } from './types.js' import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
import { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
type AccessArgs = { req: { user?: unknown } }
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */ /** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: { req: { user?: unknown } }) => Boolean(req.user) const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user)
/**
* Submissions are visitors' personal data: editors and admins only. The
* form-builder default lets ANY account of the admin collection read them —
* including a plain 'user' from an open sign-up.
*/
const submissionsReadAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor')
const submissionsDeleteAccess = ({ req }: AccessArgs) => isAdmin(req.user as never)
/**
* Forms stay publicly readable (their fields render the form), but the Emails
* tab — recipient addresses, templates — is for logged-in staff only, so
* GET /api/forms doesn't hand out the company's inboxes to spammers.
*/
function hideEmails(fields: Field[]): Field[] {
return fields.map((field) =>
'name' in field && field.name === 'emails'
? ({
...field,
access: { ...(field as { access?: object }).access, read: ({ req }: AccessArgs) => Boolean(req.user) },
} as Field)
: field,
)
}
/** /**
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption. * Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
@@ -25,16 +53,25 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {} const group = adminGroup ? { group: adminGroup } : {}
return formBuilderPlugin({ return formBuilderPlugin({
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are
// panel choices only — a form uses what the editor adds, nothing changes on
// existing forms. Switch any off with forms.fields.<type>: false.
fields: { fields: {
checkbox: true, checkbox: true,
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
date: true,
email: true, email: true,
message: true, message: true,
number: true, number: true,
payment: false, payment: false,
radio: true,
select: true, select: true,
step: forms.fields?.step === false ? false : stepBlock,
text: true, text: true,
textarea: true, textarea: true,
...forms.fields, ...Object.fromEntries(
Object.entries(forms.fields ?? {}).filter(([k]) => k !== 'checkboxGroup' && k !== 'step'),
),
}, },
...(forms.redirectRelationships ...(forms.redirectRelationships
? { redirectRelationships: forms.redirectRelationships } ? { redirectRelationships: forms.redirectRelationships }
@@ -48,12 +85,16 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
labels: { plural: 'Forms', singular: 'Form' }, labels: { plural: 'Forms', singular: 'Form' },
...forms.formOverrides, ...forms.formOverrides,
admin: { ...group, ...forms.formOverrides?.admin }, admin: { ...group, ...forms.formOverrides?.admin },
fields: ({ defaultFields }) =>
hideEmails(forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields }) : defaultFields),
}, },
formSubmissionOverrides: { formSubmissionOverrides: {
labels: { plural: 'Submissions', singular: 'Submission' }, labels: { plural: 'Submissions', singular: 'Submission' },
...forms.formSubmissionOverrides, ...forms.formSubmissionOverrides,
access: { access: {
create: submissionsCreateAccess, create: submissionsCreateAccess,
delete: submissionsDeleteAccess,
read: submissionsReadAccess,
...forms.formSubmissionOverrides?.access, ...forms.formSubmissionOverrides?.access,
}, },
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin }, admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
+5
View File
@@ -1,3 +1,8 @@
// Panel field types: step-by-step forms + multiple choice (enabled by default).
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './builderTypes.js'
export { formAnalyticsOnSuccess } from './formAnalytics.js' export { formAnalyticsOnSuccess } from './formAnalytics.js'
export type { FormAnalyticsConfig } from './formAnalytics.js' export type { FormAnalyticsConfig } from './formAnalytics.js'
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client). // Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
+3 -2
View File
@@ -61,7 +61,7 @@ export type SubmitFailure =
/** The offending field's name, when one field is at fault. */ /** The offending field's name, when one field is at fault. */
field?: string field?: string
/** What was wrong with it. */ /** What was wrong with it. */
kind?: 'required' | 'too_long' | 'unknown_fields' kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
reason: 'validation' reason: 'validation'
success: false success: false
} }
@@ -147,7 +147,8 @@ export async function submitForm({
form: formId, form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({ submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
field, field,
value: value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string), // checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
value: value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
})), })),
} as never, } as never,
}) })
+9
View File
@@ -34,11 +34,20 @@ export type FormsOption = {
/** Field types available in the form builder. Sensible defaults applied. */ /** Field types available in the form builder. Sensible defaults applied. */
fields?: { fields?: {
checkbox?: boolean checkbox?: boolean
/** Multiple choice from a list (ipal). Default on. */
checkboxGroup?: boolean
country?: boolean
date?: boolean
email?: boolean email?: boolean
message?: boolean message?: boolean
number?: boolean number?: boolean
payment?: boolean payment?: boolean
/** Single choice from a list. Default on. */
radio?: boolean
select?: boolean select?: boolean
state?: boolean
/** Step-by-step forms: divider between screens (ipal). Default on. */
step?: boolean
text?: boolean text?: boolean
textarea?: boolean textarea?: boolean
} }
+268
View File
@@ -0,0 +1,268 @@
'use client'
import type { ChangeEvent } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts, BuilderOption } from './builderTypes.js'
import { safeHref } from '../links/resolveLinkHref.js'
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
import { formAnalyticsOnSuccess } from './formAnalytics.js'
import { useForm } from './useForm.js'
export type UseBuilderFormOptions = {
/** Bound server action (RenderForm binds createSubmitAction to formId + locale). */
action: BuilderFormAction
form: BuilderFormDoc
/** Router navigation for redirect forms (e.g. router.push). Default: window.location.assign. */
navigate?: (href: string) => void
/** After a successful submit — on top of the panel's analytics event. */
onSuccess?: (values: Record<string, unknown>) => void
/** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */
redirectHref?: null | string
texts: BuilderFormTexts
}
/**
* Engine of every panel form: steps, values, per-step validation, Turnstile,
* submit through the server action, field errors from the server, redirect,
* analytics — and NO markup. <BuilderForm> renders a default on top of it; a
* form that looks or behaves differently (cards to pick from, a summary step,
* a custom field type) builds its own markup on the same hook:
*
* const f = useBuilderForm({ form, action, texts })
* <form onSubmit={f.submit}>
* {f.step.fields.map(({ field }) => <input key={field.name} {...f.getInputProps(field)} />)} // getTextareaProps, getSelectProps, getOptionProps
* <f.TurnstileWidget />
* {!f.isFirst && <button type="button" onClick={f.back}>{texts.back}</button>}
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
* </form>
*/
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
const fields = useMemo(() => form.fields ?? [], [form.fields])
const steps = useMemo(() => splitSteps(fields), [fields])
const inputs = useMemo(() => inputFields(fields), [fields])
const [stepIndex, setStepIndex] = useState(0)
const [resultMessage, setResultMessage] = useState<null | string>(null)
const ts = useOptionalTurnstile()
// A field error returned by the server (e.g. "email invalid") — applied after useForm records the failure.
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
const submitAction = useCallback(
async (values: Record<string, unknown>, token?: string) => {
const result = await action(values, token)
if (result.success) {setResultMessage(result.message ?? null)}
else if (result.field) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }}
return result
},
[action, texts.validation],
)
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(inputs, values, texts), [inputs, texts])
const f = useForm<Record<string, unknown>>({
errorFallback: texts.error,
initialValues: initialBuilderValues(fields),
onSuccess: (_result, values) => {
formAnalyticsOnSuccess(form.analytics)(_result, values)
onSuccess?.(values)
if (form.confirmationType === 'redirect') {
const href = redirectHref ?? safeHref(form.redirect?.url)
if (href) {(navigate ?? ((h: string) => window.location.assign(h)))(href)}
}
},
requireTurnstile: ts.enabled,
submitAction,
validate,
})
const { setErrors, setTurnstileToken } = f
// Turnstile token lives in the provider; the engine needs it at submit.
useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken])
useEffect(() => {
if (!f.errorMessage) {return}
ts.reset()
const fieldError = serverFieldError.current
serverFieldError.current = null
if (fieldError) {
setErrors({ [fieldError.field]: fieldError.message })
setStepIndex(stepOfField(steps, fieldError.field))
}
}, [f.errorMessage])
const step = steps[Math.min(stepIndex, steps.length - 1)]
const isFirst = stepIndex === 0
const isLast = stepIndex >= steps.length - 1
/** Validates the current step and moves on. Returns false when the step has errors. */
const next = useCallback(() => {
const errors = validateBuilderFields(step.fields.map(({ field }) => field), f.values, texts)
setErrors(errors)
if (Object.keys(errors).length) {return false}
setStepIndex((i) => Math.min(i + 1, steps.length - 1))
return true
}, [step, f.values, texts, setErrors, steps.length])
const back = useCallback(() => setStepIndex((i) => Math.max(i - 1, 0)), [])
/** Jump to a step that's already been passed (a clickable progress bar). Forward jumps validate on the way. */
const goTo = useCallback(
(target: number) => {
if (target <= stepIndex) {return setStepIndex(Math.max(target, 0))}
for (let i = stepIndex; i < target; i++) {
const errors = validateBuilderFields(steps[i].fields.map(({ field }) => field), f.values, texts)
if (Object.keys(errors).length) {
setErrors(errors)
return setStepIndex(i)
}
}
setStepIndex(Math.min(target, steps.length - 1))
},
[stepIndex, steps, f.values, texts, setErrors],
)
/** onSubmit of the <form>: Next on earlier steps, send on the last one. */
const submit = useCallback(
(e?: { preventDefault?: () => void }) => {
e?.preventDefault?.()
if (!isLast) {return void next()}
const errors = validate(f.values)
if (Object.keys(errors).length) {
setErrors(errors)
return setStepIndex(stepOfField(steps, Object.keys(errors)[0]))
}
void f.handleSubmit()
},
[isLast, next, validate, f, setErrors, steps],
)
const fieldId = useCallback((field: BuilderField) => `ipal-f-${String(form.id)}-${field.name ?? ''}`, [form.id])
const errorId = useCallback((field: BuilderField) => `${fieldId(field)}-error`, [fieldId])
/** id, name, required and aria for any field's control (or its fieldset). */
const getFieldProps = useCallback(
(field: BuilderField) => {
const error = field.name ? f.errors[field.name] : undefined
return {
id: fieldId(field),
name: field.name ?? undefined,
'aria-describedby': error ? errorId(field) : undefined,
'aria-invalid': error ? true : undefined,
required: Boolean(field.required),
}
},
[f.errors, errorId, fieldId],
)
const textValue = useCallback((name: string) => {
const value = f.values[name]
return typeof value === 'string' ? value : value == null ? '' : String(value as number)
}, [f.values])
/** Everything an <input> needs, by field type: text · email · number · date · tel · checkbox. */
const getInputProps = useCallback(
(field: BuilderField) => {
const name = field.name ?? ''
const base = { ...getFieldProps(field), autoComplete: autoCompleteFor(field) }
if (field.blockType === 'checkbox') {
return { ...base, type: 'checkbox', checked: f.values[name] === true, onChange: (e: ChangeEvent<HTMLInputElement>) => f.setField(name, e.target.checked) }
}
const type =
field.blockType === 'email' ? 'email'
: field.blockType === 'number' ? 'number'
: field.blockType === 'date' ? 'date'
: base.autoComplete === 'tel' ? 'tel'
: 'text'
return {
...base,
...(type === 'number' ? { inputMode: 'decimal' as const } : {}),
type,
onChange: (e: ChangeEvent<HTMLInputElement>) => f.setField(name, e.target.value),
placeholder: field.placeholder ?? undefined,
value: textValue(name),
}
},
[f, getFieldProps, textValue],
)
/** Props of a <textarea>. */
const getTextareaProps = useCallback(
(field: BuilderField) => ({
...getFieldProps(field),
onChange: (e: ChangeEvent<HTMLTextAreaElement>) => f.setField(field.name ?? '', e.target.value),
placeholder: field.placeholder ?? undefined,
value: textValue(field.name ?? ''),
}),
[f, getFieldProps, textValue],
)
/** Props of a <select> (render the options yourself — field.options). */
const getSelectProps = useCallback(
(field: BuilderField) => ({
...getFieldProps(field),
autoComplete: autoCompleteFor(field),
onChange: (e: ChangeEvent<HTMLSelectElement>) => f.setField(field.name ?? '', e.target.value),
value: textValue(field.name ?? ''),
}),
[f, getFieldProps, textValue],
)
/** Props of one option's input in a radio group or checkboxGroup. */
const getOptionProps = useCallback(
(field: BuilderField, option: BuilderOption, i: number) => {
const name = field.name ?? ''
const id = `${fieldId(field)}-${i}`
if (field.blockType === 'checkboxGroup') {
const picked = Array.isArray(f.values[name]) ? (f.values[name] as string[]) : []
return {
id,
name,
type: 'checkbox',
checked: picked.includes(option.value),
onChange: (e: ChangeEvent<HTMLInputElement>) =>
f.setField(name, e.target.checked ? [...picked, option.value] : picked.filter((v) => v !== option.value)),
value: option.value,
}
}
return {
id,
name,
type: 'radio',
checked: f.values[name] === option.value,
onChange: () => f.setField(name, option.value),
required: Boolean(field.required) && i === 0,
value: option.value,
}
},
[f, fieldId],
)
return {
...f,
back,
errorId,
fieldId,
form,
getFieldProps,
getInputProps,
getOptionProps,
getSelectProps,
getTextareaProps,
goTo,
isFirst,
isLast,
next,
/** Message the server returned on success (Notifications → success). */
resultMessage,
step,
stepIndex,
steps,
submit,
total: steps.length,
TurnstileWidget: ts.TurnstileWidget,
}
}
export type BuilderFormApi = ReturnType<typeof useBuilderForm>
+92 -5
View File
@@ -4,7 +4,12 @@ import type { BasePayload } from 'payload'
type FormField = { type FormField = {
blockType?: string blockType?: string
label?: string label?: string
/** checkboxGroup limits. */
maxSelected?: null | number
minSelected?: null | number
name?: string name?: string
/** select / radio / checkboxGroup choices defined in the panel. */
options?: { value?: unknown }[] | null
required?: boolean | null required?: boolean | null
} }
@@ -24,7 +29,7 @@ export type FormValidationResult =
| { | {
/** Offending field, when a single field is at fault. */ /** Offending field, when a single field is at fault. */
field?: string field?: string
kind: 'required' | 'too_long' | 'unknown_fields' kind: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
ok: false ok: false
reason: 'invalid' reason: 'invalid'
} }
@@ -33,7 +38,10 @@ export type FormValidationResult =
| { ok: false; reason: 'not_found' } | { ok: false; reason: 'not_found' }
/** Field block types that don't carry a submittable value. */ /** Field block types that don't carry a submittable value. */
const NON_DATA_BLOCKS = new Set(['message']) const NON_DATA_BLOCKS = new Set(['message', 'step'])
/** YYYY-MM-DD (a date input) or a full ISO timestamp. */
const DATE = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/
/** /**
* Keys injected by the captcha widget itself, not by the form definition. * Keys injected by the captcha widget itself, not by the form definition.
@@ -47,6 +55,77 @@ const CAPTCHA_KEYS = new Set(['cf-turnstile-response', 'g-recaptcha-response'])
/** Hard ceiling on a single field's length, independent of the form config. */ /** Hard ceiling on a single field's length, independent of the form config. */
const MAX_FIELD_LENGTH = 5000 const MAX_FIELD_LENGTH = 5000
/**
* ONE address, nothing else. The form-builder can send a confirmation to
* `{{email}}`, so a value like "[email protected], [email protected]" or one with a line break would
* turn the site into a spam relay (and CR/LF into header injection). Commas,
* semicolons, whitespace and angle brackets are rejected outright.
*/
const EMAIL = /^[^\s@,;<>"()[\]\\]+@[^\s"(),;<>@[\\\]][^\s"(),.;<>@[\\\]]*\.[^\s"(),;<>@[\\\]]{2,}$/
const MAX_EMAIL_LENGTH = 254
// Control characters except tab and line breaks (U+0000–U+001F, U+007F), plus
// bidi overrides that can disguise text in the admin panel and e-mails.
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u0008\v\f\u000E-\u001F\u007F\u202A-\u202E\u2066-\u2069]/g
type Checked = { error?: 'invalid_format' | 'required'; value?: unknown }
/**
* Type-checks one value against its field's block type, as defined in the
* panel, and normalizes it. Anything not a plain value for that type is
* rejected — a hand-crafted request can't smuggle objects, extra recipients or
* values outside a select's options.
*/
function checkValue(field: FormField, value: unknown): Checked {
if (value === undefined || value === null || value === '') {return { value }}
switch (field.blockType) {
case 'checkbox':
return typeof value === 'boolean' ? { value } : { error: 'invalid_format' }
case 'checkboxGroup': {
// string[] of distinct option values, within the panel's min/max.
if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {return { error: 'invalid_format' }}
const picked = [...new Set(value as string[])]
const allowed = new Set((field.options ?? []).map((o) => String(o?.value)))
if (picked.some((v) => !allowed.has(v))) {return { error: 'invalid_format' }}
if (picked.length === 0) {return { value: undefined }}
if (field.minSelected && picked.length < field.minSelected) {return { error: 'required' }}
if (field.maxSelected && picked.length > field.maxSelected) {return { error: 'invalid_format' }}
return { value: picked }
}
case 'date': {
if (typeof value !== 'string' || !DATE.test(value.trim()) || Number.isNaN(Date.parse(value.trim()))) {
return { error: 'invalid_format' }
}
return { value: value.trim() }
}
case 'email': {
if (typeof value !== 'string') {return { error: 'invalid_format' }}
const email = value.trim()
return email.length <= MAX_EMAIL_LENGTH && EMAIL.test(email) ? { value: email } : { error: 'invalid_format' }
}
case 'number': {
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN
return Number.isFinite(n) ? { value: n } : { error: 'invalid_format' }
}
case 'radio':
case 'select': {
if (typeof value !== 'string' && typeof value !== 'number') {return { error: 'invalid_format' }}
const allowed = (field.options ?? []).map((o) => String(o?.value))
// No options configured → nothing to compare against; still a plain value.
return allowed.length === 0 || allowed.includes(String(value)) ? { value } : { error: 'invalid_format' }
}
case 'textarea':
return typeof value === 'string' ? { value: value.replace(CONTROL, '') } : { error: 'invalid_format' }
default:
// text, country, state and custom blocks: one line of plain text.
if (typeof value === 'number') {return { value }}
return typeof value === 'string'
? { value: value.replace(CONTROL, '').replace(/[\r\n]+/g, ' ') }
: { error: 'invalid_format' }
}
}
/** /**
* Default name for a GDPR consent field. A checkbox with this name is treated * Default name for a GDPR consent field. A checkbox with this name is treated
* as a consent gate: it MUST be checked for the submission to go through, * as a consent gate: it MUST be checked for the submission to go through,
@@ -98,7 +177,10 @@ export async function validateSubmission(
for (const field of fields) { for (const field of fields) {
const value = data[field.name] const value = data[field.name]
const isBlank = const isBlank =
value == null || (typeof value === 'string' && value.trim() === '') || value === false value == null ||
(typeof value === 'string' && value.trim() === '') ||
value === false ||
(Array.isArray(value) && value.length === 0)
// GDPR consent gate: a field matching the consent name must be truthy // GDPR consent gate: a field matching the consent name must be truthy
// (checked). Enforced independently of `required`, so it can't be weakened // (checked). Enforced independently of `required`, so it can't be weakened
@@ -116,10 +198,15 @@ export async function validateSubmission(
return { field: field.name, kind: 'too_long', ok: false, reason: 'invalid' } return { field: field.name, kind: 'too_long', ok: false, reason: 'invalid' }
} }
const checked = field.name === consentFieldName ? { value } : checkValue(field, value)
if (checked.error) {
return { field: field.name, kind: checked.error, ok: false, reason: 'invalid' }
}
// Only carry through keys that belong to the form — unknown keys from a // Only carry through keys that belong to the form — unknown keys from a
// hand-crafted request are dropped, not stored. // hand-crafted request are dropped, not stored.
if (value !== undefined) { if (checked.value !== undefined) {
cleaned[field.name] = value cleaned[field.name] = checked.value
} }
} }
+74
View File
@@ -0,0 +1,74 @@
import type { ReactNode } from 'react'
import type { AnalyticsProps } from '../analytics/Analytics.js'
import type { ConsentCookieMap } from '../consent/useConsent.js'
import type { SiteShell } from './createContentHelpers.js'
import { Analytics } from '../analytics/Analytics.js'
import { ConsentProvider } from '../consent/ConsentContext.js'
import { CookieBanner } from '../consent/CookieBanner.js'
import { CookieButton } from '../consent/CookieButton.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
import { MediaPreconnect } from '../storage/MediaPreconnect.js'
import { TurnstileProvider } from '../turnstile/TurnstileProvider.js'
export type SiteProvidersProps = {
/** `defer` etc. for <Analytics>; `false` = no analytics tags at all. */
analytics?: false | Omit<AnalyticsProps, keyof SiteShell['analytics']>
/** The cookie banner. Default `<CookieBanner />`; pass your own configured one (`equalChoice`, classNames) or `false`. */
banner?: false | ReactNode
children: ReactNode
/** The "cookie settings" button. Default `<CookieButton />`; your own or `false`. */
cookieButton?: false | ReactNode
/** Extra cookies per category to delete when consent is withdrawn. */
cookieMap?: ConsentCookieMap
/** More site-wide JSON-LD nodes next to shell.jsonLd (e.g. buildNavigationJsonLd). */
jsonLd?: (null | Record<string, unknown> | undefined)[]
/** Consent log endpoint, e.g. '/api/ipal/consent' (ipalKit consentLog: true). */
logEndpoint?: string
/** <link rel=preconnect> to the media origin (R2_PUBLIC_URL). Default true. */
preconnect?: boolean
/** getSiteShell(locale) from lib/content. */
shell: SiteShell
}
/**
* The wiring every [locale] layout repeats — consent, Turnstile, analytics,
* site JSON-LD, media preconnect — in the right order (Analytics inside the
* consent provider, forms inside Turnstile). Renders no markup of its own:
* <html>, <body>, header, footer and <main> stay in the layout.
*
* const shell = await getSiteShell(locale)
* <body>
* <SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>
* <Header … /><main>{children}</main><Footer … />
* </SiteProviders>
* </body>
*
* Every part is replaceable or switchable off; for a fully custom tree use the
* providers themselves (consent.md, turnstile.md) — the shell data still fits.
*/
export function SiteProviders({
analytics,
banner,
children,
cookieButton,
cookieMap,
jsonLd = [],
logEndpoint,
preconnect = true,
shell,
}: SiteProvidersProps) {
return (
<>
{preconnect ? <MediaPreconnect /> : null}
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
<TurnstileProvider siteKey={shell.turnstileSiteKey}>{children}</TurnstileProvider>
{banner === undefined ? <CookieBanner /> : banner || null}
{cookieButton === undefined ? <CookieButton /> : cookieButton || null}
{analytics === false ? null : <Analytics {...shell.analytics} {...analytics} />}
</ConsentProvider>
</>
)
}
+284 -1
View File
@@ -3,13 +3,32 @@ import type { BasePayload, SanitizedConfig } from 'payload'
import { getPayload } from 'payload' import { getPayload } from 'payload'
import { cache } from 'react' import { cache } from 'react'
import type { AnalyticsConfig } from '../analytics/types.js'
import type { ConsentTexts } from '../consent/texts.js'
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js' import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js' import type { I18nConfig } from '../i18n/index.js'
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions } from '../links/index.js'
import type { CreateMcpRouteArgs } from '../mcp/createMcpRoute.js'
import type { FormNotificationTexts } from '../notifications/types.js'
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapStyleOptions } from '../seo/index.js' import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapStyleOptions } from '../seo/index.js'
import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js'
import { getConsentTexts } from '../consent/getConsentTexts.js'
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js' import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
import { buildRobots, buildSitemapEntries, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js' import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
import { createHealthRoute } from '../health/createHealthRoute.js'
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw } from '../links/resolveNav.js'
import { createMcpRoute } from '../mcp/createMcpRoute.js'
import { getNotificationTexts } from '../notifications/getNotificationTexts.js'
import { buildOrganizationJsonLd, sameAsUrls } from '../seo/buildOrganizationJsonLd.js'
import { buildWebPageJsonLd } from '../seo/buildWebPageJsonLd.js'
import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
import { createIndexNowKeyRoute } from '../seo/indexNow.js'
import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
import { getTurnstileConfig } from '../turnstile/config.js'
type CreateContentHelpersArgs = { type CreateContentHelpersArgs = {
/** /**
@@ -30,6 +49,8 @@ type CreateContentHelpersArgs = {
* handlers — they need the locale list to emit hreflang. * handlers — they need the locale list to emit hreflang.
*/ */
i18n?: I18nConfig i18n?: I18nConfig
/** Markdown route (`markdownRoute`): per-block overrides, frontmatter, layout field. */
markdown?: { frontmatter?: boolean; layoutField?: string; overrides?: Record<string, (block: Record<string, unknown>) => string> }
/** /**
* Advertise each page's Markdown version from generatePageMetadata: * Advertise each page's Markdown version from generatePageMetadata:
* `<link rel="alternate" type="text/markdown" href="/md/pl/o-nas">` (GEO — * `<link rel="alternate" type="text/markdown" href="/md/pl/o-nas">` (GEO —
@@ -38,8 +59,14 @@ type CreateContentHelpersArgs = {
* (content.md). Indexable pages only. * (content.md). Indexable pages only.
*/ */
markdownAlternate?: boolean | string markdownAlternate?: boolean | string
/** MCP route (`mcpRoute`): server name/version, rate limit, batch size. */
mcp?: Pick<CreateMcpRouteArgs, 'clientIp' | 'maxBatch' | 'rateLimit' | 'serverName' | 'serverVersion'>
/** Defaults for getPageJsonLd — each call can override them. */
pageJsonLd?: PageJsonLdOptions
/** Pages collection slug. Defaults to 'pages'. */ /** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string pagesSlug?: string
/** Collections checked for an old slug before a 404 (`resolvePageRedirect`). Default pages. */
redirectCollections?: { historyField?: string; slug: string; slugField?: string }[]
/** /**
* Options for the ready-made `robots` handler, e.g. * Options for the ready-made `robots` handler, e.g.
* `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or * `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or
@@ -48,11 +75,36 @@ type CreateContentHelpersArgs = {
robots?: RobotsOptions robots?: RobotsOptions
/** SiteSettings global slug. Defaults to 'site-settings'. */ /** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string settingsSlug?: string
/**
* Site-wide JSON-LD for `getSiteShell` (layout). Default: WebSite + Organization
* from Site Settings (siteName, logo, sameAs) — skipped when the name or the
* origin is missing, never a fallback name. A function replaces it (e.g.
* LocalBusiness from the Company global); `false` = none.
*/
siteJsonLd?: ((ctx: { baseUrl: string; locale: string; settings: Record<string, unknown> }) => Promise<Record<string, unknown>[]> | Record<string, unknown>[]) | false
/** Image URLs of a document for the sitemap (Google Images). Default: its SEO share image. */
sitemapImages?: (doc: Record<string, unknown>) => (null | string | undefined)[]
/** /**
* Browser look of `sitemapRoute` (/sitemap.xml). Default: built-in style, * Browser look of `sitemapRoute` (/sitemap.xml). Default: built-in style,
* header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML. * header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML.
*/ */
sitemapStyle?: false | SitemapStyleOptions sitemapStyle?: false | SitemapStyleOptions
/** Field with the AI summary (buildSummaryField) — llms.txt and MCP prefer it. */
summaryField?: string
}
export type PageJsonLdOptions = {
/** BreadcrumbList (home › archive › page) from the real route. Default true. */
breadcrumbs?: boolean
/** schema.org type of archive entries. Default 'BlogPosting'. */
entryType?: 'Article' | 'BlogPosting' | 'NewsArticle'
/**
* Q&A visible on this page (e.g. from its FAQ block) → FAQPage. The project
* knows its block shape, so it maps it: `(doc) => doc.layout…map(i => ({ question, answer }))`.
*/
faq?: (doc: Record<string, unknown>) => { answer: string; question: string }[]
/** schema.org type of ordinary pages, per document (e.g. 'ContactPage'). Default 'WebPage'. */
pageType?: (doc: Record<string, unknown>) => string | undefined
} }
/** /**
@@ -86,11 +138,18 @@ export function createContentHelpers({
config, config,
content, content,
i18n, i18n,
markdown: markdownOptions,
markdownAlternate, markdownAlternate,
mcp: mcpOptions,
pageJsonLd: pageJsonLdDefaults,
pagesSlug = 'pages', pagesSlug = 'pages',
redirectCollections,
robots: robotsOptions, robots: robotsOptions,
settingsSlug = 'site-settings', settingsSlug = 'site-settings',
siteJsonLd,
sitemapImages,
sitemapStyle, sitemapStyle,
summaryField,
}: CreateContentHelpersArgs) { }: CreateContentHelpersArgs) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '' const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
const getCachedPayload = cache( const getCachedPayload = cache(
@@ -175,6 +234,89 @@ export function createContentHelpers({
} }
} }
/**
* Per-page structured data — WebPage (BlogPosting for archive entries) with
* language and dates, BreadcrumbList from the actual route, FAQPage when the
* project maps its FAQ block. Built from the same cached route and metadata
* as the page, so it can't disagree with canonical/title. Returns plain nodes
* — render them with <JsonLdGraph schemas={…}> next to the layout's
* WebSite/Organization, add your own, or drop any.
*
* // [[...slug]]/page.tsx
* <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />
*/
const getPageJsonLd = async (
locale: string,
segments: string[] | undefined,
options: PageJsonLdOptions = {},
): Promise<Record<string, unknown>[]> => {
const opts = { ...pageJsonLdDefaults, ...options }
const [meta, route, settings] = await Promise.all([
generatePageMetadata(locale, segments),
resolveRoute(locale, segments ?? [], 1),
getSettings(locale) as Promise<Record<string, unknown>>,
])
const url = meta.alternates?.canonical
if (!route || !url || meta.robots?.index === false) {return []}
const doc = route.doc
const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined)
const name = str(doc.title) ?? meta.title
const siteName = str(settings?.siteName)
const root = new URL(url)
const singleLocale = (i18n?.locales.length ?? 0) === 1
const homeUrl = `${root.origin}${singleLocale ? '' : `/${locale}`}`
const image = meta.openGraph?.images?.[0]?.url
const nodes: (null | Record<string, unknown>)[] = []
if (route.type === 'entry') {
nodes.push(
buildArticleJsonLd({
type: opts.entryType ?? 'BlogPosting',
dateModified: str(doc.updatedAt),
datePublished: str(doc.publishedAt) ?? str(doc.createdAt),
description: meta.description,
headline: name,
image: image ? { url: image } : undefined,
publisherName: siteName,
url,
}),
)
} else {
nodes.push(
buildWebPageJsonLd({
name,
type: route.type === 'archive' ? 'CollectionPage' : (opts.pageType?.(doc) ?? 'WebPage'),
dateModified: str(doc.updatedAt),
description: meta.description,
image,
inLanguage: locale,
url,
websiteUrl: homeUrl,
}),
)
}
if (opts.breadcrumbs !== false && route.type !== 'home') {
const homepage = settings?.homepage as Record<string, unknown> | undefined
const crumbs = [{ name: str(homepage?.title) ?? siteName ?? root.host, url: homeUrl }]
if (route.type === 'entry') {
const archiveName = str(route.archive.title)
if (archiveName) {crumbs.push({ name: archiveName, url: url.replace(/\/[^/]+$/, '') })}
}
crumbs.push({ name, url })
nodes.push(buildBreadcrumbJsonLd(crumbs))
}
const faq = opts.faq?.(doc)?.filter((i) => i.question?.trim() && i.answer?.trim())
if (faq?.length) {nodes.push(buildFaqJsonLd(faq))}
// JsonLdGraph adds the @context once for the whole @graph.
return nodes
.filter((n): n is Record<string, unknown> => Boolean(n))
.map(({ '@context': _context, ...node }) => node)
}
/** ID of the page assigned as 404 — the relation isn't localized, so one read serves every locale. */ /** ID of the page assigned as 404 — the relation isn't localized, so one read serves every locale. */
const getNotFoundPageId = cache(async (): Promise<null | number | string> => { const getNotFoundPageId = cache(async (): Promise<null | number | string> => {
const payload = await getCachedPayload() const payload = await getCachedPayload()
@@ -259,6 +401,7 @@ export function createContentHelpers({
baseUrl: origin, baseUrl: origin,
config: i18n, config: i18n,
content, content,
images: sitemapImages,
pagesSlug, pagesSlug,
payload: await getCachedPayload(), payload: await getCachedPayload(),
settingsSlug, settingsSlug,
@@ -417,17 +560,157 @@ export function createContentHelpers({
*/ */
const sitemapRoute = createSitemapRouteHandler(sitemap, { style: sitemapStyle ?? {} }) const sitemapRoute = createSitemapRouteHandler(sitemap, { style: sitemapStyle ?? {} })
const needI18n = (what: string): I18nConfig => {
if (!i18n) {throw new Error(`[ipal] createContentHelpers: pass \`i18n\` to use ${what}.`)}
return i18n
}
// ── Links & navigation ────────────────────────────────────────────────────
/** Homepage slug in this locale (SiteSettings.homepage) — links to it collapse to /{locale}. */
const getHomeSlug = async (locale: string) => homeSlugFrom(await getSettings(locale))
/** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */
const getLinkOptions = async (locale: string): Promise<ResolveLinkHrefOptions> => {
const homeSlug = await getHomeSlug(locale)
return { config: needI18n('getLinkOptions'), locale, ...(homeSlug ? { homeSlug } : {}) }
}
/**
* A panel link → `{ href, label, internal, newTab, targetProps, appearance }`
* or null. The project's CMSLink only picks the element and the classes.
*/
const resolveLink = async (link: LinkValue | null | undefined, locale: string): Promise<null | ResolvedLink> =>
resolveLinkRaw(link, await getLinkOptions(locale))
/** Menu items of a Header/Footer global → serializable NavItem[] (pass to a client MobileNav as is). */
const resolveNav = async (items: unknown, locale: string, options: { childrenField?: string; linkField?: string } = {}): Promise<NavItem[]> =>
resolveNavRaw(items, { ...(await getLinkOptions(locale)), ...options })
/** Old slug → its new URL (308), for the catch-all page before notFound(). */
const resolvePageRedirect = async (locale: string, segments: string[] | undefined): Promise<null | string> =>
resolveRedirectRaw({
collections: redirectCollections,
config: needI18n('resolvePageRedirect'),
homeSlug: await getHomeSlug(locale),
locale,
payload: await getCachedPayload(),
segments,
})
// ── Layout ────────────────────────────────────────────────────────────────
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
(await getNotificationTexts({ locale, payload: await getCachedPayload() })).form,
)
/**
* Everything the [locale] layout reads, in one cached call: consent texts,
* analytics IDs, Turnstile site key, site JSON-LD, form texts and Site
* Settings. Feed it to <SiteProviders> (/rsc) — or use the pieces yourself.
*/
const getSiteShell = cache(async (locale: string): Promise<SiteShell> => {
const payload = await getCachedPayload()
const [consent, analytics, turnstile, settings, formTexts] = await Promise.all([
getConsentTexts({ config: needI18n('getSiteShell'), locale, payload, settingsSlug }),
getAnalyticsConfig(payload),
getTurnstileConfig(payload),
getSettings(locale) as Promise<Record<string, unknown>>,
getFormTexts(locale),
])
let jsonLd: Record<string, unknown>[] = []
if (typeof siteJsonLd === 'function') {
jsonLd = await siteJsonLd({ baseUrl: origin, locale, settings: settings ?? {} })
} else if (siteJsonLd !== false) {
const name = typeof settings?.siteName === 'string' && settings.siteName.trim() ? settings.siteName.trim() : undefined
if (name && origin) {
jsonLd = [
buildWebSiteJsonLd({ name, url: origin }),
buildOrganizationJsonLd({ name, logo: settings.logo as never, sameAs: sameAsUrls(settings), url: origin }),
]
}
}
return {
analytics,
consent,
formTexts,
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
settings: settings ?? {},
turnstileSiteKey: turnstile.siteKey,
}
})
// ── Ready route handlers (one line per route file) ────────────────────────
// Created on first request, so a project that doesn't use one pays nothing
// and a missing option only fails the route that needs it.
const lazy = <T>(make: () => T) => {
let value: T | undefined
return () => (value ??= make())
}
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, settingsSlug, ...markdownOptions }))
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, settingsSlug, summaryField, ...mcpOptions }))
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
const indexNowKey = lazy(() => createIndexNowKeyRoute({ getCachedPayload }))
const manifestHandler = lazy(() => createManifestHandler({ config: needI18n('manifest'), getCachedPayload, settingsSlug }))
/** app/llms.txt/route.ts: `export { llmsRoute as GET } from '@/lib/content'` */
const llmsRoute = () => llms()()
/** app/llms-full.txt/route.ts: `export { llmsFullRoute as GET } from '@/lib/content'` */
const llmsFullRoute = () => llmsFull()()
/** app/md/[locale]/[[...slug]]/route.ts: `export { markdownRoute as GET } from '@/lib/content'` */
const markdownRoute = (req: Request, ctx: { params: Promise<{ locale: string; slug?: string[] }> }) => md().GET(req, ctx)
/** app/api/mcp/route.ts: `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` */
const mcpGET = () => mcp().GET()
const mcpPOST = (req: Request) => mcp().POST(req)
/** app/api/health/route.ts: `export { healthRoute as GET } from '@/lib/content'` */
const healthRoute = () => health()()
/** app/indexnow-key.txt/route.ts: `export { indexNowKeyRoute as GET } from '@/lib/content'` */
const indexNowKeyRoute = () => indexNowKey()()
/** app/manifest.ts: `export { manifest as default } from '@/lib/content'` */
const manifest = () => manifestHandler()()
return { return {
generatePageMetadata, generatePageMetadata,
generateStaticParams, generateStaticParams,
getCachedPayload, getCachedPayload,
getConfiguredLocales, getConfiguredLocales,
getEntries, getEntries,
getFormTexts,
getHomeSlug,
getLinkOptions,
getNotFoundPage, getNotFoundPage,
getPageJsonLd,
getSettings, getSettings,
getSiteShell,
healthRoute,
i18n,
indexNowKeyRoute,
llmsFullRoute,
llmsRoute,
manifest,
markdownRoute,
mcpGET,
mcpPOST,
resolveLink,
resolveNav,
resolvePageRedirect,
resolveRoute, resolveRoute,
robots, robots,
sitemap, sitemap,
sitemapRoute, sitemapRoute,
} }
} }
/** What the layout needs — getSiteShell(locale). Plain data, safe to pass to client components. */
export type SiteShell = {
analytics: AnalyticsConfig
consent: ConsentTexts
formTexts: FormNotificationTexts
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
jsonLd: Record<string, unknown>[]
settings: Record<string, unknown>
turnstileSiteKey: null | string
}
export type ContentHelpers = ReturnType<typeof createContentHelpers>
+138
View File
@@ -0,0 +1,138 @@
import type { ReactNode } from 'react'
import type { BlockComponentMap, BlockData } from '../blocks/types.js'
import type { ResolvedRoute } from '../content/index.js'
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
import { RenderBlocks } from '../blocks/RenderBlocks.js'
import { LocaleView } from '../pages/LocaleView.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
type Helpers = Pick<
ContentHelpers,
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
>
type BlockPropsContext = { doc: Record<string, unknown>; locale: string }
export type PageRouteOptions = {
/** Props for every block on top of `locale`, computed once per page — e.g. `{ formTexts, sendForm }` for form blocks. */
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
/** blockType → component (the project's registry). */
blocks: BlockComponentMap
/** Per-page JSON-LD (WebPage, breadcrumbs, FAQ…). Default true; options as getPageJsonLd. */
jsonLd?: boolean | PageJsonLdOptions
/** Field with the blocks. Default 'layout'. */
layoutField?: string
/** `notFound` from 'next/navigation' — injected, the plugin doesn't import next/* on the server. */
notFound: () => never
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
permanentRedirect: (url: string) => never
/**
* Render a route yourself — an archive listing, a blog entry template.
* Return undefined to keep the default (the document's blocks).
*/
render?: (ctx: { blocks: ReactNode; locale: string; route: ResolvedRoute; segments: string[] }) => Promise<ReactNode | undefined> | ReactNode | undefined
}
type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
/**
* The catch-all page — route resolution, old-slug 308, 404, metadata, static
* params, per-page JSON-LD and the blocks — from one call:
*
* // src/app/(frontend)/[locale]/[[...slug]]/page.tsx
* import { notFound, permanentRedirect } from 'next/navigation'
* import { createPageRoute } from '@intecion/ipal-kit/rsc'
* import * as content from '@/lib/content'
* import { blockRegistry } from '@/blocks/registry'
*
* export const revalidate = 3600 // must stay a literal in the file (Next reads it statically)
* const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect })
* export default route.Page
* export const generateMetadata = route.generateMetadata
* export const generateStaticParams = route.generateStaticParams
*
* Archive listings / entry templates: `render`. Anything else: write the page
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
*/
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const { blockProps, blocks, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, render } = options
const localeOf = (locale: string | undefined) => {
const l = locale ?? helpers.i18n?.defaultLocale
if (!l) {throw new Error('[ipal] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
return l
}
async function generateMetadata({ params }: PageArgs) {
const { slug, locale } = await params
return helpers.generatePageMetadata(localeOf(locale), slug)
}
async function Page({ params }: PageArgs) {
const { slug, locale: param } = await params
const locale = localeOf(param)
const segments = slug ?? []
const route = await helpers.resolveRoute(locale, segments, 1)
if (!route) {
const target = await helpers.resolvePageRedirect(locale, segments)
return target ? permanentRedirect(target) : notFound()
}
const doc = route.doc
const extra = blockProps ? await blockProps({ doc, locale }) : {}
const rendered = (
<RenderBlocks
blocks={doc[layoutField] as BlockData[] | undefined}
components={blocks}
enhanceProps={() => ({ locale, ...extra })}
/>
)
const custom = render ? await render({ blocks: rendered, locale, route, segments }) : undefined
const schemas = jsonLd ? await helpers.getPageJsonLd(locale, slug, jsonLd === true ? {} : jsonLd) : []
return (
<>
{schemas.length ? <JsonLdGraph schemas={schemas} /> : null}
{custom ?? rendered}
</>
)
}
return { generateMetadata, generateStaticParams: helpers.generateStaticParams, Page }
}
export type NotFoundPageOptions = {
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
blocks: BlockComponentMap
/** Shown when no 404 page is assigned in Site Settings (or the DB is unreachable). Per locale or one node. */
fallback?: ((locale: string) => ReactNode) | ReactNode
layoutField?: string
}
/**
* app/(frontend)/[locale]/not-found.tsx — the 404 page from the panel, in the
* visitor's language, WITHOUT headers() (the route stays static): one view per
* locale rendered here, <LocaleView> picks the one from the URL.
*
* import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
* export default createNotFoundPage(content, { blocks: blockRegistry })
*/
export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOptions) {
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
return async function NotFoundPage() {
const configured = await helpers.getConfiguredLocales()
const locales = configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
const views = Object.fromEntries(
await Promise.all(
locales.map(async (locale) => {
const doc = await helpers.getNotFoundPage(locale)
const layout = doc?.[layoutField] as BlockData[] | undefined
const fb = typeof fallback === 'function' ? fallback(locale) : fallback
if (!doc || !layout?.length) {return [locale, fb] as const}
const extra = blockProps ? await blockProps({ doc, locale }) : {}
return [locale, <RenderBlocks blocks={layout} components={blocks} enhanceProps={() => ({ locale, ...extra })} key={locale} />] as const
}),
),
)
return <LocaleView defaultLocale={helpers.i18n?.defaultLocale ?? locales[0]} views={views} />
}
}
+3 -1
View File
@@ -1,4 +1,6 @@
export { buildLinkField, buildLinksField } from './buildLinkField.js' export { buildLinkField, buildLinksField } from './buildLinkField.js'
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js' export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'
export { resolveLinkHref } from './resolveLinkHref.js' export { resolveLinkHref, safeHref } from './resolveLinkHref.js'
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js' export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
export { homeSlugFrom, resolveLink, resolveNav } from './resolveNav.js'
export type { NavItem, ResolvedLink, ResolveNavOptions } from './resolveNav.js'
+16 -1
View File
@@ -6,6 +6,21 @@ import { buildLocalizedPath } from '../i18n/index.js'
* Minimal shape of a link value (the project's generated `CmsLink` fits it). * Minimal shape of a link value (the project's generated `CmsLink` fits it).
* The plugin doesn't know the project's types — only this contract. * The plugin doesn't know the project's types — only this contract.
*/ */
/**
* Schemes a CMS link may use. The field validates this too, but data can come
* from imports, seeds or older versions — `javascript:`, `data:` and other
* schemes are dropped here so a stored link can never run script on click.
*/
const SAFE_HREF = /^(?:https?:\/\/|mailto:|tel:|sms:|#|\/(?!\/))/i
/** The URL when it's a safe link target, otherwise null (control characters — e.g. "java\tscript:" — reject it). */
export function safeHref(url: null | string | undefined): null | string {
const v = url?.trim()
// eslint-disable-next-line no-control-regex
if (!v || /[\u0000-\u001F\u007F]/.test(v)) {return null}
return SAFE_HREF.test(v) ? v : null
}
export type LinkValue = { export type LinkValue = {
appearance?: null | string appearance?: null | string
file?: unknown file?: unknown
@@ -43,7 +58,7 @@ export function resolveLinkHref(
): null | string { ): null | string {
if (!link) {return null} if (!link) {return null}
if (link.type === 'external') {return link.url?.trim() || null} if (link.type === 'external') {return safeHref(link.url)}
if (link.type === 'file') { if (link.type === 'file') {
const file = link.file const file = link.file
+77
View File
@@ -0,0 +1,77 @@
import type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
import { resolveLinkHref } from './resolveLinkHref.js'
/**
* Everything an <a>/<Link> needs for a panel link — the project keeps the
* element and the classes (Button variants), the plugin decides the rest:
* href, new tab (files always open in one), rel, and whether it's internal
* (render next/link) or not (plain <a>).
*/
export type ResolvedLink = {
/** `link.appearance` from the panel (primary / secondary / link) — map it to your Button classes. */
appearance?: string
href: string
/** Internal page → next/link; external URL / file / mailto → <a>. */
internal: boolean
label: string
newTab: boolean
/** Spread on the element: target + rel for a new tab, nothing otherwise. */
targetProps: { rel: string; target: '_blank' } | Record<string, never>
}
/** A panel link → ResolvedLink, or null when it leads nowhere in this locale (no page, no file, unsafe URL). */
export function resolveLink(link: LinkValue | null | undefined, options: ResolveLinkHrefOptions): null | ResolvedLink {
const href = resolveLinkHref(link, options)
if (!link || !href) {return null}
const newTab = Boolean(link.newTab) || link.type === 'file'
return {
...(link.appearance ? { appearance: link.appearance } : {}),
href,
internal: (link.type ?? 'internal') === 'internal',
label: link.label ?? '',
newTab,
targetProps: newTab ? { rel: 'noopener noreferrer', target: '_blank' } : {},
}
}
export type NavItem = {
/** Nested items (dropdown), already resolved. */
children: NavItem[]
} & ResolvedLink
export type ResolveNavOptions = {
/** Field with the nested items inside an item. Default 'subItems'. */
childrenField?: string
/** Field with the link inside an item. Default 'link'. */
linkField?: string
} & ResolveLinkHrefOptions
/**
* Menu items from a Header/Footer global → plain, serializable items (safe to
* pass to a client MobileNav). Items whose link leads nowhere in this locale
* — a deleted or untranslated page — are dropped instead of rendering "#".
*
* const items = resolveNav(header.navItems, { locale, config: i18nConfig, homeSlug })
* // [{ href, label, newTab, internal, targetProps, children: [...] }]
*
* Any depth; the item shape is configurable (linkField, childrenField).
*/
export function resolveNav(items: unknown, options: ResolveNavOptions): NavItem[] {
const { childrenField = 'subItems', linkField = 'link', ...linkOptions } = options
if (!Array.isArray(items)) {return []}
return items.flatMap((item) => {
if (!item || typeof item !== 'object') {return []}
const record = item as Record<string, unknown>
const link = resolveLink(record[linkField] as LinkValue, linkOptions)
if (!link || !link.label) {return []}
return [{ ...link, children: resolveNav(record[childrenField], options) }]
})
}
/** Homepage slug from SiteSettings (`homepage` relationship, populated) — for links that collapse to /{locale}. */
export function homeSlugFrom(settings: unknown, field = 'homepage'): string | undefined {
const home = settings && typeof settings === 'object' ? (settings as Record<string, unknown>)[field] : undefined
const slug = home && typeof home === 'object' ? (home as { slug?: unknown }).slug : undefined
return typeof slug === 'string' && slug ? slug : undefined
}
+19 -13
View File
@@ -4,9 +4,10 @@ import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js' import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js' import type { ClientIpOptions } from '../shared/rateLimit.js'
import { createMarkdownRenderer, listContent, searchContent } from '../content/index.js' import { createMarkdownRenderer, searchContent } from '../content/index.js'
import { getDefaultLocale, isValidLocale } from '../i18n/index.js' import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js' import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js'
import { collectSiteIndex } from '../seo/siteIndex.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
/** /**
@@ -45,7 +46,7 @@ import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit
const DEFAULT_PROTOCOL = '2025-06-18' const DEFAULT_PROTOCOL = '2025-06-18'
type CreateMcpRouteArgs = { export type CreateMcpRouteArgs = {
/** Absolute origin for building result URLs. */ /** Absolute origin for building result URLs. */
baseUrl?: string baseUrl?: string
/** How to read the client IP for the rate limit — see clientIp(). */ /** How to read the client IP for the rate limit — see clientIp(). */
@@ -103,7 +104,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
const rl = args.rateLimit === false ? null : { max: 60, windowMs: 60_000, ...args.rateLimit } const rl = args.rateLimit === false ? null : { max: 60, windowMs: 60_000, ...args.rateLimit }
const origin = baseUrl?.replace(/\/$/, '') ?? '' const origin = baseUrl?.replace(/\/$/, '') ?? ''
const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug }) const renderMarkdown = createMarkdownRenderer({ baseUrl: origin || undefined, collection, config, content, settingsSlug })
const localeProp = { type: 'string', description: `Locale code (default ${config.defaultLocale})` } const localeProp = { type: 'string', description: `Locale code (default ${config.defaultLocale})` }
@@ -117,7 +118,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
{ {
name: 'list_pages', name: 'list_pages',
description: description:
'List all published pages of the site with title, URL and description — the table of contents. Fetch one with get_page.', 'List all published pages and entries (e.g. blog posts) with title, URL and description — the table of contents. Fetch one with get_page.',
inputSchema: { inputSchema: {
type: 'object', type: 'object',
properties: { properties: {
@@ -189,21 +190,26 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
async function runList(params: Record<string, unknown>): Promise<string> { async function runList(params: Record<string, unknown>): Promise<string> {
const locale = pickLocale(params) const locale = pickLocale(params)
const limit = typeof params.limit === 'number' ? params.limit : 50 const limit = Math.min(Math.max(Math.trunc(typeof params.limit === 'number' ? params.limit : 50) || 50, 1), 200)
const payload = await getCachedPayload() const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale) // Same index as llms.txt and the sitemap rules: pages AND archive entries (blog…).
const results = await listContent({ const index = await collectSiteIndex({
baseUrl: origin, baseUrl: origin,
collection,
config, config,
homeSlug: meta?.homeSlug, content,
limit, locales: [locale],
locale, pagesSlug: collection,
payload, payload,
settingsSlug,
summaryField, summaryField,
}) })
if (results.length === 0) {return 'No published pages.'} if (index.length === 0) {return 'No published pages.'}
return formatResults(results) const shown = index.slice(0, limit)
const lines = shown.map(
(e) => `- ${e.title} (${e.url})${e.description ? ` — ${e.description}` : ''}${e.collection === collection ? '' : ` [${e.collectionLabel}]`}`,
)
if (index.length > shown.length) {lines.push(`… ${index.length - shown.length} more — raise limit (max 200) or use search_content.`)}
return lines.join('\n')
} }
async function runSearch(params: Record<string, unknown>): Promise<string> { async function runSearch(params: Record<string, unknown>): Promise<string> {
+3
View File
@@ -1,3 +1,6 @@
export { MEDIA_SIZES, mediaImageProps, videoProps } from './mediaProps.js'
export type { MediaImageOptions, MediaImageProps, VideoMode, VideoProps } from './mediaProps.js'
export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js' export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js' export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'
export type { OptimizeUploadOptions } from './optimizeUpload.js' export type { OptimizeUploadOptions } from './optimizeUpload.js'
export { buildMediaPlaceholderField, buildMediaPlaceholderHook } from './placeholder.js'
+136
View File
@@ -0,0 +1,136 @@
/**
* Props for the project's own <Media> — the plugin computes the performance
* details, the project keeps the markup and the look. Nothing here renders,
* styles or limits anything: every value can be overridden by the caller.
*
* // src/components/ui/Media.tsx
* const img = mediaImageProps(resource, { sizes: MEDIA_SIZES.half, priority })
* if (img) return <Image {...img} className={className} />
* const video = videoProps(resource, { mode: 'background' })
* if (video) return <video {...video} className={className} />
*/
type MediaDoc = {
alt?: null | string
focalX?: null | number
focalY?: null | number
height?: null | number
mimeType?: null | string
placeholder?: { blurDataURL?: null | string; color?: null | string } | null
url?: null | string
width?: null | number
}
/**
* Starting points for `sizes` — how wide the image is ON SCREEN at each
* breakpoint, so the browser downloads the right file instead of a full-width
* one. Suggestions only: pass any string that matches the actual layout.
*/
export const MEDIA_SIZES = {
/** Full-bleed hero / background. */
full: '100vw',
/** Half the container from md up (two-column hero, image + text). */
half: '(min-width: 768px) 50vw, 100vw',
/** Card in a 3-column grid from lg, 2 from md. */
third: '(min-width: 1024px) 33vw, (min-width: 768px) 50vw, 100vw',
/** Card in a 4-column grid. */
quarter: '(min-width: 1024px) 25vw, (min-width: 640px) 50vw, 100vw',
/** Thumbnail / avatar / logo up to ~160 px. */
thumb: '160px',
} as const
export type MediaImageOptions = {
/** Alt override (decorative images: ''). Default: the document's alt. */
alt?: string
/**
* The LCP image (first visible image — usually the hero): loads eagerly with
* fetchPriority="high". Exactly one per page; everything else is lazy.
*/
priority?: boolean
/** How wide it is on screen. Required in practice — see MEDIA_SIZES. Default '100vw'. */
sizes?: string
}
export type MediaImageProps = {
alt: string
blurDataURL?: string
fetchPriority?: 'high'
height: number
loading: 'eager' | 'lazy'
placeholder?: 'blur' | 'empty'
/** Next 16: <link rel=preload> for the LCP image (replaces the deprecated `priority`). */
preload?: boolean
sizes: string
src: string
style?: { backgroundColor?: string; objectPosition?: string }
width: number
}
const asDoc = (resource: unknown): MediaDoc | null =>
resource && typeof resource === 'object' && typeof (resource as MediaDoc).url === 'string' ? (resource as MediaDoc) : null
/**
* next/image props for an image upload, or null for anything else (video, PDF,
* a bare id). Width/height always come from the document — no layout shift.
* Focal point (upload `focalPoint: true`) becomes object-position, so a cropped
* image keeps its subject; a placeholder (buildMediaPlaceholderHook) becomes a
* blur-up and background colour.
*/
export function mediaImageProps(resource: unknown, { alt, priority = false, sizes = '100vw' }: MediaImageOptions = {}): MediaImageProps | null {
const doc = asDoc(resource)
if (!doc || doc.mimeType?.startsWith('video/')) {return null}
if (!doc.width || !doc.height) {return null} // PDF or other non-image file — link it instead
const blur = doc.placeholder?.blurDataURL ?? undefined
const color = doc.placeholder?.color ?? undefined
const hasFocal = typeof doc.focalX === 'number' && typeof doc.focalY === 'number' && !(doc.focalX === 50 && doc.focalY === 50)
const style = {
...(hasFocal ? { objectPosition: `${doc.focalX}% ${doc.focalY}%` } : {}),
...(color ? { backgroundColor: color } : {}),
}
return {
alt: alt ?? doc.alt ?? '',
height: doc.height,
sizes,
src: doc.url!,
width: doc.width,
...(priority
? { fetchPriority: 'high' as const, loading: 'eager' as const, preload: true }
: { loading: 'lazy' as const }),
...(blur ? { blurDataURL: blur, placeholder: 'blur' as const } : {}),
...(Object.keys(style).length ? { style } : {}),
}
}
export type VideoMode = 'background' | 'player'
export type VideoProps = {
autoPlay?: boolean
controls?: boolean
loop?: boolean
muted?: boolean
playsInline: true
poster?: string
preload: 'metadata' | 'none'
src: string
}
/**
* <video> attributes for a video upload, or null when it isn't one.
* - 'background': silent loop for heroes/ambience — autoplay, muted, loop, no
* controls. Pass `reducedMotion` (from a client hook) to not autoplay for
* visitors who asked for less motion.
* - 'player': a real video — controls, nothing downloaded until play
* (preload="none"), poster shown meanwhile. Default.
*/
export function videoProps(
resource: unknown,
{ mode = 'player', poster, reducedMotion = false }: { mode?: VideoMode; poster?: unknown; reducedMotion?: boolean } = {},
): null | VideoProps {
const doc = asDoc(resource)
if (!doc || !doc.mimeType?.startsWith('video/')) {return null}
const posterUrl = typeof poster === 'string' ? poster : asDoc(poster)?.url ?? undefined
const base = { playsInline: true as const, src: doc.url!, ...(posterUrl ? { poster: posterUrl } : {}) }
return mode === 'background'
? { ...base, autoPlay: !reducedMotion, loop: true, muted: true, preload: 'metadata' }
: { ...base, controls: true, preload: 'none' }
}

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