Lint: fix all ESLint errors (391 -> 0), lint and typecheck tests

Mostly perfectionist import/key sorting and curly braces from --fix, plus:
- spread instead of .apply() in the Meta Pixel stub
- non-capturing group in the locale-code pattern
- React 19 use(Context) / <Context value> in TurnstileProvider
- email regex rewritten without super-linear backtracking (covered by a test)
- console.warn/error allowed (deliberate server diagnostics)
- test/tsconfig.json so the project service and tsc see test files

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-15 23:56:18 +02:00
co-authored by Claude Opus 5.5
parent ce0a390351
commit 4544cac69c
48 changed files with 642 additions and 589 deletions
+9
View File
@@ -26,9 +26,18 @@ export default [
...payloadEsLintConfig, ...payloadEsLintConfig,
{ {
rules: { rules: {
// console.warn/error are the plugin's deliberate server-side diagnostics.
'no-console': ['warn', { allow: ['warn', 'error'] }],
'no-restricted-exports': 'off', 'no-restricted-exports': 'off',
}, },
}, },
{
// Mocks stand in for async APIs without awaiting anything themselves.
files: ['test/**/*.ts'],
rules: {
'@typescript-eslint/require-await': 'off',
},
},
{ {
languageOptions: { languageOptions: {
parserOptions: { parserOptions: {
+2 -2
View File
@@ -1,3 +1,4 @@
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
/** /**
* Entry point: @intecion/ipal-kit/admin * Entry point: @intecion/ipal-kit/admin
* *
@@ -5,6 +6,5 @@
* importMap can resolve them by a stable path when ipalKit injects * importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon. * admin.components.graphics.Logo/Icon.
*/ */
export { AdminLogo, AdminIcon, IntecionCredit } from '../modules/branding/index.js' export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js' export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
+41 -41
View File
@@ -1,4 +1,13 @@
'use client' '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 type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js'
export type { AnalyticsProps } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js'
/** /**
* Entry point: ipal-kit/client * Entry point: ipal-kit/client
* *
@@ -7,61 +16,52 @@
* client-only code. * client-only code.
*/ */
export { export {
useConsent,
ConsentProvider, ConsentProvider,
useConsentContext, ConsentScript,
CookieBanner, CookieBanner,
CookieButton, CookieButton,
ConsentScript, useConsent,
useConsentContext,
} from '../modules/consent/client.js' } from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js' export type { CookieBannerClassNames } from '../modules/consent/client.js'
export { Turnstile } from '../modules/turnstile/client.js' export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js' export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
export { AccessibilityProvider, useAccessibility, AccessibilityWidget } from '../modules/accessibility/client.js' export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export type { A11yState, A11yTexts, A11yClassNames } from '../modules/accessibility/client.js' export { useContactForm } from '../modules/forms/useContactForm.js'
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'
export { useForm } from '../modules/forms/useForm.js'
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'
export {
buildValidator,
checked,
custom,
email,
isEmail,
maxLength,
minLength,
pattern,
required,
} from '../modules/forms/validators.js'
export type { Rule } from '../modules/forms/validators.js'
// Pure i18n path helpers — no server/RSC deps, safe to import in client // Pure i18n path helpers — no server/RSC deps, safe to import in client
// components (e.g. a LanguageSwitcher that computes locale URLs on the client). // components (e.g. a LanguageSwitcher that computes locale URLs on the client).
export { export {
switchLocalePath,
buildLocalizedPath, buildLocalizedPath,
getLocalizedSlugs,
getLocaleCodes, getLocaleCodes,
getLocalizedSlugs,
switchLocalePath,
} from '../modules/i18n/index.js' } from '../modules/i18n/index.js'
export type { LocalizedSlugs, I18nConfig } from '../modules/i18n/index.js' export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'
export type { TurnstileProps } from '../modules/turnstile/client.js'
export { LocaleView } from '../modules/pages/LocaleView.js'
export { Analytics } from '../modules/analytics/client.js'
export type { AnalyticsProps } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
export { loadMetaPixel, loadClarity, loadLinkedIn, loadTikTok } from '../modules/analytics/client.js'
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
export { export {
AlternateLinksProvider, AlternateLinksProvider,
useAlternateLinks,
useSetAlternateLinks,
AlternateLinksUpdater, AlternateLinksUpdater,
LanguageSwitcher, LanguageSwitcher,
useAlternateLinks,
useSetAlternateLinks,
} from '../modules/i18n/index.js' } from '../modules/i18n/index.js'
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js' export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
export { useForm } from '../modules/forms/useForm.js' export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js' export { LocaleView } from '../modules/pages/LocaleView.js'
export { useContactForm } from '../modules/forms/useContactForm.js' export { Turnstile } from '../modules/turnstile/client.js'
export type { ContactFormValues, ContactFormErrors, SubmitAction } from '../modules/forms/useContactForm.js' export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
export { export type { TurnstileProps } from '../modules/turnstile/client.js'
buildValidator,
isEmail,
required,
email,
minLength,
maxLength,
checked,
pattern,
custom,
} from '../modules/forms/validators.js'
export type { Rule } from '../modules/forms/validators.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
+5 -5
View File
@@ -1,3 +1,7 @@
export { sendEmail } from '../modules/email/index.js'
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
/** /**
* Entry point: ipal-kit/server * Entry point: ipal-kit/server
* *
@@ -10,9 +14,5 @@
* Import these only from Server Actions, route handlers, or server components — * Import these only from Server Actions, route handlers, or server components —
* never from the Payload config or client code. * never from the Payload config or client code.
*/ */
export { verifyTurnstile, checkTurnstile } from '../modules/turnstile/index.js' export { checkTurnstile, verifyTurnstile } from '../modules/turnstile/index.js'
export type { TurnstileCheck, TurnstileOutcome } from '../modules/turnstile/index.js' export type { TurnstileCheck, TurnstileOutcome } from '../modules/turnstile/index.js'
export { sendEmail } from '../modules/email/index.js'
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
+3 -2
View File
@@ -1,4 +1,5 @@
import type { GlobalConfig } from 'payload' import type { GlobalConfig } from 'payload'
import { notificationsFields } from './fields.js' import { notificationsFields } from './fields.js'
/** /**
@@ -9,11 +10,11 @@ import { notificationsFields } from './fields.js'
export function buildNotifications(): GlobalConfig { export function buildNotifications(): GlobalConfig {
return { return {
slug: 'notifications', slug: 'notifications',
label: 'Notifications',
admin: { group: 'Settings' },
access: { access: {
read: () => true, // texts are public-facing (shown to end users) read: () => true, // texts are public-facing (shown to end users)
}, },
admin: { group: 'Settings' },
fields: notificationsFields, fields: notificationsFields,
label: 'Notifications',
} }
} }
@@ -1,9 +1,10 @@
'use client' 'use client'
import { useField, FieldLabel, FieldDescription } from '@payloadcms/ui'
import { useState } from 'react'
import type { TextFieldClientComponent } from 'payload' import type { TextFieldClientComponent } from 'payload'
import { FieldDescription, FieldLabel, useField } from '@payloadcms/ui'
import { useState } from 'react'
/** /**
* Masked text input for sensitive values (SMTP password, R2 secret key, * Masked text input for sensitive values (SMTP password, R2 secret key,
* Turnstile secret key, etc.). * Turnstile secret key, etc.).
@@ -22,7 +23,7 @@ import type { TextFieldClientComponent } from 'payload'
* Assigned via a field's admin.components.Field. Works on any `text` field. * Assigned via a field's admin.components.Field. Works on any `text` field.
*/ */
export const MaskedField: TextFieldClientComponent = ({ field, path }) => { export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
const { value, setValue } = useField<string>({ path }) const { setValue, value } = useField<string>({ path })
const [revealed, setRevealed] = useState(false) const [revealed, setRevealed] = useState(false)
const label = const label =
@@ -31,38 +32,38 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
return ( return (
<div className="field-type text masked-field"> <div className="field-type text masked-field">
<FieldLabel label={label} htmlFor={`field-${path}`} /> <FieldLabel htmlFor={`field-${path}`} label={label} />
<div className="field-type__wrap" style={{ display: 'flex', gap: '.5rem', alignItems: 'center' }}> <div className="field-type__wrap" style={{ alignItems: 'center', display: 'flex', gap: '.5rem' }}>
<input <input
id={`field-${path}`}
type={revealed ? 'text' : 'password'}
autoComplete="off" autoComplete="off"
className="field-type__input" className="field-type__input"
value={value ?? ''} id={`field-${path}`}
onChange={(e) => setValue(e.target.value)} onChange={(e) => setValue(e.target.value)}
style={{ flex: 1 }} style={{ flex: 1 }}
type={revealed ? 'text' : 'password'}
value={value ?? ''}
/> />
<button <button
type="button"
onClick={() => setRevealed((r) => !r)} onClick={() => setRevealed((r) => !r)}
style={{ style={{
background: 'none', background: 'none',
border: 'none', border: 'none',
padding: '.25rem .5rem',
cursor: 'pointer', cursor: 'pointer',
font: 'inherit', font: 'inherit',
textDecoration: 'underline',
opacity: 0.75, opacity: 0.75,
padding: '.25rem .5rem',
textDecoration: 'underline',
whiteSpace: 'nowrap', whiteSpace: 'nowrap',
}} }}
type="button"
> >
{revealed ? 'Hide' : 'Reveal'} {revealed ? 'Hide' : 'Reveal'}
</button> </button>
</div> </div>
{description && typeof description === 'string' ? ( {description && typeof description === 'string' ? (
<FieldDescription path={path} description={description} /> <FieldDescription description={description} path={path} />
) : null} ) : null}
</div> </div>
) )
@@ -14,7 +14,7 @@ import { useState } from 'react'
export const TestEmailButton = () => { export const TestEmailButton = () => {
const [to, setTo] = useState('') const [to, setTo] = useState('')
const [status, setStatus] = useState< const [status, setStatus] = useState<
{ kind: 'idle' } | { kind: 'sending' } | { kind: 'ok'; msg: string } | { kind: 'error'; msg: string } { kind: 'error'; msg: string } | { kind: 'idle' } | { kind: 'ok'; msg: string } | { kind: 'sending' }
>({ kind: 'idle' }) >({ kind: 'idle' })
const send = async () => { const send = async () => {
@@ -25,10 +25,10 @@ export const TestEmailButton = () => {
setStatus({ kind: 'sending' }) setStatus({ kind: 'sending' })
try { try {
const res = await fetch('/api/ipal/test-email', { const res = await fetch('/api/ipal/test-email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ to: to.trim() }), body: JSON.stringify({ to: to.trim() }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
}) })
const data = await res.json() const data = await res.json()
if (data.ok) { if (data.ok) {
@@ -44,23 +44,23 @@ export const TestEmailButton = () => {
return ( return (
<div className="field-type" style={{ marginTop: '1rem' }}> <div className="field-type" style={{ marginTop: '1rem' }}>
<label className="field-label">Send a test email</label> <label className="field-label">Send a test email</label>
<p style={{ opacity: 0.7, fontSize: '.85rem', marginTop: 0 }}> <p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>
Sends through the transport selected above. Save your changes first. Sends through the transport selected above. Save your changes first.
</p> </p>
<div style={{ display: 'flex', gap: '.5rem', alignItems: 'center', flexWrap: 'wrap' }}> <div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem' }}>
<input <input
type="email"
placeholder="[email protected]"
value={to}
onChange={(e) => setTo(e.target.value)} onChange={(e) => setTo(e.target.value)}
placeholder="[email protected]"
style={{ flex: 1, minWidth: '220px' }} style={{ flex: 1, minWidth: '220px' }}
type="email"
value={to}
/> />
<button <button
type="button"
onClick={send}
disabled={status.kind === 'sending'}
className="btn btn--style-secondary" className="btn btn--style-secondary"
disabled={status.kind === 'sending'}
onClick={send}
style={{ whiteSpace: 'nowrap' }} style={{ whiteSpace: 'nowrap' }}
type="button"
> >
{status.kind === 'sending' ? 'Sending…' : 'Send test'} {status.kind === 'sending' ? 'Sending…' : 'Send test'}
</button> </button>
+145 -145
View File
@@ -1,20 +1,3 @@
export { ipalKit } from './plugin.js'
export type { IpalOptions } from './types.js'
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'
export {
buildLocalizedPath,
getDefaultLocale,
getLocaleCodes,
getLocaleDefinition,
getLocalizedSlugs,
isValidLocale,
LOCALE_COOKIE_NAME,
matchAcceptLanguage,
negotiateLocale,
switchLocalePath,
} from './modules/i18n/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'
export type { AccessOption, Role } from './modules/access/index.js' export type { AccessOption, Role } from './modules/access/index.js'
export { export {
adminOnly, adminOnly,
@@ -30,64 +13,102 @@ export {
requireRoleField, requireRoleField,
ROLE_HIERARCHY, ROLE_HIERARCHY,
} from './modules/access/index.js' } from './modules/access/index.js'
export type { GlobalQueryOptions } from './modules/payload/index.js' export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'
export type { A11yState } from './modules/accessibility/index.js'
export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
export { export {
getGlobal, ACCEPT_ALL_CONSENT,
getSiteSettings, CONSENT_CATEGORIES,
getSiteIntegrations, CONSENT_COOKIE,
SITE_SETTINGS_SLUG, CONSENT_MAX_AGE,
SITE_INTEGRATIONS_SLUG, CONSENT_VERSION,
} from './modules/payload/index.js' DEFAULT_CONSENT,
// Imported from the file, not the turnstile barrel — that one re-exports verify, getConsentTexts,
// which imports 'server-only'. parseConsent,
export { getTurnstileConfig } from './modules/turnstile/config.js' REJECT_ALL_CONSENT,
export type { TurnstileConfig } from './modules/turnstile/config.js' serializeConsent,
export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js' setDefaultConsent,
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' updateConsent,
export type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js' } from './modules/consent/index.js'
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
export { export {
composeTitle,
buildHreflangAlternates,
buildMetadata,
readSiteMetaConfig,
slugsAcrossLocales,
} from './modules/seo/index.js'
export type { SiteMetaConfig } from './modules/seo/index.js'
export type { ContentOption, ContentCollectionOption, ResolvedRoute } from './modules/content/index.js'
export { createContentHelpers } from './modules/frontend/index.js'
export {
resolveRoute,
resolveRedirect,
resolveNotFoundPage,
blocksToMarkdown,
createMarkdownRenderer,
markdownResponse,
prefersMarkdown,
markdownHref,
MARKDOWN_PREFIX,
searchContent,
createSearchRoute,
archiveFieldName, archiveFieldName,
getArchiveEntries, blocksToMarkdown,
buildArchivePath, buildArchivePath,
buildEntryPath, buildEntryPath,
createMarkdownRenderer,
createSearchRoute,
getArchiveEntries,
MARKDOWN_PREFIX,
markdownHref,
markdownResponse,
parsePageParam, parsePageParam,
prefersMarkdown,
resolveNotFoundPage,
resolveRedirect,
resolveRoute,
searchContent,
} from './modules/content/index.js' } from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js' export type { ArchiveEntries } from './modules/content/index.js'
export type { SearchResult } from './modules/content/index.js' export type { SearchResult } from './modules/content/index.js'
// Lexical → Markdown (pure, no React) — for AI-readable output. export { graphAdapter } from './modules/email/graphAdapter.js'
export { lexicalToMarkdown } from './modules/richtext/index.js' export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
export type { AutoFillMapping, SitemapEntry, RobotsRules, RobotsOptions } from './modules/seo/index.js' export { mailAdapter } from './modules/email/mailAdapter.js'
export type { MailAdapterArgs } from './modules/email/mailAdapter.js'
// Imported straight from the file, NOT from ./modules/email/index.js — that
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
// Payload loads the config (or runs generate:importmap) as a plain Node script.
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'
export type {
FormsCollectionOverrides,
FormsFieldsOverride,
FormsOption,
} from './modules/forms/types.js'
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'
// Validation rules are pure — exported server-side too, for re-validating a
// submission inside a server action. (useForm/useContactForm are client-only →
// '@intecion/ipal-kit/client'.)
export { export {
buildAutoFillMetaHook, buildValidator,
injectAutoFillMeta, checked,
createMetadataGenerator, custom,
createPageMetadata, email,
buildSitemapEntries, isEmail,
buildRobots, maxLength,
AI_ASSISTANT_BOTS, minLength,
AI_TRAINING_BOTS, pattern,
} from './modules/seo/index.js' required,
} from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js'
export { createContentHelpers } from './modules/frontend/index.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js'
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'
export {
buildLocalizedPath,
getDefaultLocale,
getLocaleCodes,
getLocaleDefinition,
getLocalizedSlugs,
isValidLocale,
LOCALE_COOKIE_NAME,
matchAcceptLanguage,
negotiateLocale,
switchLocalePath,
} from './modules/i18n/index.js'
export type { LocaleMiddlewareResult } from './modules/i18n/index.js' export type { LocaleMiddlewareResult } from './modules/i18n/index.js'
export { export {
createLocaleMiddleware, createLocaleMiddleware,
@@ -95,99 +116,78 @@ export {
} from './modules/i18n/index.js' } from './modules/i18n/index.js'
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js' export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js' export { resolveLocalized } from './modules/i18n/index.js'
export { export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
CONSENT_CATEGORIES, export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
DEFAULT_CONSENT, export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'
ACCEPT_ALL_CONSENT,
REJECT_ALL_CONSENT,
CONSENT_COOKIE,
CONSENT_VERSION,
CONSENT_MAX_AGE,
serializeConsent,
parseConsent,
setDefaultConsent,
updateConsent,
getConsentTexts,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'
// Imported straight from the file, NOT from ./modules/email/index.js — that
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
// Payload loads the config (or runs generate:importmap) as a plain Node script.
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
export { mailAdapter } from './modules/email/mailAdapter.js'
export type { MailAdapterArgs } from './modules/email/mailAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
export type { export type {
FormsOption, BuildLinkFieldOptions,
FormsCollectionOverrides, BuildLinksFieldOptions,
FormsFieldsOverride, LinkAppearance,
} from './modules/forms/types.js' LinkValue,
// Validation rules are pure — exported server-side too, for re-validating a ResolveLinkHrefOptions,
// submission inside a server action. (useForm/useContactForm are client-only → } from './modules/links/index.js'
// '@intecion/ipal-kit/client'.)
export {
buildValidator,
isEmail,
required,
email,
minLength,
maxLength,
checked,
pattern,
custom,
} from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js'
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it). // Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js' export { createMcpRoute } from './modules/mcp/index.js'
// Boot-time environment validation (fail fast on misconfigured deploys). export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
export { assertEnv, ipalEnvRules } from './modules/env/index.js' export type { OptimizeUploadOptions } from './modules/media/index.js'
export type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from './modules/env/index.js' export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js' export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js' export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
export { buildSlugField, toSlug } from './modules/slug/index.js' export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'
export { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js' export type { GlobalQueryOptions } from './modules/payload/index.js'
export {
getGlobal,
getSiteIntegrations,
getSiteSettings,
SITE_INTEGRATIONS_SLUG,
SITE_SETTINGS_SLUG,
} from './modules/payload/index.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/index.js'
export { buildSecurityHeaders } from './modules/security/index.js' export { buildSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js' export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js' export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { PageMetadata, SeoMeta, SeoOption } 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' export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js'
export { buildNoindexField } from './modules/seo/index.js' export { buildNoindexField } from './modules/seo/index.js'
export { recordIntegrationStatus, buildIntegrationStatusField, buildIntegrationStatusBanner } from './modules/integrations/index.js'
export type { IntegrationStatus, IntegrationState } from './modules/integrations/index.js'
export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'
export type {
LinkAppearance,
LinkValue,
BuildLinkFieldOptions,
BuildLinksFieldOptions,
ResolveLinkHrefOptions,
} from './modules/links/index.js'
export { buildSpeakableJsonLd } from './modules/seo/index.js' export { buildSpeakableJsonLd } from './modules/seo/index.js'
export { buildSummaryField } from './modules/seo/index.js' export { buildSummaryField } from './modules/seo/index.js'
export { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } from './modules/seo/index.js' export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage. // Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js' export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd } from './modules/seo/index.js' export { buildArticleJsonLd } from './modules/seo/index.js'
export { buildLlmsTxt } from './modules/seo/index.js' export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapXml, buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './modules/seo/index.js' export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js' export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { buildR2Storage } from './modules/storage/index.js' export { buildR2Storage } from './modules/storage/index.js'
export { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js' // Imported from the file, not the turnstile barrel — that one re-exports verify,
export type { OptimizeUploadOptions } from './modules/media/index.js' // which imports 'server-only'.
export { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/index.js' export { getTurnstileConfig } from './modules/turnstile/config.js'
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js' export type { TurnstileConfig } from './modules/turnstile/config.js'
export type { A11yState } from './modules/accessibility/index.js' export { ipalKit } from './plugin.js'
export type { SecurityHeader, BuildSecurityHeadersArgs } from './modules/security/index.js' export type { IpalOptions } from './types.js'
export type { NotificationTexts, FormNotificationTexts } from './modules/notifications/index.js'
+2 -2
View File
@@ -10,6 +10,6 @@ import type { RowLabelProps } from './RowLabelComponent.js'
* After adding it to a project: `pnpm payload generate:importmap`. * After adding it to a project: `pnpm payload generate:importmap`.
*/ */
export function rowLabel(fields: string | string[], fallback = 'Item') { export function rowLabel(fields: string | string[], fallback = 'Item') {
const clientProps: RowLabelProps = { fields: Array.isArray(fields) ? fields : [fields], fallback } const clientProps: RowLabelProps = { fallback, fields: Array.isArray(fields) ? fields : [fields] }
return { RowLabel: { path: '@intecion/ipal-kit/admin#RowLabel', clientProps } } return { RowLabel: { clientProps, path: '@intecion/ipal-kit/admin#RowLabel' } }
} }
+1 -1
View File
@@ -22,7 +22,7 @@ export function loadMetaPixel(id: string): void {
if (w.fbq) {return} if (w.fbq) {return}
const n: any = (w.fbq = function (...args: unknown[]) { const n: any = (w.fbq = function (...args: unknown[]) {
if (n.callMethod) { if (n.callMethod) {
n.callMethod.apply(n, args) n.callMethod(...args)
} else { } else {
n.queue.push(args) n.queue.push(args)
} }
+1 -1
View File
@@ -17,7 +17,7 @@
* gates the tag in GTM (ad_storage) — this only emits the event. * gates the tag in GTM (ad_storage) — this only emits the event.
*/ */
export function pushDataLayer(event: string, params: Record<string, unknown> = {}): void { export function pushDataLayer(event: string, params: Record<string, unknown> = {}): void {
if (typeof window === 'undefined') return if (typeof window === 'undefined') {return}
const w = window as unknown as { dataLayer?: unknown[] } const w = window as unknown as { dataLayer?: unknown[] }
w.dataLayer = w.dataLayer || [] w.dataLayer = w.dataLayer || []
w.dataLayer.push({ event, ...params }) w.dataLayer.push({ event, ...params })
+4 -4
View File
@@ -9,17 +9,17 @@ export type ConsentCategory = (typeof CONSENT_CATEGORIES)[number]
export type ConsentState = Record<ConsentCategory, boolean> export type ConsentState = Record<ConsentCategory, boolean>
export const DEFAULT_CONSENT: ConsentState = { export const DEFAULT_CONSENT: ConsentState = {
necessary: true,
functional: false,
analytics: false, analytics: false,
functional: false,
marketing: false, marketing: false,
necessary: true,
} }
export const ACCEPT_ALL_CONSENT: ConsentState = { export const ACCEPT_ALL_CONSENT: ConsentState = {
necessary: true,
functional: true,
analytics: true, analytics: true,
functional: true,
marketing: true, marketing: true,
necessary: true,
} }
export const REJECT_ALL_CONSENT: ConsentState = { ...DEFAULT_CONSENT } export const REJECT_ALL_CONSENT: ConsentState = { ...DEFAULT_CONSENT }
+23 -23
View File
@@ -20,7 +20,7 @@ import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js'
* }) * })
*/ */
type Block = Record<string, unknown> & { blockType?: string } type Block = { blockType?: string } & Record<string, unknown>
type BlockToMarkdown = (block: Block) => string type BlockToMarkdown = (block: Block) => string
type BlocksToMarkdownArgs = { type BlocksToMarkdownArgs = {
@@ -32,30 +32,30 @@ const HEADING_KEYS = new Set(['heading', 'title'])
const SUBHEADING_KEYS = new Set(['subheading', 'subtitle']) const SUBHEADING_KEYS = new Set(['subheading', 'subtitle'])
const QUESTION_KEYS = new Set(['question']) const QUESTION_KEYS = new Set(['question'])
const TEXT_KEYS = new Set([ const TEXT_KEYS = new Set([
'answer',
'body', 'body',
'text', 'caption',
'content',
'description', 'description',
'excerpt', 'excerpt',
'summary',
'answer',
'caption',
'label', 'label',
'content', 'summary',
'text',
]) ])
const ARRAY_KEYS = new Set([ const ARRAY_KEYS = new Set([
'items', 'benefits',
'features',
'faq',
'faqs',
'cards', 'cards',
'columns', 'columns',
'rows', 'faq',
'faqs',
'features',
'items',
'list',
'points',
'questions', 'questions',
'rows',
'services', 'services',
'steps', 'steps',
'points',
'benefits',
'list',
]) ])
/** A populated richText value is an object with a `root`. */ /** A populated richText value is an object with a `root`. */
@@ -65,7 +65,7 @@ function isRichText(v: unknown): boolean {
/** A populated upload (image) is an object with a `url`. */ /** A populated upload (image) is an object with a `url`. */
function imageMarkdown(v: unknown): string { function imageMarkdown(v: unknown): string {
if (!v || typeof v !== 'object') return '' if (!v || typeof v !== 'object') {return ''}
const o = v as Record<string, unknown> const o = v as Record<string, unknown>
const url = typeof o.url === 'string' ? o.url : '' const url = typeof o.url === 'string' ? o.url : ''
const alt = typeof o.alt === 'string' ? o.alt : '' const alt = typeof o.alt === 'string' ? o.alt : ''
@@ -77,7 +77,7 @@ function extractBlock(block: Block, depth: number): string {
const lines: string[] = [] const lines: string[] = []
for (const [key, value] of Object.entries(block)) { for (const [key, value] of Object.entries(block)) {
if (value == null) continue if (value == null) {continue}
if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) { if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
lines.push(`## ${value.trim()}`) lines.push(`## ${value.trim()}`)
@@ -87,17 +87,17 @@ function extractBlock(block: Block, depth: number): string {
lines.push(`**${value.trim()}**`) lines.push(`**${value.trim()}**`)
} else if (key === 'image') { } else if (key === 'image') {
const img = imageMarkdown(value) const img = imageMarkdown(value)
if (img) lines.push(img) if (img) {lines.push(img)}
} else if (isRichText(value)) { } else if (isRichText(value)) {
const md = lexicalToMarkdown(value as never) const md = lexicalToMarkdown(value as never)
if (md) lines.push(md) if (md) {lines.push(md)}
} else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) { } else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) {
lines.push(value.trim()) lines.push(value.trim())
} else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) { } else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) {
for (const item of value) { for (const item of value) {
if (item && typeof item === 'object') { if (item && typeof item === 'object') {
const sub = extractBlock(item as Block, depth + 1) const sub = extractBlock(item as Block, depth + 1)
if (sub.trim()) lines.push(sub) if (sub.trim()) {lines.push(sub)}
} else if (typeof item === 'string' && item.trim()) { } else if (typeof item === 'string' && item.trim()) {
lines.push(`- ${item.trim()}`) lines.push(`- ${item.trim()}`)
} }
@@ -109,23 +109,23 @@ function extractBlock(block: Block, depth: number): string {
} }
export function blocksToMarkdown(layout: unknown, args: BlocksToMarkdownArgs = {}): string { export function blocksToMarkdown(layout: unknown, args: BlocksToMarkdownArgs = {}): string {
if (!Array.isArray(layout)) return '' if (!Array.isArray(layout)) {return ''}
const { overrides = {} } = args const { overrides = {} } = args
const out: string[] = [] const out: string[] = []
for (const block of layout) { for (const block of layout) {
if (!block || typeof block !== 'object') continue if (!block || typeof block !== 'object') {continue}
const b = block as Block const b = block as Block
const type = typeof b.blockType === 'string' ? b.blockType : '' const type = typeof b.blockType === 'string' ? b.blockType : ''
if (type && overrides[type]) { if (type && overrides[type]) {
const md = overrides[type](b) const md = overrides[type](b)
if (md.trim()) out.push(md.trim()) if (md.trim()) {out.push(md.trim())}
continue continue
} }
const md = extractBlock(b, 0) const md = extractBlock(b, 0)
if (md.trim()) out.push(md.trim()) if (md.trim()) {out.push(md.trim())}
} }
return out.join('\n\n').trim() return out.join('\n\n').trim()
-1
View File
@@ -1,7 +1,6 @@
import type { BasePayload } from 'payload' import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js' import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js' import type { ClientIpOptions } from '../shared/rateLimit.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
+2 -2
View File
@@ -9,12 +9,12 @@
* "Artykuły" to "Wpisy" and the path follows, per locale, with no deploy. * "Artykuły" to "Wpisy" and the path follows, per locale, with no deploy.
*/ */
export type ContentCollectionOption = { export type ContentCollectionOption = {
/** Slug of the client's collection, e.g. 'posts'. */
slug: string
/** Admin label for the archive assignment. Defaults to the slug. */ /** Admin label for the archive assignment. Defaults to the slug. */
label?: string label?: string
/** Entries per page in listings. Defaults to 10. */ /** Entries per page in listings. Defaults to 10. */
perPage?: number perPage?: number
/** Slug of the client's collection, e.g. 'posts'. */
slug: string
} }
/** /**
+11 -10
View File
@@ -1,13 +1,14 @@
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js' import { getSiteIntegrations } from '../payload/index.js'
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js' import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
type TransportIntegrations = { type TransportIntegrations = {
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
emailTransport?: 'smtp' | 'graph' | null
emailStatus?: IntegrationStatus | null emailStatus?: IntegrationStatus | null
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
emailTransport?: 'graph' | 'smtp' | null
} }
const STATUS_FIELD = 'emailStatus' const STATUS_FIELD = 'emailStatus'
@@ -16,10 +17,10 @@ const describe = (err: unknown) =>
(err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200) (err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200)
export type MailAdapterArgs = { export type MailAdapterArgs = {
smtp?: PanelSmtpAdapterArgs
graph?: GraphAdapterArgs
fallbackFromAddress?: string fallbackFromAddress?: string
fallbackFromName?: string fallbackFromName?: string
graph?: GraphAdapterArgs
smtp?: PanelSmtpAdapterArgs
} }
/** True when the agency Graph credentials are present in the environment. */ /** True when the agency Graph credentials are present in the environment. */
@@ -94,21 +95,21 @@ export const mailAdapter =
result = await (useGraph ? graph : smtp).sendEmail(message) result = await (useGraph ? graph : smtp).sendEmail(message)
} catch (err) { } catch (err) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
state: 'degraded',
code, code,
message: `${transport}: ${describe(err)}`, message: `${transport}: ${describe(err)}`,
state: 'degraded',
}) })
throw err // callers (form-builder, Send test) still see the failure throw err // callers (form-builder, Send test) still see the failure
} }
// The delegates report failure as { sent: false, error, detail? } instead // The delegates report failure as { sent: false, error, detail? } instead
// of throwing (a broken mailbox must not crash a form submission). // of throwing (a broken mailbox must not crash a form submission).
const failed = result as { sent?: boolean; error?: string; detail?: string } | null const failed = result as { detail?: string; error?: string; sent?: boolean } | null
if (failed && typeof failed === 'object' && failed.sent === false) { if (failed && typeof failed === 'object' && failed.sent === false) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
state: 'degraded',
code, code,
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`, message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`,
state: 'degraded',
}) })
return result return result
} }
@@ -120,9 +121,9 @@ export const mailAdapter =
previous, previous,
graphFallback graphFallback
? { ? {
state: 'degraded',
code: 'graph-unavailable', code: 'graph-unavailable',
message: 'Microsoft Graph is selected but not configured on the server — e-mails are sent over SMTP.', message: 'Microsoft Graph is selected but not configured on the server — e-mails are sent over SMTP.',
state: 'degraded',
} }
: { state: 'ok' }, : { state: 'ok' },
) )
+11 -10
View File
@@ -1,14 +1,15 @@
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { getSiteIntegrations } from '../payload/index.js' import { getSiteIntegrations } from '../payload/index.js'
/** SMTP fields the adapter reads from SiteIntegrations. */ /** SMTP fields the adapter reads from SiteIntegrations. */
type SmtpIntegrations = { type SmtpIntegrations = {
smtpHost?: string | null smtpFromAddress?: null | string
smtpPort?: number | null smtpFromName?: null | string
smtpUser?: string | null smtpHost?: null | string
smtpPassword?: string | null smtpPassword?: null | string
smtpFromAddress?: string | null smtpPort?: null | number
smtpFromName?: string | null smtpUser?: null | string
} }
export type PanelSmtpAdapterArgs = { export type PanelSmtpAdapterArgs = {
@@ -61,7 +62,7 @@ export const panelSmtpAdapter =
payload.logger.error( payload.logger.error(
'[ipal] Email not sent: SMTP is not configured in Site Integrations.', '[ipal] Email not sent: SMTP is not configured in Site Integrations.',
) )
return { sent: false, error: 'SMTP is not configured in Site Integrations.' } return { error: 'SMTP is not configured in Site Integrations.', sent: false }
} }
// The panel is the source of truth for the sender; fall back to whatever // The panel is the source of truth for the sender; fall back to whatever
@@ -83,10 +84,10 @@ export const panelSmtpAdapter =
const { default: nodemailer } = await import('nodemailer') const { default: nodemailer } = await import('nodemailer')
const transporter = nodemailer.createTransport({ const transporter = nodemailer.createTransport({
auth: { pass, user },
host, host,
port, port,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
auth: { user, pass },
}) })
try { try {
@@ -95,13 +96,13 @@ export const panelSmtpAdapter =
from, from,
...(message.subject ? { subject: stripCRLF(message.subject) } : {}), ...(message.subject ? { subject: stripCRLF(message.subject) } : {}),
}) })
return { sent: true, messageId: info.messageId } return { messageId: info.messageId, sent: true }
} catch (err) { } catch (err) {
// Never surface SMTP internals to the caller — a form submission // Never surface SMTP internals to the caller — a form submission
// shouldn't fail loudly because the mailbox is misconfigured. // shouldn't fail loudly because the mailbox is misconfigured.
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`) payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
// `detail` is for the panel status (mailAdapter), not for end users. // `detail` is for the panel status (mailAdapter), not for end users.
return { sent: false, error: 'Failed to send email.', detail: (err as Error).message } return { detail: (err as Error).message, error: 'Failed to send email.', sent: false }
} }
}, },
}) })
+1 -1
View File
@@ -1,4 +1,4 @@
export { assertEnv } from './assertEnv.js' export { assertEnv } from './assertEnv.js'
export type { EnvRule, EnvKind, AssertEnvOptions } from './assertEnv.js' export type { AssertEnvOptions, EnvKind, EnvRule } from './assertEnv.js'
export { ipalEnvRules } from './ipalEnvRules.js' export { ipalEnvRules } from './ipalEnvRules.js'
export type { IpalEnvFeatures } from './ipalEnvRules.js' export type { IpalEnvFeatures } from './ipalEnvRules.js'
+12 -10
View File
@@ -1,5 +1,7 @@
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { Plugin } from 'payload' import type { Plugin } from 'payload'
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { FormsOption } from './types.js' import type { FormsOption } from './types.js'
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */ /** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
@@ -24,14 +26,14 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
const group = adminGroup ? { group: adminGroup } : {} const group = adminGroup ? { group: adminGroup } : {}
return formBuilderPlugin({ return formBuilderPlugin({
fields: { fields: {
checkbox: true,
email: true,
message: true,
number: true,
payment: false,
select: true,
text: true, text: true,
textarea: true, textarea: true,
email: true,
number: true,
select: true,
checkbox: true,
message: true,
payment: false,
...forms.fields, ...forms.fields,
}, },
...(forms.redirectRelationships ...(forms.redirectRelationships
@@ -43,18 +45,18 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
// Tidy panel by default: both collections under one sidebar group with plain // Tidy panel by default: both collections under one sidebar group with plain
// labels — no per-project overrides needed just to sort the sidebar. // labels — no per-project overrides needed just to sort the sidebar.
formOverrides: { formOverrides: {
labels: { singular: 'Form', plural: 'Forms' }, labels: { plural: 'Forms', singular: 'Form' },
...forms.formOverrides, ...forms.formOverrides,
admin: { ...group, ...forms.formOverrides?.admin }, admin: { ...group, ...forms.formOverrides?.admin },
}, },
formSubmissionOverrides: { formSubmissionOverrides: {
labels: { singular: 'Submission', plural: 'Submissions' }, labels: { plural: 'Submissions', singular: 'Submission' },
...forms.formSubmissionOverrides, ...forms.formSubmissionOverrides,
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
access: { access: {
create: submissionsCreateAccess, create: submissionsCreateAccess,
...forms.formSubmissionOverrides?.access, ...forms.formSubmissionOverrides?.access,
}, },
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
}, },
}) })
} }
+39 -37
View File
@@ -1,22 +1,22 @@
import 'server-only' import 'server-only'
import type { BasePayload } from 'payload' import type { BasePayload } from 'payload'
import { getTurnstileConfig } from '../turnstile/config.js' import { getTurnstileConfig } from '../turnstile/config.js'
import { verifyTurnstile } from '../turnstile/verify.js' import { verifyTurnstile } from '../turnstile/verify.js'
import { validateSubmission } from './validateSubmission.js'
import { consumeRateLimit } from './rateLimit.js' import { consumeRateLimit } from './rateLimit.js'
import { validateSubmission } from './validateSubmission.js'
export type SubmitFormArgs = { export type SubmitFormArgs = {
payload: BasePayload /**
/** Form-builder form ID this submission belongs to. */ * Name of the GDPR consent checkbox. A field with this name must be checked
formId: string * for the submission to succeed (enforced server-side). Defaults to 'consent'.
*/
consentFieldName?: string
/** Submitted field data — shape matches the form's fields. */ /** Submitted field data — shape matches the form's fields. */
data: Record<string, unknown> data: Record<string, unknown>
/** /** Form-builder form ID this submission belongs to. */
* Turnstile token. Required whenever Turnstile is configured (both keys — formId: string
* see getTurnstileConfig): a missing token is then rejected. Ignored when
* Turnstile is not configured.
*/
turnstileToken?: string
/** Client IP — used for Turnstile and rate limiting. */ /** Client IP — used for Turnstile and rate limiting. */
ip?: string ip?: string
/** /**
@@ -24,17 +24,19 @@ export type SubmitFormArgs = {
* Set to 0 to disable (e.g. when a real limiter sits in front). * Set to 0 to disable (e.g. when a real limiter sits in front).
*/ */
maxPerMinute?: number maxPerMinute?: number
/** payload: BasePayload
* Name of the GDPR consent checkbox. A field with this name must be checked
* for the submission to succeed (enforced server-side). Defaults to 'consent'.
*/
consentFieldName?: string
/** /**
* Turnstile can't be verified because of OUR side (missing/wrong secret, * Turnstile can't be verified because of OUR side (missing/wrong secret,
* Cloudflare unreachable): 'allow' (default) accepts the submission and shows * Cloudflare unreachable): 'allow' (default) accepts the submission and shows
* the problem in the panel; 'reject' refuses it. * the problem in the panel; 'reject' refuses it.
*/ */
turnstileOnConfigError?: 'allow' | 'reject' turnstileOnConfigError?: 'allow' | 'reject'
/**
* Turnstile token. Required whenever Turnstile is configured (both keys —
* see getTurnstileConfig): a missing token is then rejected. Ignored when
* Turnstile is not configured.
*/
turnstileToken?: string
} }
/** /**
@@ -55,26 +57,26 @@ export type SubmitFormArgs = {
* - `error` — persistence failed unexpectedly * - `error` — persistence failed unexpectedly
*/ */
export type SubmitFailure = export type SubmitFailure =
| { success: false; reason: 'rate_limited' }
| { success: false; reason: 'turnstile' }
| { | {
success: false
reason: 'validation'
/** The offending field's name, when one field is at fault. */ /** The offending field's name, when one field is at fault. */
field?: string field?: string
/** What was wrong with it. */ /** What was wrong with it. */
kind?: 'required' | 'too_long' | 'unknown_fields' kind?: 'required' | 'too_long' | 'unknown_fields'
} reason: 'validation'
| { success: false; reason: 'not_found' }
| {
success: false success: false
}
| {
field?: string
/** A GDPR consent field existed on the form but wasn't checked. */ /** A GDPR consent field existed on the form but wasn't checked. */
reason: 'consent' reason: 'consent'
field?: string success: false
} }
| { success: false; reason: 'error' } | { reason: 'error'; success: false }
| { reason: 'not_found'; success: false }
| { reason: 'rate_limited'; success: false }
| { reason: 'turnstile'; success: false }
export type SubmitFormResult = SubmitFailure | { success: true; submissionId: string | number } export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure
/** /**
* Handles a form submission end to end: rate limit, verify Turnstile, validate * Handles a form submission end to end: rate limit, verify Turnstile, validate
@@ -90,19 +92,19 @@ export type SubmitFormResult = SubmitFailure | { success: true; submissionId: st
* server-only: touches the Turnstile secret. * server-only: touches the Turnstile secret.
*/ */
export async function submitForm({ export async function submitForm({
payload, consentFieldName,
formId,
data, data,
turnstileToken, formId,
ip, ip,
maxPerMinute = 5, maxPerMinute = 5,
consentFieldName, payload,
turnstileOnConfigError = 'allow', turnstileOnConfigError = 'allow',
turnstileToken,
}: SubmitFormArgs): Promise<SubmitFormResult> { }: SubmitFormArgs): Promise<SubmitFormResult> {
// 1. Rate limit — cheapest gate, drops a flood before any real work. // 1. Rate limit — cheapest gate, drops a flood before any real work.
if (maxPerMinute > 0 && ip) { if (maxPerMinute > 0 && ip) {
if (!(await consumeRateLimit({ key: ip, max: maxPerMinute })).ok) { if (!(await consumeRateLimit({ key: ip, max: maxPerMinute })).ok) {
return { success: false, reason: 'rate_limited' } return { reason: 'rate_limited', success: false }
} }
} }
@@ -112,9 +114,9 @@ export async function submitForm({
if ((await getTurnstileConfig(payload)).enabled) { if ((await getTurnstileConfig(payload)).enabled) {
const ok = const ok =
Boolean(turnstileToken) && Boolean(turnstileToken) &&
(await verifyTurnstile({ token: turnstileToken!, payload, ip, onConfigError: turnstileOnConfigError })) (await verifyTurnstile({ ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! }))
if (!ok) { if (!ok) {
return { success: false, reason: 'turnstile' } return { reason: 'turnstile', success: false }
} }
} }
@@ -123,14 +125,14 @@ export async function submitForm({
const validation = await validateSubmission(payload, formId, data, consentFieldName) const validation = await validateSubmission(payload, formId, data, consentFieldName)
if (!validation.ok) { if (!validation.ok) {
if (validation.reason === 'not_found') { if (validation.reason === 'not_found') {
return { success: false, reason: 'not_found' } return { reason: 'not_found', success: false }
} }
if (validation.reason === 'consent') { if (validation.reason === 'consent') {
return { success: false, reason: 'consent', field: validation.field } return { field: validation.field, reason: 'consent', success: false }
} }
return { return {
success: false,
reason: 'validation', reason: 'validation',
success: false,
...(validation.field ? { field: validation.field } : {}), ...(validation.field ? { field: validation.field } : {}),
...(validation.kind ? { kind: validation.kind } : {}), ...(validation.kind ? { kind: validation.kind } : {}),
} }
@@ -149,9 +151,9 @@ export async function submitForm({
})), })),
} as never, } as never,
}) })
return { success: true, submissionId: submission.id } return { submissionId: submission.id, success: true }
} catch (err) { } catch (err) {
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`) payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
return { success: false, reason: 'error' } return { reason: 'error', success: false }
} }
} }
+19 -19
View File
@@ -19,25 +19,29 @@ export type FormsCollectionOverrides = {
* form-builder plugin. Kept minimal; the plugin passes these through. * form-builder plugin. Kept minimal; the plugin passes these through.
*/ */
export type FormsOption = { export type FormsOption = {
/** Field types available in the form builder. Sensible defaults applied. */ /**
fields?: { * Admin sidebar group for Forms + Form Submissions. Default 'Forms'.
text?: boolean * `false` = Payload default ("Collections"). An explicit `admin.group` in
textarea?: boolean * formOverrides / formSubmissionOverrides still wins.
email?: boolean */
number?: boolean adminGroup?: false | string
select?: boolean
checkbox?: boolean
message?: boolean
payment?: boolean
}
/** Collections a form can redirect to (e.g. ['pages']). */
redirectRelationships?: string[]
/** /**
* Name of the checkbox field treated as a GDPR consent gate. A form field * Name of the checkbox field treated as a GDPR consent gate. A form field
* with this name must be checked for submission to succeed — enforced * with this name must be checked for submission to succeed — enforced
* server-side in submitForm. Defaults to 'consent'. * server-side in submitForm. Defaults to 'consent'.
*/ */
consentFieldName?: string consentFieldName?: string
/** Field types available in the form builder. Sensible defaults applied. */
fields?: {
checkbox?: boolean
email?: boolean
message?: boolean
number?: boolean
payment?: boolean
select?: boolean
text?: boolean
textarea?: boolean
}
/** /**
* Override the forms collection. The plugin stays opinion-free about what a * Override the forms collection. The plugin stays opinion-free about what a
* form needs beyond its fields — a client that wants, say, a per-form * form needs beyond its fields — a client that wants, say, a per-form
@@ -53,10 +57,6 @@ export type FormsOption = {
formOverrides?: FormsCollectionOverrides formOverrides?: FormsCollectionOverrides
/** Override the form-submissions collection (same shape). */ /** Override the form-submissions collection (same shape). */
formSubmissionOverrides?: FormsCollectionOverrides formSubmissionOverrides?: FormsCollectionOverrides
/** /** Collections a form can redirect to (e.g. ['pages']). */
* Admin sidebar group for Forms + Form Submissions. Default 'Forms'. redirectRelationships?: string[]
* `false` = Payload default ("Collections"). An explicit `admin.group` in
* formOverrides / formSubmissionOverrides still wins.
*/
adminGroup?: string | false
} }
+6 -6
View File
@@ -24,9 +24,9 @@ import type { FormErrors, Validator } from './useForm.js'
*/ */
/** A rule returns `true` when the value is OK, or an error message string. */ /** A rule returns `true` when the value is OK, or an error message string. */
export type Rule = (value: unknown, values: Record<string, unknown>) => true | string export type Rule = (value: unknown, values: Record<string, unknown>) => string | true
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
/** Standalone e-mail check, handy outside the rule system too. */ /** Standalone e-mail check, handy outside the rule system too. */
export const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_RE.test(v.trim()) export const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_RE.test(v.trim())
@@ -35,9 +35,9 @@ export const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_R
export const required = export const required =
(msg = 'required'): Rule => (msg = 'required'): Rule =>
(v) => { (v) => {
if (v == null) return msg if (v == null) {return msg}
if (typeof v === 'string' && !v.trim()) return msg if (typeof v === 'string' && !v.trim()) {return msg}
if (v === false) return msg if (v === false) {return msg}
return true return true
} }
@@ -86,7 +86,7 @@ export function buildValidator<T extends Record<string, unknown>>(
const all = values as Record<string, unknown> const all = values as Record<string, unknown>
for (const key in schema) { for (const key in schema) {
const rules = schema[key as keyof T] const rules = schema[key as keyof T]
if (!rules || rules.length === 0) continue if (!rules || rules.length === 0) {continue}
for (const rule of rules) { for (const rule of rules) {
const res = rule(all[key], all) const res = rule(all[key], all)
if (res !== true) { if (res !== true) {
+12 -11
View File
@@ -1,15 +1,16 @@
import type { I18nConfig } from '../i18n/index.js' import type { I18nConfig } from '../i18n/index.js'
import { negotiateLocale, isValidLocale, LOCALE_COOKIE_NAME } from '../i18n/index.js'
import { CONSENT_COOKIE, parseConsent } from '../consent/storage.js' import { CONSENT_COOKIE, parseConsent } from '../consent/storage.js'
import { isValidLocale, LOCALE_COOKIE_NAME, negotiateLocale } from '../i18n/index.js'
/** /**
* Minimal request shape the middleware reads. Kept structural so the plugin * Minimal request shape the middleware reads. Kept structural so the plugin
* doesn't hard-depend on next/server types; a Next.js `NextRequest` satisfies it. * doesn't hard-depend on next/server types; a Next.js `NextRequest` satisfies it.
*/ */
type MiddlewareRequest = { type MiddlewareRequest = {
nextUrl: { pathname: string; search: string; clone: () => URL }
cookies: { get: (name: string) => { value: string } | undefined } cookies: { get: (name: string) => { value: string } | undefined }
headers: { get: (name: string) => string | null } headers: { get: (name: string) => null | string }
nextUrl: { clone: () => URL; pathname: string; search: string }
url: string url: string
} }
@@ -19,13 +20,11 @@ type MiddlewareRequest = {
* `next` means let the request pass through untouched. * `next` means let the request pass through untouched.
*/ */
export type LocaleMiddlewareResult = export type LocaleMiddlewareResult =
| { type: 'next'; cookie?: { name: string; value: string } } | { cookie?: { name: string; value: string }; location: string; type: 'redirect' }
| { type: 'redirect'; location: string; cookie?: { name: string; value: string } } | { cookie?: { name: string; value: string }; type: 'next' }
type CreateLocaleMiddlewareArgs = { type CreateLocaleMiddlewareArgs = {
config: I18nConfig config: I18nConfig
/** Cookie name for the locale choice. Defaults to LOCALE_COOKIE_NAME. */
cookieName?: string
/** /**
* Consent category that gates *persisting* the locale cookie. The locale is * Consent category that gates *persisting* the locale cookie. The locale is
* always detected (routing works regardless), but the choice is only written * always detected (routing works regardless), but the choice is only written
@@ -33,9 +32,11 @@ type CreateLocaleMiddlewareArgs = {
* 'functional'. Pass 'necessary' to always persist (treat locale as strictly * 'functional'. Pass 'necessary' to always persist (treat locale as strictly
* necessary), which restores the pre-consent behaviour. * necessary), which restores the pre-consent behaviour.
*/ */
consentCategory?: 'necessary' | 'functional' consentCategory?: 'functional' | 'necessary'
/** Name of the consent cookie to read. Defaults to CONSENT_COOKIE. */ /** Name of the consent cookie to read. Defaults to CONSENT_COOKIE. */
consentCookieName?: string consentCookieName?: string
/** Cookie name for the locale choice. Defaults to LOCALE_COOKIE_NAME. */
cookieName?: string
} }
/** /**
@@ -75,14 +76,14 @@ function firstSegment(pathname: string): string {
*/ */
export function createLocaleMiddleware({ export function createLocaleMiddleware({
config, config,
cookieName = LOCALE_COOKIE_NAME,
consentCategory = 'functional', consentCategory = 'functional',
consentCookieName = CONSENT_COOKIE, consentCookieName = CONSENT_COOKIE,
cookieName = LOCALE_COOKIE_NAME,
}: CreateLocaleMiddlewareArgs) { }: CreateLocaleMiddlewareArgs) {
// Whether the locale cookie may be written: 'necessary' is always granted; // Whether the locale cookie may be written: 'necessary' is always granted;
// 'functional' (default) requires the visitor to have consented. // 'functional' (default) requires the visitor to have consented.
function mayPersistLocale(request: MiddlewareRequest): boolean { function mayPersistLocale(request: MiddlewareRequest): boolean {
if (consentCategory === 'necessary') return true if (consentCategory === 'necessary') {return true}
const consent = parseConsent(request.cookies.get(consentCookieName)?.value) const consent = parseConsent(request.cookies.get(consentCookieName)?.value)
return consent?.[consentCategory] === true return consent?.[consentCategory] === true
} }
@@ -116,9 +117,9 @@ export function createLocaleMiddleware({
// Resolve the locale to use // Resolve the locale to use
const locale = negotiateLocale({ const locale = negotiateLocale({
cookieLocale: request.cookies.get(cookieName)?.value ?? null,
acceptLanguage: request.headers.get('accept-language'), acceptLanguage: request.headers.get('accept-language'),
config, config,
cookieLocale: request.cookies.get(cookieName)?.value ?? null,
}) })
// Redirect to the locale-prefixed path, preserving the rest // Redirect to the locale-prefixed path, preserving the rest
+16 -15
View File
@@ -1,4 +1,5 @@
import type { I18nConfig } from './types.js' import type { I18nConfig } from './types.js'
import { isValidLocale } from './helpers.js' import { isValidLocale } from './helpers.js'
/** /**
@@ -11,10 +12,6 @@ import { isValidLocale } from './helpers.js'
export type LocalizedSlugs = Record<string, string> export type LocalizedSlugs = Record<string, string>
type BuildPathArgs = { type BuildPathArgs = {
/** slug per locale, e.g. { pl: 'strona-glowna', en: 'home' } */
slugs: LocalizedSlugs
/** Target locale to build the path for */
locale: string
config: I18nConfig config: I18nConfig
/** /**
* Slug(s) representing the site root (served at /{locale} with no trailing * Slug(s) representing the site root (served at /{locale} with no trailing
@@ -26,7 +23,9 @@ type BuildPathArgs = {
* otherwise the home page collapses to '/pl' but '/de/startseite' stays * otherwise the home page collapses to '/pl' but '/de/startseite' stays
* un-collapsed, breaking hreflang return tags (a real GSC error). * un-collapsed, breaking hreflang return tags (a real GSC error).
*/ */
homeSlug?: string | Record<string, string> homeSlug?: Record<string, string> | string
/** Target locale to build the path for */
locale: string
/** /**
* Localized segment the document lives under, e.g. * Localized segment the document lives under, e.g.
* `{ pl: 'artykuly', en: 'articles' }` → /pl/artykuly/moj-post. * `{ pl: 'artykuly', en: 'articles' }` → /pl/artykuly/moj-post.
@@ -36,6 +35,8 @@ type BuildPathArgs = {
* A document under a prefix is never the home page, so homeSlug is ignored. * A document under a prefix is never the home page, so homeSlug is ignored.
*/ */
prefix?: LocalizedSlugs prefix?: LocalizedSlugs
/** slug per locale, e.g. { pl: 'strona-glowna', en: 'home' } */
slugs: LocalizedSlugs
} }
/** /**
@@ -61,11 +62,11 @@ type BuildPathArgs = {
* // → '/en/articles/my-post' * // → '/en/articles/my-post'
*/ */
export function buildLocalizedPath({ export function buildLocalizedPath({
slugs,
locale,
config, config,
homeSlug = 'home', homeSlug = 'home',
locale,
prefix, prefix,
slugs,
}: BuildPathArgs): string | undefined { }: BuildPathArgs): string | undefined {
if (!isValidLocale(locale, config)) { if (!isValidLocale(locale, config)) {
return undefined return undefined
@@ -109,11 +110,11 @@ export function buildLocalizedPath({
} }
type SwitchLocaleArgs = { type SwitchLocaleArgs = {
config: I18nConfig
homeSlug?: Record<string, string> | string
prefix?: LocalizedSlugs
slugs: LocalizedSlugs slugs: LocalizedSlugs
targetLocale: string targetLocale: string
config: I18nConfig
homeSlug?: string | Record<string, string>
prefix?: LocalizedSlugs
} }
/** /**
@@ -125,17 +126,17 @@ type SwitchLocaleArgs = {
* to the locale root otherwise — the closest place the visitor would want. * to the locale root otherwise — the closest place the visitor would want.
*/ */
export function switchLocalePath({ export function switchLocalePath({
slugs,
targetLocale,
config, config,
homeSlug = 'home', homeSlug = 'home',
prefix, prefix,
slugs,
targetLocale,
}: SwitchLocaleArgs): string { }: SwitchLocaleArgs): string {
const path = buildLocalizedPath({ slugs, locale: targetLocale, config, homeSlug, prefix }) const path = buildLocalizedPath({ config, homeSlug, locale: targetLocale, prefix, slugs })
if (path) return path if (path) {return path}
const archiveSegment = prefix?.[targetLocale] const archiveSegment = prefix?.[targetLocale]
if (archiveSegment) return `/${targetLocale}/${archiveSegment}` if (archiveSegment) {return `/${targetLocale}/${archiveSegment}`}
return `/${targetLocale}` return `/${targetLocale}`
} }
+1 -1
View File
@@ -1,6 +1,6 @@
import type { I18nConfig } from './types.js' import type { I18nConfig } from './types.js'
const LOCALE_CODE_PATTERN = /^[a-z]{2,3}(-[A-Z]{2})?$/ const LOCALE_CODE_PATTERN = /^[a-z]{2,3}(?:-[A-Z]{2})?$/
/** /**
* Validates i18n config at plugin initialization. * Validates i18n config at plugin initialization.
+11 -10
View File
@@ -1,13 +1,14 @@
import type { Payload } from 'payload' import type { Payload } from 'payload'
import type { IntegrationStatus } from './status.js' import type { IntegrationStatus } from './status.js'
type Props = { type Props = {
/** Injected by Payload into admin server components. */
payload?: Payload
/** Status groups to check: field name → label. */
checks?: Record<string, string>
/** Admin route, for the link. Default '/admin'. */ /** Admin route, for the link. Default '/admin'. */
adminRoute?: string adminRoute?: string
/** Status groups to check: field name → label. */
checks?: Record<string, string>
/** Injected by Payload into admin server components. */
payload?: Payload
} }
/** /**
@@ -15,8 +16,8 @@ type Props = {
* are currently failing, with a link to Site Integrations. Renders nothing when * are currently failing, with a link to Site Integrations. Renders nothing when
* everything is fine — and never throws (DB not ready → nothing). * everything is fine — and never throws (DB not ready → nothing).
*/ */
export async function IntegrationAlerts({ payload, checks = { turnstileStatus: 'Turnstile', emailStatus: 'Email' }, adminRoute = '/admin' }: Props) { export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emailStatus: 'Email', turnstileStatus: 'Turnstile' }, payload }: Props) {
if (!payload) return null if (!payload) {return null}
let doc: Record<string, unknown> let doc: Record<string, unknown>
try { try {
doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown> doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>
@@ -26,17 +27,17 @@ export async function IntegrationAlerts({ payload, checks = { turnstileStatus: '
const failing = Object.entries(checks) const failing = Object.entries(checks)
.map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined })) .map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))
.filter((x) => x.status?.state === 'degraded') .filter((x) => x.status?.state === 'degraded')
if (!failing.length) return null if (!failing.length) {return null}
return ( return (
<div <div
role="alert" role="alert"
style={{ style={{
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
border: '1px solid var(--theme-error-400, #e5484d)',
borderRadius: 4,
marginBottom: '1.5rem', marginBottom: '1.5rem',
padding: '1rem 1.25rem', padding: '1rem 1.25rem',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
}} }}
> >
<strong>Integration problem — the site still works, but something needs attention.</strong> <strong>Integration problem — the site still works, but something needs attention.</strong>
@@ -2,14 +2,14 @@
import { useFormFields } from '@payloadcms/ui' import { useFormFields } from '@payloadcms/ui'
type Props = { type Props = {
/** Name of the hidden status group (buildIntegrationStatusField). */
statusField: string
/** Integration name shown in the banner, e.g. 'Turnstile'. */ /** Integration name shown in the banner, e.g. 'Turnstile'. */
label: string label: string
/** Name of the hidden status group (buildIntegrationStatusField). */
statusField: string
} }
const fmt = (iso: unknown) => { const fmt = (iso: unknown) => {
if (typeof iso !== 'string' || !iso) return '' if (typeof iso !== 'string' || !iso) {return ''}
const d = new Date(iso) const d = new Date(iso)
return Number.isNaN(d.getTime()) ? '' : d.toLocaleString() return Number.isNaN(d.getTime()) ? '' : d.toLocaleString()
} }
@@ -19,18 +19,18 @@ const fmt = (iso: unknown) => {
* the integration has been used once; a red box while it's failing; a short * the integration has been used once; a red box while it's failing; a short
* green line once it works again. * green line once it works again.
*/ */
export function IntegrationStatusBanner({ statusField, label }: Props) { export function IntegrationStatusBanner({ label, statusField }: Props) {
const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined
const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined
const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined
const since = useFormFields(([f]) => f[`${statusField}.since`]?.value) const since = useFormFields(([f]) => f[`${statusField}.since`]?.value)
const checkedAt = useFormFields(([f]) => f[`${statusField}.checkedAt`]?.value) const checkedAt = useFormFields(([f]) => f[`${statusField}.checkedAt`]?.value)
if (!state) return null if (!state) {return null}
if (state === 'ok') { if (state === 'ok') {
return ( return (
<div style={{ marginBottom: '1.5rem', fontSize: '0.85rem', opacity: 0.75 }}> <div style={{ fontSize: '0.85rem', marginBottom: '1.5rem', opacity: 0.75 }}>
✓ {label} working{since ? ` since ${fmt(since)}` : ''}. ✓ {label} working{since ? ` since ${fmt(since)}` : ''}.
</div> </div>
) )
@@ -40,21 +40,21 @@ export function IntegrationStatusBanner({ statusField, label }: Props) {
<div <div
role="alert" role="alert"
style={{ style={{
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
border: '1px solid var(--theme-error-400, #e5484d)',
borderRadius: 4,
marginBottom: '1.5rem', marginBottom: '1.5rem',
padding: '0.9rem 1rem', padding: '0.9rem 1rem',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
}} }}
> >
<strong>{label} is not working — forms are accepted without this check.</strong> <strong>{label} is not working — forms are accepted without this check.</strong>
{message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null} {message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}> <div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
{code ? `Code: ${code}. ` : ''} {code ? `Code: ${code}. ` : ''}
{since ? `Since ${fmt(since)}. ` : ''} {since ? `Since ${fmt(since)}. ` : ''}
{checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''} {checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}
</div> </div>
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}> <div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
Fix the keys below and save — the status is checked again on the next form submission. Fix the keys below and save — the status is checked again on the next form submission.
</div> </div>
</div> </div>
+3 -3
View File
@@ -1,6 +1,6 @@
export { export {
recordIntegrationStatus,
buildIntegrationStatusField,
buildIntegrationStatusBanner, buildIntegrationStatusBanner,
buildIntegrationStatusField,
recordIntegrationStatus,
} from './status.js' } from './status.js'
export type { IntegrationStatus, IntegrationState } from './status.js' export type { IntegrationState, IntegrationStatus } from './status.js'
+16 -16
View File
@@ -12,18 +12,18 @@ import type { BasePayload, Field } from 'payload'
* busy form doesn't turn every submission into a DB write. * busy form doesn't turn every submission into a DB write.
*/ */
export type IntegrationState = 'ok' | 'degraded' export type IntegrationState = 'degraded' | 'ok'
export type IntegrationStatus = { export type IntegrationStatus = {
state?: IntegrationState | null
/** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */
code?: string | null
/** Human explanation shown in the panel (English — panel language). */
message?: string | null
/** When the current state started. */
since?: string | null
/** Last time the integration was used (refreshed at most every REFRESH_MS). */ /** Last time the integration was used (refreshed at most every REFRESH_MS). */
checkedAt?: string | null checkedAt?: null | string
/** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */
code?: null | string
/** Human explanation shown in the panel (English — panel language). */
message?: null | string
/** When the current state started. */
since?: null | string
state?: IntegrationState | null
} }
const REFRESH_MS = 10 * 60_000 const REFRESH_MS = 10 * 60_000
@@ -53,8 +53,8 @@ export function buildIntegrationStatusBanner(statusField: string, label: string)
admin: { admin: {
components: { components: {
Field: { Field: {
clientProps: { label, statusField },
path: '@intecion/ipal-kit/client#IntegrationStatusBanner', path: '@intecion/ipal-kit/client#IntegrationStatusBanner',
clientProps: { statusField, label },
}, },
}, },
}, },
@@ -69,7 +69,7 @@ export async function recordIntegrationStatus(
payload: BasePayload, payload: BasePayload,
field: string, field: string,
previous: IntegrationStatus | null | undefined, previous: IntegrationStatus | null | undefined,
next: { state: IntegrationState; code?: string; message?: string }, next: { code?: string; message?: string; state: IntegrationState },
): Promise<void> { ): Promise<void> {
const now = new Date() const now = new Date()
const changed = previous?.state !== next.state || (next.state === 'degraded' && previous?.code !== next.code) const changed = previous?.state !== next.state || (next.state === 'degraded' && previous?.code !== next.code)
@@ -78,22 +78,22 @@ export async function recordIntegrationStatus(
(!previous?.checkedAt || now.getTime() - new Date(previous.checkedAt).getTime() > REFRESH_MS) (!previous?.checkedAt || now.getTime() - new Date(previous.checkedAt).getTime() > REFRESH_MS)
// Healthy and already recorded as healthy (or never recorded) → nothing to do. // Healthy and already recorded as healthy (or never recorded) → nothing to do.
if (!changed && !stale) return if (!changed && !stale) {return}
if (next.state === 'ok' && !previous?.state) return if (next.state === 'ok' && !previous?.state) {return}
const status: IntegrationStatus = { const status: IntegrationStatus = {
state: next.state, checkedAt: now.toISOString(),
code: next.code ?? null, code: next.code ?? null,
message: next.message ?? null, message: next.message ?? null,
since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()), since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()),
checkedAt: now.toISOString(), state: next.state,
} }
try { try {
await payload.updateGlobal({ await payload.updateGlobal({
slug: SITE_INTEGRATIONS as never, slug: SITE_INTEGRATIONS as never,
context: { ipalIntegrationStatus: true },
data: { [field]: status } as never, data: { [field]: status } as never,
depth: 0, depth: 0,
context: { ipalIntegrationStatus: true },
}) })
} catch (err) { } catch (err) {
console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err) console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err)
+8 -7
View File
@@ -2,11 +2,10 @@ import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js' import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js' import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import { createMarkdownRenderer, searchContent } from '../content/index.js' import { createMarkdownRenderer, searchContent } from '../content/index.js'
import { getDefaultLocale, isValidLocale } from '../i18n/index.js' import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
/** /**
@@ -249,11 +248,13 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
} }
// No server→client SSE stream in this read-only server. // No server→client SSE stream in this read-only server.
async function GET(): Promise<Response> { function GET(): Promise<Response> {
return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', { return Promise.resolve(
headers: { allow: 'POST' }, new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {
status: 405, headers: { allow: 'POST' },
}) status: 405,
}),
)
} }
return { GET, POST } return { GET, POST }
+3 -2
View File
@@ -1,4 +1,5 @@
import type { CollectionBeforeOperationHook } from 'payload' import type { CollectionBeforeOperationHook } from 'payload'
import slugify from 'slugify' import slugify from 'slugify'
/** /**
@@ -44,8 +45,8 @@ export function normalizeFilename(filename: string): string {
* import { normalizeFilenameHook } from '@intecion/ipal-kit' * import { normalizeFilenameHook } from '@intecion/ipal-kit'
* hooks: { beforeOperation: [normalizeFilenameHook] } * hooks: { beforeOperation: [normalizeFilenameHook] }
*/ */
export const normalizeFilenameHook: CollectionBeforeOperationHook = ({ req, operation }) => { export const normalizeFilenameHook: CollectionBeforeOperationHook = ({ operation, req }) => {
if (operation !== 'create' && operation !== 'update') return if (operation !== 'create' && operation !== 'update') {return}
const file = req.file const file = req.file
if (file?.name) { if (file?.name) {
file.name = normalizeFilename(file.name) file.name = normalizeFilename(file.name)
+3 -3
View File
@@ -7,12 +7,12 @@ import type { NotificationTexts } from './types.js'
*/ */
export const NOTIFICATION_FALLBACK: NotificationTexts = { export const NOTIFICATION_FALLBACK: NotificationTexts = {
form: { form: {
success: 'Thank you — your message has been sent.', consent: 'Please accept the privacy policy to continue.',
error: 'Something went wrong. Please try again later.', error: 'Something went wrong. Please try again later.',
notFound: 'This form is no longer available.',
rateLimited: 'Too many attempts. Please wait a moment and try again.', rateLimited: 'Too many attempts. Please wait a moment and try again.',
success: 'Thank you — your message has been sent.',
turnstile: 'Captcha verification failed. Please try again.', turnstile: 'Captcha verification failed. Please try again.',
validation: 'Please check the {field} field and try again.', validation: 'Please check the {field} field and try again.',
consent: 'Please accept the privacy policy to continue.',
notFound: 'This form is no longer available.',
}, },
} }
+4 -4
View File
@@ -3,15 +3,15 @@
* `form` maps submitForm result codes to user-facing messages. * `form` maps submitForm result codes to user-facing messages.
*/ */
export type FormNotificationTexts = { export type FormNotificationTexts = {
success: string /** Shown when a required GDPR consent checkbox was left unchecked. */
consent: string
error: string error: string
notFound: string
rateLimited: string rateLimited: string
success: string
turnstile: string turnstile: string
/** May contain the {field} placeholder — resolve with resolveValidationText. */ /** May contain the {field} placeholder — resolve with resolveValidationText. */
validation: string validation: string
/** Shown when a required GDPR consent checkbox was left unchecked. */
consent: string
notFound: string
} }
export type NotificationTexts = { export type NotificationTexts = {
+1 -1
View File
@@ -21,7 +21,7 @@ type GetSystemPagePathArgs = {
* page's slug in the target locale equals this, the path collapses to the * page's slug in the target locale equals this, the path collapses to the
* locale root (/pl, /en). * locale root (/pl, /en).
*/ */
homeSlug?: string | Record<string, string> homeSlug?: Record<string, string> | string
/** Target locale to build the path for. */ /** Target locale to build the path for. */
locale: string locale: string
/** /**
+27 -27
View File
@@ -1,25 +1,25 @@
type MediaLike = { url?: string | null } | null | undefined type MediaLike = { url?: null | string } | null | undefined
type ArticleJsonLdArgs = { type ArticleJsonLdArgs = {
/** Article headline (the title). */
headline: string
/** Absolute URL of the article. */
url: string
description?: string
/** Cover/hero image. */
image?: MediaLike
/** ISO date the article was first published, e.g. '2026-01-15'. */
datePublished?: string
/** ISO date of the last modification. Defaults to datePublished. */
dateModified?: string
/** Author name (person or org). */ /** Author name (person or org). */
author?: string author?: string
/** Publisher (usually the site/organization) name. */ /** ISO date of the last modification. Defaults to datePublished. */
publisherName?: string dateModified?: string
/** ISO date the article was first published, e.g. '2026-01-15'. */
datePublished?: string
description?: string
/** Article headline (the title). */
headline: string
/** Cover/hero image. */
image?: MediaLike
/** Publisher logo (for the Article rich result). */ /** Publisher logo (for the Article rich result). */
publisherLogo?: MediaLike publisherLogo?: MediaLike
/** Publisher (usually the site/organization) name. */
publisherName?: string
/** 'Article' (default), 'BlogPosting', or 'NewsArticle'. */ /** 'Article' (default), 'BlogPosting', or 'NewsArticle'. */
type?: 'Article' | 'BlogPosting' | 'NewsArticle' type?: 'Article' | 'BlogPosting' | 'NewsArticle'
/** Absolute URL of the article. */
url: string
} }
/** /**
@@ -41,39 +41,39 @@ type ArticleJsonLdArgs = {
* and dates for the rich result; supply them from the post's real fields. * and dates for the rich result; supply them from the post's real fields.
*/ */
export function buildArticleJsonLd({ export function buildArticleJsonLd({
headline,
url,
description,
image,
datePublished,
dateModified,
author,
publisherName,
publisherLogo,
type = 'Article', type = 'Article',
author,
dateModified,
datePublished,
description,
headline,
image,
publisherLogo,
publisherName,
url,
}: ArticleJsonLdArgs) { }: ArticleJsonLdArgs) {
const imageUrl = image?.url const imageUrl = image?.url
const logoUrl = publisherLogo?.url const logoUrl = publisherLogo?.url
const abs = (u: string | null | undefined): string | undefined => const abs = (u: null | string | undefined): string | undefined =>
u ? (u.startsWith('http') ? u : `${url.split('/').slice(0, 3).join('/')}${u}`) : undefined u ? (u.startsWith('http') ? u : `${url.split('/').slice(0, 3).join('/')}${u}`) : undefined
return { return {
'@context': 'https://schema.org', '@context': 'https://schema.org',
'@type': type, '@type': type,
headline, headline,
mainEntityOfPage: { '@id': url, '@type': 'WebPage' },
url, url,
mainEntityOfPage: { '@type': 'WebPage', '@id': url },
...(description ? { description } : {}), ...(description ? { description } : {}),
...(imageUrl ? { image: abs(imageUrl) } : {}), ...(imageUrl ? { image: abs(imageUrl) } : {}),
...(datePublished ? { datePublished } : {}), ...(datePublished ? { datePublished } : {}),
...(dateModified || datePublished ? { dateModified: dateModified ?? datePublished } : {}), ...(dateModified || datePublished ? { dateModified: dateModified ?? datePublished } : {}),
...(author ? { author: { '@type': 'Person', name: author } } : {}), ...(author ? { author: { name: author, '@type': 'Person' } } : {}),
...(publisherName ...(publisherName
? { ? {
publisher: { publisher: {
'@type': 'Organization',
name: publisherName, name: publisherName,
'@type': 'Organization',
...(logoUrl ? { logo: { '@type': 'ImageObject', url: abs(logoUrl) } } : {}), ...(logoUrl ? { logo: { '@type': 'ImageObject', url: abs(logoUrl) } } : {}),
}, },
} }
+2 -2
View File
@@ -65,8 +65,8 @@ export function buildSitemapXml(
e.lastModified instanceof Date ? e.lastModified.toISOString() : String(e.lastModified) e.lastModified instanceof Date ? e.lastModified.toISOString() : String(e.lastModified)
parts.push(` <lastmod>${esc(iso)}</lastmod>`) parts.push(` <lastmod>${esc(iso)}</lastmod>`)
} }
if (e.changeFrequency) parts.push(` <changefreq>${e.changeFrequency}</changefreq>`) if (e.changeFrequency) {parts.push(` <changefreq>${e.changeFrequency}</changefreq>`)}
if (typeof e.priority === 'number') parts.push(` <priority>${e.priority}</priority>`) if (typeof e.priority === 'number') {parts.push(` <priority>${e.priority}</priority>`)}
const alternates = e.alternates?.languages const alternates = e.alternates?.languages
if (alternates) { if (alternates) {
for (const [lang, href] of Object.entries(alternates)) { for (const [lang, href] of Object.entries(alternates)) {
+9 -9
View File
@@ -2,14 +2,14 @@
export type TitleOrder = 'page-first' | 'site-first' export type TitleOrder = 'page-first' | 'site-first'
type ComposeTitleArgs = { type ComposeTitleArgs = {
/** Page-specific title, e.g. 'About Us'. */
pageTitle?: string | null
/** Site name, e.g. 'Acme Inc'. */
siteName?: string | null
/** Separator between page title and site name. Defaults to ' | '. */
separator?: string
/** Defaults to 'page-first' — the page title is what a visitor scans for. */ /** Defaults to 'page-first' — the page title is what a visitor scans for. */
order?: TitleOrder order?: TitleOrder
/** Page-specific title, e.g. 'About Us'. */
pageTitle?: null | string
/** Separator between page title and site name. Defaults to ' | '. */
separator?: string
/** Site name, e.g. 'Acme Inc'. */
siteName?: null | string
} }
/** /**
@@ -24,10 +24,10 @@ type ComposeTitleArgs = {
* Pure function — no dependency on Payload or request state. * Pure function — no dependency on Payload or request state.
*/ */
export function composeTitle({ export function composeTitle({
pageTitle,
siteName,
separator = ' | ',
order = 'page-first', order = 'page-first',
pageTitle,
separator = ' | ',
siteName,
}: ComposeTitleArgs): string { }: ComposeTitleArgs): string {
const page = pageTitle?.trim() const page = pageTitle?.trim()
const site = siteName?.trim() const site = siteName?.trim()
+1 -1
View File
@@ -20,7 +20,7 @@ type CreateMetadataGeneratorArgs = {
baseUrl?: string baseUrl?: string
config: I18nConfig config: I18nConfig
/** Home slug that collapses to the locale root. Defaults to 'home'. */ /** Home slug that collapses to the locale root. Defaults to 'home'. */
homeSlug?: string | Record<string, string> homeSlug?: Record<string, string> | string
/** /**
* Resolves the document to build metadata for, given route params. * Resolves the document to build metadata for, given route params.
* The client supplies this (they own the collections and routing); it should * The client supplies this (they own the collections and routing); it should
+8 -7
View File
@@ -1,20 +1,21 @@
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js' import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import { buildLocalizedPath, getLocaleCodes } from '../i18n/index.js' import { buildLocalizedPath, getLocaleCodes } from '../i18n/index.js'
type BuildHreflangArgs = { type BuildHreflangArgs = {
/** slug per locale for the current document, e.g. { pl: 'o-nas', en: 'about' } */
slugs: LocalizedSlugs
config: I18nConfig
/** Absolute site origin, e.g. 'https://example.com'. Omit for relative paths. */ /** Absolute site origin, e.g. 'https://example.com'. Omit for relative paths. */
baseUrl?: string baseUrl?: string
config: I18nConfig
/** Home slug that collapses to the locale root. Defaults to 'home'. */ /** Home slug that collapses to the locale root. Defaults to 'home'. */
homeSlug?: string | Record<string, string> homeSlug?: Record<string, string> | string
/** /**
* Localized segment the document lives under (an archive page's slugs), * Localized segment the document lives under (an archive page's slugs),
* e.g. { pl: 'artykuly', en: 'articles' }. Locales missing from the prefix * e.g. { pl: 'artykuly', en: 'articles' }. Locales missing from the prefix
* are omitted — an entry with no archive in that language has no URL there. * are omitted — an entry with no archive in that language has no URL there.
*/ */
prefix?: LocalizedSlugs prefix?: LocalizedSlugs
/** slug per locale for the current document, e.g. { pl: 'o-nas', en: 'about' } */
slugs: LocalizedSlugs
} }
/** /**
@@ -34,11 +35,11 @@ type BuildHreflangArgs = {
* // → { pl: 'https://example.com/pl/o-nas', en: 'https://example.com/en/about' } * // → { pl: 'https://example.com/pl/o-nas', en: 'https://example.com/en/about' }
*/ */
export function buildHreflangAlternates({ export function buildHreflangAlternates({
slugs,
config,
baseUrl, baseUrl,
config,
homeSlug = 'home', homeSlug = 'home',
prefix, prefix,
slugs,
}: BuildHreflangArgs): Record<string, string> { }: BuildHreflangArgs): Record<string, string> {
const origin = baseUrl?.replace(/\/$/, '') ?? '' const origin = baseUrl?.replace(/\/$/, '') ?? ''
const alternates: Record<string, string> = {} const alternates: Record<string, string> = {}
@@ -52,7 +53,7 @@ export function buildHreflangAlternates({
} }
for (const locale of getLocaleCodes(config)) { for (const locale of getLocaleCodes(config)) {
const path = buildLocalizedPath({ slugs, locale, config, homeSlug, prefix }) const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs })
if (path) { if (path) {
alternates[locale] = `${origin}${path}` alternates[locale] = `${origin}${path}`
} }
+32 -32
View File
@@ -1,41 +1,41 @@
export type { SeoOption, SeoMeta } from './types.js' export { buildAutoFillMetaHook } from './autoFillMeta.js'
export { composeTitle } from './composeTitle.js' export type { AutoFillMapping } from './autoFillMeta.js'
export type { TitleOrder } from './composeTitle.js' export { buildArticleJsonLd } from './buildArticleJsonLd.js'
export { buildHreflangAlternates } from './hreflang.js' export { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'
export { buildFaqJsonLd } from './buildFaqJsonLd.js'
export { buildIconsMetadata } from './buildIconsMetadata.js'
export { buildLlmsTxt } from './buildLlmsTxt.js'
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'
export { createManifestHandler } from './buildManifest.js'
export { buildMetadata } from './buildMetadata.js' export { buildMetadata } from './buildMetadata.js'
export type { PageMetadata } from './buildMetadata.js' export type { PageMetadata } from './buildMetadata.js'
export { buildSeoPlugin } from './seoPluginConfig.js'
export { buildAutoFillMetaHook } from './autoFillMeta.js'
export { injectAutoFillMeta } from './injectAutoFillMeta.js'
export { injectSeoTabs } from './injectSeoTabs.js'
export type { AutoFillMapping } from './autoFillMeta.js'
export { createMetadataGenerator } from './createMetadataGenerator.js'
export { createPageMetadata } from './createPageMetadata.js'
export { readSiteMetaConfig } from './readSiteMetaConfig.js'
export type { SiteMetaConfig } from './readSiteMetaConfig.js'
export { slugsAcrossLocales } from './slugsAcrossLocales.js'
export { buildSitemapEntries } from './buildSitemapEntries.js'
export { buildSitemapXml } from './buildSitemapXml.js'
export type { SitemapEntry } from './buildSitemapEntries.js'
export { buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS } from './buildRobots.js'
export type { RobotsRules, RobotsOptions } from './buildRobots.js'
export { buildIconsMetadata } from './buildIconsMetadata.js'
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
export { validateFaviconField } from './validateFavicon.js'
export { buildNoindexField } from './buildNoindexField.js' export { buildNoindexField } from './buildNoindexField.js'
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } 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'
export { buildSitemapXml } from './buildSitemapXml.js'
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'
export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js' export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'
export { buildSummaryField } from './buildSummaryField.js' export { buildSummaryField } from './buildSummaryField.js'
export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js' export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'
export { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js' export { composeTitle } from './composeTitle.js'
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js' export type { TitleOrder } from './composeTitle.js'
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js' export { createMetadataGenerator } from './createMetadataGenerator.js'
export { buildFaqJsonLd } from './buildFaqJsonLd.js' export { createPageMetadata } from './createPageMetadata.js'
export { buildServiceJsonLd } from './buildServiceJsonLd.js' export { buildHreflangAlternates } from './hreflang.js'
export { buildArticleJsonLd } from './buildArticleJsonLd.js' export { injectAutoFillMeta } from './injectAutoFillMeta.js'
export { buildLlmsTxt } from './buildLlmsTxt.js' export { injectSeoTabs } from './injectSeoTabs.js'
export { JsonLdGraph } from './JsonLdGraph.js'
export { readSiteMetaConfig } from './readSiteMetaConfig.js'
export type { SiteMetaConfig } from './readSiteMetaConfig.js'
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js' export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'
export type { SitemapRouteOptions } from './routeHandlers.js' export type { SitemapRouteOptions } from './routeHandlers.js'
export { buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './sitemapStyle.js' export { buildSeoPlugin } from './seoPluginConfig.js'
export { buildSitemapCss, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './sitemapStyle.js'
export type { SitemapStyleOptions } from './sitemapStyle.js' export type { SitemapStyleOptions } from './sitemapStyle.js'
export { createManifestHandler } from './buildManifest.js' export { slugsAcrossLocales } from './slugsAcrossLocales.js'
export { JsonLdGraph } from './JsonLdGraph.js' export type { SeoMeta, SeoOption } from './types.js'
export { validateFaviconField } from './validateFavicon.js'
+20 -19
View File
@@ -1,17 +1,18 @@
'use client' 'use client'
import { createContext, useCallback, useContext, useState } from 'react' import { createContext, use, useCallback, useState } from 'react'
import { Turnstile } from './Turnstile.js' import { Turnstile } from './Turnstile.js'
type TurnstileContextValue = { type TurnstileContextValue = {
setToken: (t: null | string) => void
/** Public site key from the provider (read server-side, passed once). */ /** Public site key from the provider (read server-side, passed once). */
siteKey: string | null siteKey: null | string
/** Current token (null until solved / after expiry). */ /** Current token (null until solved / after expiry). */
token: string | null token: null | string
setToken: (t: string | null) => void
} }
const TurnstileContext = createContext<TurnstileContextValue | null>(null) const TurnstileContext = createContext<null | TurnstileContextValue>(null)
/** /**
* Provides the Turnstile site key once for the whole app, like ConsentProvider * Provides the Turnstile site key once for the whole app, like ConsentProvider
@@ -29,17 +30,17 @@ const TurnstileContext = createContext<TurnstileContextValue | null>(null)
* token stays null — submitForm skips the check too, so the form just works. * token stays null — submitForm skips the check too, so the form just works.
*/ */
export function TurnstileProvider({ export function TurnstileProvider({
siteKey,
children, children,
siteKey,
}: { }: {
siteKey: string | null
children: React.ReactNode children: React.ReactNode
siteKey: null | string
}) { }) {
const [token, setToken] = useState<string | null>(null) const [token, setToken] = useState<null | string>(null)
return ( return (
<TurnstileContext.Provider value={{ siteKey, token, setToken }}> <TurnstileContext value={{ setToken, siteKey, token }}>
{children} {children}
</TurnstileContext.Provider> </TurnstileContext>
) )
} }
@@ -53,27 +54,27 @@ export function TurnstileProvider({
* // after submit: reset() // clear for the next submission * // after submit: reset() // clear for the next submission
*/ */
export function useTurnstile(): { export function useTurnstile(): {
token: string | null
TurnstileWidget: (props?: { theme?: 'light' | 'dark' | 'auto' }) => React.ReactNode
reset: () => void
/** True when Turnstile is configured (site key present). */ /** True when Turnstile is configured (site key present). */
enabled: boolean enabled: boolean
reset: () => void
token: null | string
TurnstileWidget: (props?: { theme?: 'auto' | 'dark' | 'light' }) => React.ReactNode
} { } {
const ctx = useContext(TurnstileContext) const ctx = use(TurnstileContext)
if (!ctx) { if (!ctx) {
throw new Error('useTurnstile must be used within <TurnstileProvider>') throw new Error('useTurnstile must be used within <TurnstileProvider>')
} }
const { siteKey, token, setToken } = ctx const { setToken, siteKey, token } = ctx
const reset = useCallback(() => setToken(null), [setToken]) const reset = useCallback(() => setToken(null), [setToken])
const TurnstileWidget = useCallback( const TurnstileWidget = useCallback(
(props?: { theme?: 'light' | 'dark' | 'auto' }) => { (props?: { theme?: 'auto' | 'dark' | 'light' }) => {
if (!siteKey) return null if (!siteKey) {return null}
return <Turnstile siteKey={siteKey} onToken={setToken} theme={props?.theme} /> return <Turnstile onToken={setToken} siteKey={siteKey} theme={props?.theme} />
}, },
[siteKey, setToken], [siteKey, setToken],
) )
return { token, TurnstileWidget, reset, enabled: Boolean(siteKey) } return { enabled: Boolean(siteKey), reset, token, TurnstileWidget }
} }
+4 -4
View File
@@ -1,7 +1,7 @@
// Server-only exports. verify.ts imports 'server-only', so this must never be
// imported from a client component — use ./client for the widget instead.
export { verifyTurnstile, checkTurnstile } from './verify.js'
export type { TurnstileCheck, TurnstileOutcome } from './verify.js'
export { getTurnstileConfig } from './config.js' export { getTurnstileConfig } from './config.js'
export type { TurnstileConfig } from './config.js' export type { TurnstileConfig } from './config.js'
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js' export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'
// Server-only exports. verify.ts imports 'server-only', so this must never be
// imported from a client component — use ./client for the widget instead.
export { checkTurnstile, verifyTurnstile } from './verify.js'
export type { TurnstileCheck, TurnstileOutcome } from './verify.js'
+34 -32
View File
@@ -1,34 +1,26 @@
import 'server-only' import 'server-only'
import type { BasePayload } from 'payload' import type { BasePayload } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js' import { getSiteIntegrations } from '../payload/index.js'
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
import { TURNSTILE_SECRET_ENV as ENV_SECRET } from './config.js' import { TURNSTILE_SECRET_ENV as ENV_SECRET } from './config.js'
type SiteverifyResponse = { type SiteverifyResponse = {
success: boolean
'error-codes'?: string[]
challenge_ts?: string challenge_ts?: string
'error-codes'?: string[]
hostname?: string hostname?: string
success: boolean
} }
type IntegrationsWithTurnstile = { type IntegrationsWithTurnstile = {
turnstileSecretKey?: string | null turnstileSecretKey?: null | string
turnstileStatus?: IntegrationStatus | null turnstileStatus?: IntegrationStatus | null
} }
type VerifyTurnstileArgs = { type VerifyTurnstileArgs = {
/** Token produced by the client-side widget. */
token: string
/** Payload instance — used to read the secret from SiteIntegrations. */
payload: BasePayload
/** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */ /** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */
ip?: string ip?: string
/**
* Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /
* Docker the IP the app sees can differ from the one that solved the challenge
* (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.
*/
sendRemoteIp?: boolean
/** /**
* What to do when verification can't run because of OUR side (missing/wrong * What to do when verification can't run because of OUR side (missing/wrong
* secret, Cloudflare unreachable). 'allow' (default): accept the submission — * secret, Cloudflare unreachable). 'allow' (default): accept the submission —
@@ -36,6 +28,16 @@ type VerifyTurnstileArgs = {
* the panel. 'reject': refuse (fail closed). * the panel. 'reject': refuse (fail closed).
*/ */
onConfigError?: 'allow' | 'reject' onConfigError?: 'allow' | 'reject'
/** Payload instance — used to read the secret from SiteIntegrations. */
payload: BasePayload
/**
* Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /
* Docker the IP the app sees can differ from the one that solved the challenge
* (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.
*/
sendRemoteIp?: boolean
/** Token produced by the client-side widget. */
token: string
} }
const STATUS_FIELD = 'turnstileStatus' const STATUS_FIELD = 'turnstileStatus'
@@ -47,20 +49,20 @@ const STATUS_FIELD = 'turnstileStatus'
* erroring) → the visitor can't fix it; by default the submission * erroring) → the visitor can't fix it; by default the submission
* is accepted and the panel shows the problem. * is accepted and the panel shows the problem.
*/ */
export type TurnstileOutcome = 'pass' | 'reject' | 'degraded' export type TurnstileOutcome = 'degraded' | 'pass' | 'reject'
export type TurnstileCheck = { outcome: TurnstileOutcome; code?: string } export type TurnstileCheck = { code?: string; outcome: TurnstileOutcome }
/** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */ /** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */
const CONFIG_ERRORS: Record<string, string> = { const CONFIG_ERRORS: Record<string, string> = {
'missing-input-secret': 'The secret key is missing in the request.', 'internal-error': 'Cloudflare reported an internal error while verifying.',
'invalid-input-secret': 'invalid-input-secret':
'Cloudflare rejected the secret key — check Site Integrations → Turnstile (secret and site key must come from the same widget).', 'Cloudflare rejected the secret key — check Site Integrations → Turnstile (secret and site key must come from the same widget).',
'internal-error': 'Cloudflare reported an internal error while verifying.', 'missing-input-secret': 'The secret key is missing in the request.',
} }
const PLUGIN_ERRORS: Record<string, string> = { const PLUGIN_ERRORS: Record<string, string> = {
'bad-response': 'Cloudflare returned an unexpected response.',
'missing-secret': `No secret key — fill in Site Integrations → Turnstile (or the ${ENV_SECRET} environment variable).`, 'missing-secret': `No secret key — fill in Site Integrations → Turnstile (or the ${ENV_SECRET} environment variable).`,
'network-error': 'The server could not reach Cloudflare (challenges.cloudflare.com).', 'network-error': 'The server could not reach Cloudflare (challenges.cloudflare.com).',
'bad-response': 'Cloudflare returned an unexpected response.',
} }
/** /**
@@ -71,12 +73,12 @@ const PLUGIN_ERRORS: Record<string, string> = {
* SiteIntegrations is updated (throttled) so the panel shows failures. * SiteIntegrations is updated (throttled) so the panel shows failures.
*/ */
export async function checkTurnstile({ export async function checkTurnstile({
token,
payload,
ip, ip,
payload,
sendRemoteIp = false, sendRemoteIp = false,
token,
}: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck> { }: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck> {
if (!token) return { outcome: 'reject', code: 'missing-input-response' } if (!token) {return { code: 'missing-input-response', outcome: 'reject' }}
const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload) const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload)
const previous = integrations[STATUS_FIELD] const previous = integrations[STATUS_FIELD]
@@ -85,29 +87,29 @@ export async function checkTurnstile({
const degraded = async (code: string): Promise<TurnstileCheck> => { const degraded = async (code: string): Promise<TurnstileCheck> => {
const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}` const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}`
console.warn(`[ipal] Turnstile degraded (${code}): ${message}`) console.warn(`[ipal] Turnstile degraded (${code}): ${message}`)
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'degraded', code, message }) await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, message, state: 'degraded' })
return { outcome: 'degraded', code } return { code, outcome: 'degraded' }
} }
if (!secret) return degraded('missing-secret') if (!secret) {return degraded('missing-secret')}
const body = new URLSearchParams({ secret, response: token }) const body = new URLSearchParams({ response: token, secret })
if (sendRemoteIp && ip) body.append('remoteip', ip) if (sendRemoteIp && ip) {body.append('remoteip', ip)}
let data: SiteverifyResponse let data: SiteverifyResponse
try { try {
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
body, body,
method: 'POST',
signal: AbortSignal.timeout(8000), signal: AbortSignal.timeout(8000),
}) })
if (res.status >= 500) return degraded('internal-error') if (res.status >= 500) {return degraded('internal-error')}
data = (await res.json()) as SiteverifyResponse data = (await res.json()) as SiteverifyResponse
} catch (err) { } catch (err) {
console.warn('[ipal] Turnstile: siteverify request failed:', err instanceof Error ? err.message : err) console.warn('[ipal] Turnstile: siteverify request failed:', err instanceof Error ? err.message : err)
return degraded('network-error') return degraded('network-error')
} }
if (typeof data?.success !== 'boolean') return degraded('bad-response') if (typeof data?.success !== 'boolean') {return degraded('bad-response')}
if (data.success) { if (data.success) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' }) await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' })
@@ -116,11 +118,11 @@ export async function checkTurnstile({
const codes = data['error-codes'] ?? [] const codes = data['error-codes'] ?? []
const configCode = codes.find((c) => c in CONFIG_ERRORS) const configCode = codes.find((c) => c in CONFIG_ERRORS)
if (configCode) return degraded(configCode) if (configCode) {return degraded(configCode)}
// Visitor-side: invalid-input-response, timeout-or-duplicate, missing-input-response, bad-request. // Visitor-side: invalid-input-response, timeout-or-duplicate, missing-input-response, bad-request.
console.warn(`[ipal] Turnstile rejected: ${codes.join(', ') || 'unknown'}${data.hostname ? ` (hostname ${data.hostname})` : ''}`) console.warn(`[ipal] Turnstile rejected: ${codes.join(', ') || 'unknown'}${data.hostname ? ` (hostname ${data.hostname})` : ''}`)
return { outcome: 'reject', code: codes[0] ?? 'unknown' } return { code: codes[0] ?? 'unknown', outcome: 'reject' }
} }
/** /**
+21 -20
View File
@@ -1,17 +1,18 @@
import type { Config, Plugin } from 'payload' import type { Config, Plugin } from 'payload'
import type { IpalOptions, TotpPluginFactory } from './types.js' import type { IpalOptions, TotpPluginFactory } from './types.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { injectRoles } from './modules/access/index.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { buildArchiveFields } from './modules/content/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildCookieSettings } from './globals/CookieSettings/index.js' import { buildCookieSettings } from './globals/CookieSettings/index.js'
import { buildNotifications } from './globals/Notifications/index.js' import { buildNotifications } from './globals/Notifications/index.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { injectRoles } from './modules/access/index.js'
import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js' import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
/** /**
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3. * IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
@@ -123,8 +124,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
if (options.whiteLabel) { if (options.whiteLabel) {
const wl = options.whiteLabel === true ? {} : options.whiteLabel const wl = options.whiteLabel === true ? {} : options.whiteLabel
const serverProps: Record<string, unknown> = {} const serverProps: Record<string, unknown> = {}
if (wl.settingsSlug) serverProps.settingsSlug = wl.settingsSlug if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}
if (wl.nameField) serverProps.nameField = wl.nameField if (wl.nameField) {serverProps.nameField = wl.nameField}
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) } const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) } const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
@@ -145,18 +146,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
...(config.admin?.components ?? {}), ...(config.admin?.components ?? {}),
graphics: { graphics: {
...(config.admin?.components?.graphics ?? {}), ...(config.admin?.components?.graphics ?? {}),
Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },
Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps }, Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },
Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },
}, },
...(creditOn ...(creditOn
? { ? {
afterNavLinks: [
...(config.admin?.components?.afterNavLinks ?? []),
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: { ...creditProps, variant: 'nav' },
},
],
afterLogin: [ afterLogin: [
...(config.admin?.components?.afterLogin ?? []), ...(config.admin?.components?.afterLogin ?? []),
{ {
@@ -164,6 +158,13 @@ export const ipalKit = (options: IpalOptions): Plugin => {
serverProps: { ...creditProps, variant: 'login' }, serverProps: { ...creditProps, variant: 'login' },
}, },
], ],
afterNavLinks: [
...(config.admin?.components?.afterNavLinks ?? []),
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: { ...creditProps, variant: 'nav' },
},
],
} }
: {}), : {}),
}, },
@@ -215,8 +216,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.globals = [ config.globals = [
...(config.globals ?? []), ...(config.globals ?? []),
buildSiteSettings({ buildSiteSettings({
systemPageFields,
additionalFields: options.siteSettingsFields, additionalFields: options.siteSettingsFields,
systemPageFields,
}), }),
buildSiteIntegrations({ additionalFields: options.integrationsFields }), buildSiteIntegrations({ additionalFields: options.integrationsFields }),
buildCookieSettings(), buildCookieSettings(),
@@ -244,7 +245,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// --- hooks: onInit --- // --- hooks: onInit ---
const incomingOnInit = config.onInit const incomingOnInit = config.onInit
config.onInit = async (payload) => { config.onInit = async (payload) => {
if (incomingOnInit) await incomingOnInit(payload) if (incomingOnInit) {await incomingOnInit(payload)}
payload.logger.info('[ipal] Plugin initialized.') payload.logger.info('[ipal] Plugin initialized.')
} }
+18 -4
View File
@@ -1,17 +1,20 @@
import { describe, expect, test } from 'vitest' import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { isHoneypotTripped } from '../src/modules/forms/honeypot.js'
import { isEmail } from '../src/modules/forms/validators.js'
import { buildLocalizedPath, switchLocalePath } from '../src/modules/i18n/localizedPath.js' import { buildLocalizedPath, switchLocalePath } from '../src/modules/i18n/localizedPath.js'
import { matchAcceptLanguage, negotiateLocale } from '../src/modules/i18n/negotiateLocale.js' import { matchAcceptLanguage, negotiateLocale } from '../src/modules/i18n/negotiateLocale.js'
import { isHoneypotTripped } from '../src/modules/forms/honeypot.js'
const config = { const config: I18nConfig = {
defaultLocale: 'pl', defaultLocale: 'pl',
locales: [ locales: [
{ code: 'pl', label: 'Polski' }, { code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' }, { code: 'en', label: 'English' },
], ],
} }
const single = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } const single: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
describe('negotiateLocale', () => { describe('negotiateLocale', () => {
test('cookie → Accept-Language → default', () => { test('cookie → Accept-Language → default', () => {
@@ -58,7 +61,7 @@ describe('buildLocalizedPath', () => {
describe('switchLocalePath', () => { describe('switchLocalePath', () => {
test('never dead-ends: falls back to archive, then locale root', () => { test('never dead-ends: falls back to archive, then locale root', () => {
expect(switchLocalePath({ config, slugs: { pl: 'post' }, targetLocale: 'en', prefix: { en: 'articles', pl: 'artykuly' } })).toBe( expect(switchLocalePath({ config, prefix: { en: 'articles', pl: 'artykuly' }, slugs: { pl: 'post' }, targetLocale: 'en' })).toBe(
'/en/articles', '/en/articles',
) )
expect(switchLocalePath({ config, slugs: { pl: 'o-nas' }, targetLocale: 'en' })).toBe('/en') expect(switchLocalePath({ config, slugs: { pl: 'o-nas' }, targetLocale: 'en' })).toBe('/en')
@@ -72,3 +75,14 @@ describe('honeypot', () => {
expect(isHoneypotTripped({})).toBe(false) expect(isHoneypotTripped({})).toBe(false)
}) })
}) })
describe('isEmail', () => {
test('accepts real addresses, rejects malformed ones', () => {
for (const ok of ['[email protected]', '[email protected]', '[email protected]']) {
expect(isEmail(ok)).toBe(true)
}
for (const bad of ['', 'a', 'a@b', 'a [email protected]', 'a@b c.pl', '@b.pl', '[email protected]', 'a@@b.pl']) {
expect(isEmail(bad)).toBe(false)
}
})
})
+3 -1
View File
@@ -2,9 +2,11 @@ import type { Config } from 'payload'
import { describe, expect, test, vi } from 'vitest' import { describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { ipalKit } from '../src/plugin.js' import { ipalKit } from '../src/plugin.js'
const i18n = { const i18n: I18nConfig = {
defaultLocale: 'pl', defaultLocale: 'pl',
locales: [ locales: [
{ code: 'pl', label: 'Polski' }, { code: 'pl', label: 'Polski' },
+1 -1
View File
@@ -14,7 +14,7 @@ const forms = {
], ],
}, },
} }
const data = { consent: true, name: 'Ala' } const data = { name: 'Ala', consent: true }
const keys = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' } const keys = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' }
let ipCounter = 0 let ipCounter = 0
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"composite": false,
"incremental": false,
"noEmit": true,
"emitDeclarationOnly": false,
"rootDir": ".."
},
"include": ["./**/*.ts", "../src/**/*.ts", "../src/**/*.tsx"]
}