Compare commits

...
9 Commits
Author SHA1 Message Date
radoslaw.smolinski 0ccc7e5064 1.8.3 2026-10-13 18:04:46 +02:00
radoslaw.smolinski 3d467d7350 Added module Links 2026-10-13 18:04:37 +02:00
radoslaw.smolinski db05fe814b 1.8.2 2026-10-13 16:25:28 +02:00
radoslaw.smolinski 42df05af28 Added missing LocalView export to client.ts 2026-10-13 16:25:22 +02:00
radoslaw.smolinski 089b3a29ba 1.8.1 2026-10-13 15:58:39 +02:00
radoslaw.smolinski ab16d459ed 1.7.14 2026-10-13 15:58:07 +02:00
radoslaw.smolinski 786dd346a9 Fixed notfound headers, r2storage 2026-10-13 15:57:59 +02:00
radoslaw.smolinski 86c873e4e7 1.8.0 2026-10-13 00:46:04 +02:00
radoslaw.smolinski efe8253f64 Added skills for AGENTS 2026-10-13 00:45:52 +02:00
95 changed files with 3764 additions and 2359 deletions
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env node
// ipal-skills — copies the ipal-kit agent skills into the project.
// pnpm ipal-skills → ./.agents/skills/ipal-*
// pnpm ipal-skills --dry-run → show what would change
// pnpm ipal-skills --dest .claude/skills
// Only folders named ipal-* are touched; the project's own skills stay as they are.
// ipal-* folders that no longer exist in the package are removed (renamed/retired skills).
import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const args = process.argv.slice(2)
if (args.includes('--help') || args.includes('-h')) {
console.log('Usage: ipal-skills [--dest <dir>] [--dry-run]\nDefault dest: .agents/skills')
process.exit(0)
}
const dryRun = args.includes('--dry-run')
const destArg = args.indexOf('--dest')
const dest = resolve(process.cwd(), destArg >= 0 ? args[destArg + 1] ?? '' : '.agents/skills')
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const src = join(pkgRoot, 'docs', 'agent', 'skills')
if (!existsSync(src)) {
console.error(`ipal-skills: no skills found in ${src} — is @intecion/ipal-kit installed with docs?`)
process.exit(1)
}
const isSkillDir = (base, name) => name.startsWith('ipal-') && statSync(join(base, name)).isDirectory()
const shipped = readdirSync(src).filter((n) => isSkillDir(src, n))
const existing = existsSync(dest) ? readdirSync(dest).filter((n) => isSkillDir(dest, n)) : []
const retired = existing.filter((n) => !shipped.includes(n))
if (!dryRun) mkdirSync(dest, { recursive: true })
for (const name of shipped) {
const action = existing.includes(name) ? 'update' : 'add '
console.log(`${action} ${name}`)
if (!dryRun) {
rmSync(join(dest, name), { recursive: true, force: true }) // drop files removed upstream
cpSync(join(src, name), join(dest, name), { recursive: true })
}
}
for (const name of retired) {
console.log(`remove ${name} (no longer in ipal-kit)`)
if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true })
}
console.log(`${dryRun ? '[dry-run] ' : ''}${shipped.length} skill(s) → ${dest}`)
+4 -3
View File
@@ -1,11 +1,11 @@
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
export { AccessibilityProvider, AccessibilityWidget, useAccessibility, } from '../modules/accessibility/client.js';
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js';
export { Analytics } from '../modules/analytics/client.js';
export type { AnalyticsProps } from '../modules/analytics/client.js';
export { pushDataLayer } from '../modules/analytics/client.js';
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok, } from '../modules/analytics/client.js';
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js';
/**
* Entry point: ipal-kit/client
*
@@ -19,7 +19,7 @@ export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js';
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js';
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
export { useContactForm } from '../modules/forms/useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js';
export { useForm } from '../modules/forms/useForm.js';
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from '../modules/forms/validators.js';
@@ -28,6 +28,7 @@ export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js';
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks, } from '../modules/i18n/index.js';
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js';
export { LocaleView } from '../modules/pages/LocaleView.js';
export { Turnstile } from '../modules/turnstile/client.js';
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
export type { TurnstileProps } from '../modules/turnstile/client.js';
+1
View File
@@ -21,6 +21,7 @@ export { buildValidator, checked, custom, email, isEmail, maxLength, minLength,
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js';
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks } from '../modules/i18n/index.js';
export { LocaleView } from '../modules/pages/LocaleView.js';
export { Turnstile } from '../modules/turnstile/client.js';
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport type { AnalyticsProps } from '../modules/analytics/client.js'\n\nexport { pushDataLayer } from '../modules/analytics/client.js'\nexport {\n loadClarity,\n loadLinkedIn,\n loadMetaPixel,\n loadTikTok,\n} from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","pushDataLayer","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","formAnalyticsOnSuccess","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAG1D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SACEC,WAAW,EACXC,YAAY,EACZC,aAAa,EACbC,UAAU,QACL,iCAAgC;AACvC;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,sBAAsB,QAAQ,oCAAmC;AAE1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport type { AnalyticsProps } from '../modules/analytics/client.js'\n\nexport { pushDataLayer } from '../modules/analytics/client.js'\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { LocaleView } from '../modules/pages/LocaleView.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","pushDataLayer","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","formAnalyticsOnSuccess","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","LocaleView","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SAASC,qBAAqB,EAAEC,mBAAmB,EAAEC,gBAAgB,QAAQ,qCAAoC;AAEjH,SAASC,SAAS,QAAQ,iCAAgC;AAG1D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,iCAAgC;AACrG;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,sBAAsB,QAAQ,oCAAmC;AAE1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAEnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
+5 -2
View File
@@ -34,6 +34,8 @@ export type { LocaleMiddlewareResult } from './modules/i18n/index.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js';
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance, LinkValue, ResolveLinkHrefOptions, } from './modules/links/index.js';
export { createMcpRoute } from './modules/mcp/index.js';
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage, } from './modules/notifications/index.js';
@@ -48,8 +50,9 @@ export { buildCsp } from './modules/security/index.js';
export type { BuildCspArgs } from './modules/security/index.js';
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js';
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js';
export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js';
export type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js';
export { buildHreflangAlternates, buildMetadata, composeTitle, readSiteMetaConfig, slugsAcrossLocales, } from './modules/seo/index.js';
export type { SiteMetaConfig } from './modules/seo/index.js';
export type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry, } from './modules/seo/index.js';
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta, } from './modules/seo/index.js';
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler, } from './modules/seo/index.js';
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField, } from './modules/seo/index.js';
+2 -1
View File
@@ -27,6 +27,7 @@ export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefiniti
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js';
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js';
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
@@ -37,7 +38,7 @@ export { getGlobal, getSiteIntegrations, getSiteSettings, SITE_INTEGRATIONS_SLUG
export { lexicalToMarkdown } from './modules/richtext/index.js';
export { buildSecurityHeaders } from './modules/security/index.js';
export { buildCsp } from './modules/security/index.js';
export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js';
export { buildHreflangAlternates, buildMetadata, composeTitle, readSiteMetaConfig, slugsAcrossLocales } from './modules/seo/index.js';
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildAutoFillMetaHook, buildRobots, buildSitemapEntries, createMetadataGenerator, createPageMetadata, injectAutoFillMeta } from './modules/seo/index.js';
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js';
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js';
+1 -1
View File
File diff suppressed because one or more lines are too long
+7 -1
View File
@@ -38,6 +38,12 @@ type ResolveRouteArgs = {
payload: BasePayload;
/** Route segments after the locale, e.g. ['artykuly', 'moj-post']. */
segments?: string[];
/**
* SiteSettings already read for this locale (depth ≥ 1). Pass it to skip the
* read — createContentHelpers does, so layout, metadata and page share ONE
* settings query per request.
*/
settings?: null | Record<string, unknown>;
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string;
};
@@ -64,5 +70,5 @@ type ResolveRouteArgs = {
* make canonical and hreflang ambiguous (the same entry reachable under several
* URLs).
*/
export declare function resolveRoute({ content, locale, page, pagesSlug, payload, segments, settingsSlug, }: ResolveRouteArgs): Promise<null | ResolvedRoute>;
export declare function resolveRoute({ content, locale, page, pagesSlug, payload, segments, settings: preloaded, settingsSlug, }: ResolveRouteArgs): Promise<null | ResolvedRoute>;
export {};
+2 -2
View File
@@ -21,8 +21,8 @@ import { archiveFieldName } from './types.js';
* Depth beyond {archive}/{entry} isn't supported — categories in the path would
* make canonical and hreflang ambiguous (the same entry reachable under several
* URLs).
*/ export async function resolveRoute({ content, locale, page = 1, pagesSlug = 'pages', payload, segments, settingsSlug = 'site-settings' }) {
const settings = await payload.findGlobal({
*/ export async function resolveRoute({ content, locale, page = 1, pagesSlug = 'pages', payload, segments, settings: preloaded, settingsSlug = 'site-settings' }) {
const settings = preloaded ?? await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: locale
File diff suppressed because one or more lines are too long
+9 -2
View File
@@ -1,7 +1,7 @@
import type { BasePayload, SanitizedConfig } from 'payload';
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js';
import type { I18nConfig } from '../i18n/index.js';
import type { RobotsRules, SitemapEntry } from '../seo/index.js';
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry } from '../seo/index.js';
type CreateContentHelpersArgs = {
/**
* Absolute site origin for sitemap/robots URLs. Falls back to
@@ -23,6 +23,12 @@ type CreateContentHelpersArgs = {
i18n?: I18nConfig;
/** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string;
/**
* Options for the ready-made `robots` handler, e.g.
* `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or
* `{ adminRoute: false }` when the admin path is hidden (ipalKit adminRoute).
*/
robots?: RobotsOptions;
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string;
};
@@ -52,7 +58,8 @@ type CreateContentHelpersArgs = {
* a URL is, fetching gets the listing. Metadata generation needs the first and
* not the second, and a page component composes them in two obvious lines.
*/
export declare function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug, settingsSlug, }: CreateContentHelpersArgs): {
export declare function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug, robots: robotsOptions, settingsSlug, }: CreateContentHelpersArgs): {
generatePageMetadata: (locale: string, segments: string[] | undefined, page?: number) => Promise<PageMetadata>;
generateStaticParams: () => Promise<Array<{
locale: string;
slug: string[];
+76 -12
View File
@@ -1,7 +1,7 @@
import { getPayload } from 'payload';
import { cache } from 'react';
import { getArchiveEntries, resolveNotFoundPage, resolveRoute as resolveRouteRaw } from '../content/index.js';
import { buildRobots, buildSitemapEntries } from '../seo/index.js';
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js';
import { buildRobots, buildSitemapEntries, createPageMetadata } from '../seo/index.js';
/**
* Bundles the per-request data helpers a frontend needs — the same cached
* wrappers every project was writing by hand (getPayload, settings, locale
@@ -27,7 +27,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
* `resolveRoute` and `getEntries` are separate on purpose: routing decides what
* a URL is, fetching gets the listing. Metadata generation needs the first and
* not the second, and a page component composes them in two obvious lines.
*/ export function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug = 'pages', settingsSlug = 'site-settings' }) {
*/ export function createContentHelpers({ baseUrl, config, content, i18n, pagesSlug = 'pages', robots: robotsOptions, settingsSlug = 'site-settings' }) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? '';
const getCachedPayload = cache(async ()=>getPayload({
config: await config
@@ -36,7 +36,10 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
const c = await config;
return c.localization ? c.localization.locales.map((l)=>l.code) : [];
});
const getSettings = cache(async (locale)=>{
/**
* SiteSettings for a locale — ONE query per locale per request, shared by the
* layout, generatePageMetadata, resolveRoute and anything else that asks.
*/ const getSettings = cache(async (locale)=>{
const payload = await getCachedPayload();
return payload.findGlobal({
slug: settingsSlug,
@@ -46,6 +49,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
});
/** What does this URL point at? Routing only — no listing data. */ const resolveRoute = cache(async (locale, segments, page)=>{
const payload = await getCachedPayload();
const settings = await getSettings(locale);
return resolveRouteRaw({
content,
locale,
@@ -53,24 +57,82 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
pagesSlug,
payload,
segments,
settings,
settingsSlug
});
});
/**
* generateMetadata for the catch-all page, sharing the request cache with
* the page component: the same settings read and the same resolveRoute call
* (React cache spans generateMetadata and the page within one request), so
* metadata costs no extra route/settings queries.
*
* export async function generateMetadata({ params }) {
* const { locale, slug } = await params
* return generatePageMetadata(locale, slug)
* }
*/ let pageMetadata;
const generatePageMetadata = async (locale, segments, page = 1)=>{
if (!i18n) {
throw new Error('[ipal] createContentHelpers: pass `i18n` to use generatePageMetadata.');
}
pageMetadata ??= createPageMetadata({
baseUrl: origin || undefined,
collection: pagesSlug,
config: i18n,
content,
loaders: {
getSettings: async (l)=>await getSettings(l),
resolveRoute
},
settingsSlug
});
return pageMetadata({
slug: segments,
locale,
page,
payload: await getCachedPayload()
});
};
/** ID of the page assigned as 404 — the relation isn't localized, so one read serves every locale. */ const getNotFoundPageId = cache(async ()=>{
const payload = await getCachedPayload();
const settings = await payload.findGlobal({
slug: settingsSlug,
depth: 0
});
const rel = settings.notFound;
if (typeof rel === 'string' || typeof rel === 'number') {
return rel;
}
if (rel && typeof rel === 'object') {
const id = rel.id;
if (typeof id === 'string' || typeof id === 'number') {
return id;
}
}
return null;
});
/**
* The page assigned as 404 in System Pages (or null → built-in fallback).
* For app/not-found.tsx; never throws. Locale comes from the x-locale header
* set by createProxy (not-found.tsx receives no params).
* For app/not-found.tsx; never throws. not-found.tsx receives no params and
* must NOT read headers() (breaks SSG/ISR) — call this for every configured
* locale and let <LocaleView> (client) pick the one from the URL. See pages.md.
*/ const getNotFoundPage = cache(async (locale)=>{
try {
const id = await getNotFoundPageId();
if (id === null) {
return null;
}
const payload = await getCachedPayload();
return await resolveNotFoundPage({
locale,
pagesSlug,
payload,
settingsSlug
const doc = await payload.findByID({
id,
collection: pagesSlug,
depth: 2,
locale: locale
});
return doc ?? null;
} catch {
return null // DB unreachable (container build) — fallback view
return null // DB unreachable (container build) or page deleted — fallback view
;
}
});
@@ -133,6 +195,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
* export { robots as default } from '@/lib/content'
* ```
*/ const robots = ()=>buildRobots({
...robotsOptions,
baseUrl: origin
});
/**
@@ -249,6 +312,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js';
}
};
return {
generatePageMetadata,
generateStaticParams,
getCachedPayload,
getConfiguredLocales,
File diff suppressed because one or more lines are too long
+39
View File
@@ -0,0 +1,39 @@
import type { ArrayField, GroupField } from 'payload';
export type LinkAppearance = 'link' | 'primary' | 'secondary';
export type BuildLinkFieldOptions = {
/** Visual styles the editor may pick. `false` → no appearance select. Default all three. */
appearances?: false | LinkAppearance[];
/** Hide the label — for links that wrap something (a whole card, an image). */
disableLabel?: boolean;
/** Field name. Default 'link'. */
name?: string;
/** Collection the "Page" option points at. Default 'pages'. */
relationTo?: string;
required?: boolean;
/** Upload collection for "File" links (PDF, documents). Default 'media'. */
uploadTo?: string;
};
/**
* The ONE link shape for a project: a page, an external URL (also mailto:,
* tel:, #anchor) or an uploaded file — plus label, new-tab flag and visual
* style. Every CTA, card link and download in every block uses this field, so
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
* (resolveLinkHref + the project's CMSLink) handles them all.
*
* Generates a named TypeScript type `CmsLink` in payload-types.ts.
*
* fields: [buildLinkField()] // single link
* fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card
*/
export declare function buildLinkField({ name, appearances, disableLabel, relationTo, required, uploadTo, }?: BuildLinkFieldOptions): GroupField;
export type BuildLinksFieldOptions = {
/** Max number of buttons. Default 2. */
maxRows?: number;
/** Field name. Default 'links'. */
name?: string;
} & Omit<BuildLinkFieldOptions, 'disableLabel' | 'name'>;
/**
* 0..N buttons — use for every "CTA(s)" of a section. Each row holds one
* `link` (buildLinkField). Render: `links.map(({ id, link }) => <CMSLink … />)`.
*/
export declare function buildLinksField({ name, maxRows, ...linkOptions }?: BuildLinksFieldOptions): ArrayField;
+134
View File
@@ -0,0 +1,134 @@
const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/;
/**
* The ONE link shape for a project: a page, an external URL (also mailto:,
* tel:, #anchor) or an uploaded file — plus label, new-tab flag and visual
* style. Every CTA, card link and download in every block uses this field, so
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
* (resolveLinkHref + the project's CMSLink) handles them all.
*
* Generates a named TypeScript type `CmsLink` in payload-types.ts.
*
* fields: [buildLinkField()] // single link
* fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card
*/ export function buildLinkField({ name = 'link', appearances = [
'primary',
'secondary',
'link'
], disableLabel = false, relationTo = 'pages', required = false, uploadTo = 'media' } = {}) {
const fields = [
{
type: 'row',
fields: [
{
name: 'type',
type: 'radio',
admin: {
layout: 'horizontal',
width: '50%'
},
defaultValue: 'internal',
options: [
{
label: 'Page',
value: 'internal'
},
{
label: 'URL',
value: 'external'
},
{
label: 'File',
value: 'file'
}
]
},
{
name: 'newTab',
type: 'checkbox',
admin: {
style: {
alignSelf: 'flex-end'
},
width: '50%'
},
label: 'Open in new tab'
}
]
},
{
name: 'page',
type: 'relationship',
admin: {
condition: (_, s)=>s?.type === 'internal'
},
relationTo,
required
},
{
name: 'url',
type: 'text',
admin: {
condition: (_, s)=>s?.type === 'external',
description: 'Full URL (https://…), mailto:, tel: or #section-anchor.'
},
required,
validate: (v)=>!v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor'
},
{
name: 'file',
type: 'upload',
admin: {
condition: (_, s)=>s?.type === 'file',
description: 'Upload a PDF / document / image. Never paste a file URL.'
},
relationTo: uploadTo,
required
}
];
if (!disableLabel) {
fields.push({
name: 'label',
type: 'text',
localized: true,
required
});
}
if (appearances && appearances.length) {
fields.push({
name: 'appearance',
type: 'select',
defaultValue: appearances[0],
options: appearances.map((a)=>({
label: a,
value: a
}))
});
}
return {
name,
type: 'group',
admin: {
hideGutter: true
},
fields,
interfaceName: 'CmsLink'
};
}
/**
* 0..N buttons — use for every "CTA(s)" of a section. Each row holds one
* `link` (buildLinkField). Render: `links.map(({ id, link }) => <CMSLink … />)`.
*/ export function buildLinksField({ name = 'links', maxRows = 2, ...linkOptions } = {}) {
return {
name,
type: 'array',
admin: {
initCollapsed: true
},
fields: [
buildLinkField(linkOptions)
],
maxRows
};
}
//# sourceMappingURL=buildLinkField.js.map
File diff suppressed because one or more lines are too long
+4
View File
@@ -0,0 +1,4 @@
export { buildLinkField, buildLinksField } from './buildLinkField.js';
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js';
export { resolveLinkHref } from './resolveLinkHref.js';
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js';
+4
View File
@@ -0,0 +1,4 @@
export { buildLinkField, buildLinksField } from './buildLinkField.js';
export { resolveLinkHref } from './resolveLinkHref.js';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/links/index.ts"],"sourcesContent":["export { buildLinkField, buildLinksField } from './buildLinkField.js'\nexport type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'\nexport { resolveLinkHref } from './resolveLinkHref.js'\nexport type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'\n"],"names":["buildLinkField","buildLinksField","resolveLinkHref"],"mappings":"AAAA,SAASA,cAAc,EAAEC,eAAe,QAAQ,sBAAqB;AAErE,SAASC,eAAe,QAAQ,uBAAsB"}
+35
View File
@@ -0,0 +1,35 @@
import type { I18nConfig } from '../i18n/index.js';
/**
* Minimal shape of a link value (the project's generated `CmsLink` fits it).
* The plugin doesn't know the project's types — only this contract.
*/
export type LinkValue = {
appearance?: null | string;
file?: unknown;
label?: null | string;
newTab?: boolean | null;
page?: unknown;
type?: 'external' | 'file' | 'internal' | null;
url?: null | string;
};
export type ResolveLinkHrefOptions = {
config: I18nConfig;
/**
* Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a
* string. Usually from SiteSettings.homepage.
*/
homeSlug?: Record<string, string> | string;
locale: string;
};
/**
* Turns a link value (buildLinkField) into an href — the single place that
* knows the link types. Returns null when the link is empty or its target is
* missing in this locale (deleted page, page not populated, no file).
*
* Internal links need the related page POPULATED (block depth ≥ 2) — a bare ID
* resolves to null.
*
* resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
* // internal → '/en/about' · external → 'https://…' · file → media URL
*/
export declare function resolveLinkHref(link: LinkValue | null | undefined, { config, homeSlug, locale }: ResolveLinkHrefOptions): null | string;
+48
View File
@@ -0,0 +1,48 @@
import { buildLocalizedPath } from '../i18n/index.js';
/**
* Turns a link value (buildLinkField) into an href — the single place that
* knows the link types. Returns null when the link is empty or its target is
* missing in this locale (deleted page, page not populated, no file).
*
* Internal links need the related page POPULATED (block depth ≥ 2) — a bare ID
* resolves to null.
*
* resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
* // internal → '/en/about' · external → 'https://…' · file → media URL
*/ export function resolveLinkHref(link, { config, homeSlug, locale }) {
if (!link) {
return null;
}
if (link.type === 'external') {
return link.url?.trim() || null;
}
if (link.type === 'file') {
const file = link.file;
if (file && typeof file === 'object' && 'url' in file) {
const url = file.url;
return typeof url === 'string' && url ? url : null;
}
return null;
}
// internal (default)
const page = link.page;
if (!page || typeof page !== 'object') {
return null;
}
const slug = page.slug;
if (typeof slug !== 'string' || !slug) {
return null;
}
return buildLocalizedPath({
config,
locale,
slugs: {
[locale]: slug
},
...homeSlug ? {
homeSlug
} : {}
}) ?? null;
}
//# sourceMappingURL=resolveLinkHref.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/links/resolveLinkHref.ts"],"sourcesContent":["import type { I18nConfig } from '../i18n/index.js'\n\nimport { buildLocalizedPath } from '../i18n/index.js'\n\n/**\n * Minimal shape of a link value (the project's generated `CmsLink` fits it).\n * The plugin doesn't know the project's types — only this contract.\n */\nexport type LinkValue = {\n appearance?: null | string\n file?: unknown\n label?: null | string\n newTab?: boolean | null\n page?: unknown\n type?: 'external' | 'file' | 'internal' | null\n url?: null | string\n}\n\nexport type ResolveLinkHrefOptions = {\n config: I18nConfig\n /**\n * Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a\n * string. Usually from SiteSettings.homepage.\n */\n homeSlug?: Record<string, string> | string\n locale: string\n}\n\n/**\n * Turns a link value (buildLinkField) into an href — the single place that\n * knows the link types. Returns null when the link is empty or its target is\n * missing in this locale (deleted page, page not populated, no file).\n *\n * Internal links need the related page POPULATED (block depth ≥ 2) — a bare ID\n * resolves to null.\n *\n * resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })\n * // internal → '/en/about' · external → 'https://…' · file → media URL\n */\nexport function resolveLinkHref(\n link: LinkValue | null | undefined,\n { config, homeSlug, locale }: ResolveLinkHrefOptions,\n): null | string {\n if (!link) {return null}\n\n if (link.type === 'external') {return link.url?.trim() || null}\n\n if (link.type === 'file') {\n const file = link.file\n if (file && typeof file === 'object' && 'url' in file) {\n const url = (file as { url?: unknown }).url\n return typeof url === 'string' && url ? url : null\n }\n return null\n }\n\n // internal (default)\n const page = link.page\n if (!page || typeof page !== 'object') {return null}\n const slug = (page as { slug?: unknown }).slug\n if (typeof slug !== 'string' || !slug) {return null}\n\n return (\n buildLocalizedPath({\n config,\n locale,\n slugs: { [locale]: slug },\n ...(homeSlug ? { homeSlug } : {}),\n }) ?? null\n )\n}\n"],"names":["buildLocalizedPath","resolveLinkHref","link","config","homeSlug","locale","type","url","trim","file","page","slug","slugs"],"mappings":"AAEA,SAASA,kBAAkB,QAAQ,mBAAkB;AA0BrD;;;;;;;;;;CAUC,GACD,OAAO,SAASC,gBACdC,IAAkC,EAClC,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,MAAM,EAA0B;IAEpD,IAAI,CAACH,MAAM;QAAC,OAAO;IAAI;IAEvB,IAAIA,KAAKI,IAAI,KAAK,YAAY;QAAC,OAAOJ,KAAKK,GAAG,EAAEC,UAAU;IAAI;IAE9D,IAAIN,KAAKI,IAAI,KAAK,QAAQ;QACxB,MAAMG,OAAOP,KAAKO,IAAI;QACtB,IAAIA,QAAQ,OAAOA,SAAS,YAAY,SAASA,MAAM;YACrD,MAAMF,MAAM,AAACE,KAA2BF,GAAG;YAC3C,OAAO,OAAOA,QAAQ,YAAYA,MAAMA,MAAM;QAChD;QACA,OAAO;IACT;IAEA,qBAAqB;IACrB,MAAMG,OAAOR,KAAKQ,IAAI;IACtB,IAAI,CAACA,QAAQ,OAAOA,SAAS,UAAU;QAAC,OAAO;IAAI;IACnD,MAAMC,OAAO,AAACD,KAA4BC,IAAI;IAC9C,IAAI,OAAOA,SAAS,YAAY,CAACA,MAAM;QAAC,OAAO;IAAI;IAEnD,OACEX,mBAAmB;QACjBG;QACAE;QACAO,OAAO;YAAE,CAACP,OAAO,EAAEM;QAAK;QACxB,GAAIP,WAAW;YAAEA;QAAS,IAAI,CAAC,CAAC;IAClC,MAAM;AAEV"}
+21
View File
@@ -0,0 +1,21 @@
import type { ReactNode } from 'react';
type LocaleViewProps = {
/** Used when the URL has no locale segment (single-locale site) or an unknown one. */
defaultLocale: string;
/**
* One pre-rendered view per locale, e.g. { pl: <RenderBlocks …/>, en: … }.
* Rendered on the SERVER (RSC) and passed in as props — this component only
* picks one, so the content can come from the panel and the route stays static.
*/
views: Record<string, ReactNode>;
};
/**
* Shows the view matching the locale in the current URL (`/en/...` → `en`).
*
* Made for `not-found.tsx`, which receives no `params`: reading the locale with
* `headers()` there turns an SSG/ISR route dynamic ("Page changed from static
* to dynamic at runtime"). `usePathname()` is client-side and static-safe, and
* it also runs during SSR, so the HTML already contains the right language.
*/
export declare function LocaleView({ defaultLocale, views }: LocaleViewProps): import("react/jsx-runtime").JSX.Element;
export {};
+23
View File
@@ -0,0 +1,23 @@
'use client';
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
// '.js' is required: `next` has no package.json "exports", so NodeNext resolution
// (this plugin's tsconfig) can't find 'next/navigation' without the extension.
// Bundlers in the project resolve the same file either way.
import { usePathname } from 'next/navigation.js';
/**
* Shows the view matching the locale in the current URL (`/en/...` → `en`).
*
* Made for `not-found.tsx`, which receives no `params`: reading the locale with
* `headers()` there turns an SSG/ISR route dynamic ("Page changed from static
* to dynamic at runtime"). `usePathname()` is client-side and static-safe, and
* it also runs during SSR, so the HTML already contains the right language.
*/ export function LocaleView({ defaultLocale, views }) {
const pathname = usePathname() ?? '';
const segment = pathname.split('/').filter(Boolean)[0] ?? '';
const locale = segment in views ? segment : defaultLocale;
return /*#__PURE__*/ _jsx(_Fragment, {
children: views[locale] ?? views[defaultLocale] ?? null
});
}
//# sourceMappingURL=LocaleView.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/pages/LocaleView.tsx"],"sourcesContent":["'use client'\nimport type { ReactNode } from 'react'\n// '.js' is required: `next` has no package.json \"exports\", so NodeNext resolution\n// (this plugin's tsconfig) can't find 'next/navigation' without the extension.\n// Bundlers in the project resolve the same file either way.\nimport { usePathname } from 'next/navigation.js'\n\ntype LocaleViewProps = {\n /** Used when the URL has no locale segment (single-locale site) or an unknown one. */\n defaultLocale: string\n /**\n * One pre-rendered view per locale, e.g. { pl: <RenderBlocks …/>, en: … }.\n * Rendered on the SERVER (RSC) and passed in as props — this component only\n * picks one, so the content can come from the panel and the route stays static.\n */\n views: Record<string, ReactNode>\n}\n\n/**\n * Shows the view matching the locale in the current URL (`/en/...` → `en`).\n *\n * Made for `not-found.tsx`, which receives no `params`: reading the locale with\n * `headers()` there turns an SSG/ISR route dynamic (\"Page changed from static\n * to dynamic at runtime\"). `usePathname()` is client-side and static-safe, and\n * it also runs during SSR, so the HTML already contains the right language.\n */\nexport function LocaleView({ defaultLocale, views }: LocaleViewProps) {\n const pathname = usePathname() ?? ''\n const segment = pathname.split('/').filter(Boolean)[0] ?? ''\n const locale = segment in views ? segment : defaultLocale\n return <>{views[locale] ?? views[defaultLocale] ?? null}</>\n}\n"],"names":["usePathname","LocaleView","defaultLocale","views","pathname","segment","split","filter","Boolean","locale"],"mappings":"AAAA;;AAEA,kFAAkF;AAClF,+EAA+E;AAC/E,4DAA4D;AAC5D,SAASA,WAAW,QAAQ,qBAAoB;AAahD;;;;;;;CAOC,GACD,OAAO,SAASC,WAAW,EAAEC,aAAa,EAAEC,KAAK,EAAmB;IAClE,MAAMC,WAAWJ,iBAAiB;IAClC,MAAMK,UAAUD,SAASE,KAAK,CAAC,KAAKC,MAAM,CAACC,QAAQ,CAAC,EAAE,IAAI;IAC1D,MAAMC,SAASJ,WAAWF,QAAQE,UAAUH;IAC5C,qBAAO;kBAAGC,KAAK,CAACM,OAAO,IAAIN,KAAK,CAACD,cAAc,IAAI;;AACrD"}
+28 -7
View File
@@ -14,7 +14,13 @@ type RobotRule = {
export declare const AI_ASSISTANT_BOTS: readonly ["ClaudeBot", "Claude-Web", "Claude-SearchBot", "ChatGPT-User", "OAI-SearchBot", "PerplexityBot", "Perplexity-User"];
export declare const AI_TRAINING_BOTS: readonly ["GPTBot", "Google-Extended", "CCBot", "anthropic-ai", "Applebot-Extended", "Bytespider", "Meta-ExternalAgent"];
type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false;
type BuildRobotsArgs = {
export type RobotsOptions = {
/**
* Admin path to disallow. Default '/admin'. With a hidden panel
* (ipalKit adminRoute) pass `false`: robots.txt is public, so listing the
* path would reveal it — the admin is noindex anyway.
*/
adminRoute?: false | string;
/** Override the assistant/search bot list. */
aiAssistantAgents?: readonly string[];
/**
@@ -31,13 +37,27 @@ type BuildRobotsArgs = {
aiBots?: AiBotsPolicy;
/** Override the training crawler list. */
aiTrainingAgents?: readonly string[];
/** Absolute origin, e.g. 'https://example.com'. */
baseUrl: string;
/** Paths to disallow. Defaults to Payload's admin and API. */
/**
* Full disallow list — REPLACES the defaults ([adminRoute, '/api']). Prefer
* `extraDisallow` / `disallowParams`, which add to the defaults instead.
*/
disallow?: string[];
/**
* Query parameters whose URLs crawlers should skip (thin/duplicate pages that
* waste crawl budget), e.g. ['s', 'meter', 'utm_source']. Each becomes
* `/*?name=` and `/*&name=` (the parameter may not be first).
* Don't list `page` — paginated archives are real, canonical-to-self pages.
*/
disallowParams?: string[];
/** Paths added to the default disallow list, e.g. ['/koszyk']. */
extraDisallow?: string[];
/** Whether to advertise the sitemap. Defaults to true. */
sitemap?: boolean;
};
type BuildRobotsArgs = {
/** Absolute origin, e.g. 'https://example.com'. */
baseUrl: string;
} & RobotsOptions;
/**
* Shape for Next's `app/robots.ts`. `rules` may be a single rule or an array
* (Next accepts both) — it becomes an array when AI-bot rules are added.
@@ -68,10 +88,11 @@ export type RobotsRules = {
* PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of
* model training, use `aiBots: 'block-training'`. To block them all, 'disallow'.
*
* Pass custom disallow to block parametrized/thin URLs that waste crawl budget:
* Block parametrized/thin URLs that waste crawl budget — added to the defaults:
* ```ts
* buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] })
* buildRobots({ baseUrl, disallowParams: ['s', 'meter'] })
* // Disallow: /admin, /api, /*?s=, /*&s=, /*?meter=, /*&meter=
* ```
*/
export declare function buildRobots({ aiAssistantAgents, aiBots, aiTrainingAgents, baseUrl, disallow, sitemap, }: BuildRobotsArgs): RobotsRules;
export declare function buildRobots({ adminRoute, aiAssistantAgents, aiBots, aiTrainingAgents, baseUrl, disallow: disallowOverride, disallowParams, extraDisallow, sitemap, }: BuildRobotsArgs): RobotsRules;
export {};
+21 -6
View File
@@ -44,15 +44,30 @@ export const AI_TRAINING_BOTS = [
* PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of
* model training, use `aiBots: 'block-training'`. To block them all, 'disallow'.
*
* Pass custom disallow to block parametrized/thin URLs that waste crawl budget:
* Block parametrized/thin URLs that waste crawl budget — added to the defaults:
* ```ts
* buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] })
* buildRobots({ baseUrl, disallowParams: ['s', 'meter'] })
* // Disallow: /admin, /api, /*?s=, /*&s=, /*?meter=, /*&meter=
* ```
*/ export function buildRobots({ aiAssistantAgents = AI_ASSISTANT_BOTS, aiBots = 'allow', aiTrainingAgents = AI_TRAINING_BOTS, baseUrl, disallow = [
'/admin',
'/api'
], sitemap = true }) {
*/ export function buildRobots({ adminRoute = '/admin', aiAssistantAgents = AI_ASSISTANT_BOTS, aiBots = 'allow', aiTrainingAgents = AI_TRAINING_BOTS, baseUrl, disallow: disallowOverride, disallowParams = [], extraDisallow = [], sitemap = true }) {
const origin = baseUrl.replace(/\/$/, '');
const defaults = [
...adminRoute ? [
adminRoute
] : [],
'/api'
];
const paramRules = disallowParams.map((p)=>p.trim()).filter(Boolean).flatMap((p)=>[
`/*?${p}=`,
`/*&${p}=`
]);
const disallow = [
...new Set([
...disallowOverride ?? defaults,
...extraDisallow,
...paramRules
])
];
const baseRule = {
allow: '/',
disallow,
File diff suppressed because one or more lines are too long
+10 -1
View File
@@ -1,5 +1,5 @@
import type { BasePayload } from 'payload';
import type { ContentOption } from '../content/index.js';
import type { ContentOption, ResolvedRoute } from '../content/index.js';
import type { I18nConfig } from '../i18n/index.js';
import type { PageMetadata } from './buildMetadata.js';
type CreatePageMetadataArgs = {
@@ -14,6 +14,15 @@ type CreatePageMetadataArgs = {
* omit it and only pages are handled.
*/
content?: ContentOption;
/**
* Request-cached loaders (createContentHelpers passes its own), so metadata
* reuses the SAME settings read and route resolution as the layout and the
* page component instead of querying again. Omit → plain queries.
*/
loaders?: {
getSettings?: (locale: string) => Promise<null | Record<string, unknown>>;
resolveRoute?: (locale: string, segments: string[] | undefined, page: number) => Promise<null | ResolvedRoute>;
};
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string;
/** Field on SiteSettings holding the site name. Defaults to 'siteName'. */
+6 -2
View File
@@ -34,11 +34,14 @@ import { slugsAcrossLocales } from './slugsAcrossLocales.js';
* }
* ```
*/ export function createPageMetadata(args) {
const { baseUrl, collection = 'pages', config, content, settingsSlug = 'site-settings', siteNameField = 'siteName' } = args;
const { baseUrl, collection = 'pages', config, content, loaders, settingsSlug = 'site-settings', siteNameField = 'siteName' } = args;
return async function pageMetadata({ slug, locale, page, payload }) {
const settings = loaders?.getSettings ? await loaders.getSettings(locale) : undefined;
const site = await readSiteMetaConfig({
locale,
pagesSlug: collection,
payload,
settings,
settingsSlug,
siteNameField
});
@@ -51,13 +54,14 @@ import { slugsAcrossLocales } from './slugsAcrossLocales.js';
separator: site.separator,
siteName: site.siteName
};
const route = await resolveRoute({
const route = loaders?.resolveRoute ? await loaders.resolveRoute(locale, slug, page ?? 1) : await resolveRoute({
content,
locale,
page,
pagesSlug: collection,
payload,
segments: slug,
settings,
settingsSlug
});
// Unknown route (the page component will 404) — still return something
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -12,7 +12,7 @@ export type { PageMetadata } from './buildMetadata.js';
export { buildNoindexField } from './buildNoindexField.js';
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js';
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js';
export type { RobotsRules } from './buildRobots.js';
export type { RobotsOptions, RobotsRules } from './buildRobots.js';
export { buildServiceJsonLd } from './buildServiceJsonLd.js';
export { buildSitemapEntries } from './buildSitemapEntries.js';
export type { SitemapEntry } from './buildSitemapEntries.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'\nexport { buildSummaryField } from './buildSummaryField.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,WAAW,QAAQ,mBAAkB;AAEnF,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildNoindexField } from './buildNoindexField.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'\nexport type { RobotsOptions, RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'\nexport { buildSummaryField } from './buildSummaryField.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildNoindexField","buildOrganizationJsonLd","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,iBAAiB,EAAEC,gBAAgB,EAAEC,WAAW,QAAQ,mBAAkB;AAEnF,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,oBAAoB,QAAQ,4BAA2B;AAChE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
+5 -1
View File
@@ -23,9 +23,13 @@ export type SiteMetaConfig = {
* that the separator arrives unpadded, or that the home slug hides inside a
* relationship — it should receive a resolved config.
*/
export declare function readSiteMetaConfig({ locale, payload, settingsSlug, siteNameField, }: {
export declare function readSiteMetaConfig({ locale, pagesSlug, payload, settings: preloaded, settingsSlug, siteNameField, }: {
locale: string;
/** Collection holding the homepage. Default 'pages'. */
pagesSlug?: string;
payload: BasePayload;
/** SiteSettings already read for this locale (depth ≥ 1) — skips the read. */
settings?: null | Record<string, unknown>;
settingsSlug?: string;
siteNameField?: string;
}): Promise<SiteMetaConfig>;
+3 -3
View File
@@ -5,10 +5,10 @@
* whatever an editor set in the panel. Metadata generation shouldn't also know
* that the separator arrives unpadded, or that the home slug hides inside a
* relationship — it should receive a resolved config.
*/ export async function readSiteMetaConfig({ locale, payload, settingsSlug = 'site-settings', siteNameField = 'siteName' }) {
*/ export async function readSiteMetaConfig({ locale, pagesSlug = 'pages', payload, settings: preloaded, settingsSlug = 'site-settings', siteNameField = 'siteName' }) {
// depth 1 populates the homepage relationship, so its slug is available
// without a second query.
const settings = await payload.findGlobal({
const settings = preloaded ?? await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: locale
@@ -23,7 +23,7 @@
try {
const homeDoc = await payload.findByID({
id: homepage.id,
collection: 'pages',
collection: pagesSlug,
depth: 0,
locale: 'all'
});
File diff suppressed because one or more lines are too long
+40 -1
View File
@@ -1,4 +1,32 @@
import type { Plugin } from 'payload';
type GenerateFileURL = (args: {
filename: string;
prefix?: string;
}) => string;
/**
* Minimal shape of `s3Storage` from @payloadcms/storage-s3 — the plugin never
* imports that package (it's optional: projects on local disk don't install it).
* The project injects the real function; TypeScript checks it fits this shape.
*/
export type S3StorageFactory = (options: {
bucket: string;
collections: Record<string, {
generateFileURL: GenerateFileURL;
} | true>;
config: {
credentials: {
accessKeyId: string;
secretAccessKey: string;
};
endpoint: string;
forcePathStyle: boolean;
region: string;
};
}) => Plugin;
export type BuildR2StorageDeps = {
/** `import { s3Storage } from '@payloadcms/storage-s3'` — required when R2 env is set. */
s3Storage?: S3StorageFactory;
};
/**
* Cloudflare R2 media storage — configured from environment variables (agency
* infrastructure, not per-project panel data). R2 is S3-compatible, so we use
@@ -13,6 +41,17 @@ import type { Plugin } from 'payload';
* storage (useful in dev without R2). This mirrors how mailAdapter degrades
* gracefully when a transport isn't configured.
*
* The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse):
*
* import { s3Storage } from '@payloadcms/storage-s3'
* plugins: [buildR2Storage(['media'], { s3Storage })]
*
* A static import here would make @payloadcms/storage-s3 mandatory for every
* project — including ones on local disk — because this module is exported
* from the package's main entry.
*
* @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])
* @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set)
*/
export declare const buildR2Storage: (collections?: string[]) => Plugin;
export declare const buildR2Storage: (collections?: string[], deps?: BuildR2StorageDeps) => Plugin;
export {};
+17 -2
View File
@@ -1,4 +1,3 @@
import { s3Storage } from '@payloadcms/storage-s3';
/**
* Cloudflare R2 media storage — configured from environment variables (agency
* infrastructure, not per-project panel data). R2 is S3-compatible, so we use
@@ -13,10 +12,20 @@ import { s3Storage } from '@payloadcms/storage-s3';
* storage (useful in dev without R2). This mirrors how mailAdapter degrades
* gracefully when a transport isn't configured.
*
* The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse):
*
* import { s3Storage } from '@payloadcms/storage-s3'
* plugins: [buildR2Storage(['media'], { s3Storage })]
*
* A static import here would make @payloadcms/storage-s3 mandatory for every
* project — including ones on local disk — because this module is exported
* from the package's main entry.
*
* @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])
* @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set)
*/ export const buildR2Storage = (collections = [
'media'
])=>{
], deps = {})=>{
const bucket = process.env.R2_BUCKET;
const endpoint = process.env.R2_ENDPOINT;
const accessKeyId = process.env.R2_ACCESS_KEY_ID;
@@ -47,6 +56,12 @@ import { s3Storage } from '@payloadcms/storage-s3';
prefix,
filename
].filter(Boolean).join('/') : undefined;
// R2 env is complete → the adapter is required. Fail loudly at boot rather
// than silently storing media on the container disk (lost on redeploy).
const { s3Storage } = deps;
if (!s3Storage) {
throw new Error('[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' + "Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) " + "with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md.");
}
const collectionsConfig = {};
for (const slug of collections){
collectionsConfig[slug] = generateFileURL ? {
File diff suppressed because one or more lines are too long
+1
View File
@@ -1 +1,2 @@
export { buildR2Storage } from './buildR2Storage.js';
export type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/storage/index.ts"],"sourcesContent":["export { buildR2Storage } from './buildR2Storage.js'\n"],"names":["buildR2Storage"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"}
{"version":3,"sources":["../../../src/modules/storage/index.ts"],"sourcesContent":["export { buildR2Storage } from './buildR2Storage.js'\nexport type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js'\n"],"names":["buildR2Storage"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAqB"}
+2 -1
View File
@@ -22,6 +22,7 @@ Szczegóły API — jeden plik na moduł:
| Formularze, useForm, honeypot | [forms.md](./forms.md) |
| Hooki | [hooks.md](./hooks.md) |
| i18n, proxy, przełącznik języka | [i18n.md](./i18n.md) |
| Linki / CTA: buildLinkField, buildLinksField, resolveLinkHref | [links.md](./links.md) |
| Serwer MCP strony | [mcp.md](./mcp.md) |
| Komunikaty formularzy | [notifications.md](./notifications.md) |
| Strony systemowe, 404, generateStaticParams | [pages.md](./pages.md) |
@@ -36,4 +37,4 @@ Szczegóły API — jeden plik na moduł:
Zasada utrzymania: zmiana API modułu → aktualizacja jego pliku w tym samym
commicie. Nowe reguły pracy → AGENT.md. Nowy krok procesu → PROGRAMISTA.md. Nowy etap budowy → vibe.md.
Nie dodawaj kolejnych plików ogólnych.
Nie dodawaj kolejnych plików ogólnych.
+1 -1
View File
@@ -76,4 +76,4 @@ import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/
```ts
import { ROLE_HIERARCHY } from '@intecion/ipal-kit'
// ['user', 'editor', 'admin'] — wyższa rola spełnia wymóg niższej
```
```
+1 -1
View File
@@ -190,4 +190,4 @@ to **opcja, nie obowiązek** — dodawaj gdy klient wymaga, nie z automatu.
Gdy dodajesz: widget sam w sobie NIE czyni strony w pełni dostępną — to pomoc dla
użytkownika. Pełna dostępność to też semantyczny HTML, alt teksty, nawigacja
klawiaturą, kontrast bazowy. Widget uzupełnia, nie zastępuje. Nie sprzedawaj
klientowi „mamy widget = jesteśmy zgodni z WCAG". Patrz PROGRAMISTA.md §5.
klientowi „mamy widget = jesteśmy zgodni z WCAG". Patrz PROGRAMISTA.md §5.
+77 -630
View File
@@ -8,9 +8,9 @@
>
> **W projekcie:**
> - w roocie krótki `AGENTS.md` (szablon w §13), który wskazuje na ten plik w
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` — nie kopiuj reguł, kopia się zestarzeje;
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` — nie kopiuj reguł, kopia się zestarzeje;
> - skille w `.agents/skills/` (§14) — kopiowane z pakietu jedną komendą, odświeżane
> po każdej aktualizacji ipal-kit.
> po każdej aktualizacji ipal-kit.
---
@@ -25,7 +25,7 @@
ląduje w `<body>` i SEO pada.
5. **Minimum kolekcji.** Users są wbudowane, dane firmy/nawigacja to globale,
FAQ/hero to bloki.
6. **Sekcja = kompozycja prymitywów.** `linksField()` + `<CMSLink>`, upload +
6. **Sekcja = kompozycja prymitywów.** `buildLinksField()` + `<CMSLink>`, upload +
`<Media>`, `<Section>` + `<SectionHeader>`. Zero pól `ctaLabel`/`pdfUrl`.
7. **Renderery z pluginu:** `RenderBlocks` (nie `switch`), `RenderRichText` (nie
własny parser Lexical), `useForm` (nie ręczna hydraulika formularza).
@@ -74,7 +74,7 @@ gatingiem zgody (plugin ma opcję `defer`).
|---|---|---|
| Tekst | tekst w JSX, `if (locale === 'pl')`, tablice tekstów w kodzie | pole `localized: true` z panelu |
| Obraz / plik | `import x from '@/assets/…'`, `src="/images/…"`, URL pliku w polu `text` | `upload → media` + `<Media>` / link typu `file` |
| Link | `href="/pl/kontakt"`, menu jako tablica, mapa `localizedRoutes` | `linkField()` + `<CMSLink>`, `getLocalizedSlugs`, `getSystemPagePath`, nawigacja jako relationship → pages |
| Link | `href="/pl/kontakt"`, menu jako tablica, mapa `localizedRoutes` | `buildLinkField()` + `<CMSLink>`, `getLocalizedSlugs`, `getSystemPagePath`, nawigacja jako relationship → pages |
| Konfiguracja | `locale as 'pl' \| 'en'`, zaszyty slug kolekcji, lista języków `['pl','en']` | `i18n.config.ts`, `locale as never`, lista z configu |
| Dane firmy | NIP, adres, telefon, nazwa w kodzie | global (`siteSettings` / `company`) |
| Infrastruktura | domena, klucz, bucket w kodzie | `.env` |
@@ -105,7 +105,7 @@ src/
sitemap.ts, robots.ts # z lib/content (+ force-dynamic na sitemap)
api/health/route.ts # createHealthRoute
instrumentation.ts # assertEnv(ipalEnvRules({...}))
fields/ # wspólne pola: link.ts, sectionHeader.ts, sectionSettings.ts
fields/ # sectionHeader.ts, sectionSettings.ts (linki: z pluginu)
components/
ui/ # prymitywy: CMSLink, Button, Media, Section, SectionHeader
layout/ # Header, Footer, MobileNav (§6.8)
@@ -115,7 +115,6 @@ src/
collections/ # Pages.ts, Media.ts (+ treść tylko gdy wymagana)
globals/ # Header.ts, Footer.ts, Company.ts
lib/content.ts # createContentHelpers — JEDYNY dostęp do Payloada
lib/links.ts # resolveLinkHref
lib/navigation.ts # resolveNav → dane dla menu
i18n.config.ts # locale — jedno źródło
payload.config.ts
@@ -150,8 +149,11 @@ Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`,
dynamiczna → metadata w body.
5. **`htmlLimitedBots`** w `next.config.ts` (seo.md).
6. **Nie czytaj `searchParams`** w stronie bez paginacji — deoptymalizuje
ISR/SSG. Nie czytaj `headers()` w komponentach bloków (to samo). Locale do
bloków wstrzykuj przez `enhanceProps`.
ISR/SSG. **Nie czytaj `headers()` / `cookies()`** nigdzie w drzewie stron
statycznych — w blokach, komponentach, layoucie `[locale]` ani w
`not-found.tsx` (Next 16: `Page changed from static to dynamic at runtime`).
Locale do bloków → `enhanceProps`; w `not-found.tsx` (brak `params`) →
wersja na każdy język + `<LocaleView>` (pages.md).
7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę:
`manifest.ts`, `sitemap.ts`/`sitemap.xml`, `llms.txt`, `api/health`. Handlery
pluginu mają try/catch, ale `dynamic` musi być w pliku trasy.
@@ -219,7 +221,8 @@ Trzy problemy, których nie wolno powtarzać: **zoo pól CTA** (`ctaLabel`,
### 6.1 Trzy warstwy
```
src/fields/ WARSTWA 1 — wspólne pola schematu (link, header, settings)
WARSTWA 1 — wspólne pola: linki z pluginu (buildLinkField, buildLinksField)
+ src/fields/ projektu (sectionHeader, sectionSettings)
src/components/ui/ WARSTWA 2 — prymitywy UI (CMSLink, Button, Media, Section, SectionHeader)
src/blocks/X/ WARSTWA 3 — sekcja = kompozycja warstw 1 i 2
```
@@ -228,364 +231,51 @@ musisz zmieniać 12 bloków, architektura jest zła.
### 6.2 Warstwa 1 — wspólne pola
`src/fields/link.ts` — **jedyny sposób na link/CTA**:
**Link / CTA — z pluginu** ([links.md](../links.md)), nigdy kopia w projekcie:
```ts
import type { ArrayField, Field, GroupField } from 'payload'
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
export type LinkAppearance = 'primary' | 'secondary' | 'link'
type LinkFieldOptions = {
name?: string
/** Which visual styles the editor may pick. false → no appearance select. */
appearances?: LinkAppearance[] | false
/** Label hidden for links that wrap something (a card, an image). */
disableLabel?: boolean
required?: boolean
}
const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/
export function linkField({
name = 'link',
appearances = ['primary', 'secondary', 'link'],
disableLabel = false,
required = false,
}: LinkFieldOptions = {}): GroupField {
const fields: Field[] = [
{
type: 'row',
fields: [
{
name: 'type',
type: 'radio',
defaultValue: 'internal',
options: [
{ label: 'Page', value: 'internal' },
{ label: 'URL', value: 'external' },
{ label: 'File', value: 'file' },
],
admin: { layout: 'horizontal', width: '50%' },
},
{
name: 'newTab',
type: 'checkbox',
label: 'Open in new tab',
admin: { width: '50%', style: { alignSelf: 'flex-end' } },
},
],
},
{
name: 'page',
type: 'relationship',
relationTo: 'pages',
required,
admin: { condition: (_, s) => s?.type === 'internal' },
},
{
name: 'url',
type: 'text',
required,
validate: (v: string | null | undefined) =>
!v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor',
admin: {
condition: (_, s) => s?.type === 'external',
description: 'Full URL (https://…), mailto:, tel: or #section-anchor.',
},
},
{
name: 'file',
type: 'upload',
relationTo: 'media',
required,
admin: {
condition: (_, s) => s?.type === 'file',
description: 'Upload a PDF / document / image. Never paste a file URL.',
},
},
]
if (!disableLabel) {
fields.push({ name: 'label', type: 'text', localized: true, required })
}
if (appearances && appearances.length) {
fields.push({
name: 'appearance',
type: 'select',
defaultValue: appearances[0],
options: appearances.map((a) => ({ label: a, value: a })),
})
}
return {
name,
type: 'group',
interfaceName: 'CmsLink', // → `CmsLink` type in payload-types.ts
admin: { hideGutter: true },
fields,
}
}
/** 0..N buttons. Use this for every "CTA(s)" in a section. */
export function linksField({
name = 'links',
maxRows = 2,
appearances,
}: { name?: string; maxRows?: number; appearances?: LinkAppearance[] } = {}): ArrayField {
return {
name,
type: 'array',
maxRows,
admin: { initCollapsed: true },
fields: [linkField({ appearances })],
}
}
buildLinksField() // pole `links`: 0–2 przyciski sekcji
buildLinkField() // pole `link`: pojedynczy link
buildLinkField({ disableLabel: true, appearances: false }) // klikalna cała karta
```
Typ linku: strona / URL (też mailto, tel, #anchor) / **plik** (upload). Plik do
pobrania = link typu `file`, nigdy pole `pdfUrl`. W `payload-types.ts`: `CmsLink`.
Całe CTA w bloku to jedna linia: `linksField()`. Karta klikalna w całości:
`linkField({ disableLabel: true, appearances: false })`.
**Obraz / wideo:** `{ name: 'media', type: 'upload', relationTo: 'media' }`. Kolekcja
`media` dopuszcza PDF, ma `alt` (required, localized) i `normalizeFilenameHook`.
**Pliki i obrazy:** `{ name: 'media', type: 'upload', relationTo: 'media' }`.
Kolekcja `media` dopuszcza PDF (`upload.mimeTypes: ['image/*', 'application/pdf',
'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`.
„Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`.
`src/fields/sectionHeader.ts` i `src/fields/sectionSettings.ts`:
```ts
import type { GroupField } from 'payload'
export function sectionHeaderField(name = 'header'): GroupField {
return {
name,
type: 'group',
interfaceName: 'SectionHeaderData',
fields: [
{ name: 'eyebrow', type: 'text', localized: true },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', localized: true },
],
}
}
export function sectionSettingsField(): GroupField {
return {
name: 'settings',
type: 'group',
interfaceName: 'SectionSettings',
admin: { position: 'sidebar' },
fields: [
{
name: 'anchor',
type: 'text',
admin: { description: 'Section id for #links and section nav, e.g. "pricing".' },
},
{
name: 'background',
type: 'select',
defaultValue: 'default',
options: ['default', 'muted', 'inverted'].map((v) => ({ label: v, value: v })),
},
],
}
}
```
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN).
**W projekcie (`src/fields/`)** — dwa małe helpery, kod w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md):
- `sectionHeaderField()` → grupa `header`: `eyebrow`, `heading`, `intro` (localized),
- `sectionSettingsField()` → grupa `settings` (sidebar): `anchor`, `background`.
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `sectionId` per blok.
Etykiety pól po angielsku (panel jest EN).
### 6.3 Warstwa 2 — prymitywy UI
`src/lib/links.ts` — jedyne miejsce, które zna typy linków:
Kod 1:1: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). Każdy ma jedno zadanie:
```ts
import type { CmsLink } from '@/payload-types'
import { buildLocalizedPath } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
export function resolveLinkHref(
link: CmsLink | null | undefined,
locale: string,
homeSlug?: string,
): string | null {
if (!link) return null
if (link.type === 'external') return link.url || null
if (link.type === 'file') {
const file = link.file
return file && typeof file === 'object' && file.url ? file.url : null
}
// internal — `page` must be populated (block depth ≥ 2), not a bare ID
const page = link.page
if (!page || typeof page !== 'object' || typeof page.slug !== 'string') return null
return (
buildLocalizedPath({
slugs: { [locale]: page.slug },
locale,
config: i18nConfig,
...(homeSlug ? { homeSlug } : {}),
}) ?? null
)
}
```
`src/components/ui/CMSLink.tsx` — **każdy** link/przycisk z panelu:
```tsx
import Link from 'next/link'
import type { ReactNode } from 'react'
import type { CmsLink } from '@/payload-types'
import { resolveLinkHref } from '@/lib/links'
import { getSettings } from '@/lib/content'
import { buttonClass } from './Button'
type Props = {
link: CmsLink | null | undefined
locale: string
className?: string
/** For wrapping links (cards): content instead of link.label. */
children?: ReactNode
}
export async function CMSLink({ link, locale, className, children }: Props) {
const settings = await getSettings(locale) // react cache → one query per request
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
const href = resolveLinkHref(link, locale, homeSlug)
const content = children ?? link?.label
if (!link || !href || !content) return null
const cls = [link.appearance ? buttonClass(link.appearance) : '', className]
.filter(Boolean)
.join(' ')
const newTab = link.newTab || link.type === 'file'
const targetProps = newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {}
if (link.type === 'internal') {
return <Link href={href} className={cls} {...targetProps}>{content}</Link>
}
return <a href={href} className={cls} {...targetProps}>{content}</a>
}
```
`src/components/ui/Button.tsx` — warianty jako mapa, nie ternary:
```ts
import type { LinkAppearance } from '@/fields/link'
const VARIANTS: Record<LinkAppearance, string> = {
primary: 'btn btn-primary',
secondary: 'btn btn-secondary',
link: 'link-arrow',
}
export function buttonClass(appearance: LinkAppearance): string {
return VARIANTS[appearance]
}
```
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu:
```tsx
import Image from 'next/image'
import type { Media as MediaDoc } from '@/payload-types'
type Props = {
resource: MediaDoc | string | number | null | undefined
sizes?: string
priority?: boolean
className?: string
}
export function Media({ resource, sizes = '100vw', priority = false, className }: Props) {
if (!resource || typeof resource !== 'object' || !resource.url) return null
const { url, alt, width, height, mimeType } = resource
if (mimeType?.startsWith('video/')) {
return <video src={url} className={className} autoPlay muted loop playsInline />
}
if (!width || !height) return null // non-image file (PDF) — use CMSLink type 'file'
return (
<Image src={url} alt={alt ?? ''} width={width} height={height}
sizes={sizes} priority={priority} className={className} />
)
}
```
`Section.tsx` i `SectionHeader.tsx`:
```tsx
// src/components/ui/Section.tsx
import type { ReactNode } from 'react'
import type { SectionSettings } from '@/payload-types'
const BACKGROUNDS: Record<NonNullable<SectionSettings['background']>, string> = {
default: 'bg-background',
muted: 'bg-muted',
inverted: 'bg-foreground text-background',
}
export function Section({ settings, children }: { settings?: SectionSettings | null; children: ReactNode }) {
return (
<section
id={settings?.anchor || undefined}
className={`py-16 md:py-24 ${BACKGROUNDS[settings?.background ?? 'default']}`}
>
<div className="container">{children}</div>
</section>
)
}
```
```tsx
// src/components/ui/SectionHeader.tsx
import type { SectionHeaderData } from '@/payload-types'
export function SectionHeader({ header, as: H = 'h2' }: { header?: SectionHeaderData | null; as?: 'h1' | 'h2' }) {
if (!header?.heading && !header?.eyebrow && !header?.intro) return null
return (
<header className="mb-10 max-w-2xl">
{header.eyebrow && <p className="eyebrow">{header.eyebrow}</p>}
{header.heading && <H className="heading">{header.heading}</H>}
{header.intro && <p className="lead">{header.intro}</p>}
</header>
)
}
```
**`locale` dla każdego bloku — raz, w trasie strony:**
| Prymityw | Robi | Zamiast |
|---|---|---|
| `CMSLink` (async, serwer) | każdy link z panelu: `resolveLinkHref` z pluginu + styl z `Button` + `newTab`/plik | `<a href>`, `<Link href>` w sekcjach |
| `Button.tsx` | `Record<LinkAppearance, string>` z klasami wariantów | łańcuchy ternary, style przycisków w sekcjach |
| `Media` | każdy obraz/wideo z panelu (`next/image`, alt z dokumentu) | `<img src={x.url}>` |
| `Section` | `id` z anchora, tło z mapy, kontener | ręczne `<section className=…>` |
| `SectionHeader` | eyebrow + nagłówek (`h1`/`h2`) + intro | luźne nagłówki w każdej sekcji |
**`locale` dla bloków — raz, w trasie strony** (nigdy `headers()` w komponentach):
```tsx
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
locale,
...(block.blockType === 'formBlock' ? { turnstileSiteKey } : {}),
})
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
```
### 6.4 Warstwa 3 — sekcja = kompozycja
```ts
// src/blocks/Hero/config.ts
import type { Block } from 'payload'
import { linksField } from '@/fields/link'
import { sectionHeaderField } from '@/fields/sectionHeader'
import { sectionSettingsField } from '@/fields/sectionSettings'
export const HeroBlock: Block = {
slug: 'hero',
interfaceName: 'HeroBlock',
labels: { singular: 'Hero', plural: 'Heroes' },
fields: [
sectionHeaderField(),
{ name: 'media', type: 'upload', relationTo: 'media' },
linksField(),
sectionSettingsField(),
],
}
```
Wzorcowy kształt sekcji (cały komponent; schemat `config.ts` i przykład z
powtarzalnymi elementami — `FeatureGrid` + `FeatureCard` — w [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md)):
```tsx
// src/blocks/Hero/Component.tsx — cały komponent
@@ -614,66 +304,17 @@ export function Hero({ header, media, links, settings, locale }: HeroBlock & { l
}
```
Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
```ts
// src/blocks/FeatureGrid/config.ts (fields)
sectionHeaderField(),
{
name: 'items',
type: 'array',
interfaceName: 'FeatureItem',
fields: [
{ name: 'media', type: 'upload', relationTo: 'media' },
{ name: 'heading', type: 'text', localized: true, required: true },
{ name: 'text', type: 'textarea', localized: true },
linkField({ appearances: ['link'] }),
],
},
linksField({ maxRows: 1 }),
sectionSettingsField(),
```
```tsx
// src/blocks/FeatureGrid/FeatureCard.tsx
export function FeatureCard({ item, locale }: { item: FeatureItem; locale: string }) {
return (
<article className="card">
<Media resource={item.media} sizes="(min-width: 1024px) 33vw, 100vw" />
<h3>{item.heading}</h3>
{item.text && <p>{item.text}</p>}
<CMSLink link={item.link} locale={locale} />
</article>
)
}
// src/blocks/FeatureGrid/Component.tsx
export function FeatureGrid({ header, items, links, settings, locale }: FeatureGridBlock & { locale: string }) {
return (
<Section settings={settings}>
<SectionHeader header={header} />
<div className="grid gap-6 md:grid-cols-3">
{items?.map((item) => <FeatureCard key={item.id} item={item} locale={locale} />)}
</div>
{links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} className="mt-10" />)}
</Section>
)
}
```
**Wydziel podkomponent, gdy którekolwiek jest prawdą:** ten sam JSX 2+ razy;
element `items[]` ma >5 linii markupu; `Component.tsx` >80 linii JSX; jest stan/
interakcja (accordion, slider, tabs → osobny `'use client'`). Podkomponent
jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/components/ui/`.
Ikony: upload albo `select` z mapą w `src/components/icons` — nigdy SVG wklejone
w sekcję.
element `items[]` ma >5 linii markupu (→ `<Nazwa>Card.tsx`); `Component.tsx` >80
linii JSX; jest stan/interakcja (→ osobny plik `'use client'`, §6.9).
Podkomponent jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/components/ui/`.
### 6.5 Stałe słownictwo pól
| Rzecz | Nazwa pola | ZAKAZANE |
|---|---|---|
| Przyciski / CTA sekcji | `links` (`linksField()`) | `cta`, `ctaLabel`, `ctaHref`, `ctaTarget`, `cta2…`, `buttons`, `buttonText`, `buttonUrl`, `primaryCta` |
| Pojedynczy link (karta, element) | `link` (`linkField()`) | `href`, `url`, `target`, `linkTo`, `readMoreUrl` |
| Przyciski / CTA sekcji | `links` (`buildLinksField()`) | `cta`, `ctaLabel`, `ctaHref`, `ctaTarget`, `cta2…`, `buttons`, `buttonText`, `buttonUrl`, `primaryCta` |
| Pojedynczy link (karta, element) | `link` (`buildLinkField()`) | `href`, `url`, `target`, `linkTo`, `readMoreUrl` |
| Obraz / wideo | `media` | `image`, `img`, `imageUrl`, `photo`, `bgImage`, `heroImage` |
| Plik do pobrania | `link` typu `file` | osobne `pdf`, `pdfUrl`, `file`, `download`, `attachment` |
| Nagłówek sekcji | `header` (`sectionHeaderField()`) | luźne `title`, `headline`, `sectionTitle`, `subheading`, `subtitle` |
@@ -694,7 +335,7 @@ Wyjątek tylko przy dwóch rzeczach tego samego rodzaju o różnej roli
{ name: 'secondaryCtaTarget', type: 'relationship', relationTo: 'pages' },
{ name: 'pdfUrl', type: 'text' },
// DOBRZE
linksField({ maxRows: 3 })
buildLinksField({ maxRows: 3 })
```
```tsx
// ŹLE — sekcja sama składa href i stylizuje przycisk
@@ -713,7 +354,7 @@ className={v === 'a' ? 'x' : v === 'b' ? 'y' : 'z'}
### 6.7 Refaktor sekcji-monolitu
1. Spisz, co sekcja wyświetla (nagłówek, obrazy, przyciski, powtórzenia).
2. Schemat wg §6.5; CTA → `linksField()`.
2. Schemat wg §6.5; CTA → `buildLinksField()`.
3. **Zmiana nazw pól gubi treść w bazie.** Projekt z treścią → najpierw migracja
(stare pole → nowe), potem usunięcie starych. Pusty projekt → sama zmiana.
4. Komponent: `<Section>`, `<SectionHeader>`, `<Media>`, `<CMSLink>`,
@@ -722,173 +363,19 @@ className={v === 'a' ? 'x' : v === 'b' ? 'y' : 'z'}
### 6.8 Header i Footer (globale nawigacji)
Nawigacja, stopka i dane firmy to **globale projektu** (model zależy od klienta
i kraju), budowane z tych samych wspólnych pól co sekcje. Logo i nazwa są w
Site Settings — nie duplikuj ich w Header.
Kod (globale, `resolveNav`, `Header`, `Footer`, `MobileNav`): [kod-nawigacji.md](./skills/ipal-nav/resources/kod-nawigacji.md).
Skill: **ipal-nav**.
```ts
// src/globals/Header.ts
import type { GlobalConfig } from 'payload'
import { linkField, linksField } from '@/fields/link'
export const Header: GlobalConfig = {
slug: 'header',
access: { read: () => true },
fields: [
{
name: 'navItems',
type: 'array',
maxRows: 8,
fields: [
linkField({ appearances: false }),
{
name: 'subItems', // jeden poziom podmenu — głębiej nie budujemy
type: 'array',
maxRows: 10,
fields: [linkField({ appearances: false })],
},
],
},
linksField({ maxRows: 1 }), // przycisk CTA w nagłówku
{
name: 'menuLabel',
type: 'text',
localized: true,
admin: { description: 'Accessible label of the mobile menu button, e.g. "Menu".' },
},
],
}
```
```ts
// src/globals/Footer.ts
import type { GlobalConfig } from 'payload'
import { linkField } from '@/fields/link'
export const Footer: GlobalConfig = {
slug: 'footer',
access: { read: () => true },
fields: [
{
name: 'columns',
type: 'array',
maxRows: 4,
fields: [
{ name: 'heading', type: 'text', localized: true },
{ name: 'items', type: 'array', fields: [linkField({ appearances: false })] },
],
},
{ name: 'note', type: 'textarea', localized: true }, // np. „Wszelkie prawa zastrzeżone”
],
}
```
- **Linki prawne w stopce** (polityka, cookies, regulamin) renderuj z ról System
Pages (`getSystemPagePath` + tytuł strony) — nie dodawaj ich ręcznie do `columns`.
- **Dane firmy** (nazwa, adres, NIP/ABN, telefon) — global `company` projektu;
stopka i JSON-LD czytają z niego. Rok w copyright licz w kodzie
(`new Date().getFullYear()`), nazwę bierz z globala.
- **Odświeżanie:** global zmienia się na każdej stronie → hook `afterChange`
z `revalidatePath('/', 'layout')` (hooks.md).
Linki rozwiązuj **na serwerze** do zwykłych danych, a do klienta (menu mobilne)
przekazuj tylko `{ href, label, newTab }` — komponent kliencki nie może wołać
`CMSLink` (to async server component).
```ts
// src/lib/navigation.ts
import type { CmsLink } from '@/payload-types'
import { resolveLinkHref } from '@/lib/links'
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, homeSlug)
if (!link || !href || !link.label) return null
return { href, label: link.label, newTab: Boolean(link.newTab), subItems: [] }
}
export async function resolveNav(items: NavSource[] | null | undefined, locale: string): Promise<NavItem[]> {
const settings = await getSettings(locale)
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
return (items ?? []).flatMap((item) => {
const node = toNavItem(item.link, locale, homeSlug)
if (!node) return []
node.subItems = (item.subItems ?? []).flatMap((sub) => {
const child = toNavItem(sub.link, locale, homeSlug)
return child ? [child] : []
})
return [node]
})
}
```
```tsx
// src/components/layout/Header.tsx — serwer
import Link from 'next/link'
import type { Header as HeaderData } from '@/payload-types'
import { resolveNav } from '@/lib/navigation'
import { CMSLink } from '@/components/ui/CMSLink'
import { MobileNav } from './MobileNav'
export async function Header({ header, locale }: { header: HeaderData; locale: string }) {
const items = await resolveNav(header.navItems, locale)
return (
<header className="border-b">
<nav className="container flex items-center justify-between py-4">
{/* logo: Site Settings → <Media> */}
<ul className="hidden gap-6 md:flex">
{items.map((item) => (
<li key={item.href}>
<Link href={item.href} {...(item.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})}>
{item.label}
</Link>
</li>
))}
</ul>
{header.links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
<MobileNav items={items} menuLabel={header.menuLabel ?? ''} />
</nav>
</header>
)
}
```
```tsx
// src/components/layout/MobileNav.tsx — klient, tylko stan otwarcia
'use client'
import { useState } from 'react'
import Link from 'next/link'
import type { NavItem } from '@/lib/navigation' // import TYPU — nie ciągnie kodu serwera
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
const [open, setOpen] = useState(false)
return (
<div className="md:hidden">
<button type="button" aria-expanded={open} aria-label={menuLabel} onClick={() => setOpen(!open)}>
<span aria-hidden>☰</span>
</button>
{open && (
<ul>
{items.map((item) => (
<li key={item.href}>
<Link href={item.href} onClick={() => setOpen(false)}>{item.label}</Link>
</li>
))}
</ul>
)}
</div>
)
}
```
Header/Footer pobierasz w `[locale]/layout.tsx` (przez cached getter w
`lib/`) i podajesz jako props — layout to jedyne miejsce, które je składa.
- Nawigacja, stopka, dane firmy = **globale projektu** (`header`, `footer`, `company`),
zbudowane z `buildLinkField` — model danych firmy zależy od kraju (NIP/ABN/EIN).
- Menu: jeden poziom podmenu, nie głębiej. CTA w nagłówku = `links`.
- Logo i nazwa z Site Settings — nie duplikuj pól w Header.
- **Linki prawne w stopce** z ról System Pages (`getSystemPagePath`), nie ręcznie.
- Linki rozwiązuj **na serwerze** (`resolveNav` → `{ href, label, newTab }`); do
komponentu klienckiego idą tylko proste dane — `CMSLink` jest serwerowy.
- Etykiety a11y (przycisk menu) — pola w panelu.
- Global zmieniany na każdej stronie → `afterChange` z `revalidatePath('/', 'layout')`.
- Globale pobiera tylko `[locale]/layout.tsx` i podaje jako props.
### 6.9 Komponenty klienckie (`'use client'`)
@@ -914,64 +401,21 @@ Header/Footer pobierasz w `[locale]/layout.tsx` (przez cached getter w
### 6.10 Ikony
Dwa źródła, nic pomiędzy:
- **Dowolna grafika od klienta** → upload do `media` + `<Media>` (także logo, ikony SVG marki).
- **Stały zestaw ikon UI** → pole `select` + mapa `lucide-react`:
```ts
// src/components/icons/names.ts — same nazwy, importowane przez config bloku
export const ICON_NAMES = ['phone', 'mail', 'mapPin', 'clock', 'check'] as const
export type IconName = (typeof ICON_NAMES)[number]
export const iconField = {
name: 'icon',
type: 'select',
options: ICON_NAMES.map((value) => ({ label: value, value })),
} as const
```
```tsx
// src/components/icons/Icon.tsx — mapa, importowana tylko przez komponenty
import { Check, Clock, Mail, MapPin, Phone, type LucideIcon } from 'lucide-react'
import type { IconName } from './names'
const ICONS: Record<IconName, LucideIcon> = { phone: Phone, mail: Mail, mapPin: MapPin, clock: Clock, check: Check }
export function Icon({ name, className }: { name?: IconName | null; className?: string }) {
if (!name) return null
const Component = ICONS[name]
return <Component className={className} aria-hidden />
}
```
Nazwy są osobno, żeby config bloku (`payload.config`) nie importował komponentów
React. **Nigdy** SVG wklejone w JSX sekcji.
Dwa źródła, nic pomiędzy: **grafika od klienta** (także logo, ikony marki) →
upload + `<Media>`; **stały zestaw ikon UI** → pole `select` z nazwami +
mapa `lucide-react` w `src/components/icons/` (nazwy w osobnym pliku, żeby config
bloku nie importował Reacta). Kod: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md). **Nigdy** SVG wklejone w JSX sekcji.
### 6.11 Style
- **Tailwind w komponentach**, kolory i fonty jako **tokeny** w `styles.css`
(`@theme`) — źródłem jest `DESIGN.md` (Impeccable). W komponentach tylko nazwy
tokenów (`bg-primary`, `text-foreground`), **nigdy** `bg-[#ff6600]` ani hex.
- Tokeny pluginu mapuj na tokeny projektu — jeden kolor marki w jednym miejscu.
- Fonty przez `next/font` w layoucie, podpięte zmienną CSS do `@theme`.
- Tailwind w komponentach; kolory i fonty jako **tokeny** w `styles.css` (`@theme`)
ze źródła `DESIGN.md`. W komponentach tylko tokeny (`bg-primary`), **nigdy**
`bg-[#ff6600]` ani hex.
- Tokeny pluginu mapuj na projekt: `--ipal-primary: var(--color-primary)`.
- Fonty przez `next/font`, podpięte zmienną CSS do `@theme`.
- Bez CSS Modules i `style={{…}}` — wyjątek: wartość dynamiczna z danych.
- Warianty wizualne → `Record<Variant, string>` (§6.3), nie łańcuchy ternary.
```css
/* src/app/(frontend)/styles.css */
@import "tailwindcss";
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
@theme {
--color-primary: oklch(0.62 0.19 45);
--color-background: oklch(0.99 0 0);
--color-foreground: oklch(0.2 0 0);
--color-muted: oklch(0.96 0 0);
--font-sans: var(--font-body); /* next/font: variable '--font-body' */
}
:root {
--ipal-primary: var(--color-primary); /* baner cookies, Turnstile = kolor marki */
--ipal-radius: 0.75rem;
}
```
- Warianty → `Record<Variant, string>`, nie łańcuchy ternary.
Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sekcji.md).
### 6.12 Eksporty i importy
@@ -994,6 +438,7 @@ React. **Nigdy** SVG wklejone w JSX sekcji.
| Potrzeba | Użyj | Doc |
|---|---|---|
| Link / CTA / plik do pobrania | `buildLinkField`, `buildLinksField`, `resolveLinkHref` | links.md |
| Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md |
| Rich text | `RenderRichText` (`/rsc`), styl przez `converters` | richtext.md |
| Wartość zlokalizowana | `resolveLocalized(value, locale)` (nie `getSafeString`) | forms.md |
@@ -1008,10 +453,10 @@ React. **Nigdy** SVG wklejone w JSX sekcji.
| Stary slug → 308 | `trackSlugHistoryHook` + `resolveRedirect` | hooks.md |
| Obrazy między językami | `buildCrossLocaleFieldSync` (języki z configu) | hooks.md |
| Ochrona stron systemowych | `buildPreventDeleteSystemPage`, `buildValidateUniqueRole` | hooks.md |
| Metadata, sitemap, JSON-LD, llms.txt | `createPageMetadata`, `sitemap`, `build*JsonLd`, `createLlmsTxtRoute` | seo.md |
| Metadata, sitemap, JSON-LD, llms.txt | `generatePageMetadata` (z `createContentHelpers`), `sitemap`, `build*JsonLd`, `createLlmsTxtRoute` | seo.md |
| Consent, analytics, pixele | `ConsentProvider`, `CookieBanner`, `Analytics` (wewnątrz providera) | consent.md, analytics.md |
| Nagłówki, CSP, 2FA | `buildSecurityHeaders`, `buildCsp`, `twoFactor` (wstrzyknięty `payloadTotp`) | security.md |
| Media, R2 | `buildR2Storage`, `normalizeFilenameHook`, `MediaPreconnect` | storage.md |
| Media, R2 | `buildR2Storage(['media'], { s3Storage })` (adapter wstrzyknięty), `normalizeFilenameHook`, `MediaPreconnect` | storage.md |
| Email | `email: mailAdapter()` | email.md |
| Walidacja env | `assertEnv(ipalEnvRules({...}))` | env.md |
@@ -1078,7 +523,7 @@ payloadTotp } })`, nigdy `twoFactor: false` bez decyzji klienta). CSP: najpierw
| favicon renderowany ręcznie | Google go nie pokazuje | `buildIconsMetadata` |
| skopiowany `Analytics` w projekcie | pixele bez zgody (RODO) | opcje pluginu (`defer`) |
| `import('@payload-config')` przez zmienną | `Cannot find module` w buildzie | wstrzyknięcie / props |
| `ctaLabel`, `buttonUrl`, `pdfUrl` w blokach | zoo pól, brak spójności | `linksField()` |
| `ctaLabel`, `buttonUrl`, `pdfUrl` w blokach | zoo pól, brak spójności | `buildLinksField()` |
| brak `@source` na plugin w CSS | komponenty pluginu bez stylów | `@source` |
| kolekcja `users`/`settings`/`faq` | duplikat Payloada / zły byt | §5.3 |
@@ -1153,6 +598,7 @@ Cokolwiek wymaga dewelopera → przenieś do panelu.
| Formularze, useForm, honeypot | [forms.md](../forms.md) |
| Hooki | [hooks.md](../hooks.md) |
| i18n, proxy, przełącznik języka | [i18n.md](../i18n.md) |
| Linki / CTA (pola + href) | [links.md](../links.md) |
| Serwer MCP strony | [mcp.md](../mcp.md) |
| Komunikaty formularzy | [notifications.md](../notifications.md) |
| Strony systemowe, 404, generateStaticParams | [pages.md](../pages.md) |
@@ -1212,12 +658,13 @@ zadanie pasuje — ręcznie: `/<nazwa>`.
`package.json` projektu:
```json
"scripts": {
"ipal:skills": "mkdir -p .agents/skills && cp -R node_modules/@intecion/ipal-kit/docs/agent/skills/. .agents/skills/"
"ipal:skills": "ipal-skills"
}
```
```bash
pnpm ipal:skills
```
Commituj `.agents/skills/ipal-*` do repo projektu (agent ma je bez instalacji).
Własne skille projektu nazywaj bez prefiksu `ipal-` — kopiowanie nadpisuje tylko
skille pluginu.
`ipal-skills` (komenda z pakietu) kopiuje tylko foldery `ipal-*`: dodaje nowe,
nadpisuje zmienione, usuwa wycofane. Własne skille projektu nazywaj **bez**
prefiksu `ipal-` — zostaną nietknięte. Opcje: `--dry-run`, `--dest .claude/skills`
(Claude Code). Commituj `.agents/skills/ipal-*` do repo projektu.
+36
View File
@@ -0,0 +1,36 @@
---
name: ipal-audit
description: Audits an ipal-kit (Payload 3 + Next 16) project against AGENT.md rules with a deterministic script — hardcoded texts/links, forbidden field names, monolithic sections, middleware.ts, missing ISR/generateStaticParams, hex colors, server imports in client components, extra collections, then tsc and build. Use before saying a task is done, after any block/collection/layout change, after an Impeccable pass, and when asked to review or audit the project.
---
# ipal-audit
Kontrole z AGENT.md §11 jako skrypt — zawsze te same, bez interpretacji.
## Kroki
1. Z roota projektu uruchom:
```bash
bash .agents/skills/ipal-audit/scripts/audit.sh --quick # w trakcie pracy
bash .agents/skills/ipal-audit/scripts/audit.sh # przed „gotowe” (+ tsc + build)
```
Opcje: `--help`. Nie czytaj źródła skryptu — wynik wystarczy.
2. Pokaż użytkownikowi **pełny wynik** (podsumowanie + listę naruszeń).
3. Każde `[ERROR]` napraw albo — jeśli to świadomy wyjątek — dodaj w kodzie
komentarz z uzasadnieniem i wymień go w odpowiedzi.
Reguła przy każdym naruszeniu wskazuje sekcję w
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` — przeczytaj ją przed poprawką.
4. `[WARNING]` — oceń i powiedz użytkownikowi, co z nim zrobić; nie poprawiaj
na ślepo (np. `searchParams` jest OK w trasie archiwum z paginacją).
5. Uruchom ponownie, aż wynik to `0 error(s)`.
## Czego skrypt nie sprawdzi (zrób ręcznie)
- **Test redaktora** (AGENT.md §11): czy każdy tekst, obraz, przycisk, sekcja,
menu, stopka i SEO zmienia się w panelu, w każdym języku.
- **Zgoda cookies:** w Network przed akceptacją brak żądań do
google-analytics / googletagmanager (poza Consent Mode), facebook.net,
clarity.ms, licdn, tiktok.
- **Treść**: czy fallbacki nie zawierają danych klienta (`|| 'Firma X'`).
Nie mów „gotowe”, dopóki pełny audyt (bez `--quick`) nie ma błędów.
@@ -0,0 +1,159 @@
#!/usr/bin/env bash
# ipal-audit — deterministic checks of an ipal-kit project against AGENT.md.
# Run from the project root:
# bash .agents/skills/ipal-audit/scripts/audit.sh # all checks + tsc + build
# bash .agents/skills/ipal-audit/scripts/audit.sh --quick # static checks only
# bash .agents/skills/ipal-audit/scripts/audit.sh --help
# Exit code: 0 = no errors (warnings allowed), 1 = at least one error.
set -u
QUICK=0
for arg in "$@"; do
case "$arg" in
--quick) QUICK=1 ;;
--help|-h)
sed -n '2,7p' "$0" | sed 's/^# \{0,1\}//'
exit 0
;;
esac
done
if [ ! -d src ]; then
echo "ipal-audit: run from the project root (no ./src found)." >&2
exit 2
fi
ERRORS=0
WARNINGS=0
# report LEVEL "title" "rule" <<< "$matches"
report() {
local level="$1" title="$2" rule="$3" matches="$4"
[ -z "$matches" ] && return 0
local count
count=$(printf '%s\n' "$matches" | grep -c .)
if [ "$level" = ERROR ]; then ERRORS=$((ERRORS + count)); else WARNINGS=$((WARNINGS + count)); fi
printf '\n[%s] %s (%s) — %s\n' "$level" "$title" "$count" "$rule"
printf '%s\n' "$matches" | head -20 | sed 's/^/ /'
[ "$count" -gt 20 ] && printf ' … and %s more\n' "$((count - 20))"
}
g() { grep -rnE "$@" 2>/dev/null || true; }
# drop matches that sit inside a // or /* comment (keeps http:// URLs)
nc() { grep -vE "(^|[^:])//.*$1|/\*.*$1" || true; }
dirs() { for d in "$@"; do [ -d "$d" ] && printf '%s ' "$d"; done; }
BLOCKS=$(dirs src/blocks)
UI=$(dirs src/blocks src/components)
echo "ipal-audit — $(pwd)"
# --- Architecture (AGENT.md §4) ---
report ERROR "middleware.ts exists" "§4.1 Next 16 uses proxy.ts only" \
"$(ls src/middleware.ts middleware.ts 2>/dev/null)"
report ERROR "<head> in app" "§4.2 no explicit <head> — metadata ends up in <body>" \
"$(g '<head[ >]' src/app --include=*.tsx | nc '<head')"
PAGES=$(find src/app -path '*\[\[...slug\]\]*' -name 'page.tsx' 2>/dev/null)
for p in $PAGES; do
grep -q 'revalidate' "$p" || report ERROR "no ISR" "§4.3 export const revalidate" "$p"
grep -q 'generateStaticParams' "$p" || report ERROR "no generateStaticParams" "§4.4 without it the route is dynamic and metadata lands in <body>" "$p"
report WARNING "searchParams in catch-all page" "§4.6 deoptimizes SSG/ISR — only for paginated archives" \
"$(grep -n 'searchParams' "$p" | nc 'searchParams' | sed "s|^|$p:|")"
done
for r in src/app/sitemap.ts src/app/manifest.ts src/app/llms.txt/route.ts src/app/sitemap.xml/route.ts src/app/api/health/route.ts; do
[ -f "$r" ] && ! grep -q "dynamic = 'force-dynamic'" "$r" && \
report ERROR "DB route without force-dynamic" "§4.7 build without DB will crash" "$r"
done
report ERROR "headers()/cookies() in blocks/components" "§4.6 forces dynamic rendering — pass locale via enhanceProps" \
"$( [ -n "$UI" ] && g "from 'next/headers'" $UI)"
report ERROR "headers()/cookies() in static page tree" "§4.6 SSG/ISR → 'Page changed from static to dynamic' — not-found: LocaleView (pages.md)" \
"$(g "from 'next/headers'" src/app --include=page.tsx --include=layout.tsx --include=not-found.tsx --include=template.tsx | grep -v '/api/\|(payload)')"
# --- Hardcoding & types (§2, §8) ---
report ERROR "hardcoded locale map / any / ts-ignore" "§2, §8" \
"$(g 'localizedRoutes|as any\b|@ts-ignore|: any\b' src --include=*.ts --include=*.tsx | grep -v '/payload-types.ts:')"
report ERROR "hardcoded locale list" "§2 languages come from i18n.config.ts" \
"$(g "\[ *'(pl|en|de|fr|es|it)' *, *'(pl|en|de|fr|es|it)'" src --include=*.ts --include=*.tsx | grep -v 'i18n.config.ts')"
# --- Sections (§6) ---
if [ -n "$BLOCKS" ]; then
report ERROR "forbidden field names" "§6.5 use links/link/media (linksField, linkField, upload)" \
"$(g "name: *'[a-zA-Z]*([cC]ta|[bB]utton|Url|Href|[pP]df|[iI]mage)[a-zA-Z]*'" $BLOCKS --include=config.ts)"
report ERROR "hardcoded href/src/file paths in blocks" "§2, §6 use CMSLink / Media" \
"$(g 'href=\{?["`]/|<img |/files/|/images/|\.pdf' $BLOCKS --include=*.tsx | nc '(href|<img|/files/|/images/|\.pdf)')"
report ERROR "raw <a>/<Link> in blocks" "§6.3 links from the panel render via CMSLink" \
"$(g '<(a|Link)[ >]' $BLOCKS --include=*.tsx)"
report WARNING "inline <svg> in blocks" "§6.10 icons via media upload or Icon map" \
"$(g '<svg[ >]' $BLOCKS --include=*.tsx)"
report WARNING "large section component (>120 lines)" "§6.4 split into subcomponents" \
"$(find $BLOCKS -name '*.tsx' -exec wc -l {} + 2>/dev/null | awk '$2 != "total" && $1 > 120 {print $2": "$1" lines"}')"
report ERROR "Component imported into block config" "§6.12 payload.config must not pull React components" \
"$(g "from '\./Component'|/Component'" $BLOCKS --include=config.ts)"
fi
if [ -n "$UI" ]; then
report ERROR "hex colors in classes" "§6.11 use design tokens (bg-primary…)" \
"$(g '(bg|text|border|from|to|via|fill|stroke)-\[#' $UI --include=*.tsx)"
report ERROR "barrel index.ts" "§6.12 import files directly" \
"$(find $UI -name 'index.ts' 2>/dev/null)"
CLIENT=$(grep -rlE "^['\"]use client['\"]" $UI 2>/dev/null)
for c in $CLIENT; do
report ERROR "server import in client component" "§6.9 no payload / lib/content / server-only in 'use client'" \
"$(grep -nE "from '(payload|server-only|@/lib/content|@/payload\.config)'" "$c" | grep -v 'import type' | sed "s|^|$c:|")"
done
fi
# --- Collections (§5.3) ---
if [ -d src/collections ]; then
report ERROR "forbidden collection" "§5.3 users are built in; settings/nav/footer are globals; FAQ/hero are blocks" \
"$(ls src/collections | grep -iE '^(users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
report WARNING "collections present — confirm each passed the §5.3 test" "minimum: Pages, Media" \
"$(ls src/collections | grep -viE '^(pages|media|users|user|settings|navigation|nav|footer|header|faq|hero|company|danefirmy)\.ts$')"
fi
# --- Plugin duplicates (§1, §7) ---
report ERROR "own block renderer switch" "§7 use RenderBlocks + registry" \
"$(g 'switch *\(.*blockType' src --include=*.tsx --include=*.ts)"
report WARNING "files that usually duplicate the plugin" "§3 plugin has resolveRoute / getConfiguredLocales" \
"$(ls src/lib/pages.ts src/lib/locales.ts 2>/dev/null)"
report ERROR "project copy of link fields" "links.md — use buildLinkField / buildLinksField / resolveLinkHref from the plugin" \
"$(ls src/fields/link.ts src/lib/links.ts 2>/dev/null; g "from '@/fields/link'|from '@/lib/links'" src --include=*.ts --include=*.tsx)"
report ERROR "manual Lexical rendering" "§7 use RenderRichText" \
"$(g 'node\.type *===|dangerouslySetInnerHTML' src --include=*.tsx)"
# --- Compile & build ---
if [ "$QUICK" -eq 0 ]; then
echo
echo "== pnpm generate:types && tsc --noEmit =="
if ! (pnpm -s generate:types >/dev/null && pnpm -s exec tsc --noEmit); then
ERRORS=$((ERRORS + 1)); echo "[ERROR] type check failed"
fi
echo
echo "== pnpm build =="
BUILD_LOG=$(mktemp)
if pnpm -s build >"$BUILD_LOG" 2>&1; then
DYN=$(grep -E '^[│├└ ]*ƒ .*\[locale\]' "$BUILD_LOG" || true)
report WARNING "page routes rendered dynamically (ƒ)" "§4 expected ● SSG — does the build see the DB?" "$DYN"
else
ERRORS=$((ERRORS + 1)); echo "[ERROR] build failed — last lines:"; tail -30 "$BUILD_LOG" | sed 's/^/ /'
fi
rm -f "$BUILD_LOG"
fi
echo
echo "ipal-audit: $ERRORS error(s), $WARNINGS warning(s)$( [ "$QUICK" -eq 1 ] && echo ' (quick: no tsc/build)')"
[ "$ERRORS" -eq 0 ]
+45
View File
@@ -0,0 +1,45 @@
---
name: ipal-block
description: Builds or refactors one page section (Payload block + React component) in an ipal-kit project the correct way — shared fields (sectionHeaderField, buildLinksField, buildLinkField, sectionSettingsField), UI primitives (Section, SectionHeader, Media, CMSLink), fixed field vocabulary, max ~80 lines of JSX, subcomponents for repeated items, registry wiring. Use when creating a new section/block (hero, features, CTA, FAQ, gallery, pricing, testimonials…), changing a block's fields, or fixing a block with ctaLabel/buttonUrl/pdfUrl fields or a monolithic component.
---
# ipal-block
Jedna sekcja na jedno użycie skilla. Szczegóły i gotowy kod:
`node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.
## 0. Warunki wstępne
Sprawdź, czy istnieją: `src/fields/sectionHeader.ts`,
`sectionSettings.ts`, `src/components/ui/{CMSLink,Button,Media,Section,SectionHeader}.tsx`.
Linki (`buildLinkField`, `buildLinksField`, `resolveLinkHref`) są w pluginie — nie twórz ich w projekcie.
Brakuje → najpierw utwórz je 1:1 z `resources/kod-sekcji.md` (ten skill)
(i powiedz o tym użytkownikowi). Nie pisz własnych wersji.
## 1. Plan (pokaż i czekaj na OK)
- slug bloku (camelCase), nazwa folderu (PascalCase),
- lista pól **tylko** ze słownika AGENT.md §6.5:
`header`, `media`, `links`, `link`, `items` (+ `heading`, `text`, `content`), `settings`,
- czy elementy `items` dostają podkomponent `<Nazwa>Card.tsx`,
- czy potrzebna interakcja → osobny plik `'use client'` (najpierw `<details>`/`<dialog>`),
- czy sekcja to wariant istniejącego bloku (wtedy pole `variant: select`, nie nowy blok).
## 2. Kod
Wzorce plików (Hero, FeatureGrid + FeatureCard): `resources/kod-sekcji.md`.
1. `src/blocks/<Nazwa>/config.ts` — `interfaceName: '<Nazwa>Block'`, pola z planu,
zawsze `sectionSettingsField()`. CTA = `buildLinksField()`, nigdy pola `cta*`/`button*`.
Plik do pobrania = link typu `file`. Etykiety i opisy pól po angielsku.
2. `src/blocks/<Nazwa>/Component.tsx` — nazwany eksport, typ z `@/payload-types`
(`<Nazwa>Block & { locale: string }`), struktura:
`<Section settings>` → `<SectionHeader header>` → treść z `<Media>`, `<CMSLink>`,
`items.map(<Card/>)`. Zero tekstu, `href`, `<img>`, hexów, inline SVG.
3. Podkomponenty w tym samym folderze; wspólne dla 2+ sekcji → `src/components/ui/`.
4. Dodaj `config.ts` do `layout` w `src/collections/Pages.ts`,
komponent do `src/blocks/registry.ts` (klucz = slug).
5. `pnpm generate:types`.
## 3. Weryfikacja
- `Component.tsx` ≤ ~80 linii JSX.
- Uruchom skill **ipal-audit** (`--quick`), napraw wszystkie `[ERROR]`.
- Refaktor istniejącego bloku ze zmianą nazw pól: **najpierw migracja danych**
(stare pole → nowe), dopiero potem usunięcie starych pól (AGENT.md §6.7).
@@ -0,0 +1,378 @@
# Kod sekcji — gotowe pliki dla projektu
> Zasoby skilla **ipal-block**. Reguły (dlaczego tak, czego nie robić) są w
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6 — ten plik to tylko kod
> do utworzenia w projekcie **1:1**. Linki (`buildLinkField`, `buildLinksField`,
> `resolveLinkHref`) są w pluginie — nie twórz ich kopii.
## Warstwa 1 — wspólne pola
**Link / CTA — z pluginu, nie kopiuj kodu** (`docs/links.md`):
```ts
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
buildLinksField() // 0–2 przyciski sekcji → pole `links`
buildLinksField({ maxRows: 3, appearances: ['primary', 'secondary'] })
buildLinkField() // pojedynczy link → pole `link`
buildLinkField({ disableLabel: true, appearances: false }) // klikalna cała karta
```
Jeden kształt linku: typ (`internal` strona / `external` URL, mailto, tel, #anchor /
`file` upload), `label` (localized), `newTab`, `appearance`. W `payload-types.ts`
powstaje typ `CmsLink`. Opcje: `relationTo` (domyślnie `'pages'`), `uploadTo`
(domyślnie `'media'`), `required`.
**Pliki i obrazy:** `{ name: 'media', type: 'upload', relationTo: 'media' }`.
Kolekcja `media` dopuszcza PDF (`upload.mimeTypes: ['image/*', 'application/pdf',
'video/mp4']`), ma `alt` (required, localized) i `normalizeFilenameHook`.
„Pobierz cennik (PDF)” to **link typu `file`**, nie osobne pole `pdf`/`pdfUrl`.
`src/fields/sectionHeader.ts` i `src/fields/sectionSettings.ts`:
```ts
import type { GroupField } from 'payload'
export function sectionHeaderField(name = 'header'): GroupField {
return {
name,
type: 'group',
interfaceName: 'SectionHeaderData',
fields: [
{ name: 'eyebrow', type: 'text', localized: true },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', localized: true },
],
}
}
export function sectionSettingsField(): GroupField {
return {
name: 'settings',
type: 'group',
interfaceName: 'SectionSettings',
admin: { position: 'sidebar' },
fields: [
{
name: 'anchor',
type: 'text',
admin: { description: 'Section id for #links and section nav, e.g. "pricing".' },
},
{
name: 'background',
type: 'select',
defaultValue: 'default',
options: ['default', 'muted', 'inverted'].map((v) => ({ label: v, value: v })),
},
],
}
}
```
Każda sekcja ma `sectionSettingsField()` — żadnych `bgColor`, `darkMode`,
`sectionId` w poszczególnych blokach. Etykiety pól po angielsku (panel jest EN).
## Warstwa 2 — prymitywy UI
`src/components/ui/CMSLink.tsx` — **każdy** link/przycisk z panelu:
```tsx
import Link from 'next/link'
import type { ReactNode } from 'react'
import { resolveLinkHref } from '@intecion/ipal-kit'
import type { CmsLink } from '@/payload-types'
import { i18nConfig } from '@/i18n.config'
import { getSettings } from '@/lib/content'
import { buttonClass } from './Button'
type Props = {
link: CmsLink | null | undefined
locale: string
className?: string
/** For wrapping links (cards): content instead of link.label. */
children?: ReactNode
}
export async function CMSLink({ link, locale, className, children }: Props) {
const settings = await getSettings(locale) // react cache → one query per request
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
const content = children ?? link?.label
if (!link || !href || !content) return null
const cls = [link.appearance ? buttonClass(link.appearance) : '', className]
.filter(Boolean)
.join(' ')
const newTab = link.newTab || link.type === 'file'
const targetProps = newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {}
if (link.type === 'internal') {
return <Link href={href} className={cls} {...targetProps}>{content}</Link>
}
return <a href={href} className={cls} {...targetProps}>{content}</a>
}
```
`src/components/ui/Button.tsx` — warianty jako mapa, nie ternary:
```ts
import type { LinkAppearance } from '@intecion/ipal-kit'
const VARIANTS: Record<LinkAppearance, string> = {
primary: 'btn btn-primary',
secondary: 'btn btn-secondary',
link: 'link-arrow',
}
export function buttonClass(appearance: LinkAppearance): string {
return VARIANTS[appearance]
}
```
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu:
```tsx
import Image from 'next/image'
import type { Media as MediaDoc } from '@/payload-types'
type Props = {
resource: MediaDoc | string | number | null | undefined
sizes?: string
priority?: boolean
className?: string
}
export function Media({ resource, sizes = '100vw', priority = false, className }: Props) {
if (!resource || typeof resource !== 'object' || !resource.url) return null
const { url, alt, width, height, mimeType } = resource
if (mimeType?.startsWith('video/')) {
return <video src={url} className={className} autoPlay muted loop playsInline />
}
if (!width || !height) return null // non-image file (PDF) — use CMSLink type 'file'
return (
<Image src={url} alt={alt ?? ''} width={width} height={height}
sizes={sizes} priority={priority} className={className} />
)
}
```
`Section.tsx` i `SectionHeader.tsx`:
```tsx
// src/components/ui/Section.tsx
import type { ReactNode } from 'react'
import type { SectionSettings } from '@/payload-types'
const BACKGROUNDS: Record<NonNullable<SectionSettings['background']>, string> = {
default: 'bg-background',
muted: 'bg-muted',
inverted: 'bg-foreground text-background',
}
export function Section({ settings, children }: { settings?: SectionSettings | null; children: ReactNode }) {
return (
<section
id={settings?.anchor || undefined}
className={`py-16 md:py-24 ${BACKGROUNDS[settings?.background ?? 'default']}`}
>
<div className="container">{children}</div>
</section>
)
}
```
```tsx
// src/components/ui/SectionHeader.tsx
import type { SectionHeaderData } from '@/payload-types'
export function SectionHeader({ header, as: H = 'h2' }: { header?: SectionHeaderData | null; as?: 'h1' | 'h2' }) {
if (!header?.heading && !header?.eyebrow && !header?.intro) return null
return (
<header className="mb-10 max-w-2xl">
{header.eyebrow && <p className="eyebrow">{header.eyebrow}</p>}
{header.heading && <H className="heading">{header.heading}</H>}
{header.intro && <p className="lead">{header.intro}</p>}
</header>
)
}
```
**`locale` dla każdego bloku — raz, w trasie strony:**
```tsx
const enhanceProps = ({ block }: { block: { blockType: string } }) => ({
locale,
...(block.blockType === 'formBlock' ? { turnstileSiteKey } : {}),
})
<RenderBlocks blocks={doc.layout as never} components={blockRegistry} enhanceProps={enhanceProps} />
```
## Warstwa 3 — sekcja = kompozycja
```ts
// src/blocks/Hero/config.ts
import type { Block } from 'payload'
import { buildLinksField } from '@intecion/ipal-kit'
import { sectionHeaderField } from '@/fields/sectionHeader'
import { sectionSettingsField } from '@/fields/sectionSettings'
export const HeroBlock: Block = {
slug: 'hero',
interfaceName: 'HeroBlock',
labels: { singular: 'Hero', plural: 'Heroes' },
fields: [
sectionHeaderField(),
{ name: 'media', type: 'upload', relationTo: 'media' },
buildLinksField(),
sectionSettingsField(),
],
}
```
```tsx
// src/blocks/Hero/Component.tsx — cały komponent
import type { HeroBlock } from '@/payload-types'
import { Section } from '@/components/ui/Section'
import { SectionHeader } from '@/components/ui/SectionHeader'
import { Media } from '@/components/ui/Media'
import { CMSLink } from '@/components/ui/CMSLink'
export function Hero({ header, media, links, settings, locale }: HeroBlock & { locale: string }) {
return (
<Section settings={settings}>
<div className="grid items-center gap-10 md:grid-cols-2">
<div>
<SectionHeader header={header} as="h1" />
{links?.length ? (
<div className="flex flex-wrap gap-3">
{links.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
</div>
) : null}
</div>
<Media resource={media} priority sizes="(min-width: 768px) 50vw, 100vw" />
</div>
</Section>
)
}
```
Sekcja z powtarzalnymi elementami — element tablicy to podkomponent:
```ts
// src/blocks/FeatureGrid/config.ts (fields)
sectionHeaderField(),
{
name: 'items',
type: 'array',
interfaceName: 'FeatureItem',
fields: [
{ name: 'media', type: 'upload', relationTo: 'media' },
{ name: 'heading', type: 'text', localized: true, required: true },
{ name: 'text', type: 'textarea', localized: true },
buildLinkField({ appearances: ['link'] }),
],
},
buildLinksField({ maxRows: 1 }),
sectionSettingsField(),
```
```tsx
// src/blocks/FeatureGrid/FeatureCard.tsx
export function FeatureCard({ item, locale }: { item: FeatureItem; locale: string }) {
return (
<article className="card">
<Media resource={item.media} sizes="(min-width: 1024px) 33vw, 100vw" />
<h3>{item.heading}</h3>
{item.text && <p>{item.text}</p>}
<CMSLink link={item.link} locale={locale} />
</article>
)
}
// src/blocks/FeatureGrid/Component.tsx
export function FeatureGrid({ header, items, links, settings, locale }: FeatureGridBlock & { locale: string }) {
return (
<Section settings={settings}>
<SectionHeader header={header} />
<div className="grid gap-6 md:grid-cols-3">
{items?.map((item) => <FeatureCard key={item.id} item={item} locale={locale} />)}
</div>
{links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} className="mt-10" />)}
</Section>
)
}
```
**Wydziel podkomponent, gdy którekolwiek jest prawdą:** ten sam JSX 2+ razy;
element `items[]` ma >5 linii markupu; `Component.tsx` >80 linii JSX; jest stan/
interakcja (accordion, slider, tabs → osobny `'use client'`). Podkomponent
jednej sekcji → w jej folderze; używany w 2+ sekcjach → `src/components/ui/`.
Ikony: upload albo `select` z mapą w `src/components/icons` — nigdy SVG wklejone
w sekcję.
## Ikony
Dwa źródła, nic pomiędzy:
- **Dowolna grafika od klienta** → upload do `media` + `<Media>` (także logo, ikony SVG marki).
- **Stały zestaw ikon UI** → pole `select` + mapa `lucide-react`:
```ts
// src/components/icons/names.ts — same nazwy, importowane przez config bloku
export const ICON_NAMES = ['phone', 'mail', 'mapPin', 'clock', 'check'] as const
export type IconName = (typeof ICON_NAMES)[number]
export const iconField = {
name: 'icon',
type: 'select',
options: ICON_NAMES.map((value) => ({ label: value, value })),
} as const
```
```tsx
// src/components/icons/Icon.tsx — mapa, importowana tylko przez komponenty
import { Check, Clock, Mail, MapPin, Phone, type LucideIcon } from 'lucide-react'
import type { IconName } from './names'
const ICONS: Record<IconName, LucideIcon> = { phone: Phone, mail: Mail, mapPin: MapPin, clock: Clock, check: Check }
export function Icon({ name, className }: { name?: IconName | null; className?: string }) {
if (!name) return null
const Component = ICONS[name]
return <Component className={className} aria-hidden />
}
```
Nazwy są osobno, żeby config bloku (`payload.config`) nie importował komponentów
React. **Nigdy** SVG wklejone w JSX sekcji.
## Style
- **Tailwind w komponentach**, kolory i fonty jako **tokeny** w `styles.css`
(`@theme`) — źródłem jest `DESIGN.md` (Impeccable). W komponentach tylko nazwy
tokenów (`bg-primary`, `text-foreground`), **nigdy** `bg-[#ff6600]` ani hex.
- Tokeny pluginu mapuj na tokeny projektu — jeden kolor marki w jednym miejscu.
- Fonty przez `next/font` w layoucie, podpięte zmienną CSS do `@theme`.
- Bez CSS Modules i `style={{…}}` — wyjątek: wartość dynamiczna z danych.
- Warianty wizualne → `Record<Variant, string>` (§6.3), nie łańcuchy ternary.
```css
/* src/app/(frontend)/styles.css */
@import "tailwindcss";
@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js";
@theme {
--color-primary: oklch(0.62 0.19 45);
--color-background: oklch(0.99 0 0);
--color-foreground: oklch(0.2 0 0);
--color-muted: oklch(0.96 0 0);
--font-sans: var(--font-body); /* next/font: variable '--font-body' */
}
:root {
--ipal-primary: var(--color-primary); /* baner cookies, Turnstile = kolor marki */
--ipal-radius: 0.75rem;
}
```
@@ -0,0 +1,45 @@
---
name: ipal-collection
description: Decides whether something should be a Payload collection, a global, or a block, and builds a content collection the ipal-kit way (title, buildSlugField, SEO tab, buildNoindexField, trackSlugHistoryHook, revalidate hook, archive page from System Pages, sitemap and routing via content option). Use when the user asks for a blog, news, products, portfolio, testimonials, authors, categories, or any new collection — and whenever you are about to create a file in src/collections.
---
# ipal-collection
Źródła: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §5,
`docs/content.md`, `docs/hooks.md`, `docs/seo.md`.
## 1. Test (zawsze, przed jakimkolwiek kodem)
Odpowiedz użytkownikowi na 4 pytania — wszystkie muszą być TAK:
1. Lista wielu rekordów tego samego typu?
2. Każdy rekord ma **własny URL**?
3. Klient **jawnie** tego wymaga?
4. Payload nie ma tego wbudowanego?
Którekolwiek NIE → to nie kolekcja:
- jeden zestaw danych (firma, menu, stopka, ustawienia) → **global**,
- część strony (FAQ, hero, opinie w sekcji) → **blok** (skill ipal-block),
- `users` → wbudowane w Payload, nie twórz.
Wyjątek: lista bez własnych URL-i zarządzana osobno (np. opinie używane w wielu
blokach) — kolekcja **bez** wpięcia w `content`. Uzasadnij to w planie.
## 2. Plan (pokaż i czekaj na OK)
slug (camelCase, l.mn.), pola, relacje, czy ma URL-e (archiwum), JSON-LD.
## 3. Kod
1. `src/collections/<Nazwa>.ts`: `title` (localized), `buildSlugField({ from: 'title' })`,
tab SEO (plugin-seo), `buildNoindexField()`, `trackSlugHistoryHook`,
`buildRevalidateHook`, `setPublishedAtHook` (wpisy z datą), upload przez
`media`, linki przez `buildLinkField()`. Nazwy pól wg AGENT.md §6.5.
2. Z URL-ami: dopisz do `content.config.ts` → `{ slug, perPage }`.
**Prefiks URL nie w kodzie** — redaktor przypisuje stronę-archiwum w
Site Settings (`<slug>Archive`). Plugin robi routing, sitemap,
generateStaticParams, hreflang.
3. Lista wpisów = blok (EntriesList) z `getEntries`; strona wpisu z
`resolveRoute` (typ `entry`); JSON-LD wg seo.md (np. Article).
4. `pnpm generate:types`, `pnpm payload generate:importmap`.
5. Postgres z migracjami → `pnpm payload migrate:create`.
## 4. Weryfikacja
Skill **ipal-audit**. Ręcznie: wpis w panelu → widoczny pod `/<locale>/<archiwum>/<slug>`,
w sitemapie, zmiana sluga → 308 ze starego adresu.
+34
View File
@@ -0,0 +1,34 @@
---
name: ipal-nav
description: Builds the site header, footer, mobile menu and company data in an ipal-kit project — Header/Footer/Company globals with buildLinkField from the plugin, server-side link resolution (resolveNav), a small client MobileNav, legal links from System Pages, revalidation on change. Use when creating or changing navigation, menu, header, footer, contact details, social links or the company global.
---
# ipal-nav
Gotowy kod: `resources/kod-nawigacji.md` (ten skill). Reguły: AGENT.md §6.8.
Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (jak skill ipal-block, krok 0).
## Plan (pokaż i czekaj na OK)
- pozycje menu (jeden poziom podmenu, nie głębiej), CTA w nagłówku (`links`),
- kolumny stopki, notka,
- model `Company` dla rynku z AGENTS.md (PL: NIP/REGON, AU: ABN, US: EIN…),
- etykiety a11y (przycisk menu itp.) — pola w panelu.
## Kod
1. `src/globals/Header.ts`, `Footer.ts` — z §6.8; `Company.ts` — dane firmy
(teksty localized), `access.read: () => true`.
2. Hook `afterChange` na każdym globalu: `revalidatePath('/', 'layout')`
(wstrzyknięty z `next/cache`, hooks.md).
3. `src/lib/navigation.ts` (`resolveNav`) — linki rozwiązane na serwerze do
`{ href, label, newTab, subItems }`.
4. `src/components/layout/Header.tsx`, `Footer.tsx` (serwer), `MobileNav.tsx`
(`'use client'`, tylko stan otwarcia, dane przez props, `import type` z lib).
5. **Linki prawne w stopce** z ról System Pages (`getSystemPagePath` + tytuł
strony) — nie jako ręczne pozycje. Rok w copyright z kodu, nazwa z `Company`.
6. Logo z Site Settings przez `<Media>` — nie duplikuj pola w Header.
7. Podepnij w `src/app/(frontend)/[locale]/layout.tsx` (pobranie globali przez
cached gettery w `lib/`, przekazanie jako props).
## Weryfikacja
Skill **ipal-audit**. Ręcznie: dodanie pozycji menu w panelu widać od razu po
zapisie; menu mobilne działa z klawiatury (Tab, Enter, Esc).
@@ -0,0 +1,176 @@
# Kod nawigacji — Header, Footer, menu mobilne
> Zasoby skilla **ipal-nav**. Reguły: `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md` §6.8.
> Wymaga prymitywów z `../ipal-block/resources/kod-sekcji.md` (CMSLink, Media).
## Header i Footer (globale nawigacji)
Nawigacja, stopka i dane firmy to **globale projektu** (model zależy od klienta
i kraju), budowane z tych samych wspólnych pól co sekcje. Logo i nazwa są w
Site Settings — nie duplikuj ich w Header.
```ts
// src/globals/Header.ts
import type { GlobalConfig } from 'payload'
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
export const Header: GlobalConfig = {
slug: 'header',
access: { read: () => true },
fields: [
{
name: 'navItems',
type: 'array',
maxRows: 8,
fields: [
buildLinkField({ appearances: false }),
{
name: 'subItems', // jeden poziom podmenu — głębiej nie budujemy
type: 'array',
maxRows: 10,
fields: [buildLinkField({ appearances: false })],
},
],
},
buildLinksField({ maxRows: 1 }), // przycisk CTA w nagłówku
{
name: 'menuLabel',
type: 'text',
localized: true,
admin: { description: 'Accessible label of the mobile menu button, e.g. "Menu".' },
},
],
}
```
```ts
// src/globals/Footer.ts
import type { GlobalConfig } from 'payload'
import { buildLinkField } from '@intecion/ipal-kit'
export const Footer: GlobalConfig = {
slug: 'footer',
access: { read: () => true },
fields: [
{
name: 'columns',
type: 'array',
maxRows: 4,
fields: [
{ name: 'heading', type: 'text', localized: true },
{ name: 'items', type: 'array', fields: [buildLinkField({ appearances: false })] },
],
},
{ name: 'note', type: 'textarea', localized: true }, // np. „Wszelkie prawa zastrzeżone”
],
}
```
- **Linki prawne w stopce** (polityka, cookies, regulamin) renderuj z ról System
Pages (`getSystemPagePath` + tytuł strony) — nie dodawaj ich ręcznie do `columns`.
- **Dane firmy** (nazwa, adres, NIP/ABN, telefon) — global `company` projektu;
stopka i JSON-LD czytają z niego. Rok w copyright licz w kodzie
(`new Date().getFullYear()`), nazwę bierz z globala.
- **Odświeżanie:** global zmienia się na każdej stronie → hook `afterChange`
z `revalidatePath('/', 'layout')` (hooks.md).
Linki rozwiązuj **na serwerze** do zwykłych danych, a do klienta (menu mobilne)
przekazuj tylko `{ href, label, newTab }` — komponent kliencki nie może wołać
`CMSLink` (to async server component).
```ts
// src/lib/navigation.ts
import { resolveLinkHref } from '@intecion/ipal-kit'
import type { CmsLink } from '@/payload-types'
import { i18nConfig } from '@/i18n.config'
import { getSettings } from '@/lib/content'
export type NavItem = { href: string; label: string; newTab: boolean; subItems: NavItem[] }
type NavSource = { link?: CmsLink | null; subItems?: { link?: CmsLink | null }[] | null }
function toNavItem(link: CmsLink | null | undefined, locale: string, homeSlug?: string): NavItem | null {
const href = resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
if (!link || !href || !link.label) return null
return { href, label: link.label, newTab: Boolean(link.newTab), subItems: [] }
}
export async function resolveNav(items: NavSource[] | null | undefined, locale: string): Promise<NavItem[]> {
const settings = await getSettings(locale)
const home = settings?.homepage
const homeSlug = home && typeof home === 'object' && typeof home.slug === 'string' ? home.slug : undefined
return (items ?? []).flatMap((item) => {
const node = toNavItem(item.link, locale, homeSlug)
if (!node) return []
node.subItems = (item.subItems ?? []).flatMap((sub) => {
const child = toNavItem(sub.link, locale, homeSlug)
return child ? [child] : []
})
return [node]
})
}
```
```tsx
// src/components/layout/Header.tsx — serwer
import Link from 'next/link'
import type { Header as HeaderData } from '@/payload-types'
import { resolveNav } from '@/lib/navigation'
import { CMSLink } from '@/components/ui/CMSLink'
import { MobileNav } from './MobileNav'
export async function Header({ header, locale }: { header: HeaderData; locale: string }) {
const items = await resolveNav(header.navItems, locale)
return (
<header className="border-b">
<nav className="container flex items-center justify-between py-4">
{/* logo: Site Settings → <Media> */}
<ul className="hidden gap-6 md:flex">
{items.map((item) => (
<li key={item.href}>
<Link href={item.href} {...(item.newTab ? { target: '_blank', rel: 'noopener noreferrer' } : {})}>
{item.label}
</Link>
</li>
))}
</ul>
{header.links?.map(({ id, link }) => <CMSLink key={id} link={link} locale={locale} />)}
<MobileNav items={items} menuLabel={header.menuLabel ?? ''} />
</nav>
</header>
)
}
```
```tsx
// src/components/layout/MobileNav.tsx — klient, tylko stan otwarcia
'use client'
import { useState } from 'react'
import Link from 'next/link'
import type { NavItem } from '@/lib/navigation' // import TYPU — nie ciągnie kodu serwera
export function MobileNav({ items, menuLabel }: { items: NavItem[]; menuLabel: string }) {
const [open, setOpen] = useState(false)
return (
<div className="md:hidden">
<button type="button" aria-expanded={open} aria-label={menuLabel} onClick={() => setOpen(!open)}>
<span aria-hidden>☰</span>
</button>
{open && (
<ul>
{items.map((item) => (
<li key={item.href}>
<Link href={item.href} onClick={() => setOpen(false)}>{item.label}</Link>
</li>
))}
</ul>
)}
</div>
)
}
```
Header/Footer pobierasz w `[locale]/layout.tsx` (przez cached getter w
`lib/`) i podajesz jako props — layout to jedyne miejsce, które je składa.
@@ -0,0 +1,38 @@
---
name: ipal-plugin-gap
description: Handles the moment when @intecion/ipal-kit seems to lack a feature or behaves wrongly — verifies against the plugin docs and type definitions first, then writes a structured report for the plugin instead of patching the project with hooks, hardcoded values or copied plugin code. Use when tempted to work around the plugin, when a plugin function errors or is missing, or when the same need appears in several projects.
---
# ipal-plugin-gap
Reguła: AGENT.md §1.3 — **nie łataj w projekcie**.
## 1. Sprawdź, czy plugin tego nie ma
- `ls node_modules/@intecion/ipal-kit/docs/` — przeczytaj plik modułu,
- `grep -rn "<słowo kluczowe>" node_modules/@intecion/ipal-kit/dist --include=*.d.ts`,
- sprawdź wersję: `grep '"version"' node_modules/@intecion/ipal-kit/package.json`
(może problem jest naprawiony w nowszej — skill **ipal-upgrade**).
Plugin to ma → użyj go i powiedz użytkownikowi, gdzie to było.
## 2. Raport (gdy naprawdę brakuje albo nie działa)
Zapisz w `docs/plugin-requests/<data>-<temat>.md` projektu i pokaż użytkownikowi:
```markdown
# <temat>
**Projekt:** <nazwa> · **ipal-kit:** <wersja>
## Problem
<co nie działa / czego brakuje; komunikat błędu; kroki odtworzenia>
## Dlaczego to do pluginu
<czy przyda się w innych projektach — konkretnie>
## Proponowane API
<sygnatura funkcji / opcja ipalKit / pole w panelu; przykład użycia w projekcie>
## Obejście tymczasowe (jeśli konieczne)
<minimalne, w jednym pliku, z komentarzem TODO odsyłającym do tego raportu>
```
## 3. Czego nie robić
- hooka z zaszytą domeną/nazwą/kolorem klienta,
- kopii komponentu pluginu do projektu (np. `Analytics`, `CookieBanner`),
- `as any` / `@ts-ignore` żeby „przeszło”,
- dynamicznego `import()` przez zmienną (nie wbundluje się).
+38
View File
@@ -0,0 +1,38 @@
---
name: ipal-setup
description: Sets up a new client project on Payload 3 + Next 16 + @intecion/ipal-kit from an empty folder — registry and dependencies, version overrides, i18n config, payload.config with ipalKit (2FA injected, white-label), core collections, design tokens, UI primitives, proxy, layout and catch-all page, SEO routes, security headers, env validation. Use when starting a new website project or when a project is missing its ipal-kit foundation.
---
# ipal-setup
Kod i szczegóły: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md` §1–2
(przed instalacją pakietu: poproś użytkownika o ten plik albo działaj wg kroków
poniżej i doczytaj po `pnpm add`). Reguły: `docs/agent/AGENT.md`.
**Jeden etap = jeden commit. Po każdym etapie pokaż wynik i czekaj na OK.**
1. **Instalacja** — `.npmrc` (`@intecion:registry=…`, `legacy-peer-deps=true`),
`pnpm add @intecion/ipal-kit` + zależności z PROGRAMISTA §1, `pnpm.overrides`
na wersję `payload` dla wszystkich `@payloadcms/*`, build z `--webpack`.
Nigdy instalacja z gita. Nie twórz `middleware.ts`.
2. **Skille i AGENTS.md** — skopiuj skille (AGENT.md §14), utwórz `AGENTS.md`
wg AGENT.md §13 z danymi od użytkownika (zapytaj o: klient, domena, rynek,
języki, R2/lokalnie, SMTP/Graph).
3. **Konfiguracja** — `src/i18n.config.ts` (`as const satisfies I18nConfig`),
`payload.config.ts` wg PROGRAMISTA §2.3: `twoFactor` z **wstrzykniętym**
`payloadTotp`, `whiteLabel: true`, `email: mailAdapter()`.
4. **Rdzeń** — wspólne pola i prymitywy (`../ipal-block/resources/kod-sekcji.md`), `Pages`, `Media`
(PROGRAMISTA §2.4). Żadnych innych kolekcji.
5. **Style** — `styles.css` z `@theme` z `DESIGN.md` (jeśli brak — zapytaj o
Impeccable albo załóż neutralne tokeny), `@source` na plugin (AGENT.md §6.11, przykład w `../ipal-block/resources/kod-sekcji.md`).
6. **Routing** — `proxy.ts` (`createProxy`), `lib/content.ts`, layout bez
`<head>`, catch-all z ISR + `generateStaticParams` + `resolveRedirect`,
`not-found.tsx` z `LocaleView` — bez `headers()`, wersja na każdy język (PROGRAMISTA §2.6–2.8, pages.md).
7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, llms.txt, health
(wszystkie z `force-dynamic`), `htmlLimitedBots`, `buildSecurityHeaders`,
`instrumentation.ts` z `assertEnv` (PROGRAMISTA §2.8–2.9).
8. **Nawigacja** — skill **ipal-nav**.
9. `pnpm generate:types`, `pnpm payload generate:importmap`, skill **ipal-audit**
(pełny), lista kroków w panelu dla użytkownika (PROGRAMISTA §2.11).
Dalej: bloki (skill **ipal-block**), kolekcje treści (**ipal-collection**).
+36
View File
@@ -0,0 +1,36 @@
---
name: ipal-upgrade
description: Upgrades an existing project to the latest @intecion/ipal-kit and replaces hand-written code that the plugin now provides — proxy, route handlers, consent wrapper, language switcher, rich text parser, form logic, noindex, redirects, env validation, privacy link label, 404 page, CTA field zoo. Use when the user asks to update ipal-kit, migrate an older project, or clean up duplicated logic in a project.
---
# ipal-upgrade
Lista zmian: `node_modules/@intecion/ipal-kit/docs/dev/PROGRAMISTA.md` §6.
Zasada: gdy plugin dostarcza coś, co projekt ma ręcznie — **usuń lokalną wersję**.
## 1. Aktualizacja pakietu
```bash
pnpm add @intecion/ipal-kit@latest
rm -rf .next
```
Skopiuj skille na nowo (AGENT.md §14) — mogły się zmienić.
Postgres z migracjami: nowe pola pluginu (np. `privacyLinkLabel`) →
`pnpm payload migrate:create`.
## 2. Inwentaryzacja (bez zmian w kodzie)
Dla **każdej** pozycji tabeli PROGRAMISTA §6 pokaż dowód (grep / plik), czy
dotyczy projektu. Uruchom skill **ipal-audit** (`--quick`) i dołącz wynik.
Wynik: lista do zrobienia z priorytetem. Czekaj na OK.
## 3. Pozycja po pozycji
Jedna pozycja = jedna zmiana = jeden commit:
1. przeczytaj wskazany plik docs,
2. zastąp lokalny kod funkcją pluginu, usuń stary kod (nie zostawiaj obu),
3. `pnpm build`, pokaż wynik.
Pozycje zmieniające nazwy pól w bazie (np. refaktor `ctaLabel` → `links`)
wymagają **migracji danych przed** usunięciem starych pól — zapytaj
użytkownika, czy projekt ma już treść.
## 4. Koniec
Pełny **ipal-audit** bez błędów + lista rzeczy do sprawdzenia w panelu.
+2 -2
View File
@@ -77,7 +77,7 @@ export default async function LocaleLayout({ children, params }) {
```
`Analytics` nie renderuje nic — wstrzykuje skrypty. Zamontuj raz, wysoko w
drzewie. **Musi być wewnątrz `ConsentProvider`** (od 1.8.0 czyta stan zgody na
drzewie. **Musi być wewnątrz `ConsentProvider`** (od 1.7.12 czyta stan zgody na
żywo — poza providerem rzuci błąd kontekstu).
## Tryb Core Web Vitals — `defer` (opcjonalny)
@@ -325,4 +325,4 @@ forms + analytics, nie konfiguracja GTM.
| Event `form_submit` + parametry | panel Payload (grupa „Analytics" na formularzu) |
| Pixel ID, tagi, triggery, warunki zgody | panel GTM |
| Publikacja kontenera | panel GTM |
| Kod projektu | nic (poza jednorazowym `onSuccess` w rendererze) |
| Kod projektu | nic (poza jednorazowym `onSuccess` w rendererze) |
+1 -1
View File
@@ -84,4 +84,4 @@ bloków żadnym markupem.
export function Hero(props) {
return <section className="py-16">{/* ... */}</section>
}
```
```
+2 -2
View File
@@ -20,7 +20,7 @@ treścią bannera (message, przyciski, kategorie, settingsTitle) w panelu,
localized. Link do polityki prywatności bierze się z system pages
(`privacyPolicy`), nie z osobnego pola.
**Link do polityki prywatności w banerze (od 1.8.1)** — zero kodu:
**Link do polityki prywatności w banerze (od 1.7.12)** — zero kodu:
| Co | Skąd |
|---|---|
@@ -199,4 +199,4 @@ Przekazana mapa zastępuje domyślną — pamiętaj dołączyć `NEXT_LOCALE`, j
chcesz zachować sprzątanie locale (albo zaimportuj `LOCALE_COOKIE_NAME` i dodaj).
> Mechanizm zgody dla locale jest opisany też od strony i18n:
> [i18n.md](./i18n.md#cookie-locale-a-zgoda-rodo).
> [i18n.md](./i18n.md#cookie-locale-a-zgoda-rodo).
+1 -1
View File
@@ -352,4 +352,4 @@ import {
archiveFieldName,
} from '@intecion/ipal-kit'
import type { ContentOption, ResolvedRoute, ArchiveEntries } from '@intecion/ipal-kit'
```
```
@@ -28,6 +28,7 @@ pnpm add @intecion/ipal-kit
pnpm add @payloadcms/plugin-seo @payloadcms/plugin-form-builder \
nodemailer lucide-react slugify server-only
pnpm add @clocklimited/payload-2fa@3.0.0-beta.7 # 2FA (wymuszone)
pnpm add @payloadcms/storage-s3 # tylko gdy media w R2
pnpm add tailwindcss @tailwindcss/postcss
```
@@ -45,7 +46,8 @@ SEO, brak kolekcji Forms albo crash. W `package.json`:
"@payloadcms/db-postgres": "3.90.2",
"@payloadcms/richtext-lexical": "3.90.2",
"@payloadcms/plugin-seo": "3.90.2",
"@payloadcms/plugin-form-builder": "3.90.2"
"@payloadcms/plugin-form-builder": "3.90.2",
"@payloadcms/storage-s3": "3.90.2"
}
}
```
@@ -81,7 +83,7 @@ layout pod `[locale]` (bo `<html lang>` musi znać język).
```json
// package.json projektu
"scripts": {
"ipal:skills": "mkdir -p .agents/skills && cp -R node_modules/@intecion/ipal-kit/docs/agent/skills/. .agents/skills/"
"ipal:skills": "ipal-skills"
}
```
`pnpm ipal:skills` po instalacji i po każdej aktualizacji ipal-kit; `.agents/skills/`
@@ -137,9 +139,12 @@ export default buildConfig({
`buildNoindexField()`, `layout` typu `blocks` (min. 1 blok), `trackSlugHistoryHook`,
`buildRevalidateHook`.
- `Media`: upload z `mimeTypes` (obrazy + PDF), `alt` (required, localized),
`normalizeFilenameHook`; R2 przez `buildR2Storage(['media'])` (storage.md).
- `src/fields/` (link, sectionHeader, sectionSettings) i `src/components/ui/`
(CMSLink, Button, Media, Section, SectionHeader) — gotowy kod w AGENT.md §6.
`normalizeFilenameHook`; R2 przez `buildR2Storage(['media'], { s3Storage })` —
`s3Storage` z `@payloadcms/storage-s3`, wstrzykiwany (storage.md).
- Linki z pluginu (`buildLinkField`, `buildLinksField`, `resolveLinkHref` — links.md),
`src/fields/` (sectionHeader, sectionSettings) i `src/components/ui/`
(CMSLink, Button, Media, Section, SectionHeader) — gotowy kod w
`agent/skills/ipal-block/resources/kod-sekcji.md`, reguły w AGENT.md §6.
Załóż je **przed** pierwszym blokiem.
### 2.5 Tailwind
@@ -168,6 +173,8 @@ export const proxy = createProxy(i18nConfig, { NextResponse })
export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
```
Ustawia `x-locale` / `x-pathname`, cookie języka za zgodą, przekierowuje `/`.
Nagłówki są dla tras dynamicznych (API, route handlery) — w stronach SSG/ISR,
layoutach i `not-found.tsx` **nie czytaj `headers()`** (AGENT.md §4.6).
### 2.7 Warstwa danych — jedno źródło
```ts
@@ -179,7 +186,7 @@ import { contentConfig } from '@/content.config'
export const {
getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries,
getNotFoundPage, generateStaticParams, sitemap, robots,
generatePageMetadata, getNotFoundPage, generateStaticParams, sitemap, robots,
} = createContentHelpers({
config,
content: contentConfig,
@@ -233,21 +240,20 @@ export default async function LocaleLayout({ children, params }: Props) {
import { notFound, permanentRedirect } from 'next/navigation'
import type { Metadata } from 'next'
import { RenderBlocks } from '@intecion/ipal-kit/rsc'
import { createPageMetadata, resolveRedirect } from '@intecion/ipal-kit'
import { resolveRedirect } from '@intecion/ipal-kit'
import { i18nConfig } from '@/i18n.config'
import { blockRegistry } from '@/blocks/registry'
import { getCachedPayload, resolveRoute } from '@/lib/content'
import { generatePageMetadata, getCachedPayload, resolveRoute } from '@/lib/content'
export { generateStaticParams } from '@/lib/content' // SSG → <head> synchroniczny
export const revalidate = 3600 // ISR
const pageMetadata = createPageMetadata({ config: i18nConfig, baseUrl: process.env.NEXT_PUBLIC_SERVER_URL })
type Args = { params: Promise<{ locale: string; slug?: string[] }> } // bez searchParams!
// Ten sam cache co strona: jedno odczytanie ustawień i jedno resolveRoute na żądanie
export async function generateMetadata({ params }: Args): Promise<Metadata> {
const { locale, slug } = await params
return pageMetadata({ payload: await getCachedPayload(), locale, slug })
return generatePageMetadata(locale, slug)
}
export default async function Page({ params }: Args) {
@@ -410,8 +416,8 @@ Klient na M365/Exchange → Graph (SMTP AUTH bywa wyłączony). Własny SMTP/Gma
SMTP. Przełącznik w panelu (Site Integrations → SMTP → Email Transport).
Graph jednorazowo: App registration w Azure, uprawnienie aplikacyjne `Mail.Send`
+ **Grant admin consent**, zmienne `GRAPH_*`. `from.address` zawsze =
`GRAPH_SENDER` (inaczej `ErrorSendAsDenied`); nazwa nadawcy z panelu; adres
klienta idzie w `replyTo`. Więcej: email.md.
`GRAPH_SENDER` (inaczej `ErrorSendAsDenied`); nazwa nadawcy z panelu; adres
klienta idzie w `replyTo`. Więcej: email.md.
---
@@ -456,6 +462,9 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi:
| 13 | Brak health checku | `createHealthRoute` (§2.8) | — |
| 14 | 2FA crash „Cannot find module” | wstrzyknij `plugin: payloadTotp` | security.md |
| 15 | Pola `ctaLabel`/`pdfUrl`, sekcje-monolity | refaktor wg AGENT.md §6.7 (z migracją danych!) | AGENT.md |
| 15a | `buildR2Storage(['media'])` bez adaptera (od 1.8.1 błąd przy env R2) | `pnpm add @payloadcms/storage-s3`, `buildR2Storage(['media'], { s3Storage })` | storage.md |
| 15b | `src/fields/link.ts`, `src/lib/links.ts` w projekcie | importy z pluginu, usuń kopie (bez migracji bazy) | links.md |
| 15c | `createPageMetadata(...)` w `page.tsx` | `generatePageMetadata(locale, slug)` z `lib/content` — wspólny cache z komponentem strony, mniej zapytań | seo.md |
| 16 | 404 na sztywno | rola 404 w System Pages + `getNotFoundPage` | pages.md |
| 16a | `privacyPolicy: { label: 'Polityka prywatności', … }` w layoucie | usuń cały parametr; tekst wpisz w Cookie Settings → Privacy link label | consent.md |
| 17 | Opcjonalnie — AI/GEO | Markdown per strona, llms-full, boty AI w robots, MCP, wyszukiwarka, speakable, aiSummary | content.md, seo.md, mcp.md |
@@ -473,6 +482,7 @@ Po aktualizacji pakietu: `pnpm ipal:skills` (nowe wersje skilli), `rm -rf .next`
| `PayloadComponent not found in importMap` | `pnpm payload generate:importmap` |
| `Cannot destructure property 'config'` | dublet `@payloadcms/ui` w pluginie — `ls node_modules/@intecion/ipal-kit/node_modules/@payloadcms/ui` |
| `Cannot find module '@clocklimited/payload-2fa'` | wstrzyknij `plugin: payloadTotp` w `twoFactor` |
| `[ipal] R2 storage: … adapter was not injected` | `pnpm add @payloadcms/storage-s3` + `buildR2Storage(['media'], { s3Storage })` |
| Baner bez stylów | brak Tailwinda albo `@source` na plugin |
| `/admin`, `/_next` → 500 | matcher proxy nie jest literałem inline |
| `slug.join is not a function` | `[slug]` zamiast `[[...slug]]` |
@@ -520,7 +530,7 @@ fałszywe 0. Typowe pułapki: `npm version` przed commitem (brudne repo),
function` w projekcie), `pnpm add` przy działającym dev.
### 8.2 package.json pluginu
- `"files": ["dist", "docs"]` — **docs 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.
- Jeden blok `exports`, wszystkie ścieżki na `./dist/` (nie `./src/`).
- `payload`, `@payloadcms/*`, `next`, `react`, `react-dom` → **`peerDependencies`**
@@ -528,7 +538,10 @@ function` w projekcie), `pnpm add` przy działającym dev.
- Brak self-reference (nigdy `pnpm add` w katalogu pluginu).
- Plugin nigdy nie importuje `next/server`, `next/cache`, `@payload-config` ani
opcjonalnych pakietów wprost — projekt je wstrzykuje (wzorzec `NextResponse`,
`revalidatePath`, `payloadTotp`).
`revalidatePath`, `payloadTotp`, `s3Storage`). Opcjonalny pakiet = optional
`peerDependency` + typ minimalnego kształtu w pluginie, zero importu.
- Import z `next/*` w komponencie klienckim pluginu: z rozszerzeniem
(`'next/navigation.js'`) — `next` nie ma pola `exports`, NodeNext inaczej nie znajdzie.
```bash
grep -c '"exports"' package.json # 1
@@ -599,4 +612,4 @@ Git działa na katalogu, w którym jesteś — po `cd` zawsze `git status` i
| `Unauthorized` / pytanie o hasło w kółko | użyj tokenu zamiast hasła; zakres `write:repository` |
| `non-fast-forward`, „tip … is behind” | `git pull`, rozwiąż konflikty, `git push` |
| `repository not found` | zły adres albo brak dostępu do repo |
| 404 przy `pnpm add @intecion/…` | brak linii `@intecion:registry` w `.npmrc` projektu |
| 404 przy `pnpm add @intecion/…` | brak linii `@intecion:registry` w `.npmrc` projektu |
+14 -10
View File
@@ -46,7 +46,7 @@ najważniejsze, i wypisz, na którym kroku z node_modules/@intecion/ipal-kit/doc
(sprawdź stan repo: git log, istniejące pliki).
```
Sprawdź: agent wymienia m.in. proxy.ts zamiast middleware, zakaz hardkodowania,
linksField/CMSLink, minimum kolekcji. Jeśli nie — każ mu przeczytać jeszcze raz.
buildLinksField/CMSLink, minimum kolekcji. Jeśli nie — każ mu przeczytać jeszcze raz.
---
@@ -100,9 +100,12 @@ 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:
1. src/fields/link.ts, sectionHeader.ts, sectionSettings.ts — kod 1:1 z AGENT.md §6.2.
1. src/fields/sectionHeader.ts, sectionSettings.ts — kod 1:1 z
node_modules/@intecion/ipal-kit/docs/agent/skills/ipal-block/resources/kod-sekcji.md
(linki: buildLinkField/buildLinksField z @intecion/ipal-kit — nie kopiuj).
2. collections/Media.ts: upload (mimeTypes obrazy + PDF + mp4), alt required localized,
normalizeFilenameHook; jeśli R2 — buildR2Storage(['media']) z env (storage.md).
normalizeFilenameHook; jeśli R2 — buildR2Storage(['media'], { s3Storage }) z env, s3Storage
wstrzyknięty z @payloadcms/storage-s3 (storage.md).
3. collections/Pages.ts: title localized, buildSlugField, buildNoindexField,
layout typu blocks (na razie jeden blok Content: sectionHeaderField + content richText),
trackSlugHistoryHook, buildRevalidateHook (hooks.md).
@@ -123,7 +126,8 @@ Wcześniej: `/impeccable init` i `/impeccable document` → `PRODUCT.md`, `DESIG
Na podstawie DESIGN.md zrób src/app/(frontend)/styles.css wg AGENT.md §6.11:
@theme z tokenami (primary, background, foreground, muted + fonty), @source na plugin,
mapowanie --ipal-primary / --ipal-radius. Fonty przez next/font.
Potem prymitywy 1:1 z AGENT.md §6.3: lib/links.ts, components/ui/CMSLink.tsx,
Potem prymitywy 1:1 z node_modules/@intecion/ipal-kit/docs/agent/skills/ipal-block/resources/kod-sekcji.md:
components/ui/CMSLink.tsx,
Button.tsx, Media.tsx, Section.tsx, SectionHeader.tsx, oraz components/icons wg §6.10.
Zero hexów w komponentach — tylko tokeny.
Plan najpierw.
@@ -141,7 +145,7 @@ Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4:
ConsentProvider + CookieBanner + CookieButton + Analytics wewnątrz providera,
- [locale]/[[...slug]]/page.tsx: revalidate, generateStaticParams, BEZ searchParams,
resolveRedirect przed notFound, enhanceProps wstrzykuje locale do bloków,
- [locale]/not-found.tsx z getNotFoundPage (pages.md).
- [locale]/not-found.tsx z getNotFoundPage dla każdego języka + LocaleView, BEZ headers() (pages.md).
Plan najpierw.
```
Sprawdź: `/` → `/<domyślny język>`; `pnpm build` pokazuje strony jako `●`;
@@ -156,7 +160,7 @@ Zrób wg PROGRAMISTA.md §2.8–2.9 i seo.md:
- app/sitemap.ts, robots.ts, manifest.ts (createManifestHandler), llms.txt/route.ts,
api/health/route.ts — każda trasa czytająca bazę z export const dynamic = 'force-dynamic',
- next.config.ts: htmlLimitedBots, buildSecurityHeaders,
- metadata strony przez createPageMetadata, 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,
- src/instrumentation.ts z assertEnv(ipalEnvRules(...)) (env.md).
CSP jeszcze nie — będzie w kroku 14.
@@ -172,7 +176,7 @@ Skrót: `/ipal-nav <pozycje menu, kolumny stopki, rynek>`.
```
Zrób wg AGENT.md §6.8:
Zrób wg AGENT.md §6.8, kod z node_modules/@intecion/ipal-kit/docs/agent/skills/ipal-nav/resources/kod-nawigacji.md:
- globals/Header.ts, Footer.ts (kod z §6.8),
- globals/Company.ts dla rynku <PL/AU/…>: nazwa, adres, <NIP/ABN/…>, telefon, email —
wszystko localized tam, gdzie tekst,
@@ -203,7 +207,7 @@ Skrót: `/ipal-block <Nazwa> — <pola z 9a>, <opis wyglądu / zrzut>`.
```
Zbuduj blok <nazwa> wg AGENT.md §6 (warstwa 3):
- src/blocks/<Nazwa>/config.ts: sectionHeaderField, linksField, media, items,
- src/blocks/<Nazwa>/config.ts: sectionHeaderField, buildLinksField, media, items,
sectionSettingsField — tylko pola z listy z kroku 9a, nazwy z §6.5,
- Component.tsx: Section + SectionHeader + Media + CMSLink, max ~80 linii JSX,
powtarzalne elementy w <Nazwa>Card.tsx, interakcja w osobnym pliku 'use client' (§6.9),
@@ -335,7 +339,7 @@ Przenieś <co> do pola w <bloku/globalu> i pokaż diff.
**Zoo pól CTA / sekcja-monolit:**
```
Stop. AGENT.md §6.5–6.6: CTA = linksField() + CMSLink, obraz = media + Media,
Stop. AGENT.md §6.5–6.6: CTA = buildLinksField() + CMSLink, obraz = media + Media,
max ~80 linii JSX. Zrefaktoruj <blok> wg §6.7. Jeśli w bazie jest treść — najpierw migracja.
```
@@ -385,4 +389,4 @@ Potem jedna pozycja z listy = jedno polecenie:
```
Zrób pozycję <nr> z PROGRAMISTA.md §6 wg wskazanego pliku docs. Usuń lokalną
wersję, którą zastępuje plugin. Plan najpierw, na końcu pnpm build.
```
```
+1 -1
View File
@@ -176,4 +176,4 @@ mail przez AKTUALNY transport. Pokazuje wynik (✓/✗ z błędem). Endpoint
czyta z bazy, nie z pola na ekranie.
> Bezcenne przy diagnozie Graph — od razu widzisz `ErrorSendAsDenied`,
> `Insufficient privileges` itp. zamiast zgadywać.
> `Insufficient privileges` itp. zamiast zgadywać.
+2 -2
View File
@@ -4,7 +4,7 @@
WSZYSTKIMI brakami naraz — zamiast kryptograficznego crashu gdzieś w połowie
builda (`getaddrinfo ENOTFOUND`) albo runtime'u. Fail fast.
Powiązane: [PROGRAMISTA.md §3–4](./PROGRAMISTA.md), [storage.md](./storage.md),
Powiązane: [PROGRAMISTA.md §3–4](./dev/PROGRAMISTA.md), [storage.md](./storage.md),
[forms.md](./forms.md).
## Dlaczego bez zod
@@ -116,4 +116,4 @@ redeployów.
```ts
import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit'
import type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from '@intecion/ipal-kit'
```
```
+1 -1
View File
@@ -413,4 +413,4 @@ const label = resolveLocalized(topic.label, locale)
Turnstile wstrzykuje ukryte pole `cf-turnstile-response`. Plugin je toleruje
(nie odrzuca jako `unknown_fields`) — bo sam obsługuje Turnstile. Nie musisz go
filtrować w kliencie.
filtrować w kliencie.
+2 -2
View File
@@ -3,7 +3,7 @@
Plugin dostarcza hooki, które zdejmują z projektów powtarzalną robotę. Wpinasz je
w kolekcje; działają automatycznie. Wszystkie gotowe do użycia (import z pluginu).
Powiązane: [pages.md](./pages.md), [seo.md](./seo.md), [PROGRAMISTA.md §5](./PROGRAMISTA.md).
Powiązane: [pages.md](./pages.md), [seo.md](./seo.md), [PROGRAMISTA.md §5](./dev/PROGRAMISTA.md).
---
@@ -203,4 +203,4 @@ hooks: {
```
Które hooki wpiąć zależy od kolekcji — nie każda potrzebuje wszystkich (blog:
setPublishedAt; wszystkie z URL: revalidate + slugHistory; Pages: + preventDelete).
setPublishedAt; wszystkie z URL: revalidate + slugHistory; Pages: + preventDelete).
+1 -1
View File
@@ -319,4 +319,4 @@ export const config = { matcher: ['/((?!api|admin|_next|.*\\..*).*)'] }
```
`DEFAULT_PROXY_MATCHER` używaj jako referencji wartości, ale jeśli Next narzeka
na matcher — wklej go inline. To ograniczenie Next, nie pluginu.
na matcher — wklej go inline. To ograniczenie Next, nie pluginu.
+65
View File
@@ -0,0 +1,65 @@
# links
Jeden kształt linku dla całego projektu — przyciski CTA, linki w kartach,
pliki do pobrania. Pole schematu + funkcja zamieniająca wartość na `href`.
Wygląd (komponent `CMSLink`, warianty przycisków) zostaje w projekcie.
## Pola
```ts
import { buildLinkField, buildLinksField } from '@intecion/ipal-kit'
fields: [
buildLinksField(), // `links`: 0–2 przyciski sekcji
buildLinksField({ maxRows: 3, appearances: ['primary', 'secondary'] }),
buildLinkField(), // `link`: pojedynczy link
buildLinkField({ disableLabel: true, appearances: false }), // klikalna cała karta
]
```
| Opcja | Domyślnie | Co robi |
|---|---|---|
| `name` | `'link'` / `'links'` | nazwa pola |
| `relationTo` | `'pages'` | kolekcja dla typu „Page” |
| `uploadTo` | `'media'` | kolekcja dla typu „File” (PDF, dokumenty) |
| `appearances` | `['primary','secondary','link']` | style do wyboru; `false` = bez pola |
| `disableLabel` | `false` | bez etykiety (link owija kartę / obraz) — tylko `buildLinkField` |
| `required` | `false` | wymagane pola celu i etykiety |
| `maxRows` | `2` | tylko `buildLinksField` |
Wartość linku: `type` (`internal` strona · `external` URL, `mailto:`, `tel:`,
`#anchor` · `file` upload), `page`, `url`, `file`, `label` (localized), `newTab`,
`appearance`. W `payload-types.ts` powstaje typ **`CmsLink`**.
Plik do pobrania to link typu `file` — **nie** osobne pole `pdfUrl`.
## href
```ts
import { resolveLinkHref } from '@intecion/ipal-kit'
resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
// internal → '/en/about' (strona główna → '/en') · external → URL · file → URL pliku
// null → pusty link, brak strony w tym języku, strona niezpopulowana (sam ID), brak pliku
```
Linki wewnętrzne wymagają **zpopulowanej** strony (`depth ≥ 2` w bloku).
`homeSlug` — slug strony głównej (string albo mapa per język, np. z
`SiteSettings.homepage`), żeby zwinąć ją do `/{locale}`.
## Render w projekcie
Komponent `CMSLink` jest w projekcie (wygląd przycisków to sprawa projektu) —
gotowy kod: [kod-sekcji.md](./agent/skills/ipal-block/resources/kod-sekcji.md). Menu: `resolveNav` w
`lib/navigation.ts` ([kod-nawigacji.md](./agent/skills/ipal-nav/resources/kod-nawigacji.md)) korzysta z tego samego `resolveLinkHref`.
## Migracja z `src/fields/link.ts`
Projekty sprzed 1.8.x mają kopię w `src/fields/link.ts` i `src/lib/links.ts`.
Kształt danych jest identyczny (`interfaceName: 'CmsLink'`), więc **migracja
bazy nie jest potrzebna**:
1. importy `linkField` / `linksField` z `@/fields/link` → `buildLinkField` /
`buildLinksField` z `@intecion/ipal-kit`,
2. `resolveLinkHref(link, locale, homeSlug)` z `@/lib/links` →
`resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })` z pluginu,
3. usuń `src/fields/link.ts` i `src/lib/links.ts`, `pnpm generate:types`.
+1 -1
View File
@@ -72,4 +72,4 @@ wykona `initialize` → `tools/list` → i będzie mógł wołać `search_conten
Pojedynczy obiekt JSON-RPC albo batch (tablica). Notyfikacje (`notifications/*`,
bez `id`) → HTTP 202 bez ciała. Żądania → `{ jsonrpc:'2.0', id, result }` albo
`error` (`-32601` nieznana metoda, `-32700` parse error). `initialize` odbija
`protocolVersion` klienta (fallback `2025-06-18`).
`protocolVersion` klienta (fallback `2025-06-18`).
+1 -1
View File
@@ -66,4 +66,4 @@ fallback. `getNotificationTexts` resolwuje, co istnieje.
Global ma `read: () => true` — teksty są publiczne (pokazywane użytkownikom
końcowym), więc front czyta je bez sesji. Inaczej niż SiteIntegrations
(`read: isAdmin` — tam sekrety).
(`read: isAdmin` — tam sekrety).
+63 -13
View File
@@ -54,7 +54,7 @@ import { ALL_SYSTEM_PAGE_ROLES } from '@intecion/ipal-kit'
// ['homepage', 'notFound', 'privacyPolicy', 'cookiePolicy', 'termsOfService']
```
## Strona 404 — wybierana w panelu (od 1.8.0)
## Strona 404 — wybierana w panelu (od 1.7.12)
Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
@@ -62,24 +62,74 @@ Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera:
- stronę główną (część klientów tak woli), **albo**
- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`.
Projekt (`app/(frontend)/[locale]/not-found.tsx`) — gotowy przykład w
`frontend/[locale]/not-found.tsx`:
Projekt — `app/(frontend)/[locale]/not-found.tsx` (pełny plik):
```tsx
import { headers } from 'next/headers'
import { getNotFoundPage } from '@/lib/content' // z createContentHelpers
import React from 'react'
import { RenderBlocks } from '@intecion/ipal-kit/rsc'
import { LocaleView } from '@intecion/ipal-kit/client'
import { i18nConfig } from '@/i18n.config'
import { blockRegistry } from '@/blocks/registry'
import { getConfiguredLocales, getNotFoundPage } from '@/lib/content'
/**
* 404 view. The editor picks which page plays the 404 role in
* Site Settings → System Pages → "404 (Not Found)" — a dedicated page or the
* homepage — or leaves it empty → the fallback below.
*
* not-found.tsx receives no params, and reading headers() here would turn the
* SSG/ISR site dynamic ("Page changed from static to dynamic at runtime").
* So: render the 404 page for EVERY locale on the server (DB reads only — stays
* static) and let <LocaleView> pick the one from the URL (/en/... → en).
* Next still answers HTTP 404.
*/
export default async function NotFound() {
const locale = (await headers()).get('x-locale') ?? i18nConfig.defaultLocale
const page = await getNotFoundPage(locale) // null → fallback
if (page?.layout?.length) return <RenderBlocks blocks={page.layout} components={blockRegistry} />
return <Fallback404 locale={locale} />
const locales = await getConfiguredLocales()
const views = Object.fromEntries(
await Promise.all(
locales.map(async (locale) => {
const page = (await getNotFoundPage(locale)) as { layout?: unknown[] } | null
const view = page?.layout?.length ? (
<RenderBlocks
blocks={page.layout as never}
components={blockRegistry}
enhanceProps={() => ({ locale })}
/>
) : null
return [locale, view] as const
}),
),
)
// No 404 page assigned in any locale (or DB unreachable during build):
// the project's own minimal view — style it, keep it text-free or panel-driven.
if (Object.values(views).every((v) => v === null)) {
return (
<main className="container py-24 text-center">
<h1 className="text-6xl font-bold">404</h1>
</main>
)
}
return <LocaleView views={views} defaultLocale={i18nConfig.defaultLocale} />
}
```
`not-found.tsx` nie dostaje `params` — locale bierzemy z nagłówka `x-locale`,
który ustawia proxy z `createProxy`. Status HTTP zostaje **404** (renderuje go
Next po `notFound()`), treść jest z panelu.
> **NIE czytaj `headers()` w `not-found.tsx`** (`LocaleView` od 1.8.2). `not-found.tsx` nie dostaje
> `params`, ale `headers()` (np. `x-locale` z proxy) zamienia stronę SSG/ISR w
> dynamiczną — Next 16 rzuca `Page changed from static to dynamic at runtime`
> (AGENT.md §4.6). Dlatego serwer renderuje stronę 404 **dla każdego języka**
> (same odczyty z bazy — trasa zostaje statyczna), a `<LocaleView>` (komponent
> kliencki pluginu) wybiera wersję po pierwszym segmencie URL (`usePathname`).
> Działa też przy SSR — HTML ma od razu właściwy język. Layout `[locale]`
> (nagłówek, menu, stopka) i tak dostaje `params.locale` z URL.
Status HTTP zostaje **404** (renderuje go Next po `notFound()`), treść jest z
panelu we właściwym języku. Koszt: w payloadzie RSC strony 404 są wersje dla
wszystkich języków — przy stronie 404 to pomijalne.
Co plugin robi automatycznie z przypisaną stroną 404:
@@ -158,4 +208,4 @@ tego requestu (traci cały zysk SSG/ISR + wraca problem metadata w body).
strony zostały SSG.
Reguła: `searchParams` tylko tam, gdzie NAPRAWDĘ potrzebujesz (paginacja). Wszędzie
indziej pomiń — inaczej tracisz SSG i SEO.
indziej pomiń — inaczej tracisz SSG i SEO.
+1 -1
View File
@@ -51,4 +51,4 @@ return <Form siteKey={turnstileSiteKey} />
```ts
import { getGlobal } from '@intecion/ipal-kit'
const data = await getGlobal<MyType>(payload, 'moj-global', { locale: 'pl', depth: 1 })
```
```
+1 -1
View File
@@ -85,4 +85,4 @@ Payload już ma (to edytor). Zero dodatkowych zależności.
- **Brakujące węzły** — oficjalny konwerter obsługuje wszystkie (zagnieżdżone
listy, upload, relacje, horizontal rule…)
- **Rozjazd przy aktualizacji** — Payload utrzymuje konwerter, nie Ty
- **`any`** — typowane (SerializedEditorState)
- **`any`** — typowane (SerializedEditorState)
+5 -1
View File
@@ -212,6 +212,10 @@ ipalKit({
})
```
**`robots.txt` przy ukrytym panelu:** domyślny `robots` blokuje `/admin`. Nie
wpisuj tam `/its` — `robots.txt` jest publiczny i zdradziłby ścieżkę (panel i
tak ma `noindex`). W `createContentHelpers` ustaw `robots: { adminRoute: false }`.
### WYMAGANE — przenieś folder panelu w projekcie
Plugin ustawia `config.routes.admin`, ale NIE tworzy plików w `app/` projektu.
@@ -319,4 +323,4 @@ Admin może zresetować 2FA innego użytkownika (gdy zgubi telefon) — przez
Wybrany, bo wrapuje ACCESS CONTROL (TOTP przed dostępem do danych) + forceSetup
(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
dostęp do danych, nie tylko UI.
dostęp do danych, nie tylko UI.
+70 -22
View File
@@ -78,10 +78,29 @@ pusty tytuł ani sam siteName.
> coś ze słowami kluczowymi. Fallback page.title nie pomoże, bo problemem jest
> sama treść nazwy, nie brak tytułu.
## Front — createPageMetadata
## Front — generatePageMetadata (zalecane)
Dla zwykłych stron. Zna konwencje pluginu (kolekcja pages, SiteSettings, System
Pages, grupa meta), więc nie trzeba mu tego opisywać:
Z `createContentHelpers` (lib/content) — dzieli cache żądania z layoutem i
komponentem strony: **jedno** odczytanie SiteSettings i **jedno** `resolveRoute`
na żądanie, zamiast osobnych zapytań w metadata i w stronie:
```ts
// app/(frontend)/[locale]/[[...slug]]/page.tsx
import { generatePageMetadata } from '@/lib/content'
export async function generateMetadata({ params }): Promise<Metadata> {
const { locale, slug } = await params
return generatePageMetadata(locale, slug) // archiwum z paginacją: (locale, slug, page)
}
```
Wymaga `i18n` w `createContentHelpers`. Pod spodem to `createPageMetadata` z
wstrzykniętymi loaderami z cache — wszystko poniżej dotyczy też jego.
## createPageMetadata (niskopoziomowo)
Gdy nie używasz `createContentHelpers` albo trasa ma własne konwencje. Zna
konwencje pluginu (kolekcja pages, SiteSettings, System Pages, grupa meta):
```ts
// app/(frontend)/[locale]/[[...slug]]/page.tsx
@@ -103,7 +122,8 @@ export async function generateMetadata({ params }): Promise<Metadata> {
```
Wrapper jest konieczny: Next woła `generateMetadata({ params })` bez payloada, a
plugin nigdy nie wywołuje `getPayload` sam.
plugin nigdy nie wywołuje `getPayload` sam. Opcja `loaders: { getSettings,
resolveRoute }` pozwala podać własne funkcje z cache (tak robi `generatePageMetadata`).
Ogarnia: tytuł (order/separator/override z panelu), description, canonical,
hreflang dla wszystkich locale, OG, home zwinięty do `/pl` (slug home czytany z
@@ -318,7 +338,7 @@ Favicon jest GLOBALNY (ten sam wszędzie) — wpina się RAZ w root layout, nie
// app/(frontend)/[locale]/layout.tsx
import type { Metadata } from 'next'
import { buildIconsMetadata } from '@intecion/ipal-kit'
import { getSettings } from '@/lib/payload'
import { getSettings } from '@/lib/content' // z createContentHelpers
export async function generateMetadata({ params }): Promise<Metadata> {
const { locale } = await params
@@ -385,7 +405,7 @@ poprawnie: czytając z panelu/env, nie zaszywając wartości klienta.
> **Zasada:** nawet gdy coś robisz ręcznie w projekcie, dane (nazwa, kolory,
> opis, logo) czytaj z panelu (SiteSettings) albo env. Zaszyta nazwa/kolor
> klienta = antywzorzec (patrz standardy-kodu.md). Manifest „R Custom Cars" z
> klienta = antywzorzec (patrz AGENT.md §2). Manifest „R Custom Cars" z
> hardkodem zadziała tylko dla jednego klienta.
### Web App Manifest (PWA) — jak zrobić DOBRZE
@@ -394,6 +414,18 @@ Zasada nadrzędna: **brak danych → POMIŃ pole, NIE zaszywaj wartości.** Mani
jest ważny bez `name`? Nie — ale lepszy manifest bez nazwy niż z cudzą nazwą
klienta w fallbacku. Fallback z nazwą/kolorem klienta to ukryty hardkod.
> **Zalecane (aktualne): `createManifestHandler`** — to samo bez ręcznego kodu,
> z try/catch na brak bazy w buildzie:
> ```ts
> // app/manifest.ts
> import { createManifestHandler } from '@intecion/ipal-kit'
> import { getCachedPayload } from '@/lib/content'
> import { i18nConfig } from '@/i18n.config'
> export const dynamic = 'force-dynamic'
> export default createManifestHandler({ getCachedPayload, config: i18nConfig })
> ```
> Ręczny wariant poniżej — gdy manifest potrzebuje pól spoza panelu.
```ts
// app/manifest.ts
import type { MetadataRoute } from 'next'
@@ -480,7 +512,7 @@ typu, itp.):
- dane z panelu (SiteSettings / pola strony) albo env
- nic zaszytego per klient (nazwa, kolor, adres, domena)
- jeśli to uniwersalne i powtarzalne → rozważ zgłoszenie do pluginu zamiast
ręcznie (patrz antigravity_zasady_agent.md A0)
ręcznie (patrz AGENT.md §2)
## KRYTYCZNE: metadata w <head> dla Google
@@ -637,7 +669,7 @@ zwiększają szansę — nie gwarancję.
1. **Ranking na 1. stronie Google** — bez tego sitelinków nie ma. To robota SEO
(treść, linki), nie kodu.
2. **Czysta struktura + jasne tytuły** — logiczna hierarchia stron, opisowe title
(nie „Strona 1"). Patrz fundamenty-projektu.md.
(nie „Strona 1"). Patrz AGENT.md §3.
3. **Linkowanie wewnętrzne** — ważne strony podlinkowane z głównej.
4. **Structured data** (poniżej) — sygnał pomocniczy, nie przełącznik.
5. **Sitemap + robots** — żeby Google w ogóle widział wszystkie strony (patrz
@@ -703,7 +735,7 @@ Plugin dostarcza helpery — projekt MUSI je wpiąć i podać dane z panelu:
- [ ] `buildBreadcrumbJsonLd` na podstronach (z realnej ścieżki)
- [ ] `buildSiteNavigationJsonLd` z pozycji menu (jeśli jest header nav)
- [ ] `app/robots.ts` i `app/sitemap.ts` wystawione (patrz niżej — bez tego
Google nie widzi stron!)
Google nie widzi stron!)
- [ ] Jasne, opisowe tytuły stron (nie generyczne)
- [ ] Logiczna hierarchia + linkowanie wewnętrzne z głównej
@@ -763,21 +795,36 @@ Opcje: `name` (domyślnie `'noindex'`), `label`, `description`, `overrides`
## robots.txt — blokada parametrów (crawl budget)
URL-e z parametrami (`?meter=101-120m2`, `?s=fraza`) marnują budżet indeksowania —
Google skanuje dziesiątki pustych wariantów. Zablokuj je w robots:
Google skanuje dziesiątki pustych wariantów. Zablokuj je w robots — **dopisują
się** do domyślnych `/admin` i `/api`:
```ts
// lib/content.ts — gotowy handler robots z opcjami
createContentHelpers({
config, content, i18n: i18nConfig, baseUrl,
robots: {
disallowParams: ['s', 'meter'], // → /*?s=, /*&s=, /*?meter=, /*&meter=
extraDisallow: ['/koszyk'], // dodatkowe ścieżki (opcjonalnie)
// aiBots: 'block-training', // patrz „wpuść boty AI” niżej
},
})
// app/robots.ts
import { buildRobots } from '@intecion/ipal-kit'
export default function robots() {
return buildRobots({
baseUrl: process.env.NEXT_PUBLIC_SERVER_URL!,
disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'], // + parametry
})
}
export { robots as default } from '@/lib/content'
```
Wzorce `/*?param=*` odcinają parametryzowane URL-e. Realne z audytu: 55
niezindeksowanych stron kalkulatora — blokada w robots by temu zapobiegła.
Bez `createContentHelpers`: `buildRobots({ baseUrl, disallowParams: ['s', 'meter'] })`.
| Opcja | Działanie |
|---|---|
| `disallowParams` | nazwy parametrów → `/*?nazwa=` i `/*&nazwa=` (parametr nie musi być pierwszy) |
| `extraDisallow` | ścieżki dopisane do domyślnych |
| `adminRoute` | ścieżka panelu do zablokowania (domyślnie `/admin`); `false` = nie wpisuj (ukryty panel — patrz security.md) |
| `disallow` | **pełna** lista — zastępuje domyślne (stary sposób; łatwo zgubić `/admin`) |
**Nie blokuj `page`** — strony archiwum `?page=2` to prawdziwe strony z
canonical na siebie. Realne z audytu: 55 niezindeksowanych stron kalkulatora
(`?meter=`) — blokada w robots by temu zapobiegła.
## Local SEO — LocalBusiness, Service, FAQPage (structured data)
@@ -1089,7 +1136,8 @@ komponent opakowujący węzły w `@graph` + bezpieczny `<script>`. Ale NIE narzu
modelu danych firmy.
```tsx
import { JsonLdGraph, buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'
import { buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'
import { JsonLdGraph } from '@intecion/ipal-kit/rsc' // komponent → wejście /rsc
// Projekt buduje węzły ze SWOICH danych i wybiera @type dla SWOJEGO rynku
const website = buildWebSiteJsonLd({ name, url })
@@ -1115,7 +1163,7 @@ Sztywny `buildCompanyGlobal()` w pluginie byłby **leaky abstraction** — austr
projekt miałby martwe pole NIP i brakujący ABN. Dlatego:
- **Plugin:** klocki Schema (Organization, LocalBusiness, WebSite, SiteNavigation)
+ JsonLdGraph (opakowanie + bezpieczny render)
+ JsonLdGraph (opakowanie + bezpieczny render)
- **Projekt:** własny `src/globals/Company.ts` pod kraj/branżę + mapowanie swoich
danych na właściwy `@type` (LegalService w PL, HVACBusiness w AU)
@@ -1141,4 +1189,4 @@ const speakable = buildSpeakableJsonLd({
W markupie projektu oznacz pasujące elementy (np. `className="speakable"` albo
sekcja `.lead` ze streszczeniem). Selektory nietrafiające w nic są ignorowane —
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 -1
View File
@@ -63,4 +63,4 @@ buildSlugField({
import { toSlug } from '@intecion/ipal-kit'
toSlug('Strona główna') // 'strona-glowna'
```
```
+27 -7
View File
@@ -16,7 +16,7 @@ pnpm add @payloadcms/storage-s3
## Zmienne .env
Patrz [R2-ENV-przyklad](../R2-ENV-przyklad.md) po pełną instrukcję skąd wziąć wartości.
Skąd wziąć wartości: Cloudflare → R2 → bucket (nazwa), Overview → S3 API (endpoint `https://<ACCOUNT_ID>.r2.cloudflarestorage.com`), Manage R2 API Tokens → „Object Read & Write” (para kluczy; secret widać raz). Wszystkie 4 zmienne → R2; brak którejś → dysk lokalny (częściowa konfiguracja = ostrzeżenie w logu).
```bash
R2_BUCKET=nazwa-bucketa
@@ -27,20 +27,33 @@ R2_SECRET_ACCESS_KEY=<secret-access-key>
## Wpięcie (payload.config.ts)
```bash
pnpm add @payloadcms/storage-s3 # ta sama wersja co payload (pnpm.overrides)
```
```ts
import { buildR2Storage } from '@intecion/ipal-kit'
import { s3Storage } from '@payloadcms/storage-s3'
export default buildConfig({
// ...
plugins: [
ipalKit({ /* ... */ }),
buildR2Storage(['media']), // slugi kolekcji upload do offloadu
buildR2Storage(['media'], { s3Storage }), // slugi kolekcji + WSTRZYKNIĘTY adapter
],
})
```
`buildR2Storage` przyjmuje listę kolekcji upload (domyślnie `['media']`). Jeśli
masz więcej kolekcji plików: `buildR2Storage(['media', 'documents'])`.
masz więcej kolekcji plików: `buildR2Storage(['media', 'documents'], { s3Storage })`.
**Adapter jest wstrzykiwany (od 1.8.1)** — plugin nie importuje
`@payloadcms/storage-s3`, bo to opcjonalna zależność: projekty na dysku lokalnym
jej nie instalują. Ten sam wzorzec co `payloadTotp` w 2FA i `NextResponse` w
proxy. Gdy env R2 jest ustawione, a `s3Storage` nie przekazano, start kończy się
czytelnym błędem (zamiast cichego zapisu mediów na dysk kontenera, który znika
przy redeployu). Starsze wywołanie `buildR2Storage(['media'])` bez adaptera
działa tylko bez env R2.
## Zachowanie (fallback)
@@ -214,14 +227,21 @@ z CDN zawczasu, zanim napotka pierwszy `<img>`. Zysk ~150–300 ms na pierwszym
obrazie.
```tsx
// layout.tsx — w <head> (albo górze <body>, Next hoistuje link tagi)
// layout.tsx — na GÓRZE <body>, NIE w jawnym <head>
import { MediaPreconnect } from '@intecion/ipal-kit/rsc'
<head>
<body className={...}>
<MediaPreconnect />
</head>
{children}
</body>
```
> **NIE umieszczaj w jawnym `<head>`!** Sztywny `<head><MediaPreconnect/></head>`
> w layoutcie App Router wymusza przedwczesne zamknięcie head — zanim strona
> wygeneruje metadane — przez co title/canonical/hreflang lądują w `<body>`
> (crawlery ich nie widzą). React 19 sam hoistuje `<link rel="preconnect">` do
> `<head>`, więc renderowanie w `<body>` jest poprawne. Patrz seo.md (metadata w head).
Czyta domenę z **R2_PUBLIC_URL** (to samo źródło co buildR2Storage) — zero
hardkodu, jedno źródło prawdy. Gdy R2_PUBLIC_URL nie ustawione (lokalny dysk,
brak CDN) → nie renderuje nic. Zmiana domeny mediów = zmiana jednej zmiennej
@@ -229,4 +249,4 @@ env, komponent podąża automatycznie.
> 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
> bierze ją z env.
> bierze ją z env.
+7 -3
View File
@@ -69,11 +69,15 @@ przekazywania siteKey do każdego formularza.
```tsx
// app/(frontend)/[locale]/layout.tsx (server)
import { getSiteIntegrations } from '@intecion/ipal-kit'
import { TurnstileProvider } from '@intecion/ipal-kit/client'
import { getTurnstileSiteKey } from '@/lib/payload' // Twój helper server-side
import { getCachedPayload } from '@/lib/content'
export default async function Layout({ children }) {
const siteKey = await getTurnstileSiteKey() // z panelu (SiteIntegrations)
// tylko publiczny siteKey — sekret Turnstile nigdy nie trafia do klienta
const { turnstileSiteKey: siteKey } = await getSiteIntegrations<{ turnstileSiteKey?: string }>(
await getCachedPayload(),
)
return (
<html>
<body>
@@ -127,4 +131,4 @@ w submitForm automatycznie.
### Stary sposób (nadal działa)
`<Turnstile siteKey={...} onToken={...} />` bezpośrednio — jeśli potrzebujesz
pełnej kontroli albo masz nietypowy przypadek. Provider to warstwa wygody nad tym.
pełnej kontroli albo masz nietypowy przypadek. Provider to warstwa wygody nad tym.
+1 -1
View File
@@ -88,4 +88,4 @@ przez `AdminIcon`.
- [ ] `ipalKit({ whiteLabel: true })`
- [ ] Redaktor wgrał `logo` i `favicon` w SiteSettings (+ `siteName`)
- [ ] `pnpm generate:importmap`
- [ ] Restart dev / rebuild → panel pokazuje markę klienta na loginie i w nav
- [ ] Restart dev / rebuild → panel pokazuje markę klienta na loginie i w nav
+51
View File
@@ -0,0 +1,51 @@
import React from 'react'
import { RenderBlocks } from 'ipal-kit/rsc'
import { LocaleView } from 'ipal-kit/client'
import { i18nConfig } from '@/i18n.config'
import { blockRegistry } from '@/blocks/registry'
import { getConfiguredLocales, getNotFoundPage } from '@/lib/content'
/**
* 404 view. The editor picks which page plays the 404 role in
* Site Settings → System Pages → "404 (Not Found)" — a dedicated page or the
* homepage — or leaves it empty → the fallback below.
*
* not-found.tsx receives no params, and reading headers() here would turn the
* SSG/ISR site dynamic ("Page changed from static to dynamic at runtime").
* So: render the 404 page for EVERY locale on the server (DB reads only — stays
* static) and let <LocaleView> pick the one from the URL (/en/... → en).
* Next still answers HTTP 404.
*/
export default async function NotFound() {
const locales = await getConfiguredLocales()
const views = Object.fromEntries(
await Promise.all(
locales.map(async (locale) => {
const page = (await getNotFoundPage(locale)) as { layout?: unknown[] } | null
const view = page?.layout?.length ? (
<RenderBlocks
blocks={page.layout as never}
components={blockRegistry}
enhanceProps={() => ({ locale })}
/>
) : null
return [locale, view] as const
}),
),
)
// No 404 page assigned in any locale (or DB unreachable during build):
// the project's own minimal view — style it, keep it text-free or panel-driven.
if (Object.values(views).every((v) => v === null)) {
return (
<main className="container py-24 text-center">
<h1 className="text-6xl font-bold">404</h1>
</main>
)
}
return <LocaleView views={views} defaultLocale={i18nConfig.defaultLocale} />
}
+9 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.7.12",
"version": "1.8.3",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
@@ -73,6 +73,9 @@
"peerDependencies": {
"@payloadcms/plugin-form-builder": "^3.90.2",
"@payloadcms/plugin-seo": "^3.90.2",
"@payloadcms/richtext-lexical": "^3.90.2",
"@payloadcms/storage-s3": "^3.90.2",
"@payloadcms/ui": "^3.90.2",
"next": ">=15",
"payload": "^3.90.2",
"react": "^19.0.0"
@@ -127,5 +130,10 @@
"esbuild",
"unrs-resolver"
]
},
"peerDependenciesMeta": {
"@payloadcms/storage-s3": {
"optional": true
}
}
}
+1161 -1458
View File
File diff suppressed because it is too large Load Diff
+4 -16
View File
@@ -1,22 +1,13 @@
'use client'
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
export {
AccessibilityProvider,
AccessibilityWidget,
useAccessibility,
} from '../modules/accessibility/client.js'
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js'
export type { AnalyticsProps } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
export {
loadClarity,
loadLinkedIn,
loadMetaPixel,
loadTikTok,
} from '../modules/analytics/client.js'
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js'
/**
* Entry point: ipal-kit/client
*
@@ -37,11 +28,7 @@ export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export { useContactForm } from '../modules/forms/useContactForm.js'
export type {
ContactFormErrors,
ContactFormValues,
SubmitAction,
} from '../modules/forms/useContactForm.js'
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'
export { useForm } from '../modules/forms/useForm.js'
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'
export {
@@ -73,6 +60,7 @@ export {
useSetAlternateLinks,
} from '../modules/i18n/index.js'
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
export { LocaleView } from '../modules/pages/LocaleView.js'
export { Turnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
export type { TurnstileProps } from '../modules/turnstile/client.js'
+23 -3
View File
@@ -128,6 +128,14 @@ export type { LocaleMiddlewareResult } from './modules/i18n/index.js'
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'
export type {
BuildLinkFieldOptions,
BuildLinksFieldOptions,
LinkAppearance,
LinkValue,
ResolveLinkHrefOptions,
} from './modules/links/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js'
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
@@ -150,13 +158,25 @@ export {
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export { buildSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
export { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'
export type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js'
export {
buildHreflangAlternates,
buildMetadata,
composeTitle,
readSiteMetaConfig,
slugsAcrossLocales,
} from './modules/seo/index.js'
export type { SiteMetaConfig } from './modules/seo/index.js'
export type {
AutoFillMapping,
RobotsOptions,
RobotsRules,
SitemapEntry,
} from './modules/seo/index.js'
export {
AI_ASSISTANT_BOTS,
AI_TRAINING_BOTS,
+14 -5
View File
@@ -39,6 +39,12 @@ type ResolveRouteArgs = {
payload: BasePayload
/** Route segments after the locale, e.g. ['artykuly', 'moj-post']. */
segments?: string[]
/**
* SiteSettings already read for this locale (depth ≥ 1). Pass it to skip the
* read — createContentHelpers does, so layout, metadata and page share ONE
* settings query per request.
*/
settings?: null | Record<string, unknown>
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
@@ -73,13 +79,16 @@ export async function resolveRoute({
pagesSlug = 'pages',
payload,
segments,
settings: preloaded,
settingsSlug = 'site-settings',
}: ResolveRouteArgs): Promise<null | ResolvedRoute> {
const settings = (await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: locale as never,
})) as Record<string, unknown>
const settings =
preloaded ??
((await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: locale as never,
})) as Record<string, unknown>)
// Locale root → Homepage from System Pages.
// settings.homepage is a shallow relation (depth: 1 above) — it identifies
+144 -67
View File
@@ -5,14 +5,10 @@ import { cache } from 'react'
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { RobotsRules, SitemapEntry } from '../seo/index.js'
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry } from '../seo/index.js'
import {
getArchiveEntries,
resolveNotFoundPage,
resolveRoute as resolveRouteRaw,
} from '../content/index.js'
import { buildRobots, buildSitemapEntries } from '../seo/index.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { buildRobots, buildSitemapEntries, createPageMetadata } from '../seo/index.js'
type CreateContentHelpersArgs = {
/**
@@ -35,6 +31,12 @@ type CreateContentHelpersArgs = {
i18n?: I18nConfig
/** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
/**
* Options for the ready-made `robots` handler, e.g.
* `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or
* `{ adminRoute: false }` when the admin path is hidden (ipalKit adminRoute).
*/
robots?: RobotsOptions
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
@@ -71,11 +73,12 @@ export function createContentHelpers({
content,
i18n,
pagesSlug = 'pages',
robots: robotsOptions,
settingsSlug = 'site-settings',
}: CreateContentHelpersArgs) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
const getCachedPayload = cache(async (): Promise<BasePayload> =>
getPayload({ config: await config }),
const getCachedPayload = cache(
async (): Promise<BasePayload> => getPayload({ config: await config }),
)
const getConfiguredLocales = cache(async (): Promise<string[]> => {
@@ -83,6 +86,10 @@ export function createContentHelpers({
return c.localization ? c.localization.locales.map((l) => l.code) : []
})
/**
* SiteSettings for a locale — ONE query per locale per request, shared by the
* layout, generatePageMetadata, resolveRoute and anything else that asks.
*/
const getSettings = cache(async (locale: string) => {
const payload = await getCachedPayload()
return payload.findGlobal({ slug: settingsSlug as never, depth: 2, locale: locale as never })
@@ -96,21 +103,90 @@ export function createContentHelpers({
page: number,
): Promise<null | ResolvedRoute> => {
const payload = await getCachedPayload()
return resolveRouteRaw({ content, locale, page, pagesSlug, payload, segments, settingsSlug })
const settings = (await getSettings(locale)) as Record<string, unknown>
return resolveRouteRaw({
content,
locale,
page,
pagesSlug,
payload,
segments,
settings,
settingsSlug,
})
},
)
/**
* generateMetadata for the catch-all page, sharing the request cache with
* the page component: the same settings read and the same resolveRoute call
* (React cache spans generateMetadata and the page within one request), so
* metadata costs no extra route/settings queries.
*
* export async function generateMetadata({ params }) {
* const { locale, slug } = await params
* return generatePageMetadata(locale, slug)
* }
*/
let pageMetadata: ReturnType<typeof createPageMetadata> | undefined
const generatePageMetadata = async (
locale: string,
segments: string[] | undefined,
page = 1,
): Promise<PageMetadata> => {
if (!i18n) {
throw new Error('[ipal] createContentHelpers: pass `i18n` to use generatePageMetadata.')
}
pageMetadata ??= createPageMetadata({
baseUrl: origin || undefined,
collection: pagesSlug,
config: i18n,
content,
loaders: {
getSettings: async (l) => (await getSettings(l)) as Record<string, unknown>,
resolveRoute,
},
settingsSlug,
})
return pageMetadata({ slug: segments, locale, page, payload: await getCachedPayload() })
}
/** ID of the page assigned as 404 — the relation isn't localized, so one read serves every locale. */
const getNotFoundPageId = cache(async (): Promise<null | number | string> => {
const payload = await getCachedPayload()
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 0,
})) as { notFound?: unknown }
const rel = settings.notFound
if (typeof rel === 'string' || typeof rel === 'number') {return rel}
if (rel && typeof rel === 'object') {
const id = (rel as { id?: unknown }).id
if (typeof id === 'string' || typeof id === 'number') {return id}
}
return null
})
/**
* The page assigned as 404 in System Pages (or null → built-in fallback).
* For app/not-found.tsx; never throws. Locale comes from the x-locale header
* set by createProxy (not-found.tsx receives no params).
* For app/not-found.tsx; never throws. not-found.tsx receives no params and
* must NOT read headers() (breaks SSG/ISR) — call this for every configured
* locale and let <LocaleView> (client) pick the one from the URL. See pages.md.
*/
const getNotFoundPage = cache(async (locale: string) => {
try {
const id = await getNotFoundPageId()
if (id === null) {return null}
const payload = await getCachedPayload()
return await resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug })
const doc = await payload.findByID({
id,
collection: pagesSlug as never,
depth: 2,
locale: locale as never,
})
return (doc as null | Record<string, unknown>) ?? null
} catch {
return null // DB unreachable (container build) — fallback view
return null // DB unreachable (container build) or page deleted — fallback view
}
})
@@ -150,7 +226,9 @@ export function createContentHelpers({
*/
const sitemap = cache(async (): Promise<SitemapEntry[]> => {
if (!i18n) {
throw new Error('[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.')
throw new Error(
'[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.',
)
}
try {
return await buildSitemapEntries({
@@ -183,7 +261,7 @@ export function createContentHelpers({
* export { robots as default } from '@/lib/content'
* ```
*/
const robots = (): RobotsRules => buildRobots({ baseUrl: origin })
const robots = (): RobotsRules => buildRobots({ ...robotsOptions, baseUrl: origin })
/**
* Next.js generateStaticParams for the [[...slug]] route (or
@@ -235,62 +313,60 @@ export function createContentHelpers({
const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []
for (const locale of locales) {
// NO where:{_status} filter — collections without drafts enabled don't
// register the _status field, and querying it throws
// "path cannot be queried: _status". We filter drafts in memory below,
// which is safe for every collection (with or without drafts).
const result = await payload.find({
collection: pagesSlug as never,
depth: 0,
limit: 1000,
locale: (locale ?? 'all') as never,
})
// NO where:{_status} filter — collections without drafts enabled don't
// register the _status field, and querying it throws
// "path cannot be queried: _status". We filter drafts in memory below,
// which is safe for every collection (with or without drafts).
const result = await payload.find({
collection: pagesSlug as never,
depth: 0,
limit: 1000,
locale: (locale ?? 'all') as never,
})
for (const raw of result.docs as Array<{
_status?: string
id: number | string
meta?: { noindex?: boolean } | null
slug?: unknown
}>) {
// Draft filter in memory (safe whether or not the collection has drafts).
if (raw._status && raw._status !== 'published') {continue}
if (notFoundId !== undefined && raw.id === notFoundId) {continue}
for (const raw of result.docs as Array<{
_status?: string
id: number | string
meta?: { noindex?: boolean } | null
slug?: unknown
}>) {
// Draft filter in memory (safe whether or not the collection has drafts).
if (raw._status && raw._status !== 'published') {continue}
if (notFoundId !== undefined && raw.id === notFoundId) {continue}
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
// it as SSG so it's fast and its <head> is complete; noindex controls
// INDEXING, not whether the page exists. Skipping it would force dynamic
// rendering (the very streaming problem we're avoiding).
// NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex
// page (privacy, cookies, terms) still needs to render — users reach it
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
// it as SSG so it's fast and its <head> is complete; noindex controls
// INDEXING, not whether the page exists. Skipping it would force dynamic
// rendering (the very streaming problem we're avoiding).
if (homeId && raw.id === homeId) {
// Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.
const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }
if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}
continue
}
// Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when
// read with locale:'all' or left unflattened. Handle both, or localized
// pages get silently dropped.
const rawSlug = raw.slug
const slug =
typeof rawSlug === 'string'
? rawSlug
: rawSlug && typeof rawSlug === 'object'
? (((rawSlug as Record<string, unknown>)[locale ?? ''] as string | undefined) ??
(Object.values(rawSlug as Record<string, unknown>)[0] as string | undefined))
: undefined
if (!slug || EXCLUDED.has(slug)) {continue}
// Multi-level slugs ('atrakcje/telefon') → array segments.
const segments = String(slug).split('/').filter(Boolean)
params.push(
singleLocale ? { slug: segments } : { slug: segments, locale: locale as string },
)
if (homeId && raw.id === homeId) {
// Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.
const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }
if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}
continue
}
// Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when
// read with locale:'all' or left unflattened. Handle both, or localized
// pages get silently dropped.
const rawSlug = raw.slug
const slug =
typeof rawSlug === 'string'
? rawSlug
: rawSlug && typeof rawSlug === 'object'
? ((rawSlug as Record<string, unknown>)[locale ?? ''] as string | undefined) ??
(Object.values(rawSlug as Record<string, unknown>)[0] as string | undefined)
: undefined
if (!slug || EXCLUDED.has(slug)) {continue}
// Multi-level slugs ('atrakcje/telefon') → array segments.
const segments = String(slug).split('/').filter(Boolean)
params.push(singleLocale ? { slug: segments } : { slug: segments, locale: locale as string })
}
}
return params
} catch (err) {
@@ -309,6 +385,7 @@ export function createContentHelpers({
}
return {
generatePageMetadata,
generateStaticParams,
getCachedPayload,
getConfiguredLocales,
+141
View File
@@ -0,0 +1,141 @@
import type { ArrayField, Field, GroupField } from 'payload'
export type LinkAppearance = 'link' | 'primary' | 'secondary'
export type BuildLinkFieldOptions = {
/** Visual styles the editor may pick. `false` → no appearance select. Default all three. */
appearances?: false | LinkAppearance[]
/** Hide the label — for links that wrap something (a whole card, an image). */
disableLabel?: boolean
/** Field name. Default 'link'. */
name?: string
/** Collection the "Page" option points at. Default 'pages'. */
relationTo?: string
required?: boolean
/** Upload collection for "File" links (PDF, documents). Default 'media'. */
uploadTo?: string
}
const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/
type SiblingWithType = { type?: string } | undefined
/**
* The ONE link shape for a project: a page, an external URL (also mailto:,
* tel:, #anchor) or an uploaded file — plus label, new-tab flag and visual
* style. Every CTA, card link and download in every block uses this field, so
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
* (resolveLinkHref + the project's CMSLink) handles them all.
*
* Generates a named TypeScript type `CmsLink` in payload-types.ts.
*
* fields: [buildLinkField()] // single link
* fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card
*/
export function buildLinkField({
name = 'link',
appearances = ['primary', 'secondary', 'link'],
disableLabel = false,
relationTo = 'pages',
required = false,
uploadTo = 'media',
}: BuildLinkFieldOptions = {}): GroupField {
const fields: Field[] = [
{
type: 'row',
fields: [
{
name: 'type',
type: 'radio',
admin: { layout: 'horizontal', width: '50%' },
defaultValue: 'internal',
options: [
{ label: 'Page', value: 'internal' },
{ label: 'URL', value: 'external' },
{ label: 'File', value: 'file' },
],
},
{
name: 'newTab',
type: 'checkbox',
admin: { style: { alignSelf: 'flex-end' }, width: '50%' },
label: 'Open in new tab',
},
],
},
{
name: 'page',
type: 'relationship',
admin: { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' },
relationTo,
required,
},
{
name: 'url',
type: 'text',
admin: {
condition: (_: unknown, s: SiblingWithType) => s?.type === 'external',
description: 'Full URL (https://…), mailto:, tel: or #section-anchor.',
},
required,
validate: (v: null | string | undefined) =>
!v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor',
},
{
name: 'file',
type: 'upload',
admin: {
condition: (_: unknown, s: SiblingWithType) => s?.type === 'file',
description: 'Upload a PDF / document / image. Never paste a file URL.',
},
relationTo: uploadTo,
required,
},
]
if (!disableLabel) {
fields.push({ name: 'label', type: 'text', localized: true, required })
}
if (appearances && appearances.length) {
fields.push({
name: 'appearance',
type: 'select',
defaultValue: appearances[0],
options: appearances.map((a) => ({ label: a, value: a })),
})
}
return {
name,
type: 'group',
admin: { hideGutter: true },
fields,
interfaceName: 'CmsLink',
}
}
export type BuildLinksFieldOptions = {
/** Max number of buttons. Default 2. */
maxRows?: number
/** Field name. Default 'links'. */
name?: string
} & Omit<BuildLinkFieldOptions, 'disableLabel' | 'name'>
/**
* 0..N buttons — use for every "CTA(s)" of a section. Each row holds one
* `link` (buildLinkField). Render: `links.map(({ id, link }) => <CMSLink … />)`.
*/
export function buildLinksField({
name = 'links',
maxRows = 2,
...linkOptions
}: BuildLinksFieldOptions = {}): ArrayField {
return {
name,
type: 'array',
admin: { initCollapsed: true },
fields: [buildLinkField(linkOptions)],
maxRows,
}
}
+4
View File
@@ -0,0 +1,4 @@
export { buildLinkField, buildLinksField } from './buildLinkField.js'
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'
export { resolveLinkHref } from './resolveLinkHref.js'
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
+71
View File
@@ -0,0 +1,71 @@
import type { I18nConfig } from '../i18n/index.js'
import { buildLocalizedPath } from '../i18n/index.js'
/**
* Minimal shape of a link value (the project's generated `CmsLink` fits it).
* The plugin doesn't know the project's types — only this contract.
*/
export type LinkValue = {
appearance?: null | string
file?: unknown
label?: null | string
newTab?: boolean | null
page?: unknown
type?: 'external' | 'file' | 'internal' | null
url?: null | string
}
export type ResolveLinkHrefOptions = {
config: I18nConfig
/**
* Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a
* string. Usually from SiteSettings.homepage.
*/
homeSlug?: Record<string, string> | string
locale: string
}
/**
* Turns a link value (buildLinkField) into an href — the single place that
* knows the link types. Returns null when the link is empty or its target is
* missing in this locale (deleted page, page not populated, no file).
*
* Internal links need the related page POPULATED (block depth ≥ 2) — a bare ID
* resolves to null.
*
* resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
* // internal → '/en/about' · external → 'https://…' · file → media URL
*/
export function resolveLinkHref(
link: LinkValue | null | undefined,
{ config, homeSlug, locale }: ResolveLinkHrefOptions,
): null | string {
if (!link) {return null}
if (link.type === 'external') {return link.url?.trim() || null}
if (link.type === 'file') {
const file = link.file
if (file && typeof file === 'object' && 'url' in file) {
const url = (file as { url?: unknown }).url
return typeof url === 'string' && url ? url : null
}
return null
}
// internal (default)
const page = link.page
if (!page || typeof page !== 'object') {return null}
const slug = (page as { slug?: unknown }).slug
if (typeof slug !== 'string' || !slug) {return null}
return (
buildLocalizedPath({
config,
locale,
slugs: { [locale]: slug },
...(homeSlug ? { homeSlug } : {}),
}) ?? null
)
}
+32
View File
@@ -0,0 +1,32 @@
'use client'
import type { ReactNode } from 'react'
// '.js' is required: `next` has no package.json "exports", so NodeNext resolution
// (this plugin's tsconfig) can't find 'next/navigation' without the extension.
// Bundlers in the project resolve the same file either way.
import { usePathname } from 'next/navigation.js'
type LocaleViewProps = {
/** Used when the URL has no locale segment (single-locale site) or an unknown one. */
defaultLocale: string
/**
* One pre-rendered view per locale, e.g. { pl: <RenderBlocks …/>, en: … }.
* Rendered on the SERVER (RSC) and passed in as props — this component only
* picks one, so the content can come from the panel and the route stays static.
*/
views: Record<string, ReactNode>
}
/**
* Shows the view matching the locale in the current URL (`/en/...` → `en`).
*
* Made for `not-found.tsx`, which receives no `params`: reading the locale with
* `headers()` there turns an SSG/ISR route dynamic ("Page changed from static
* to dynamic at runtime"). `usePathname()` is client-side and static-safe, and
* it also runs during SSR, so the HTML already contains the right language.
*/
export function LocaleView({ defaultLocale, views }: LocaleViewProps) {
const pathname = usePathname() ?? ''
const segment = pathname.split('/').filter(Boolean)[0] ?? ''
const locale = segment in views ? segment : defaultLocale
return <>{views[locale] ?? views[defaultLocale] ?? null}</>
}
+39 -7
View File
@@ -30,7 +30,13 @@ export const AI_TRAINING_BOTS = [
type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false
type BuildRobotsArgs = {
export type RobotsOptions = {
/**
* Admin path to disallow. Default '/admin'. With a hidden panel
* (ipalKit adminRoute) pass `false`: robots.txt is public, so listing the
* path would reveal it — the admin is noindex anyway.
*/
adminRoute?: false | string
/** Override the assistant/search bot list. */
aiAssistantAgents?: readonly string[]
/**
@@ -47,14 +53,29 @@ type BuildRobotsArgs = {
aiBots?: AiBotsPolicy
/** Override the training crawler list. */
aiTrainingAgents?: readonly string[]
/** Absolute origin, e.g. 'https://example.com'. */
baseUrl: string
/** Paths to disallow. Defaults to Payload's admin and API. */
/**
* Full disallow list — REPLACES the defaults ([adminRoute, '/api']). Prefer
* `extraDisallow` / `disallowParams`, which add to the defaults instead.
*/
disallow?: string[]
/**
* Query parameters whose URLs crawlers should skip (thin/duplicate pages that
* waste crawl budget), e.g. ['s', 'meter', 'utm_source']. Each becomes
* `/*?name=` and `/*&name=` (the parameter may not be first).
* Don't list `page` — paginated archives are real, canonical-to-self pages.
*/
disallowParams?: string[]
/** Paths added to the default disallow list, e.g. ['/koszyk']. */
extraDisallow?: string[]
/** Whether to advertise the sitemap. Defaults to true. */
sitemap?: boolean
}
type BuildRobotsArgs = {
/** Absolute origin, e.g. 'https://example.com'. */
baseUrl: string
} & RobotsOptions
/**
* Shape for Next's `app/robots.ts`. `rules` may be a single rule or an array
* (Next accepts both) — it becomes an array when AI-bot rules are added.
@@ -86,21 +107,32 @@ export type RobotsRules = {
* PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of
* model training, use `aiBots: 'block-training'`. To block them all, 'disallow'.
*
* Pass custom disallow to block parametrized/thin URLs that waste crawl budget:
* Block parametrized/thin URLs that waste crawl budget — added to the defaults:
* ```ts
* buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] })
* buildRobots({ baseUrl, disallowParams: ['s', 'meter'] })
* // Disallow: /admin, /api, /*?s=, /*&s=, /*?meter=, /*&meter=
* ```
*/
export function buildRobots({
adminRoute = '/admin',
aiAssistantAgents = AI_ASSISTANT_BOTS,
aiBots = 'allow',
aiTrainingAgents = AI_TRAINING_BOTS,
baseUrl,
disallow = ['/admin', '/api'],
disallow: disallowOverride,
disallowParams = [],
extraDisallow = [],
sitemap = true,
}: BuildRobotsArgs): RobotsRules {
const origin = baseUrl.replace(/\/$/, '')
const defaults = [...(adminRoute ? [adminRoute] : []), '/api']
const paramRules = disallowParams
.map((p) => p.trim())
.filter(Boolean)
.flatMap((p) => [`/*?${p}=`, `/*&${p}=`])
const disallow = [...new Set([...(disallowOverride ?? defaults), ...extraDisallow, ...paramRules])]
const baseRule: RobotRule = { allow: '/', disallow, userAgent: '*' }
const aiRules: RobotRule[] = []
+36 -11
View File
@@ -1,6 +1,6 @@
import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { PageMetadata } from './buildMetadata.js'
import type { SeoMeta } from './types.js'
@@ -22,6 +22,19 @@ type CreatePageMetadataArgs = {
* omit it and only pages are handled.
*/
content?: ContentOption
/**
* Request-cached loaders (createContentHelpers passes its own), so metadata
* reuses the SAME settings read and route resolution as the layout and the
* page component instead of querying again. Omit → plain queries.
*/
loaders?: {
getSettings?: (locale: string) => Promise<null | Record<string, unknown>>
resolveRoute?: (
locale: string,
segments: string[] | undefined,
page: number,
) => Promise<null | ResolvedRoute>
}
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
/** Field on SiteSettings holding the site name. Defaults to 'siteName'. */
@@ -89,6 +102,7 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
collection = 'pages',
config,
content,
loaders,
settingsSlug = 'site-settings',
siteNameField = 'siteName',
} = args
@@ -99,7 +113,15 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
page,
payload,
}: PageMetadataContext): Promise<PageMetadata> {
const site = await readSiteMetaConfig({ locale, payload, settingsSlug, siteNameField })
const settings = loaders?.getSettings ? await loaders.getSettings(locale) : undefined
const site = await readSiteMetaConfig({
locale,
pagesSlug: collection,
payload,
settings,
settingsSlug,
siteNameField,
})
const base = {
baseUrl,
@@ -111,15 +133,18 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
siteName: site.siteName,
}
const route = await resolveRoute({
content,
locale,
page,
pagesSlug: collection,
payload,
segments: slug,
settingsSlug,
})
const route = loaders?.resolveRoute
? await loaders.resolveRoute(locale, slug, page ?? 1)
: await resolveRoute({
content,
locale,
page,
pagesSlug: collection,
payload,
segments: slug,
settings,
settingsSlug,
})
// Unknown route (the page component will 404) — still return something
// coherent rather than throwing during metadata generation.
+1 -1
View File
@@ -12,7 +12,7 @@ export type { PageMetadata } from './buildMetadata.js'
export { buildNoindexField } from './buildNoindexField.js'
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
export type { RobotsRules } from './buildRobots.js'
export type { RobotsOptions, RobotsRules } from './buildRobots.js'
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
export { buildSitemapEntries } from './buildSitemapEntries.js'
export type { SitemapEntry } from './buildSitemapEntries.js'
+13 -6
View File
@@ -35,22 +35,29 @@ export type SiteMetaConfig = {
*/
export async function readSiteMetaConfig({
locale,
pagesSlug = 'pages',
payload,
settings: preloaded,
settingsSlug = 'site-settings',
siteNameField = 'siteName',
}: {
locale: string
/** Collection holding the homepage. Default 'pages'. */
pagesSlug?: string
payload: BasePayload
/** SiteSettings already read for this locale (depth ≥ 1) — skips the read. */
settings?: null | Record<string, unknown>
settingsSlug?: string
siteNameField?: string
}): Promise<SiteMetaConfig> {
// depth 1 populates the homepage relationship, so its slug is available
// without a second query.
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 1,
locale: locale as never,
})) as SettingsShape
const settings = (preloaded ??
(await payload.findGlobal({
slug: settingsSlug as never,
depth: 1,
locale: locale as never,
}))) as SettingsShape
const homepage =
settings.homepage && typeof settings.homepage === 'object' ? settings.homepage : null
@@ -64,7 +71,7 @@ export async function readSiteMetaConfig({
try {
const homeDoc = (await payload.findByID({
id: homepage.id,
collection: 'pages' as never,
collection: pagesSlug as never,
depth: 0,
locale: 'all' as never,
})) as { slug?: unknown }
+48 -3
View File
@@ -1,6 +1,27 @@
import type { Plugin } from 'payload'
import { s3Storage } from '@payloadcms/storage-s3'
type GenerateFileURL = (args: { filename: string; prefix?: string }) => string
/**
* Minimal shape of `s3Storage` from @payloadcms/storage-s3 — the plugin never
* imports that package (it's optional: projects on local disk don't install it).
* The project injects the real function; TypeScript checks it fits this shape.
*/
export type S3StorageFactory = (options: {
bucket: string
collections: Record<string, { generateFileURL: GenerateFileURL } | true>
config: {
credentials: { accessKeyId: string; secretAccessKey: string }
endpoint: string
forcePathStyle: boolean
region: string
}
}) => Plugin
export type BuildR2StorageDeps = {
/** `import { s3Storage } from '@payloadcms/storage-s3'` — required when R2 env is set. */
s3Storage?: S3StorageFactory
}
/**
* Cloudflare R2 media storage — configured from environment variables (agency
@@ -16,9 +37,22 @@ import { s3Storage } from '@payloadcms/storage-s3'
* storage (useful in dev without R2). This mirrors how mailAdapter degrades
* gracefully when a transport isn't configured.
*
* The S3 adapter is INJECTED by the project (same pattern as 2FA / NextResponse):
*
* import { s3Storage } from '@payloadcms/storage-s3'
* plugins: [buildR2Storage(['media'], { s3Storage })]
*
* A static import here would make @payloadcms/storage-s3 mandatory for every
* project — including ones on local disk — because this module is exported
* from the package's main entry.
*
* @param collections - slugs of upload collections to offload to R2 (e.g. ['media'])
* @param deps - `{ s3Storage }` from @payloadcms/storage-s3 (needed only when R2 env is set)
*/
export const buildR2Storage = (collections: string[] = ['media']): Plugin => {
export const buildR2Storage = (
collections: string[] = ['media'],
deps: BuildR2StorageDeps = {},
): Plugin => {
const bucket = process.env.R2_BUCKET
const endpoint = process.env.R2_ENDPOINT
const accessKeyId = process.env.R2_ACCESS_KEY_ID
@@ -54,7 +88,18 @@ export const buildR2Storage = (collections: string[] = ['media']): Plugin => {
[publicUrl, prefix, filename].filter(Boolean).join('/')
: undefined
const collectionsConfig: Record<string, { generateFileURL: typeof generateFileURL } | true> = {}
// R2 env is complete → the adapter is required. Fail loudly at boot rather
// than silently storing media on the container disk (lost on redeploy).
const { s3Storage } = deps
if (!s3Storage) {
throw new Error(
'[ipal] R2 storage: R2_* env is set but the S3 adapter was not injected. ' +
"Install @payloadcms/storage-s3 and pass it: buildR2Storage(['media'], { s3Storage }) " +
"with `import { s3Storage } from '@payloadcms/storage-s3'`. See docs/storage.md.",
)
}
const collectionsConfig: Record<string, { generateFileURL: GenerateFileURL } | true> = {}
for (const slug of collections) {
collectionsConfig[slug] = generateFileURL ? { generateFileURL } : true
}
+1
View File
@@ -1 +1,2 @@
export { buildR2Storage } from './buildR2Storage.js'
export type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js'