From 4544cac69c59afdc092a5d3f5a7c905a3b17020c Mon Sep 17 00:00:00 2001 From: rasm-its Date: Thu, 15 Oct 2026 23:56:18 +0200 Subject: [PATCH] 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) / 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 --- eslint.config.js | 9 + src/exports/admin.ts | 4 +- src/exports/client.ts | 82 ++--- src/exports/server.ts | 10 +- src/globals/Notifications/index.ts | 5 +- .../components/MaskedField.tsx | 25 +- .../components/TestEmailButton.tsx | 24 +- src/index.ts | 290 +++++++++--------- src/modules/admin-ui/rowLabel.ts | 4 +- src/modules/analytics/pixels.ts | 2 +- src/modules/analytics/pushDataLayer.ts | 2 +- src/modules/consent/categories.ts | 8 +- src/modules/content/blocksToMarkdown.ts | 46 +-- src/modules/content/createSearchRoute.ts | 1 - src/modules/content/types.ts | 4 +- src/modules/email/mailAdapter.ts | 21 +- src/modules/email/panelSmtpAdapter.ts | 21 +- src/modules/env/index.ts | 2 +- src/modules/forms/formsPluginConfig.ts | 22 +- src/modules/forms/submitForm.ts | 76 ++--- src/modules/forms/types.ts | 38 +-- src/modules/forms/validators.ts | 12 +- src/modules/i18n/localeMiddleware.ts | 23 +- src/modules/i18n/localizedPath.ts | 31 +- src/modules/i18n/validation.ts | 2 +- .../integrations/IntegrationAlerts.tsx | 21 +- .../integrations/IntegrationStatusBanner.tsx | 22 +- src/modules/integrations/index.ts | 6 +- src/modules/integrations/status.ts | 32 +- src/modules/mcp/createMcpRoute.ts | 15 +- src/modules/media/normalizeFilename.ts | 5 +- src/modules/notifications/defaults.ts | 6 +- src/modules/notifications/types.ts | 8 +- src/modules/pages/getSystemPagePath.ts | 2 +- src/modules/seo/buildArticleJsonLd.ts | 54 ++-- src/modules/seo/buildSitemapXml.ts | 4 +- src/modules/seo/composeTitle.ts | 18 +- src/modules/seo/createMetadataGenerator.ts | 2 +- src/modules/seo/hreflang.ts | 15 +- src/modules/seo/index.ts | 64 ++-- src/modules/turnstile/TurnstileProvider.tsx | 39 +-- src/modules/turnstile/index.ts | 8 +- src/modules/turnstile/verify.ts | 66 ++-- src/plugin.ts | 41 +-- test/i18n.test.ts | 22 +- test/plugin.test.ts | 4 +- test/submitForm.test.ts | 2 +- test/tsconfig.json | 11 + 48 files changed, 642 insertions(+), 589 deletions(-) create mode 100644 test/tsconfig.json diff --git a/eslint.config.js b/eslint.config.js index 958e859..7b46160 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -26,9 +26,18 @@ export default [ ...payloadEsLintConfig, { rules: { + // console.warn/error are the plugin's deliberate server-side diagnostics. + 'no-console': ['warn', { allow: ['warn', 'error'] }], 'no-restricted-exports': 'off', }, }, + { + // Mocks stand in for async APIs without awaiting anything themselves. + files: ['test/**/*.ts'], + rules: { + '@typescript-eslint/require-await': 'off', + }, + }, { languageOptions: { parserOptions: { diff --git a/src/exports/admin.ts b/src/exports/admin.ts index ae49e14..c04efe3 100644 --- a/src/exports/admin.ts +++ b/src/exports/admin.ts @@ -1,3 +1,4 @@ +export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js' /** * Entry point: @intecion/ipal-kit/admin * @@ -5,6 +6,5 @@ * importMap can resolve them by a stable path when ipalKit injects * admin.components.graphics.Logo/Icon. */ -export { AdminLogo, AdminIcon, IntecionCredit } from '../modules/branding/index.js' -export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js' +export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js' export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js' diff --git a/src/exports/client.ts b/src/exports/client.ts index 486ee76..9c7cb8c 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -1,4 +1,13 @@ 'use client' +export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js' +export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js' +export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js' +export 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 * @@ -7,61 +16,52 @@ * client-only code. */ export { - useConsent, ConsentProvider, - useConsentContext, + ConsentScript, CookieBanner, CookieButton, - ConsentScript, + useConsent, + useConsentContext, } from '../modules/consent/client.js' export type { CookieBannerClassNames } from '../modules/consent/client.js' -export { Turnstile } from '../modules/turnstile/client.js' -export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js' -export { AccessibilityProvider, useAccessibility, AccessibilityWidget } from '../modules/accessibility/client.js' -export type { A11yState, A11yTexts, A11yClassNames } from '../modules/accessibility/client.js' - +export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js' +export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js' +export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js' +export { useContactForm } from '../modules/forms/useContactForm.js' +export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js' +export { 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 // components (e.g. a LanguageSwitcher that computes locale URLs on the client). export { - switchLocalePath, buildLocalizedPath, - getLocalizedSlugs, getLocaleCodes, + getLocalizedSlugs, + switchLocalePath, } from '../modules/i18n/index.js' -export type { LocalizedSlugs, I18nConfig } 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 type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js' export { AlternateLinksProvider, - useAlternateLinks, - useSetAlternateLinks, AlternateLinksUpdater, LanguageSwitcher, + useAlternateLinks, + useSetAlternateLinks, } from '../modules/i18n/index.js' export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js' -export { useForm } from '../modules/forms/useForm.js' -export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js' -export { useContactForm } from '../modules/forms/useContactForm.js' -export type { ContactFormValues, ContactFormErrors, SubmitAction } from '../modules/forms/useContactForm.js' -export { - 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' +export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js' +export { LocaleView } from '../modules/pages/LocaleView.js' +export { Turnstile } from '../modules/turnstile/client.js' +export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js' +export type { TurnstileProps } from '../modules/turnstile/client.js' diff --git a/src/exports/server.ts b/src/exports/server.ts index a206ef2..1964906 100644 --- a/src/exports/server.ts +++ b/src/exports/server.ts @@ -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 * @@ -10,9 +14,5 @@ * Import these only from Server Actions, route handlers, or server components — * 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 { 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' diff --git a/src/globals/Notifications/index.ts b/src/globals/Notifications/index.ts index c425dbc..308b23f 100644 --- a/src/globals/Notifications/index.ts +++ b/src/globals/Notifications/index.ts @@ -1,4 +1,5 @@ import type { GlobalConfig } from 'payload' + import { notificationsFields } from './fields.js' /** @@ -9,11 +10,11 @@ import { notificationsFields } from './fields.js' export function buildNotifications(): GlobalConfig { return { slug: 'notifications', - label: 'Notifications', - admin: { group: 'Settings' }, access: { read: () => true, // texts are public-facing (shown to end users) }, + admin: { group: 'Settings' }, fields: notificationsFields, + label: 'Notifications', } } diff --git a/src/globals/SiteIntegrations/components/MaskedField.tsx b/src/globals/SiteIntegrations/components/MaskedField.tsx index 6e21723..091b586 100644 --- a/src/globals/SiteIntegrations/components/MaskedField.tsx +++ b/src/globals/SiteIntegrations/components/MaskedField.tsx @@ -1,9 +1,10 @@ 'use client' -import { useField, FieldLabel, FieldDescription } from '@payloadcms/ui' -import { useState } from 'react' 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, * 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. */ export const MaskedField: TextFieldClientComponent = ({ field, path }) => { - const { value, setValue } = useField({ path }) + const { setValue, value } = useField({ path }) const [revealed, setRevealed] = useState(false) const label = @@ -31,38 +32,38 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => { return (
- + -
+
setValue(e.target.value)} style={{ flex: 1 }} + type={revealed ? 'text' : 'password'} + value={value ?? ''} />
{description && typeof description === 'string' ? ( - + ) : null}
) diff --git a/src/globals/SiteIntegrations/components/TestEmailButton.tsx b/src/globals/SiteIntegrations/components/TestEmailButton.tsx index bc5e645..ac00ca9 100644 --- a/src/globals/SiteIntegrations/components/TestEmailButton.tsx +++ b/src/globals/SiteIntegrations/components/TestEmailButton.tsx @@ -14,7 +14,7 @@ import { useState } from 'react' export const TestEmailButton = () => { const [to, setTo] = 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' }) const send = async () => { @@ -25,10 +25,10 @@ export const TestEmailButton = () => { setStatus({ kind: 'sending' }) try { const res = await fetch('/api/ipal/test-email', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - credentials: 'include', body: JSON.stringify({ to: to.trim() }), + credentials: 'include', + headers: { 'Content-Type': 'application/json' }, + method: 'POST', }) const data = await res.json() if (data.ok) { @@ -44,23 +44,23 @@ export const TestEmailButton = () => { return (
-

+

Sends through the transport selected above. Save your changes first.

-
+
setTo(e.target.value)} + placeholder="you@example.com" style={{ flex: 1, minWidth: '220px' }} + type="email" + value={to} /> diff --git a/src/index.ts b/src/index.ts index 325bce8..5ace1d2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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 { adminOnly, @@ -30,64 +13,102 @@ export { requireRoleField, ROLE_HIERARCHY, } 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 { - getGlobal, - getSiteSettings, - getSiteIntegrations, - SITE_SETTINGS_SLUG, - SITE_INTEGRATIONS_SLUG, -} from './modules/payload/index.js' -// Imported from the file, not the turnstile barrel — that one re-exports verify, -// which imports 'server-only'. -export { getTurnstileConfig } from './modules/turnstile/config.js' -export type { TurnstileConfig } from './modules/turnstile/config.js' -export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js' -export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js' -export type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js' + ACCEPT_ALL_CONSENT, + CONSENT_CATEGORIES, + CONSENT_COOKIE, + CONSENT_MAX_AGE, + CONSENT_VERSION, + DEFAULT_CONSENT, + getConsentTexts, + parseConsent, + REJECT_ALL_CONSENT, + serializeConsent, + setDefaultConsent, + updateConsent, +} from './modules/consent/index.js' +export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js' +export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js' export { - 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, - getArchiveEntries, + blocksToMarkdown, buildArchivePath, buildEntryPath, + createMarkdownRenderer, + createSearchRoute, + getArchiveEntries, + MARKDOWN_PREFIX, + markdownHref, + markdownResponse, parsePageParam, + prefersMarkdown, + resolveNotFoundPage, + resolveRedirect, + resolveRoute, + searchContent, } from './modules/content/index.js' export type { ArchiveEntries } from './modules/content/index.js' export type { SearchResult } from './modules/content/index.js' -// Lexical → Markdown (pure, no React) — for AI-readable output. -export { lexicalToMarkdown } from './modules/richtext/index.js' -export type { AutoFillMapping, SitemapEntry, RobotsRules, RobotsOptions } from './modules/seo/index.js' +export { graphAdapter } from './modules/email/graphAdapter.js' +export type { GraphAdapterArgs } from './modules/email/graphAdapter.js' +export { mailAdapter } from './modules/email/mailAdapter.js' +export type { MailAdapterArgs } from './modules/email/mailAdapter.js' +// 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 { - buildAutoFillMetaHook, - injectAutoFillMeta, - createMetadataGenerator, - createPageMetadata, - buildSitemapEntries, - buildRobots, - AI_ASSISTANT_BOTS, - AI_TRAINING_BOTS, -} from './modules/seo/index.js' + buildValidator, + checked, + custom, + email, + isEmail, + maxLength, + minLength, + pattern, + required, +} from './modules/forms/validators.js' +export type { Rule } from './modules/forms/validators.js' +export { createContentHelpers } from './modules/frontend/index.js' +// 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 { createLocaleMiddleware, @@ -95,99 +116,78 @@ export { } from './modules/i18n/index.js' export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js' export { resolveLocalized } from './modules/i18n/index.js' -export { - CONSENT_CATEGORIES, - DEFAULT_CONSENT, - 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 { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js' +export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js' +export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js' export type { - FormsOption, - FormsCollectionOverrides, - FormsFieldsOverride, -} from './modules/forms/types.js' -// Validation rules are pure — exported server-side too, for re-validating a -// submission inside a server action. (useForm/useContactForm are client-only → -// '@intecion/ipal-kit/client'.) -export { - buildValidator, - 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' + BuildLinkFieldOptions, + BuildLinksFieldOptions, + LinkAppearance, + LinkValue, + ResolveLinkHrefOptions, +} from './modules/links/index.js' // Read-only MCP server (Claude/agents connect to the site and query it). export { createMcpRoute } from './modules/mcp/index.js' -// Boot-time environment validation (fail fast on misconfigured deploys). -export { assertEnv, ipalEnvRules } from './modules/env/index.js' -export type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from './modules/env/index.js' -export type { AnalyticsConfig } from './modules/analytics/index.js' -export { getAnalyticsConfig } from './modules/analytics/index.js' -export { buildSlugField, toSlug } from './modules/slug/index.js' -export { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js' +export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js' +export type { OptimizeUploadOptions } from './modules/media/index.js' +export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js' +export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js' +export type { PagesOption, SystemPageRole } from './modules/pages/index.js' +export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js' +export type { GlobalQueryOptions } from './modules/payload/index.js' +export { + getGlobal, + getSiteIntegrations, + getSiteSettings, + SITE_INTEGRATIONS_SLUG, + SITE_SETTINGS_SLUG, +} from './modules/payload/index.js' +// 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 { buildCsp } from './modules/security/index.js' export type { BuildCspArgs } from './modules/security/index.js' +export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js' +export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js' +export { + buildHreflangAlternates, + buildMetadata, + composeTitle, + 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 { 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 { 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. -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 { 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 { 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 { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js' -export type { OptimizeUploadOptions } from './modules/media/index.js' -export { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/index.js' -export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js' -export type { A11yState } from './modules/accessibility/index.js' -export type { SecurityHeader, BuildSecurityHeadersArgs } from './modules/security/index.js' -export type { NotificationTexts, FormNotificationTexts } from './modules/notifications/index.js' +// Imported from the file, not the turnstile barrel — that one re-exports verify, +// which imports 'server-only'. +export { getTurnstileConfig } from './modules/turnstile/config.js' +export type { TurnstileConfig } from './modules/turnstile/config.js' +export { ipalKit } from './plugin.js' +export type { IpalOptions } from './types.js' diff --git a/src/modules/admin-ui/rowLabel.ts b/src/modules/admin-ui/rowLabel.ts index 2b6ee79..589650c 100644 --- a/src/modules/admin-ui/rowLabel.ts +++ b/src/modules/admin-ui/rowLabel.ts @@ -10,6 +10,6 @@ import type { RowLabelProps } from './RowLabelComponent.js' * After adding it to a project: `pnpm payload generate:importmap`. */ export function rowLabel(fields: string | string[], fallback = 'Item') { - const clientProps: RowLabelProps = { fields: Array.isArray(fields) ? fields : [fields], fallback } - return { RowLabel: { path: '@intecion/ipal-kit/admin#RowLabel', clientProps } } + const clientProps: RowLabelProps = { fallback, fields: Array.isArray(fields) ? fields : [fields] } + return { RowLabel: { clientProps, path: '@intecion/ipal-kit/admin#RowLabel' } } } diff --git a/src/modules/analytics/pixels.ts b/src/modules/analytics/pixels.ts index ea40de0..3d46bcb 100644 --- a/src/modules/analytics/pixels.ts +++ b/src/modules/analytics/pixels.ts @@ -22,7 +22,7 @@ export function loadMetaPixel(id: string): void { if (w.fbq) {return} const n: any = (w.fbq = function (...args: unknown[]) { if (n.callMethod) { - n.callMethod.apply(n, args) + n.callMethod(...args) } else { n.queue.push(args) } diff --git a/src/modules/analytics/pushDataLayer.ts b/src/modules/analytics/pushDataLayer.ts index 1fa99c8..5189e9e 100644 --- a/src/modules/analytics/pushDataLayer.ts +++ b/src/modules/analytics/pushDataLayer.ts @@ -17,7 +17,7 @@ * gates the tag in GTM (ad_storage) — this only emits the event. */ export function pushDataLayer(event: string, params: Record = {}): void { - if (typeof window === 'undefined') return + if (typeof window === 'undefined') {return} const w = window as unknown as { dataLayer?: unknown[] } w.dataLayer = w.dataLayer || [] w.dataLayer.push({ event, ...params }) diff --git a/src/modules/consent/categories.ts b/src/modules/consent/categories.ts index 0164510..d67aff0 100644 --- a/src/modules/consent/categories.ts +++ b/src/modules/consent/categories.ts @@ -9,17 +9,17 @@ export type ConsentCategory = (typeof CONSENT_CATEGORIES)[number] export type ConsentState = Record export const DEFAULT_CONSENT: ConsentState = { - necessary: true, - functional: false, analytics: false, + functional: false, marketing: false, + necessary: true, } export const ACCEPT_ALL_CONSENT: ConsentState = { - necessary: true, - functional: true, analytics: true, + functional: true, marketing: true, + necessary: true, } export const REJECT_ALL_CONSENT: ConsentState = { ...DEFAULT_CONSENT } diff --git a/src/modules/content/blocksToMarkdown.ts b/src/modules/content/blocksToMarkdown.ts index a8af491..527b3ed 100644 --- a/src/modules/content/blocksToMarkdown.ts +++ b/src/modules/content/blocksToMarkdown.ts @@ -20,7 +20,7 @@ import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js' * }) */ -type Block = Record & { blockType?: string } +type Block = { blockType?: string } & Record type BlockToMarkdown = (block: Block) => string type BlocksToMarkdownArgs = { @@ -32,30 +32,30 @@ const HEADING_KEYS = new Set(['heading', 'title']) const SUBHEADING_KEYS = new Set(['subheading', 'subtitle']) const QUESTION_KEYS = new Set(['question']) const TEXT_KEYS = new Set([ + 'answer', 'body', - 'text', + 'caption', + 'content', 'description', 'excerpt', - 'summary', - 'answer', - 'caption', 'label', - 'content', + 'summary', + 'text', ]) const ARRAY_KEYS = new Set([ - 'items', - 'features', - 'faq', - 'faqs', + 'benefits', 'cards', 'columns', - 'rows', + 'faq', + 'faqs', + 'features', + 'items', + 'list', + 'points', 'questions', + 'rows', 'services', 'steps', - 'points', - 'benefits', - 'list', ]) /** 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`. */ function imageMarkdown(v: unknown): string { - if (!v || typeof v !== 'object') return '' + if (!v || typeof v !== 'object') {return ''} const o = v as Record const url = typeof o.url === 'string' ? o.url : '' const alt = typeof o.alt === 'string' ? o.alt : '' @@ -77,7 +77,7 @@ function extractBlock(block: Block, depth: number): string { const lines: string[] = [] 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()) { lines.push(`## ${value.trim()}`) @@ -87,17 +87,17 @@ function extractBlock(block: Block, depth: number): string { lines.push(`**${value.trim()}**`) } else if (key === 'image') { const img = imageMarkdown(value) - if (img) lines.push(img) + if (img) {lines.push(img)} } else if (isRichText(value)) { 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()) { lines.push(value.trim()) } else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) { for (const item of value) { if (item && typeof item === 'object') { 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()) { lines.push(`- ${item.trim()}`) } @@ -109,23 +109,23 @@ function extractBlock(block: Block, depth: number): string { } export function blocksToMarkdown(layout: unknown, args: BlocksToMarkdownArgs = {}): string { - if (!Array.isArray(layout)) return '' + if (!Array.isArray(layout)) {return ''} const { overrides = {} } = args const out: string[] = [] for (const block of layout) { - if (!block || typeof block !== 'object') continue + if (!block || typeof block !== 'object') {continue} const b = block as Block const type = typeof b.blockType === 'string' ? b.blockType : '' if (type && overrides[type]) { const md = overrides[type](b) - if (md.trim()) out.push(md.trim()) + if (md.trim()) {out.push(md.trim())} continue } 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() diff --git a/src/modules/content/createSearchRoute.ts b/src/modules/content/createSearchRoute.ts index 26ba5cf..3daf5c5 100644 --- a/src/modules/content/createSearchRoute.ts +++ b/src/modules/content/createSearchRoute.ts @@ -1,7 +1,6 @@ import type { BasePayload } from 'payload' import type { I18nConfig } from '../i18n/index.js' - import type { ClientIpOptions } from '../shared/rateLimit.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js' diff --git a/src/modules/content/types.ts b/src/modules/content/types.ts index 99ee850..8c45e49 100644 --- a/src/modules/content/types.ts +++ b/src/modules/content/types.ts @@ -9,12 +9,12 @@ * "Artykuły" to "Wpisy" and the path follows, per locale, with no deploy. */ export type ContentCollectionOption = { - /** Slug of the client's collection, e.g. 'posts'. */ - slug: string /** Admin label for the archive assignment. Defaults to the slug. */ label?: string /** Entries per page in listings. Defaults to 10. */ perPage?: number + /** Slug of the client's collection, e.g. 'posts'. */ + slug: string } /** diff --git a/src/modules/email/mailAdapter.ts b/src/modules/email/mailAdapter.ts index 1758885..adcebff 100644 --- a/src/modules/email/mailAdapter.ts +++ b/src/modules/email/mailAdapter.ts @@ -1,13 +1,14 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' + +import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.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 { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js' type TransportIntegrations = { - /** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */ - emailTransport?: 'smtp' | 'graph' | null emailStatus?: IntegrationStatus | null + /** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */ + emailTransport?: 'graph' | 'smtp' | null } 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) export type MailAdapterArgs = { - smtp?: PanelSmtpAdapterArgs - graph?: GraphAdapterArgs fallbackFromAddress?: string fallbackFromName?: string + graph?: GraphAdapterArgs + smtp?: PanelSmtpAdapterArgs } /** 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) } catch (err) { await recordIntegrationStatus(payload, STATUS_FIELD, previous, { - state: 'degraded', code, message: `${transport}: ${describe(err)}`, + state: 'degraded', }) throw err // callers (form-builder, Send test) still see the failure } // The delegates report failure as { sent: false, error, detail? } instead // 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) { await recordIntegrationStatus(payload, STATUS_FIELD, previous, { - state: 'degraded', code, message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`, + state: 'degraded', }) return result } @@ -120,9 +121,9 @@ export const mailAdapter = previous, graphFallback ? { - state: 'degraded', code: 'graph-unavailable', message: 'Microsoft Graph is selected but not configured on the server — e-mails are sent over SMTP.', + state: 'degraded', } : { state: 'ok' }, ) diff --git a/src/modules/email/panelSmtpAdapter.ts b/src/modules/email/panelSmtpAdapter.ts index d790ba1..6e58637 100644 --- a/src/modules/email/panelSmtpAdapter.ts +++ b/src/modules/email/panelSmtpAdapter.ts @@ -1,14 +1,15 @@ import type { PayloadEmailAdapter, SendEmailOptions } from 'payload' + import { getSiteIntegrations } from '../payload/index.js' /** SMTP fields the adapter reads from SiteIntegrations. */ type SmtpIntegrations = { - smtpHost?: string | null - smtpPort?: number | null - smtpUser?: string | null - smtpPassword?: string | null - smtpFromAddress?: string | null - smtpFromName?: string | null + smtpFromAddress?: null | string + smtpFromName?: null | string + smtpHost?: null | string + smtpPassword?: null | string + smtpPort?: null | number + smtpUser?: null | string } export type PanelSmtpAdapterArgs = { @@ -61,7 +62,7 @@ export const panelSmtpAdapter = payload.logger.error( '[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 @@ -83,10 +84,10 @@ export const panelSmtpAdapter = const { default: nodemailer } = await import('nodemailer') const transporter = nodemailer.createTransport({ + auth: { pass, user }, host, port, secure: port === 465, // implicit TLS on 465, STARTTLS otherwise - auth: { user, pass }, }) try { @@ -95,13 +96,13 @@ export const panelSmtpAdapter = from, ...(message.subject ? { subject: stripCRLF(message.subject) } : {}), }) - return { sent: true, messageId: info.messageId } + return { messageId: info.messageId, sent: true } } catch (err) { // Never surface SMTP internals to the caller — a form submission // shouldn't fail loudly because the mailbox is misconfigured. payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`) // `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 } } }, }) diff --git a/src/modules/env/index.ts b/src/modules/env/index.ts index 9b4b7c2..3ad7ab5 100644 --- a/src/modules/env/index.ts +++ b/src/modules/env/index.ts @@ -1,4 +1,4 @@ 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 type { IpalEnvFeatures } from './ipalEnvRules.js' diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index c0376dd..fc85b9e 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -1,5 +1,7 @@ -import { formBuilderPlugin } from '@payloadcms/plugin-form-builder' import type { Plugin } from 'payload' + +import { formBuilderPlugin } from '@payloadcms/plugin-form-builder' + import type { FormsOption } from './types.js' /** 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 } : {} return formBuilderPlugin({ fields: { + checkbox: true, + email: true, + message: true, + number: true, + payment: false, + select: true, text: true, textarea: true, - email: true, - number: true, - select: true, - checkbox: true, - message: true, - payment: false, ...forms.fields, }, ...(forms.redirectRelationships @@ -43,18 +45,18 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { // Tidy panel by default: both collections under one sidebar group with plain // labels — no per-project overrides needed just to sort the sidebar. formOverrides: { - labels: { singular: 'Form', plural: 'Forms' }, + labels: { plural: 'Forms', singular: 'Form' }, ...forms.formOverrides, admin: { ...group, ...forms.formOverrides?.admin }, }, formSubmissionOverrides: { - labels: { singular: 'Submission', plural: 'Submissions' }, + labels: { plural: 'Submissions', singular: 'Submission' }, ...forms.formSubmissionOverrides, - admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin }, access: { create: submissionsCreateAccess, ...forms.formSubmissionOverrides?.access, }, + admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin }, }, }) } diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index 45eb902..18ccf46 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -1,22 +1,22 @@ import 'server-only' + import type { BasePayload } from 'payload' + import { getTurnstileConfig } from '../turnstile/config.js' import { verifyTurnstile } from '../turnstile/verify.js' -import { validateSubmission } from './validateSubmission.js' import { consumeRateLimit } from './rateLimit.js' +import { validateSubmission } from './validateSubmission.js' export type SubmitFormArgs = { - payload: BasePayload - /** Form-builder form ID this submission belongs to. */ - formId: string + /** + * 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 /** Submitted field data — shape matches the form's fields. */ data: Record - /** - * 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 + /** Form-builder form ID this submission belongs to. */ + formId: string /** Client IP — used for Turnstile and rate limiting. */ ip?: string /** @@ -24,17 +24,19 @@ export type SubmitFormArgs = { * Set to 0 to disable (e.g. when a real limiter sits in front). */ maxPerMinute?: number - /** - * 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 + payload: BasePayload /** * Turnstile can't be verified because of OUR side (missing/wrong secret, * Cloudflare unreachable): 'allow' (default) accepts the submission and shows * the problem in the panel; 'reject' refuses it. */ 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 */ 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. */ field?: string /** What was wrong with it. */ kind?: 'required' | 'too_long' | 'unknown_fields' - } - | { success: false; reason: 'not_found' } - | { + reason: 'validation' success: false + } + | { + field?: string /** A GDPR consent field existed on the form but wasn't checked. */ 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 @@ -90,19 +92,19 @@ export type SubmitFormResult = SubmitFailure | { success: true; submissionId: st * server-only: touches the Turnstile secret. */ export async function submitForm({ - payload, - formId, + consentFieldName, data, - turnstileToken, + formId, ip, maxPerMinute = 5, - consentFieldName, + payload, turnstileOnConfigError = 'allow', + turnstileToken, }: SubmitFormArgs): Promise { // 1. Rate limit — cheapest gate, drops a flood before any real work. if (maxPerMinute > 0 && ip) { 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) { const ok = Boolean(turnstileToken) && - (await verifyTurnstile({ token: turnstileToken!, payload, ip, onConfigError: turnstileOnConfigError })) + (await verifyTurnstile({ ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! })) 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) if (!validation.ok) { if (validation.reason === 'not_found') { - return { success: false, reason: 'not_found' } + return { reason: 'not_found', success: false } } if (validation.reason === 'consent') { - return { success: false, reason: 'consent', field: validation.field } + return { field: validation.field, reason: 'consent', success: false } } return { - success: false, reason: 'validation', + success: false, ...(validation.field ? { field: validation.field } : {}), ...(validation.kind ? { kind: validation.kind } : {}), } @@ -149,9 +151,9 @@ export async function submitForm({ })), } as never, }) - return { success: true, submissionId: submission.id } + return { submissionId: submission.id, success: true } } catch (err) { payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`) - return { success: false, reason: 'error' } + return { reason: 'error', success: false } } } diff --git a/src/modules/forms/types.ts b/src/modules/forms/types.ts index 2fe1540..6e0b82b 100644 --- a/src/modules/forms/types.ts +++ b/src/modules/forms/types.ts @@ -19,25 +19,29 @@ export type FormsCollectionOverrides = { * form-builder plugin. Kept minimal; the plugin passes these through. */ export type FormsOption = { - /** Field types available in the form builder. Sensible defaults applied. */ - fields?: { - text?: boolean - textarea?: boolean - email?: boolean - number?: boolean - select?: boolean - checkbox?: boolean - message?: boolean - payment?: boolean - } - /** Collections a form can redirect to (e.g. ['pages']). */ - redirectRelationships?: string[] + /** + * Admin sidebar group for Forms + Form Submissions. Default 'Forms'. + * `false` = Payload default ("Collections"). An explicit `admin.group` in + * formOverrides / formSubmissionOverrides still wins. + */ + adminGroup?: false | string /** * 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 * server-side in submitForm. Defaults to 'consent'. */ 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 * form needs beyond its fields — a client that wants, say, a per-form @@ -53,10 +57,6 @@ export type FormsOption = { formOverrides?: FormsCollectionOverrides /** Override the form-submissions collection (same shape). */ formSubmissionOverrides?: FormsCollectionOverrides - /** - * Admin sidebar group for Forms + Form Submissions. Default 'Forms'. - * `false` = Payload default ("Collections"). An explicit `admin.group` in - * formOverrides / formSubmissionOverrides still wins. - */ - adminGroup?: string | false + /** Collections a form can redirect to (e.g. ['pages']). */ + redirectRelationships?: string[] } diff --git a/src/modules/forms/validators.ts b/src/modules/forms/validators.ts index 115b2a8..f78eb9f 100644 --- a/src/modules/forms/validators.ts +++ b/src/modules/forms/validators.ts @@ -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. */ -export type Rule = (value: unknown, values: Record) => true | string +export type Rule = (value: unknown, values: Record) => 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. */ 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 = (msg = 'required'): Rule => (v) => { - if (v == null) return msg - if (typeof v === 'string' && !v.trim()) return msg - if (v === false) return msg + if (v == null) {return msg} + if (typeof v === 'string' && !v.trim()) {return msg} + if (v === false) {return msg} return true } @@ -86,7 +86,7 @@ export function buildValidator>( const all = values as Record for (const key in schema) { const rules = schema[key as keyof T] - if (!rules || rules.length === 0) continue + if (!rules || rules.length === 0) {continue} for (const rule of rules) { const res = rule(all[key], all) if (res !== true) { diff --git a/src/modules/i18n/localeMiddleware.ts b/src/modules/i18n/localeMiddleware.ts index 11f9458..05d58b7 100644 --- a/src/modules/i18n/localeMiddleware.ts +++ b/src/modules/i18n/localeMiddleware.ts @@ -1,15 +1,16 @@ 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 { isValidLocale, LOCALE_COOKIE_NAME, negotiateLocale } from '../i18n/index.js' /** * 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. */ type MiddlewareRequest = { - nextUrl: { pathname: string; search: string; clone: () => URL } 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 } @@ -19,13 +20,11 @@ type MiddlewareRequest = { * `next` means let the request pass through untouched. */ export type LocaleMiddlewareResult = - | { type: 'next'; cookie?: { name: string; value: string } } - | { type: 'redirect'; location: string; cookie?: { name: string; value: string } } + | { cookie?: { name: string; value: string }; location: string; type: 'redirect' } + | { cookie?: { name: string; value: string }; type: 'next' } type CreateLocaleMiddlewareArgs = { 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 * 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 * necessary), which restores the pre-consent behaviour. */ - consentCategory?: 'necessary' | 'functional' + consentCategory?: 'functional' | 'necessary' /** Name of the consent cookie to read. Defaults to CONSENT_COOKIE. */ 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({ config, - cookieName = LOCALE_COOKIE_NAME, consentCategory = 'functional', consentCookieName = CONSENT_COOKIE, + cookieName = LOCALE_COOKIE_NAME, }: CreateLocaleMiddlewareArgs) { // Whether the locale cookie may be written: 'necessary' is always granted; // 'functional' (default) requires the visitor to have consented. function mayPersistLocale(request: MiddlewareRequest): boolean { - if (consentCategory === 'necessary') return true + if (consentCategory === 'necessary') {return true} const consent = parseConsent(request.cookies.get(consentCookieName)?.value) return consent?.[consentCategory] === true } @@ -116,9 +117,9 @@ export function createLocaleMiddleware({ // Resolve the locale to use const locale = negotiateLocale({ - cookieLocale: request.cookies.get(cookieName)?.value ?? null, acceptLanguage: request.headers.get('accept-language'), config, + cookieLocale: request.cookies.get(cookieName)?.value ?? null, }) // Redirect to the locale-prefixed path, preserving the rest diff --git a/src/modules/i18n/localizedPath.ts b/src/modules/i18n/localizedPath.ts index 5b7113e..3c568e5 100644 --- a/src/modules/i18n/localizedPath.ts +++ b/src/modules/i18n/localizedPath.ts @@ -1,4 +1,5 @@ import type { I18nConfig } from './types.js' + import { isValidLocale } from './helpers.js' /** @@ -11,10 +12,6 @@ import { isValidLocale } from './helpers.js' export type LocalizedSlugs = Record 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 /** * 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 * un-collapsed, breaking hreflang return tags (a real GSC error). */ - homeSlug?: string | Record + homeSlug?: Record | string + /** Target locale to build the path for */ + locale: string /** * Localized segment the document lives under, e.g. * `{ 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. */ prefix?: LocalizedSlugs + /** slug per locale, e.g. { pl: 'strona-glowna', en: 'home' } */ + slugs: LocalizedSlugs } /** @@ -61,11 +62,11 @@ type BuildPathArgs = { * // → '/en/articles/my-post' */ export function buildLocalizedPath({ - slugs, - locale, config, homeSlug = 'home', + locale, prefix, + slugs, }: BuildPathArgs): string | undefined { if (!isValidLocale(locale, config)) { return undefined @@ -109,11 +110,11 @@ export function buildLocalizedPath({ } type SwitchLocaleArgs = { + config: I18nConfig + homeSlug?: Record | string + prefix?: LocalizedSlugs slugs: LocalizedSlugs targetLocale: string - config: I18nConfig - homeSlug?: string | Record - prefix?: LocalizedSlugs } /** @@ -125,17 +126,17 @@ type SwitchLocaleArgs = { * to the locale root otherwise — the closest place the visitor would want. */ export function switchLocalePath({ - slugs, - targetLocale, config, homeSlug = 'home', prefix, + slugs, + targetLocale, }: SwitchLocaleArgs): string { - const path = buildLocalizedPath({ slugs, locale: targetLocale, config, homeSlug, prefix }) - if (path) return path + const path = buildLocalizedPath({ config, homeSlug, locale: targetLocale, prefix, slugs }) + if (path) {return path} const archiveSegment = prefix?.[targetLocale] - if (archiveSegment) return `/${targetLocale}/${archiveSegment}` + if (archiveSegment) {return `/${targetLocale}/${archiveSegment}`} return `/${targetLocale}` } diff --git a/src/modules/i18n/validation.ts b/src/modules/i18n/validation.ts index f2a0786..6eab6fa 100644 --- a/src/modules/i18n/validation.ts +++ b/src/modules/i18n/validation.ts @@ -1,6 +1,6 @@ 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. diff --git a/src/modules/integrations/IntegrationAlerts.tsx b/src/modules/integrations/IntegrationAlerts.tsx index b40134e..55bbb11 100644 --- a/src/modules/integrations/IntegrationAlerts.tsx +++ b/src/modules/integrations/IntegrationAlerts.tsx @@ -1,13 +1,14 @@ import type { Payload } from 'payload' + import type { IntegrationStatus } from './status.js' type Props = { - /** Injected by Payload into admin server components. */ - payload?: Payload - /** Status groups to check: field name → label. */ - checks?: Record /** Admin route, for the link. Default '/admin'. */ adminRoute?: string + /** Status groups to check: field name → label. */ + checks?: Record + /** 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 * everything is fine — and never throws (DB not ready → nothing). */ -export async function IntegrationAlerts({ payload, checks = { turnstileStatus: 'Turnstile', emailStatus: 'Email' }, adminRoute = '/admin' }: Props) { - if (!payload) return null +export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emailStatus: 'Email', turnstileStatus: 'Turnstile' }, payload }: Props) { + if (!payload) {return null} let doc: Record try { doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record @@ -26,17 +27,17 @@ export async function IntegrationAlerts({ payload, checks = { turnstileStatus: ' const failing = Object.entries(checks) .map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined })) .filter((x) => x.status?.state === 'degraded') - if (!failing.length) return null + if (!failing.length) {return null} return (
Integration problem — the site still works, but something needs attention. diff --git a/src/modules/integrations/IntegrationStatusBanner.tsx b/src/modules/integrations/IntegrationStatusBanner.tsx index 08e0ec6..9e0ff18 100644 --- a/src/modules/integrations/IntegrationStatusBanner.tsx +++ b/src/modules/integrations/IntegrationStatusBanner.tsx @@ -2,14 +2,14 @@ import { useFormFields } from '@payloadcms/ui' type Props = { - /** Name of the hidden status group (buildIntegrationStatusField). */ - statusField: string /** Integration name shown in the banner, e.g. 'Turnstile'. */ label: string + /** Name of the hidden status group (buildIntegrationStatusField). */ + statusField: string } const fmt = (iso: unknown) => { - if (typeof iso !== 'string' || !iso) return '' + if (typeof iso !== 'string' || !iso) {return ''} const d = new Date(iso) 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 * 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 message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined const since = useFormFields(([f]) => f[`${statusField}.since`]?.value) const checkedAt = useFormFields(([f]) => f[`${statusField}.checkedAt`]?.value) - if (!state) return null + if (!state) {return null} if (state === 'ok') { return ( -
+
✓ {label} working{since ? ` since ${fmt(since)}` : ''}.
) @@ -40,21 +40,21 @@ export function IntegrationStatusBanner({ statusField, label }: Props) {
{label} is not working — forms are accepted without this check. {message ?
{message}
: null} -
+
{code ? `Code: ${code}. ` : ''} {since ? `Since ${fmt(since)}. ` : ''} {checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}
-
+
Fix the keys below and save — the status is checked again on the next form submission.
diff --git a/src/modules/integrations/index.ts b/src/modules/integrations/index.ts index 3866ef6..b84f1b0 100644 --- a/src/modules/integrations/index.ts +++ b/src/modules/integrations/index.ts @@ -1,6 +1,6 @@ export { - recordIntegrationStatus, - buildIntegrationStatusField, buildIntegrationStatusBanner, + buildIntegrationStatusField, + recordIntegrationStatus, } from './status.js' -export type { IntegrationStatus, IntegrationState } from './status.js' +export type { IntegrationState, IntegrationStatus } from './status.js' diff --git a/src/modules/integrations/status.ts b/src/modules/integrations/status.ts index 0f7e938..601c90d 100644 --- a/src/modules/integrations/status.ts +++ b/src/modules/integrations/status.ts @@ -12,18 +12,18 @@ import type { BasePayload, Field } from 'payload' * busy form doesn't turn every submission into a DB write. */ -export type IntegrationState = 'ok' | 'degraded' +export type IntegrationState = 'degraded' | 'ok' 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). */ - 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 @@ -53,8 +53,8 @@ export function buildIntegrationStatusBanner(statusField: string, label: string) admin: { components: { Field: { + clientProps: { label, statusField }, path: '@intecion/ipal-kit/client#IntegrationStatusBanner', - clientProps: { statusField, label }, }, }, }, @@ -69,7 +69,7 @@ export async function recordIntegrationStatus( payload: BasePayload, field: string, previous: IntegrationStatus | null | undefined, - next: { state: IntegrationState; code?: string; message?: string }, + next: { code?: string; message?: string; state: IntegrationState }, ): Promise { const now = new Date() 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) // Healthy and already recorded as healthy (or never recorded) → nothing to do. - if (!changed && !stale) return - if (next.state === 'ok' && !previous?.state) return + if (!changed && !stale) {return} + if (next.state === 'ok' && !previous?.state) {return} const status: IntegrationStatus = { - state: next.state, + checkedAt: now.toISOString(), code: next.code ?? null, message: next.message ?? null, since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()), - checkedAt: now.toISOString(), + state: next.state, } try { await payload.updateGlobal({ slug: SITE_INTEGRATIONS as never, + context: { ipalIntegrationStatus: true }, data: { [field]: status } as never, depth: 0, - context: { ipalIntegrationStatus: true }, }) } catch (err) { console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err) diff --git a/src/modules/mcp/createMcpRoute.ts b/src/modules/mcp/createMcpRoute.ts index 42195d7..8e5e19f 100644 --- a/src/modules/mcp/createMcpRoute.ts +++ b/src/modules/mcp/createMcpRoute.ts @@ -2,11 +2,10 @@ import type { BasePayload } from 'payload' import type { ContentOption } from '../content/index.js' import type { I18nConfig } from '../i18n/index.js' +import type { ClientIpOptions } from '../shared/rateLimit.js' import { createMarkdownRenderer, searchContent } from '../content/index.js' import { getDefaultLocale, isValidLocale } from '../i18n/index.js' -import type { ClientIpOptions } 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. - async function GET(): Promise { - return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', { - headers: { allow: 'POST' }, - status: 405, - }) + function GET(): Promise { + return Promise.resolve( + new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', { + headers: { allow: 'POST' }, + status: 405, + }), + ) } return { GET, POST } diff --git a/src/modules/media/normalizeFilename.ts b/src/modules/media/normalizeFilename.ts index c56cd43..0c3babd 100644 --- a/src/modules/media/normalizeFilename.ts +++ b/src/modules/media/normalizeFilename.ts @@ -1,4 +1,5 @@ import type { CollectionBeforeOperationHook } from 'payload' + import slugify from 'slugify' /** @@ -44,8 +45,8 @@ export function normalizeFilename(filename: string): string { * import { normalizeFilenameHook } from '@intecion/ipal-kit' * hooks: { beforeOperation: [normalizeFilenameHook] } */ -export const normalizeFilenameHook: CollectionBeforeOperationHook = ({ req, operation }) => { - if (operation !== 'create' && operation !== 'update') return +export const normalizeFilenameHook: CollectionBeforeOperationHook = ({ operation, req }) => { + if (operation !== 'create' && operation !== 'update') {return} const file = req.file if (file?.name) { file.name = normalizeFilename(file.name) diff --git a/src/modules/notifications/defaults.ts b/src/modules/notifications/defaults.ts index 9a9faac..21bbdd6 100644 --- a/src/modules/notifications/defaults.ts +++ b/src/modules/notifications/defaults.ts @@ -7,12 +7,12 @@ import type { NotificationTexts } from './types.js' */ export const NOTIFICATION_FALLBACK: NotificationTexts = { 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.', + notFound: 'This form is no longer available.', 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.', validation: 'Please check the {field} field and try again.', - consent: 'Please accept the privacy policy to continue.', - notFound: 'This form is no longer available.', }, } diff --git a/src/modules/notifications/types.ts b/src/modules/notifications/types.ts index c6f0666..6ff7def 100644 --- a/src/modules/notifications/types.ts +++ b/src/modules/notifications/types.ts @@ -3,15 +3,15 @@ * `form` maps submitForm result codes to user-facing messages. */ export type FormNotificationTexts = { - success: string + /** Shown when a required GDPR consent checkbox was left unchecked. */ + consent: string error: string + notFound: string rateLimited: string + success: string turnstile: string /** May contain the {field} placeholder — resolve with resolveValidationText. */ validation: string - /** Shown when a required GDPR consent checkbox was left unchecked. */ - consent: string - notFound: string } export type NotificationTexts = { diff --git a/src/modules/pages/getSystemPagePath.ts b/src/modules/pages/getSystemPagePath.ts index 0412c83..01a6d40 100644 --- a/src/modules/pages/getSystemPagePath.ts +++ b/src/modules/pages/getSystemPagePath.ts @@ -21,7 +21,7 @@ type GetSystemPagePathArgs = { * page's slug in the target locale equals this, the path collapses to the * locale root (/pl, /en). */ - homeSlug?: string | Record + homeSlug?: Record | string /** Target locale to build the path for. */ locale: string /** diff --git a/src/modules/seo/buildArticleJsonLd.ts b/src/modules/seo/buildArticleJsonLd.ts index 2669c0b..e0b67aa 100644 --- a/src/modules/seo/buildArticleJsonLd.ts +++ b/src/modules/seo/buildArticleJsonLd.ts @@ -1,25 +1,25 @@ -type MediaLike = { url?: string | null } | null | undefined +type MediaLike = { url?: null | string } | null | undefined 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?: string - /** Publisher (usually the site/organization) name. */ - publisherName?: string + /** ISO date of the last modification. Defaults to datePublished. */ + 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). */ publisherLogo?: MediaLike + /** Publisher (usually the site/organization) name. */ + publisherName?: string /** 'Article' (default), 'BlogPosting', or '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. */ export function buildArticleJsonLd({ - headline, - url, - description, - image, - datePublished, - dateModified, - author, - publisherName, - publisherLogo, type = 'Article', + author, + dateModified, + datePublished, + description, + headline, + image, + publisherLogo, + publisherName, + url, }: ArticleJsonLdArgs) { const imageUrl = image?.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 return { '@context': 'https://schema.org', '@type': type, headline, + mainEntityOfPage: { '@id': url, '@type': 'WebPage' }, url, - mainEntityOfPage: { '@type': 'WebPage', '@id': url }, ...(description ? { description } : {}), ...(imageUrl ? { image: abs(imageUrl) } : {}), ...(datePublished ? { datePublished } : {}), ...(dateModified || datePublished ? { dateModified: dateModified ?? datePublished } : {}), - ...(author ? { author: { '@type': 'Person', name: author } } : {}), + ...(author ? { author: { name: author, '@type': 'Person' } } : {}), ...(publisherName ? { publisher: { - '@type': 'Organization', name: publisherName, + '@type': 'Organization', ...(logoUrl ? { logo: { '@type': 'ImageObject', url: abs(logoUrl) } } : {}), }, } diff --git a/src/modules/seo/buildSitemapXml.ts b/src/modules/seo/buildSitemapXml.ts index a9648a6..d1eaaab 100644 --- a/src/modules/seo/buildSitemapXml.ts +++ b/src/modules/seo/buildSitemapXml.ts @@ -65,8 +65,8 @@ export function buildSitemapXml( e.lastModified instanceof Date ? e.lastModified.toISOString() : String(e.lastModified) parts.push(` ${esc(iso)}`) } - if (e.changeFrequency) parts.push(` ${e.changeFrequency}`) - if (typeof e.priority === 'number') parts.push(` ${e.priority}`) + if (e.changeFrequency) {parts.push(` ${e.changeFrequency}`)} + if (typeof e.priority === 'number') {parts.push(` ${e.priority}`)} const alternates = e.alternates?.languages if (alternates) { for (const [lang, href] of Object.entries(alternates)) { diff --git a/src/modules/seo/composeTitle.ts b/src/modules/seo/composeTitle.ts index c36e971..c6bf207 100644 --- a/src/modules/seo/composeTitle.ts +++ b/src/modules/seo/composeTitle.ts @@ -2,14 +2,14 @@ export type TitleOrder = 'page-first' | 'site-first' 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. */ 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. */ export function composeTitle({ - pageTitle, - siteName, - separator = ' | ', order = 'page-first', + pageTitle, + separator = ' | ', + siteName, }: ComposeTitleArgs): string { const page = pageTitle?.trim() const site = siteName?.trim() diff --git a/src/modules/seo/createMetadataGenerator.ts b/src/modules/seo/createMetadataGenerator.ts index 12da11b..faee99c 100644 --- a/src/modules/seo/createMetadataGenerator.ts +++ b/src/modules/seo/createMetadataGenerator.ts @@ -20,7 +20,7 @@ type CreateMetadataGeneratorArgs = { baseUrl?: string config: I18nConfig /** Home slug that collapses to the locale root. Defaults to 'home'. */ - homeSlug?: string | Record + homeSlug?: Record | string /** * Resolves the document to build metadata for, given route params. * The client supplies this (they own the collections and routing); it should diff --git a/src/modules/seo/hreflang.ts b/src/modules/seo/hreflang.ts index 852d7cc..77703de 100644 --- a/src/modules/seo/hreflang.ts +++ b/src/modules/seo/hreflang.ts @@ -1,20 +1,21 @@ import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js' + import { buildLocalizedPath, getLocaleCodes } from '../i18n/index.js' 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. */ baseUrl?: string + config: I18nConfig /** Home slug that collapses to the locale root. Defaults to 'home'. */ - homeSlug?: string | Record + homeSlug?: Record | string /** * Localized segment the document lives under (an archive page's slugs), * 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. */ 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' } */ export function buildHreflangAlternates({ - slugs, - config, baseUrl, + config, homeSlug = 'home', prefix, + slugs, }: BuildHreflangArgs): Record { const origin = baseUrl?.replace(/\/$/, '') ?? '' const alternates: Record = {} @@ -52,7 +53,7 @@ export function buildHreflangAlternates({ } for (const locale of getLocaleCodes(config)) { - const path = buildLocalizedPath({ slugs, locale, config, homeSlug, prefix }) + const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs }) if (path) { alternates[locale] = `${origin}${path}` } diff --git a/src/modules/seo/index.ts b/src/modules/seo/index.ts index 249ae4b..23bb361 100644 --- a/src/modules/seo/index.ts +++ b/src/modules/seo/index.ts @@ -1,41 +1,41 @@ -export type { SeoOption, SeoMeta } from './types.js' -export { composeTitle } from './composeTitle.js' -export type { TitleOrder } from './composeTitle.js' -export { buildHreflangAlternates } from './hreflang.js' +export { buildAutoFillMetaHook } from './autoFillMeta.js' +export type { AutoFillMapping } from './autoFillMeta.js' +export { buildArticleJsonLd } from './buildArticleJsonLd.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 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 { 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 { buildSummaryField } from './buildSummaryField.js' export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js' -export { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js' -export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js' -export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js' -export { buildFaqJsonLd } from './buildFaqJsonLd.js' -export { buildServiceJsonLd } from './buildServiceJsonLd.js' -export { buildArticleJsonLd } from './buildArticleJsonLd.js' -export { buildLlmsTxt } from './buildLlmsTxt.js' +export { composeTitle } from './composeTitle.js' +export type { TitleOrder } from './composeTitle.js' +export { createMetadataGenerator } from './createMetadataGenerator.js' +export { createPageMetadata } from './createPageMetadata.js' +export { buildHreflangAlternates } from './hreflang.js' +export { injectAutoFillMeta } from './injectAutoFillMeta.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 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 { createManifestHandler } from './buildManifest.js' -export { JsonLdGraph } from './JsonLdGraph.js' +export { slugsAcrossLocales } from './slugsAcrossLocales.js' +export type { SeoMeta, SeoOption } from './types.js' +export { validateFaviconField } from './validateFavicon.js' diff --git a/src/modules/turnstile/TurnstileProvider.tsx b/src/modules/turnstile/TurnstileProvider.tsx index 8ec7bad..9a56edd 100644 --- a/src/modules/turnstile/TurnstileProvider.tsx +++ b/src/modules/turnstile/TurnstileProvider.tsx @@ -1,17 +1,18 @@ 'use client' -import { createContext, useCallback, useContext, useState } from 'react' +import { createContext, use, useCallback, useState } from 'react' + import { Turnstile } from './Turnstile.js' type TurnstileContextValue = { + setToken: (t: null | string) => void /** Public site key from the provider (read server-side, passed once). */ - siteKey: string | null + siteKey: null | string /** Current token (null until solved / after expiry). */ - token: string | null - setToken: (t: string | null) => void + token: null | string } -const TurnstileContext = createContext(null) +const TurnstileContext = createContext(null) /** * Provides the Turnstile site key once for the whole app, like ConsentProvider @@ -29,17 +30,17 @@ const TurnstileContext = createContext(null) * token stays null — submitForm skips the check too, so the form just works. */ export function TurnstileProvider({ - siteKey, children, + siteKey, }: { - siteKey: string | null children: React.ReactNode + siteKey: null | string }) { - const [token, setToken] = useState(null) + const [token, setToken] = useState(null) return ( - + {children} - + ) } @@ -53,27 +54,27 @@ export function TurnstileProvider({ * // after submit: reset() // clear for the next submission */ export function useTurnstile(): { - token: string | null - TurnstileWidget: (props?: { theme?: 'light' | 'dark' | 'auto' }) => React.ReactNode - reset: () => void /** True when Turnstile is configured (site key present). */ 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) { throw new Error('useTurnstile must be used within ') } - const { siteKey, token, setToken } = ctx + const { setToken, siteKey, token } = ctx const reset = useCallback(() => setToken(null), [setToken]) const TurnstileWidget = useCallback( - (props?: { theme?: 'light' | 'dark' | 'auto' }) => { - if (!siteKey) return null - return + (props?: { theme?: 'auto' | 'dark' | 'light' }) => { + if (!siteKey) {return null} + return }, [siteKey, setToken], ) - return { token, TurnstileWidget, reset, enabled: Boolean(siteKey) } + return { enabled: Boolean(siteKey), reset, token, TurnstileWidget } } diff --git a/src/modules/turnstile/index.ts b/src/modules/turnstile/index.ts index 72eaa21..956f83b 100644 --- a/src/modules/turnstile/index.ts +++ b/src/modules/turnstile/index.ts @@ -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 type { TurnstileConfig } from './config.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' diff --git a/src/modules/turnstile/verify.ts b/src/modules/turnstile/verify.ts index 6de4359..8a6b38d 100644 --- a/src/modules/turnstile/verify.ts +++ b/src/modules/turnstile/verify.ts @@ -1,34 +1,26 @@ import 'server-only' + import type { BasePayload } from 'payload' + +import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.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' type SiteverifyResponse = { - success: boolean - 'error-codes'?: string[] challenge_ts?: string + 'error-codes'?: string[] hostname?: string + success: boolean } type IntegrationsWithTurnstile = { - turnstileSecretKey?: string | null + turnstileSecretKey?: null | string turnstileStatus?: IntegrationStatus | null } 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`. */ 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 * secret, Cloudflare unreachable). 'allow' (default): accept the submission — @@ -36,6 +28,16 @@ type VerifyTurnstileArgs = { * the panel. 'reject': refuse (fail closed). */ 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' @@ -47,20 +49,20 @@ const STATUS_FIELD = 'turnstileStatus' * erroring) → the visitor can't fix it; by default the submission * is accepted and the panel shows the problem. */ -export type TurnstileOutcome = 'pass' | 'reject' | 'degraded' -export type TurnstileCheck = { outcome: TurnstileOutcome; code?: string } +export type TurnstileOutcome = 'degraded' | 'pass' | 'reject' +export type TurnstileCheck = { code?: string; outcome: TurnstileOutcome } /** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */ const CONFIG_ERRORS: Record = { - 'missing-input-secret': 'The secret key is missing in the request.', + 'internal-error': 'Cloudflare reported an internal error while verifying.', 'invalid-input-secret': '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 = { + 'bad-response': 'Cloudflare returned an unexpected response.', '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).', - 'bad-response': 'Cloudflare returned an unexpected response.', } /** @@ -71,12 +73,12 @@ const PLUGIN_ERRORS: Record = { * SiteIntegrations is updated (throttled) so the panel shows failures. */ export async function checkTurnstile({ - token, - payload, ip, + payload, sendRemoteIp = false, + token, }: Omit): Promise { - if (!token) return { outcome: 'reject', code: 'missing-input-response' } + if (!token) {return { code: 'missing-input-response', outcome: 'reject' }} const integrations = await getSiteIntegrations(payload) const previous = integrations[STATUS_FIELD] @@ -85,29 +87,29 @@ export async function checkTurnstile({ const degraded = async (code: string): Promise => { const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}` console.warn(`[ipal] Turnstile degraded (${code}): ${message}`) - await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'degraded', code, message }) - return { outcome: 'degraded', code } + await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, message, state: 'degraded' }) + return { code, outcome: 'degraded' } } - if (!secret) return degraded('missing-secret') + if (!secret) {return degraded('missing-secret')} - const body = new URLSearchParams({ secret, response: token }) - if (sendRemoteIp && ip) body.append('remoteip', ip) + const body = new URLSearchParams({ response: token, secret }) + if (sendRemoteIp && ip) {body.append('remoteip', ip)} let data: SiteverifyResponse try { const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { - method: 'POST', body, + method: 'POST', 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 } catch (err) { console.warn('[ipal] Turnstile: siteverify request failed:', err instanceof Error ? err.message : err) 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) { await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' }) @@ -116,11 +118,11 @@ export async function checkTurnstile({ const codes = data['error-codes'] ?? [] 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. 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' } } /** diff --git a/src/plugin.ts b/src/plugin.ts index 26d91f8..6e0d162 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1,17 +1,18 @@ import type { Config, Plugin } from 'payload' 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 { 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 { 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. @@ -123,8 +124,8 @@ export const ipalKit = (options: IpalOptions): Plugin => { if (options.whiteLabel) { const wl = options.whiteLabel === true ? {} : options.whiteLabel const serverProps: Record = {} - if (wl.settingsSlug) serverProps.settingsSlug = wl.settingsSlug - if (wl.nameField) serverProps.nameField = wl.nameField + if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug} + if (wl.nameField) {serverProps.nameField = wl.nameField} const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) } const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) } @@ -145,18 +146,11 @@ export const ipalKit = (options: IpalOptions): Plugin => { ...(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 }, + Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps }, }, ...(creditOn ? { - afterNavLinks: [ - ...(config.admin?.components?.afterNavLinks ?? []), - { - path: '@intecion/ipal-kit/admin#IntecionCredit', - serverProps: { ...creditProps, variant: 'nav' }, - }, - ], afterLogin: [ ...(config.admin?.components?.afterLogin ?? []), { @@ -164,6 +158,13 @@ export const ipalKit = (options: IpalOptions): Plugin => { 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 ?? []), buildSiteSettings({ - systemPageFields, additionalFields: options.siteSettingsFields, + systemPageFields, }), buildSiteIntegrations({ additionalFields: options.integrationsFields }), buildCookieSettings(), @@ -244,7 +245,7 @@ export const ipalKit = (options: IpalOptions): Plugin => { // --- hooks: onInit --- const incomingOnInit = config.onInit config.onInit = async (payload) => { - if (incomingOnInit) await incomingOnInit(payload) + if (incomingOnInit) {await incomingOnInit(payload)} payload.logger.info('[ipal] Plugin initialized.') } diff --git a/test/i18n.test.ts b/test/i18n.test.ts index f6fc6f8..a215d7c 100644 --- a/test/i18n.test.ts +++ b/test/i18n.test.ts @@ -1,17 +1,20 @@ 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 { matchAcceptLanguage, negotiateLocale } from '../src/modules/i18n/negotiateLocale.js' -import { isHoneypotTripped } from '../src/modules/forms/honeypot.js' -const config = { +const config: I18nConfig = { defaultLocale: 'pl', locales: [ { code: 'pl', label: 'Polski' }, { 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', () => { test('cookie → Accept-Language → default', () => { @@ -58,7 +61,7 @@ describe('buildLocalizedPath', () => { describe('switchLocalePath', () => { 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', ) expect(switchLocalePath({ config, slugs: { pl: 'o-nas' }, targetLocale: 'en' })).toBe('/en') @@ -72,3 +75,14 @@ describe('honeypot', () => { expect(isHoneypotTripped({})).toBe(false) }) }) + +describe('isEmail', () => { + test('accepts real addresses, rejects malformed ones', () => { + for (const ok of ['a@b.co', 'jan.kowalski@mail.example.com', 'x+tag@sub.domain.pl']) { + expect(isEmail(ok)).toBe(true) + } + for (const bad of ['', 'a', 'a@b', 'a b@c.pl', 'a@b c.pl', '@b.pl', 'a@.pl', 'a@@b.pl']) { + expect(isEmail(bad)).toBe(false) + } + }) +}) diff --git a/test/plugin.test.ts b/test/plugin.test.ts index dece15a..fcefcae 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -2,9 +2,11 @@ import type { Config } from 'payload' import { describe, expect, test, vi } from 'vitest' +import type { I18nConfig } from '../src/modules/i18n/types.js' + import { ipalKit } from '../src/plugin.js' -const i18n = { +const i18n: I18nConfig = { defaultLocale: 'pl', locales: [ { code: 'pl', label: 'Polski' }, diff --git a/test/submitForm.test.ts b/test/submitForm.test.ts index d8d51db..68a5c15 100644 --- a/test/submitForm.test.ts +++ b/test/submitForm.test.ts @@ -14,7 +14,7 @@ const forms = { ], }, } -const data = { consent: true, name: 'Ala' } +const data = { name: 'Ala', consent: true } const keys = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' } let ipCounter = 0 diff --git a/test/tsconfig.json b/test/tsconfig.json new file mode 100644 index 0000000..2b970b2 --- /dev/null +++ b/test/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "composite": false, + "incremental": false, + "noEmit": true, + "emitDeclarationOnly": false, + "rootDir": ".." + }, + "include": ["./**/*.ts", "../src/**/*.ts", "../src/**/*.tsx"] +}