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

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-15 23:56:18 +02:00
co-authored by Claude Opus 5.5
parent ce0a390351
commit 4544cac69c
48 changed files with 642 additions and 589 deletions
+9
View File
@@ -26,9 +26,18 @@ export default [
...payloadEsLintConfig,
{
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: {
+2 -2
View File
@@ -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'
+41 -41
View File
@@ -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'
+5 -5
View File
@@ -1,3 +1,7 @@
export { sendEmail } from '../modules/email/index.js'
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
/**
* Entry point: ipal-kit/server
*
@@ -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'
+3 -2
View File
@@ -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',
}
}
@@ -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<string>({ path })
const { setValue, value } = useField<string>({ path })
const [revealed, setRevealed] = useState(false)
const label =
@@ -31,38 +32,38 @@ export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
return (
<div className="field-type text masked-field">
<FieldLabel label={label} htmlFor={`field-${path}`} />
<FieldLabel htmlFor={`field-${path}`} label={label} />
<div className="field-type__wrap" style={{ display: 'flex', gap: '.5rem', alignItems: 'center' }}>
<div className="field-type__wrap" style={{ alignItems: 'center', display: 'flex', gap: '.5rem' }}>
<input
id={`field-${path}`}
type={revealed ? 'text' : 'password'}
autoComplete="off"
className="field-type__input"
value={value ?? ''}
id={`field-${path}`}
onChange={(e) => setValue(e.target.value)}
style={{ flex: 1 }}
type={revealed ? 'text' : 'password'}
value={value ?? ''}
/>
<button
type="button"
onClick={() => setRevealed((r) => !r)}
style={{
background: 'none',
border: 'none',
padding: '.25rem .5rem',
cursor: 'pointer',
font: 'inherit',
textDecoration: 'underline',
opacity: 0.75,
padding: '.25rem .5rem',
textDecoration: 'underline',
whiteSpace: 'nowrap',
}}
type="button"
>
{revealed ? 'Hide' : 'Reveal'}
</button>
</div>
{description && typeof description === 'string' ? (
<FieldDescription path={path} description={description} />
<FieldDescription description={description} path={path} />
) : null}
</div>
)
@@ -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 (
<div className="field-type" style={{ marginTop: '1rem' }}>
<label className="field-label">Send a test email</label>
<p style={{ opacity: 0.7, fontSize: '.85rem', marginTop: 0 }}>
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>
Sends through the transport selected above. Save your changes first.
</p>
<div style={{ display: 'flex', gap: '.5rem', alignItems: 'center', flexWrap: 'wrap' }}>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem' }}>
<input
type="email"
placeholder="[email protected]"
value={to}
onChange={(e) => setTo(e.target.value)}
placeholder="[email protected]"
style={{ flex: 1, minWidth: '220px' }}
type="email"
value={to}
/>
<button
type="button"
onClick={send}
disabled={status.kind === 'sending'}
className="btn btn--style-secondary"
disabled={status.kind === 'sending'}
onClick={send}
style={{ whiteSpace: 'nowrap' }}
type="button"
>
{status.kind === 'sending' ? 'Sending…' : 'Send test'}
</button>
+145 -145
View File
@@ -1,20 +1,3 @@
export { ipalKit } from './plugin.js'
export type { IpalOptions } from './types.js'
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'
export {
buildLocalizedPath,
getDefaultLocale,
getLocaleCodes,
getLocaleDefinition,
getLocalizedSlugs,
isValidLocale,
LOCALE_COOKIE_NAME,
matchAcceptLanguage,
negotiateLocale,
switchLocalePath,
} from './modules/i18n/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'
export type { AccessOption, Role } from './modules/access/index.js'
export {
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'
+2 -2
View File
@@ -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' } }
}
+1 -1
View File
@@ -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)
}
+1 -1
View File
@@ -17,7 +17,7 @@
* gates the tag in GTM (ad_storage) — this only emits the event.
*/
export function pushDataLayer(event: string, params: Record<string, unknown> = {}): void {
if (typeof window === 'undefined') return
if (typeof window === 'undefined') {return}
const w = window as unknown as { dataLayer?: unknown[] }
w.dataLayer = w.dataLayer || []
w.dataLayer.push({ event, ...params })
+4 -4
View File
@@ -9,17 +9,17 @@ export type ConsentCategory = (typeof CONSENT_CATEGORIES)[number]
export type ConsentState = Record<ConsentCategory, boolean>
export 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 }
+23 -23
View File
@@ -20,7 +20,7 @@ import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js'
* })
*/
type Block = Record<string, unknown> & { blockType?: string }
type Block = { blockType?: string } & Record<string, unknown>
type BlockToMarkdown = (block: Block) => string
type 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<string, unknown>
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()
-1
View File
@@ -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'
+2 -2
View File
@@ -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
}
/**
+11 -10
View File
@@ -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' },
)
+11 -10
View File
@@ -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 }
}
},
})
+1 -1
View File
@@ -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'
+12 -10
View File
@@ -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 },
},
})
}
+39 -37
View File
@@ -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<string, unknown>
/**
* 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<SubmitFormResult> {
// 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 }
}
}
+19 -19
View File
@@ -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[]
}
+6 -6
View File
@@ -24,9 +24,9 @@ import type { FormErrors, Validator } from './useForm.js'
*/
/** A rule returns `true` when the value is OK, or an error message string. */
export type Rule = (value: unknown, values: Record<string, unknown>) => true | string
export type Rule = (value: unknown, values: Record<string, unknown>) => string | true
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
/** Standalone e-mail check, handy outside the rule system too. */
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<T extends Record<string, unknown>>(
const all = values as Record<string, unknown>
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) {
+12 -11
View File
@@ -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
+16 -15
View File
@@ -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<string, string>
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<string, string>
homeSlug?: Record<string, string> | 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, string> | string
prefix?: LocalizedSlugs
slugs: LocalizedSlugs
targetLocale: string
config: I18nConfig
homeSlug?: string | Record<string, string>
prefix?: LocalizedSlugs
}
/**
@@ -125,17 +126,17 @@ type SwitchLocaleArgs = {
* to the locale root otherwise — the closest place the visitor would want.
*/
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}`
}
+1 -1
View File
@@ -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.
+11 -10
View File
@@ -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<string, string>
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string
/** Status groups to check: field name → label. */
checks?: Record<string, string>
/** Injected by Payload into admin server components. */
payload?: Payload
}
/**
@@ -15,8 +16,8 @@ type Props = {
* are currently failing, with a link to Site Integrations. Renders nothing when
* 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<string, unknown>
try {
doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>
@@ -26,17 +27,17 @@ export async function IntegrationAlerts({ payload, checks = { turnstileStatus: '
const failing = Object.entries(checks)
.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 (
<div
role="alert"
style={{
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
border: '1px solid var(--theme-error-400, #e5484d)',
borderRadius: 4,
marginBottom: '1.5rem',
padding: '1rem 1.25rem',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
}}
>
<strong>Integration problem — the site still works, but something needs attention.</strong>
@@ -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 (
<div style={{ marginBottom: '1.5rem', fontSize: '0.85rem', opacity: 0.75 }}>
<div style={{ fontSize: '0.85rem', marginBottom: '1.5rem', opacity: 0.75 }}>
✓ {label} working{since ? ` since ${fmt(since)}` : ''}.
</div>
)
@@ -40,21 +40,21 @@ export function IntegrationStatusBanner({ statusField, label }: Props) {
<div
role="alert"
style={{
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
border: '1px solid var(--theme-error-400, #e5484d)',
borderRadius: 4,
marginBottom: '1.5rem',
padding: '0.9rem 1rem',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
}}
>
<strong>{label} is not working — forms are accepted without this check.</strong>
{message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
{code ? `Code: ${code}. ` : ''}
{since ? `Since ${fmt(since)}. ` : ''}
{checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}
</div>
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
Fix the keys below and save — the status is checked again on the next form submission.
</div>
</div>
+3 -3
View File
@@ -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'
+16 -16
View File
@@ -12,18 +12,18 @@ import type { BasePayload, Field } from 'payload'
* busy form doesn't turn every submission into a DB write.
*/
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<void> {
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)
+8 -7
View File
@@ -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<Response> {
return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {
headers: { allow: 'POST' },
status: 405,
})
function GET(): Promise<Response> {
return Promise.resolve(
new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {
headers: { allow: 'POST' },
status: 405,
}),
)
}
return { GET, POST }
+3 -2
View File
@@ -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)
+3 -3
View File
@@ -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.',
},
}
+4 -4
View File
@@ -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 = {
+1 -1
View File
@@ -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<string, string>
homeSlug?: Record<string, string> | string
/** Target locale to build the path for. */
locale: string
/**
+27 -27
View File
@@ -1,25 +1,25 @@
type MediaLike = { url?: string | null } | null | undefined
type MediaLike = { url?: null | string } | null | undefined
type ArticleJsonLdArgs = {
/** 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) } } : {}),
},
}
+2 -2
View File
@@ -65,8 +65,8 @@ export function buildSitemapXml(
e.lastModified instanceof Date ? e.lastModified.toISOString() : String(e.lastModified)
parts.push(` <lastmod>${esc(iso)}</lastmod>`)
}
if (e.changeFrequency) parts.push(` <changefreq>${e.changeFrequency}</changefreq>`)
if (typeof e.priority === 'number') parts.push(` <priority>${e.priority}</priority>`)
if (e.changeFrequency) {parts.push(` <changefreq>${e.changeFrequency}</changefreq>`)}
if (typeof e.priority === 'number') {parts.push(` <priority>${e.priority}</priority>`)}
const alternates = e.alternates?.languages
if (alternates) {
for (const [lang, href] of Object.entries(alternates)) {
+9 -9
View File
@@ -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()
+1 -1
View File
@@ -20,7 +20,7 @@ type CreateMetadataGeneratorArgs = {
baseUrl?: string
config: I18nConfig
/** Home slug that collapses to the locale root. Defaults to 'home'. */
homeSlug?: string | Record<string, string>
homeSlug?: Record<string, string> | string
/**
* Resolves the document to build metadata for, given route params.
* The client supplies this (they own the collections and routing); it should
+8 -7
View File
@@ -1,20 +1,21 @@
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import { 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<string, string>
homeSlug?: Record<string, string> | 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<string, string> {
const origin = baseUrl?.replace(/\/$/, '') ?? ''
const alternates: Record<string, string> = {}
@@ -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}`
}
+32 -32
View File
@@ -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'
+20 -19
View File
@@ -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<TurnstileContextValue | null>(null)
const TurnstileContext = createContext<null | TurnstileContextValue>(null)
/**
* Provides the Turnstile site key once for the whole app, like ConsentProvider
@@ -29,17 +30,17 @@ const TurnstileContext = createContext<TurnstileContextValue | null>(null)
* token stays null — submitForm skips the check too, so the form just works.
*/
export function TurnstileProvider({
siteKey,
children,
siteKey,
}: {
siteKey: string | null
children: React.ReactNode
siteKey: null | string
}) {
const [token, setToken] = useState<string | null>(null)
const [token, setToken] = useState<null | string>(null)
return (
<TurnstileContext.Provider value={{ siteKey, token, setToken }}>
<TurnstileContext value={{ setToken, siteKey, token }}>
{children}
</TurnstileContext.Provider>
</TurnstileContext>
)
}
@@ -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 <TurnstileProvider>')
}
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 <Turnstile siteKey={siteKey} onToken={setToken} theme={props?.theme} />
(props?: { theme?: 'auto' | 'dark' | 'light' }) => {
if (!siteKey) {return null}
return <Turnstile onToken={setToken} siteKey={siteKey} theme={props?.theme} />
},
[siteKey, setToken],
)
return { token, TurnstileWidget, reset, enabled: Boolean(siteKey) }
return { enabled: Boolean(siteKey), reset, token, TurnstileWidget }
}
+4 -4
View File
@@ -1,7 +1,7 @@
// Server-only exports. verify.ts imports 'server-only', so this must never be
// imported from a client component — use ./client for the widget instead.
export { verifyTurnstile, checkTurnstile } from './verify.js'
export type { TurnstileCheck, TurnstileOutcome } from './verify.js'
export { getTurnstileConfig } from './config.js'
export 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'
+34 -32
View File
@@ -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<string, string> = {
'missing-input-secret': 'The secret key is missing in the request.',
'internal-error': 'Cloudflare reported an internal error while verifying.',
'invalid-input-secret':
'Cloudflare rejected the secret key — check Site Integrations → Turnstile (secret and site key must come from the same widget).',
'internal-error': 'Cloudflare reported an internal error while verifying.',
'missing-input-secret': 'The secret key is missing in the request.',
}
const PLUGIN_ERRORS: Record<string, string> = {
'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<string, string> = {
* SiteIntegrations is updated (throttled) so the panel shows failures.
*/
export async function checkTurnstile({
token,
payload,
ip,
payload,
sendRemoteIp = false,
token,
}: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck> {
if (!token) return { outcome: 'reject', code: 'missing-input-response' }
if (!token) {return { code: 'missing-input-response', outcome: 'reject' }}
const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload)
const previous = integrations[STATUS_FIELD]
@@ -85,29 +87,29 @@ export async function checkTurnstile({
const degraded = async (code: string): Promise<TurnstileCheck> => {
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' }
}
/**
+21 -20
View File
@@ -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<string, unknown> = {}
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.')
}
+18 -4
View File
@@ -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 ['[email protected]', '[email protected]', '[email protected]']) {
expect(isEmail(ok)).toBe(true)
}
for (const bad of ['', 'a', 'a@b', 'a [email protected]', 'a@b c.pl', '@b.pl', '[email protected]', 'a@@b.pl']) {
expect(isEmail(bad)).toBe(false)
}
})
})
+3 -1
View File
@@ -2,9 +2,11 @@ import type { Config } from 'payload'
import { describe, expect, test, vi } from 'vitest'
import 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' },
+1 -1
View File
@@ -14,7 +14,7 @@ const forms = {
],
},
}
const data = { consent: true, name: 'Ala' }
const data = { name: 'Ala', consent: true }
const keys = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' }
let ipCounter = 0
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"composite": false,
"incremental": false,
"noEmit": true,
"emitDeclarationOnly": false,
"rootDir": ".."
},
"include": ["./**/*.ts", "../src/**/*.ts", "../src/**/*.tsx"]
}