import type { BasePayload } from 'payload' import type { I18nConfig } from '../i18n/index.js' import type { ConsentTexts } from './texts.js' import { resolveLocalized } from '../i18n/resolveLocalized.js' import { getSystemPagePath } from '../pages/index.js' import { getGlobal } from '../payload/index.js' import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js' /** English fallback used when the global has no value for a field. */ const FALLBACK: ConsentTexts = { buttons: { acceptAll: 'Accept all', back: 'Back', reject: 'Reject', save: 'Save preferences', settings: 'Settings', }, categories: { analytics: { description: 'Help us understand usage.', title: 'Analytics' }, functional: { description: 'Remember preferences.', title: 'Functional' }, marketing: { description: 'Used to show relevant ads.', title: 'Marketing' }, necessary: { description: 'Required for the site to work, including your language and theme preferences. Always on.', title: 'Necessary', }, }, message: 'We use cookies to run the site, analyze traffic, and improve your experience. You can accept all, reject non-essential, or choose which to allow.', privacyLink: null, settingsTitle: 'Cookie settings', } /** Last-resort link text — only when neither the panel nor the page has one. */ const FALLBACK_PRIVACY_LABEL = 'Privacy policy' type CookieSettingsData = { buttons?: null | Partial categories?: Array<{ description?: null | string; key: string; title?: null | string }> | null cookies?: Array<{ category?: null | string; duration?: null | string; name?: null | string; provider?: null | string; purpose?: null | string }> | null message?: null | string policyVersion?: null | number privacyLinkLabel?: null | string settingsTitle?: null | string } type PrivacyPage = { slug?: null | Record; title?: unknown } | null type GetConsentTextsArgs = { config: I18nConfig locale?: string payload: BasePayload /** * Privacy-policy link. Omit it — the page is read automatically from * SiteSettings → System Pages → Privacy Policy, and the link text from * CookieSettings → privacyLinkLabel (per locale, editable in the panel). * * - `false` → no link. * - `{ page }` → use this page (SiteSettings.privacyPolicy read with locale:'all'). * - `label` → DEPRECATED (hardcoded text); used only when the panel field is empty. */ privacyPolicy?: | { /** @deprecated Set CookieSettings → privacyLinkLabel in the panel instead. */ label?: string page?: PrivacyPage } | false /** SiteSettings global slug for the automatic privacy page lookup. Default 'site-settings'. */ settingsSlug?: string } /** Reads SiteSettings.privacyPolicy with all locales (slug + title as maps). */ async function readPrivacyPage(payload: BasePayload, settingsSlug: string): Promise { try { const settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never, })) as { privacyPolicy?: unknown } const page = settings.privacyPolicy return page && typeof page === 'object' ? (page as PrivacyPage) : null } catch (error) { // No pages option / no privacyPolicy field / DB unreachable at build → no link. console.warn('[ipal] getConsentTexts: privacy page lookup failed, banner without link:', error) return null } } /** * Resolves consent banner texts from the CookieSettings global, falling back to * English defaults per field. The privacy-policy link target comes from the * pages module (system page role, read automatically); its text from * CookieSettings.privacyLinkLabel — both editable in the panel, per locale. */ export async function getConsentTexts({ config, locale, payload, privacyPolicy, settingsSlug = 'site-settings', }: GetConsentTextsArgs): Promise { const g = await getGlobal(payload, 'cookie-settings', { locale }) const categories = {} as ConsentTexts['categories'] for (const cat of CONSENT_CATEGORIES) { const entry = g.categories?.find((c) => c.key === cat) categories[cat] = { description: entry?.description || FALLBACK.categories[cat].description, title: entry?.title || FALLBACK.categories[cat].title, } } let privacyLink: ConsentTexts['privacyLink'] = null if (privacyPolicy !== false && locale) { const page = privacyPolicy?.page !== undefined ? privacyPolicy.page : await readPrivacyPage(payload, settingsSlug) const href = page ? getSystemPagePath({ config, locale, page }) : undefined if (page && href) { // Panel first, then the deprecated code label, then the page's own title. const label = g.privacyLinkLabel?.trim() || privacyPolicy?.label?.trim() || resolveLocalized(page.title, locale).trim() || FALLBACK_PRIVACY_LABEL privacyLink = { href, label } } } return { buttons: { acceptAll: g.buttons?.acceptAll || FALLBACK.buttons.acceptAll, back: g.buttons?.back || FALLBACK.buttons.back, reject: g.buttons?.reject || FALLBACK.buttons.reject, save: g.buttons?.save || FALLBACK.buttons.save, settings: g.buttons?.settings || FALLBACK.buttons.settings, }, categories, message: g.message || FALLBACK.message, privacyLink, settingsTitle: g.settingsTitle || FALLBACK.settingsTitle, ...(typeof g.policyVersion === 'number' && g.policyVersion >= 1 ? { version: Math.trunc(g.policyVersion) } : {}), } } export type CookieTableRow = { category: ConsentCategory duration?: string name: string provider?: string purpose?: string } /** * Rows of Cookie Settings → Cookies in one language, for the cookie policy page * (). Server-side; never throws (empty list). */ export async function getCookieTable({ locale, payload }: { locale?: string; payload: BasePayload }): Promise { try { const g = await getGlobal(payload, 'cookie-settings', { locale }) return (g.cookies ?? []) .filter((c) => typeof c.name === 'string' && c.name.trim()) .map((c) => ({ name: c.name!.trim(), category: (CONSENT_CATEGORIES as readonly string[]).includes(c.category ?? '') ? (c.category as ConsentCategory) : 'necessary', ...(c.provider?.trim() ? { provider: c.provider.trim() } : {}), ...(c.purpose?.trim() ? { purpose: c.purpose.trim() } : {}), ...(c.duration?.trim() ? { duration: c.duration.trim() } : {}), })) } catch { return [] } }