Compare commits

...
8 Commits
Author SHA1 Message Date
radoslaw.smolinski f9d3d9ae97 1.6.4 2026-10-09 19:10:25 +02:00
radoslaw.smolinski 962b9cb640 Fixed buildManifest.ts 2026-10-09 19:10:20 +02:00
radoslaw.smolinski 9b9bbc1a9f 1.6.3 2026-10-09 18:23:18 +02:00
radoslaw.smolinski abf2e7d40f Added form validators 2026-10-09 18:23:08 +02:00
radoslaw.smolinski d500d9412f 1.6.2 2026-10-09 18:00:32 +02:00
radoslaw.smolinski d034ddf990 Security patch for contact 2026-10-09 18:00:24 +02:00
radoslaw.smolinski 2dfacb0414 1.6.1 2026-10-09 17:25:28 +02:00
radoslaw.smolinski eb6efa26f6 Added JsonLdGraph.tsx 2026-10-09 17:25:22 +02:00
51 changed files with 1432 additions and 71 deletions
+6
View File
@@ -12,6 +12,12 @@ export { Analytics } from '../modules/analytics/client.js';
*/
export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js';
export type { CookieBannerClassNames } from '../modules/consent/client.js';
export { useContactForm } from '../modules/forms/useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction, } from '../modules/forms/useContactForm.js';
export { useForm } from '../modules/forms/useForm.js';
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from '../modules/forms/validators.js';
export type { Rule } from '../modules/forms/validators.js';
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath, } from '../modules/i18n/index.js';
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js';
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks, } from '../modules/i18n/index.js';
+3
View File
@@ -10,6 +10,9 @@ export { Analytics } from '../modules/analytics/client.js';
* components. Kept separate from the main entry so server bundles don't pull in
* client-only code.
*/ export { ConsentProvider, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js';
export { useContactForm } from '../modules/forms/useContactForm.js';
export { useForm } from '../modules/forms/useForm.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } 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 { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AccessibilityProvider,\n AccessibilityWidget,\n useAccessibility,\n} from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\n\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type {\n ContactFormErrors,\n ContactFormValues,\n SubmitAction,\n} from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","ConsentProvider","CookieBanner","CookieButton","useConsent","useConsentContext","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAoC;AAE3C,SAASC,SAAS,QAAQ,iCAAgC;AAC1D;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAGrC,SAASC,cAAc,QAAQ,qCAAoC;AAMnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"}
+1
View File
@@ -9,4 +9,5 @@ export { RenderBlocks } from '../modules/blocks/index.js';
export type { BlockComponentMap, BlockData, EnhanceProps, RenderBlocksProps, } from '../modules/blocks/index.js';
export { RenderRichText } from '../modules/richtext/index.js';
export type { RenderRichTextProps } from '../modules/richtext/index.js';
export { JsonLdGraph } from '../modules/seo/index.js';
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js';
+1
View File
@@ -6,6 +6,7 @@
* server-config bundle.
*/ export { RenderBlocks } from '../modules/blocks/index.js';
export { RenderRichText } from '../modules/richtext/index.js';
export { JsonLdGraph } from '../modules/seo/index.js';
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js';
//# sourceMappingURL=rsc.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/rsc\n *\n * Server-component exports. RenderBlocks is a React Server Component, so it\n * lives here rather than in the main package entry to keep React out of the\n * server-config bundle.\n */\nexport { RenderBlocks } from '../modules/blocks/index.js'\nexport type {\n BlockComponentMap,\n BlockData,\n EnhanceProps,\n RenderBlocksProps,\n} from '../modules/blocks/index.js'\nexport { RenderRichText } from '../modules/richtext/index.js'\nexport type { RenderRichTextProps } from '../modules/richtext/index.js'\nexport { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'\n"],"names":["RenderBlocks","RenderRichText","MediaPreconnect"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,YAAY,QAAQ,6BAA4B;AAOzD,SAASC,cAAc,QAAQ,+BAA8B;AAE7D,SAASC,eAAe,QAAQ,wCAAuC"}
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/rsc\n *\n * Server-component exports. RenderBlocks is a React Server Component, so it\n * lives here rather than in the main package entry to keep React out of the\n * server-config bundle.\n */\nexport { RenderBlocks } from '../modules/blocks/index.js'\nexport type {\n BlockComponentMap,\n BlockData,\n EnhanceProps,\n RenderBlocksProps,\n} from '../modules/blocks/index.js'\nexport { RenderRichText } from '../modules/richtext/index.js'\nexport type { RenderRichTextProps } from '../modules/richtext/index.js'\nexport { JsonLdGraph } from '../modules/seo/index.js'\nexport { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'\n"],"names":["RenderBlocks","RenderRichText","JsonLdGraph","MediaPreconnect"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,YAAY,QAAQ,6BAA4B;AAOzD,SAASC,cAAc,QAAQ,+BAA8B;AAE7D,SAASC,WAAW,QAAQ,0BAAyB;AACrD,SAASC,eAAe,QAAQ,wCAAuC"}
+4
View File
@@ -17,6 +17,9 @@ export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js';
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption, } from './modules/forms/types.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';
export { createContentHelpers } from './modules/frontend/index.js';
export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook, } from './modules/hooks/index.js';
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js';
@@ -24,6 +27,7 @@ export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefiniti
export type { LocaleMiddlewareResult } from './modules/i18n/index.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage, } from './modules/notifications/index.js';
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js';
+5
View File
@@ -10,11 +10,16 @@ export { mailAdapter } from './modules/email/mailAdapter.js';
// Payload loads the config (or runs generate:importmap) as a plain Node script.
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js';
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.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, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './modules/forms/validators.js';
export { createContentHelpers } from './modules/frontend/index.js';
export { buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js';
export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js';
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js';
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js';
export { resolveLocalized } from './modules/i18n/index.js';
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js';
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js';
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js';
+1 -1
View File
File diff suppressed because one or more lines are too long
+6
View File
@@ -4,5 +4,11 @@ export type { RateLimitArgs } from './rateLimit.js';
export { submitForm } from './submitForm.js';
export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js';
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js';
export { useContactForm } from './useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js';
export { useForm } from './useForm.js';
export type { FormErrors, FormSubmitAction, Validator } from './useForm.js';
export { validateSubmission } from './validateSubmission.js';
export type { FormValidationResult } from './validateSubmission.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './validators.js';
export type { Rule } from './validators.js';
+5
View File
@@ -3,6 +3,11 @@
export { buildFormsPlugin } from './formsPluginConfig.js';
export { checkRateLimit } from './rateLimit.js';
export { submitForm } from './submitForm.js';
export { useContactForm } from './useContactForm.js';
// Generic form engine (any field set) + the standard contact-form preset.
export { useForm } from './useForm.js';
export { validateSubmission } from './validateSubmission.js';
// Composable validation rules (pure — safe on server or client).
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './validators.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,kBAAkB,QAAQ,0BAAyB"}
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\n// Generic form engine (any field set) + the standard contact-form preset.\nexport { useForm } from './useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './useForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n// Composable validation rules (pure — safe on server or client).\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './validators.js'\nexport type { Rule } from './validators.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","useContactForm","useForm","validateSubmission","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,0EAA0E;AAC1E,SAASC,OAAO,QAAQ,eAAc;AAEtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,iEAAiE;AACjE,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,kBAAiB"}
+60
View File
@@ -0,0 +1,60 @@
import { type FormSubmitAction } from './useForm.js';
/**
* Field values of the STANDARD contact form. This is a preset shape — projects
* that need a different field set (or dynamic builder fields) should use
* `useForm` directly instead, where the shape is fully open.
*/
export type ContactFormValues = {
consent: boolean;
email: string;
message: string;
name: string;
phone: string;
topic: string;
};
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>;
export type SubmitAction = FormSubmitAction<ContactFormValues>;
type UseContactFormOptions = {
/** Generic error message shown when the action fails/throws. */
errorFallback?: string;
initialTopic?: string;
/** Override the per-field error message (shown via `errors.<field>`). */
messages?: Partial<Record<keyof ContactFormValues, string>>;
/** Minimum message length. Default 10. */
minMessageLength?: number;
/** Whether consent is required (project passes true when consentText shown). */
requireConsent?: boolean;
/** Whether a topic must be chosen (project passes this when topics exist). */
requireTopic?: boolean;
/** Require a Turnstile token before submit (when the widget is shown). */
requireTurnstile?: boolean;
submitAction: SubmitAction;
};
/**
* Zero-config preset over `useForm` for the everyday contact form: standard
* fields (name/email/phone/topic/message/consent) and standard rules, wired
* for you. Markup and styling stay 100% in the project — this only removes the
* duplicated logic.
*
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
*
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
*/
export declare function useContactForm(options: UseContactFormOptions): {
values: ContactFormValues;
errors: Partial<Record<keyof ContactFormValues, string>>;
isSubmitting: boolean;
isSuccess: boolean;
errorMessage: string | null;
turnstileToken: string | null;
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
setValues: import("react").Dispatch<import("react").SetStateAction<ContactFormValues>>;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof ContactFormValues, string>>>>;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
handleSubmit: (e?: {
preventDefault?: (() => void) | undefined;
} | undefined) => Promise<void>;
reset: () => void;
};
export {};
+61
View File
@@ -0,0 +1,61 @@
'use client';
import { useMemo } from 'react';
import { useForm } from './useForm.js';
import { buildValidator, checked, email, minLength, required } from './validators.js';
/**
* Zero-config preset over `useForm` for the everyday contact form: standard
* fields (name/email/phone/topic/message/consent) and standard rules, wired
* for you. Markup and styling stay 100% in the project — this only removes the
* duplicated logic.
*
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
*
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
*/ export function useContactForm(options) {
const { errorFallback, initialTopic = '', messages, minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
const validate = useMemo(()=>buildValidator({
name: [
required(messages?.name)
],
email: [
required(messages?.email),
email(messages?.email)
],
...requireTopic ? {
topic: [
required(messages?.topic)
]
} : {},
message: [
required(messages?.message),
minLength(minMessageLength, messages?.message)
],
...requireConsent ? {
consent: [
checked(messages?.consent)
]
} : {}
}), [
requireTopic,
requireConsent,
minMessageLength,
messages
]);
return useForm({
errorFallback,
initialValues: {
name: '',
consent: false,
email: '',
message: '',
phone: '',
topic: initialTopic
},
requireTurnstile,
submitAction,
validate
});
}
//# sourceMappingURL=useContactForm.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/forms/useContactForm.ts"],"sourcesContent":["'use client'\n\nimport { useMemo } from 'react'\n\nimport { type FormSubmitAction, useForm } from './useForm.js'\nimport { buildValidator, checked, email, minLength, required } from './validators.js'\n\n/**\n * Field values of the STANDARD contact form. This is a preset shape — projects\n * that need a different field set (or dynamic builder fields) should use\n * `useForm` directly instead, where the shape is fully open.\n */\nexport type ContactFormValues = {\n consent: boolean\n email: string\n message: string\n name: string\n phone: string\n topic: string\n}\n\nexport type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>\nexport type SubmitAction = FormSubmitAction<ContactFormValues>\n\ntype UseContactFormOptions = {\n /** Generic error message shown when the action fails/throws. */\n errorFallback?: string\n initialTopic?: string\n /** Override the per-field error message (shown via `errors.<field>`). */\n messages?: Partial<Record<keyof ContactFormValues, string>>\n /** Minimum message length. Default 10. */\n minMessageLength?: number\n /** Whether consent is required (project passes true when consentText shown). */\n requireConsent?: boolean\n /** Whether a topic must be chosen (project passes this when topics exist). */\n requireTopic?: boolean\n /** Require a Turnstile token before submit (when the widget is shown). */\n requireTurnstile?: boolean\n submitAction: SubmitAction\n}\n\n/**\n * Zero-config preset over `useForm` for the everyday contact form: standard\n * fields (name/email/phone/topic/message/consent) and standard rules, wired\n * for you. Markup and styling stay 100% in the project — this only removes the\n * duplicated logic.\n *\n * const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),\n * requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })\n *\n * Need custom or dynamic fields? Drop the preset and call `useForm` + validators.\n */\nexport function useContactForm(options: UseContactFormOptions) {\n const {\n errorFallback,\n initialTopic = '',\n messages,\n minMessageLength = 10,\n requireConsent = false,\n requireTopic = false,\n requireTurnstile = false,\n submitAction,\n } = options\n\n const validate = useMemo(\n () =>\n buildValidator<ContactFormValues>({\n name: [required(messages?.name)],\n email: [required(messages?.email), email(messages?.email)],\n ...(requireTopic ? { topic: [required(messages?.topic)] } : {}),\n message: [required(messages?.message), minLength(minMessageLength, messages?.message)],\n ...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),\n }),\n [requireTopic, requireConsent, minMessageLength, messages],\n )\n\n return useForm<ContactFormValues>({\n errorFallback,\n initialValues: {\n name: '',\n consent: false,\n email: '',\n message: '',\n phone: '',\n topic: initialTopic,\n },\n requireTurnstile,\n submitAction,\n validate,\n })\n}\n"],"names":["useMemo","useForm","buildValidator","checked","email","minLength","required","useContactForm","options","errorFallback","initialTopic","messages","minMessageLength","requireConsent","requireTopic","requireTurnstile","submitAction","validate","name","topic","message","consent","initialValues","phone"],"mappings":"AAAA;AAEA,SAASA,OAAO,QAAQ,QAAO;AAE/B,SAAgCC,OAAO,QAAQ,eAAc;AAC7D,SAASC,cAAc,EAAEC,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,kBAAiB;AAoCrF;;;;;;;;;;CAUC,GACD,OAAO,SAASC,eAAeC,OAA8B;IAC3D,MAAM,EACJC,aAAa,EACbC,eAAe,EAAE,EACjBC,QAAQ,EACRC,mBAAmB,EAAE,EACrBC,iBAAiB,KAAK,EACtBC,eAAe,KAAK,EACpBC,mBAAmB,KAAK,EACxBC,YAAY,EACb,GAAGR;IAEJ,MAAMS,WAAWjB,QACf,IACEE,eAAkC;YAChCgB,MAAM;gBAACZ,SAASK,UAAUO;aAAM;YAChCd,OAAO;gBAACE,SAASK,UAAUP;gBAAQA,MAAMO,UAAUP;aAAO;YAC1D,GAAIU,eAAe;gBAAEK,OAAO;oBAACb,SAASK,UAAUQ;iBAAO;YAAC,IAAI,CAAC,CAAC;YAC9DC,SAAS;gBAACd,SAASK,UAAUS;gBAAUf,UAAUO,kBAAkBD,UAAUS;aAAS;YACtF,GAAIP,iBAAiB;gBAAEQ,SAAS;oBAAClB,QAAQQ,UAAUU;iBAAS;YAAC,IAAI,CAAC,CAAC;QACrE,IACF;QAACP;QAAcD;QAAgBD;QAAkBD;KAAS;IAG5D,OAAOV,QAA2B;QAChCQ;QACAa,eAAe;YACbJ,MAAM;YACNG,SAAS;YACTjB,OAAO;YACPgB,SAAS;YACTG,OAAO;YACPJ,OAAOT;QACT;QACAK;QACAC;QACAC;IACF;AACF"}
+70
View File
@@ -0,0 +1,70 @@
/**
* Error map: a field key → its error message. A field is "in error" iff it has
* a key here, so `errors.email` is both the truthy flag (for a red border) AND
* the message (to display). Empty object = valid.
*/
export type FormErrors<T> = Partial<Record<keyof T, string>>;
/**
* The project's server action that calls submitForm (server-only, holds the
* Turnstile secret). This hook is a client hook, so it can't call submitForm
* directly — the project injects its action. The result only needs `success`
* plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.
*/
export type FormSubmitAction<T> = (values: T, turnstileToken?: string) => Promise<{
success: boolean;
message?: string;
}>;
/** Turns the current values into an error map. Empty map = valid. */
export type Validator<T> = (values: T) => FormErrors<T>;
type UseFormOptions<T extends Record<string, unknown>> = {
/** Defines the field set AND the reset state. Any shape you like. */
initialValues: T;
submitAction: FormSubmitAction<T>;
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
validate?: Validator<T>;
/** Require a Turnstile token before submit (when the widget is shown). */
requireTurnstile?: boolean;
/** Generic error message shown when the action fails/throws with no message. */
errorFallback?: string;
/** Clear a field's error as soon as the user edits it. Default true. */
clearErrorOnChange?: boolean;
};
/**
* Fully generic form engine: state, validation, Turnstile token, submit,
* success/error — WITHOUT any markup. The project owns 100% of the look AND
* the field set: there is no baked-in shape here. Replaces the identical
* ~150 lines of form plumbing copied into every project.
*
* The field set comes from `initialValues`; the rules come from `validate`
* (so dynamic/builder-driven forms just build both at runtime). For the
* everyday contact form use the `useContactForm` preset instead — it wires
* the standard fields and rules for you.
*
* const f = useForm({
* initialValues: { email: '', message: '' },
* submitAction, // your server action
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
* requireTurnstile: Boolean(siteKey),
* })
* <input value={f.values.email}
* onChange={(e) => f.setField('email', e.target.value)}
* className={f.errors.email ? 'border-red-500' : '…'} />
* <form onSubmit={f.handleSubmit}>…</form>
*/
export declare function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>): {
values: T;
errors: Partial<Record<keyof T, string>>;
isSubmitting: boolean;
isSuccess: boolean;
errorMessage: string | null;
turnstileToken: string | null;
setField: <K extends keyof T>(key: K, value: T[K]) => void;
setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof T, string>>>>;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
handleSubmit: (e?: {
preventDefault?: () => void;
}) => Promise<void>;
reset: () => void;
};
export {};
+122
View File
@@ -0,0 +1,122 @@
'use client';
import { useState, useCallback, useRef, useMemo } from 'react';
/**
* Fully generic form engine: state, validation, Turnstile token, submit,
* success/error — WITHOUT any markup. The project owns 100% of the look AND
* the field set: there is no baked-in shape here. Replaces the identical
* ~150 lines of form plumbing copied into every project.
*
* The field set comes from `initialValues`; the rules come from `validate`
* (so dynamic/builder-driven forms just build both at runtime). For the
* everyday contact form use the `useContactForm` preset instead — it wires
* the standard fields and rules for you.
*
* const f = useForm({
* initialValues: { email: '', message: '' },
* submitAction, // your server action
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
* requireTurnstile: Boolean(siteKey),
* })
* <input value={f.values.email}
* onChange={(e) => f.setField('email', e.target.value)}
* className={f.errors.email ? 'border-red-500' : '…'} />
* <form onSubmit={f.handleSubmit}>…</form>
*/ export function useForm(options) {
const { initialValues, submitAction, validate, requireTurnstile = false, errorFallback = 'Something went wrong. Please try again.', clearErrorOnChange = true } = options;
// Freeze the initial snapshot so `reset` is stable even though callers pass a
// fresh object literal every render.
const initialRef = useRef(initialValues);
const [values, setValues] = useState(initialRef.current);
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [errorMessage, setErrorMessage] = useState(null);
const [turnstileToken, setTurnstileToken] = useState(null);
const setField = useCallback((key, value)=>{
setValues((prev)=>({
...prev,
[key]: value
}));
if (clearErrorOnChange) {
setErrors((prev)=>{
if (!prev[key]) return prev;
const next = {
...prev
};
delete next[key];
return next;
});
}
}, [
clearErrorOnChange
]);
// Validate against the LATEST values via a ref, so handleSubmit stays stable
// and never reads a stale snapshot.
const valuesRef = useRef(values);
valuesRef.current = values;
const validateRef = useRef(validate);
validateRef.current = validate;
const handleSubmit = useCallback(async (e)=>{
e?.preventDefault?.();
setErrorMessage(null);
const errs = validateRef.current ? validateRef.current(valuesRef.current) : {};
setErrors(errs);
if (Object.keys(errs).length > 0) return;
if (requireTurnstile && !turnstileToken) {
setErrorMessage(errorFallback);
return;
}
setIsSubmitting(true);
try {
const result = await submitAction(valuesRef.current, turnstileToken ?? undefined);
if (result.success) {
setIsSuccess(true);
setTurnstileToken(null);
} else {
setErrorMessage(result.message || errorFallback);
}
} catch (err) {
setErrorMessage(err instanceof Error ? err.message : errorFallback);
} finally{
setIsSubmitting(false);
}
}, [
requireTurnstile,
turnstileToken,
submitAction,
errorFallback
]);
const reset = useCallback(()=>{
setValues(initialRef.current);
setErrors({});
setIsSuccess(false);
setErrorMessage(null);
setTurnstileToken(null);
}, []);
return useMemo(()=>({
values,
errors,
isSubmitting,
isSuccess,
errorMessage,
turnstileToken,
setField,
setValues,
setErrors,
setTurnstileToken,
handleSubmit,
reset
}), [
values,
errors,
isSubmitting,
isSuccess,
errorMessage,
turnstileToken,
setField,
handleSubmit,
reset
]);
}
//# sourceMappingURL=useForm.js.map
File diff suppressed because one or more lines are too long
+43
View File
@@ -0,0 +1,43 @@
import type { Validator } from './useForm.js';
/**
* Composable validation rules + a builder that turns a per-field schema into a
* `Validator<T>`. These are the bits that actually repeat across projects
* (required / email / min-length / checkbox-must-be-true); the field SET and
* the MARKUP stay in the project.
*
* Pure functions, no 'use client' — usable both in the client `useForm` hook
* and server-side (e.g. re-validating inside a server action).
*
* const validate = buildValidator<MyValues>({
* email: [required(), email()],
* message: [required(), minLength(10)],
* consent: [checked()],
* })
*
* Dynamic / builder-driven forms build the schema at runtime:
*
* const schema = Object.fromEntries(
* fields.map((f) => [f.name, f.required ? [required()] : []]),
* )
* const validate = buildValidator(schema)
*/
/** 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;
/** Standalone e-mail check, handy outside the rule system too. */
export declare const isEmail: (v: unknown) => boolean;
/** Non-empty string, non-null, and (for checkboxes) not `false`. */
export declare const required: (msg?: string) => Rule;
export declare const email: (msg?: string) => Rule;
export declare const minLength: (n: number, msg?: string) => Rule;
export declare const maxLength: (n: number, msg?: string) => Rule;
/** Checkbox must be ticked (true). */
export declare const checked: (msg?: string) => Rule;
/** Value must match a regex (ignored when empty — pair with `required` to force). */
export declare const pattern: (re: RegExp, msg?: string) => Rule;
/** Escape hatch: any predicate → rule. */
export declare const custom: (test: (value: unknown, values: Record<string, unknown>) => boolean, msg: string) => Rule;
/**
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
* field wins. Fields with no rules (or an empty list) are skipped.
*/
export declare function buildValidator<T extends Record<string, unknown>>(schema: Partial<Record<keyof T, Rule[]>>): Validator<T>;
+37
View File
@@ -0,0 +1,37 @@
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
/** Standalone e-mail check, handy outside the rule system too. */ export const isEmail = (v)=>typeof v === 'string' && EMAIL_RE.test(v.trim());
/** Non-empty string, non-null, and (for checkboxes) not `false`. */ export const required = (msg = 'required')=>(v)=>{
if (v == null) return msg;
if (typeof v === 'string' && !v.trim()) return msg;
if (v === false) return msg;
return true;
};
export const email = (msg = 'invalid email')=>(v)=>isEmail(v) ? true : msg;
export const minLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length >= n ? true : msg ?? `min ${n} chars`;
export const maxLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length <= n ? true : msg ?? `max ${n} chars`;
/** Checkbox must be ticked (true). */ export const checked = (msg = 'required')=>(v)=>v === true ? true : msg;
/** Value must match a regex (ignored when empty — pair with `required` to force). */ export const pattern = (re, msg = 'invalid format')=>(v)=>typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg;
/** Escape hatch: any predicate → rule. */ export const custom = (test, msg)=>(v, values)=>test(v, values) ? true : msg;
/**
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
* field wins. Fields with no rules (or an empty list) are skipped.
*/ export function buildValidator(schema) {
return (values)=>{
const errs = {};
const all = values;
for(const key in schema){
const rules = schema[key];
if (!rules || rules.length === 0) continue;
for (const rule of rules){
const res = rule(all[key], all);
if (res !== true) {
errs[key] = res;
break;
}
}
}
return errs;
};
}
//# sourceMappingURL=validators.js.map
File diff suppressed because one or more lines are too long
+1
View File
@@ -12,5 +12,6 @@ export { buildLocalizationConfig } from './localizationConfig.js';
export { buildLocalizedPath, switchLocalePath } from './localizedPath.js';
export type { LocalizedSlugs } from './localizedPath.js';
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js';
export { resolveLocalized } from './resolveLocalized.js';
export type { I18nConfig, LocaleDefinition } from './types.js';
export { validateI18nConfig } from './validation.js';
+1
View File
@@ -8,6 +8,7 @@ export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMidd
export { buildLocalizationConfig } from './localizationConfig.js';
export { buildLocalizedPath, switchLocalePath } from './localizedPath.js';
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js';
export { resolveLocalized } from './resolveLocalized.js';
export { validateI18nConfig } from './validation.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export {\n AlternateLinksProvider,\n useAlternateLinks,\n useSetAlternateLinks,\n} from './AlternateLinksContext.js'\nexport type { AlternateLinks } from './AlternateLinksContext.js'\nexport { AlternateLinksUpdater } from './AlternateLinksUpdater.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'\nexport { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { LanguageSwitcher } from './LanguageSwitcher.js'\nexport type { LanguageSwitcherClassNames } from './LanguageSwitcher.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["AlternateLinksProvider","useAlternateLinks","useSetAlternateLinks","AlternateLinksUpdater","createProxy","DEFAULT_PROXY_MATCHER","getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","LanguageSwitcher","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","validateI18nConfig"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,iBAAiB,EACjBC,oBAAoB,QACf,6BAA4B;AAEnC,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,mBAAkB;AACrE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAE/F,SAASC,kBAAkB,QAAQ,kBAAiB"}
{"version":3,"sources":["../../../src/modules/i18n/index.ts"],"sourcesContent":["export {\n AlternateLinksProvider,\n useAlternateLinks,\n useSetAlternateLinks,\n} from './AlternateLinksContext.js'\nexport type { AlternateLinks } from './AlternateLinksContext.js'\nexport { AlternateLinksUpdater } from './AlternateLinksUpdater.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'\nexport { getLocalizedSlugs } from './getLocalizedSlugs.js'\nexport { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'\nexport { LanguageSwitcher } from './LanguageSwitcher.js'\nexport type { LanguageSwitcherClassNames } from './LanguageSwitcher.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'\nexport type { LocaleMiddlewareResult } from './localeMiddleware.js'\nexport { buildLocalizationConfig } from './localizationConfig.js'\nexport { buildLocalizedPath, switchLocalePath } from './localizedPath.js'\nexport type { LocalizedSlugs } from './localizedPath.js'\nexport { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'\nexport { resolveLocalized } from './resolveLocalized.js'\nexport type { I18nConfig, LocaleDefinition } from './types.js'\nexport { validateI18nConfig } from './validation.js'\n"],"names":["AlternateLinksProvider","useAlternateLinks","useSetAlternateLinks","AlternateLinksUpdater","createProxy","DEFAULT_PROXY_MATCHER","getLocalizedSlugs","getDefaultLocale","getLocaleCodes","getLocaleDefinition","isValidLocale","LanguageSwitcher","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","buildLocalizationConfig","buildLocalizedPath","switchLocalePath","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","resolveLocalized","validateI18nConfig"],"mappings":"AAAA,SACEA,sBAAsB,EACtBC,iBAAiB,EACjBC,oBAAoB,QACf,6BAA4B;AAEnC,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,WAAW,EAAEC,qBAAqB,QAAQ,mBAAkB;AACrE,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,mBAAmB,EAAEC,aAAa,QAAQ,eAAc;AACnG,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,sBAAsB,EAAEC,0BAA0B,QAAQ,wBAAuB;AAE1F,SAASC,uBAAuB,QAAQ,0BAAyB;AACjE,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,qBAAoB;AAEzE,SAASC,kBAAkB,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAsB;AAC/F,SAASC,gBAAgB,QAAQ,wBAAuB;AAExD,SAASC,kBAAkB,QAAQ,kBAAiB"}
+13
View File
@@ -0,0 +1,13 @@
/**
* Resolves a possibly-localized value to a string for the given locale.
* Payload returns a localized field as a plain string (current locale) OR, with
* locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles
* both, with a safe fallback to the first available value — replacing the
* hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,
* rich text, form topics, …).
*
* import { resolveLocalized } from '@intecion/ipal-kit'
* const name = resolveLocalized(item.label, locale) // '' if nothing
* const city = resolveLocalized(company.city, locale, '—') // custom fallback
*/
export declare function resolveLocalized(value: unknown, locale: string, fallback?: string): string;
+31
View File
@@ -0,0 +1,31 @@
/**
* Resolves a possibly-localized value to a string for the given locale.
* Payload returns a localized field as a plain string (current locale) OR, with
* locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles
* both, with a safe fallback to the first available value — replacing the
* hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,
* rich text, form topics, …).
*
* import { resolveLocalized } from '@intecion/ipal-kit'
* const name = resolveLocalized(item.label, locale) // '' if nothing
* const city = resolveLocalized(company.city, locale, '—') // custom fallback
*/ export function resolveLocalized(value, locale, fallback = '') {
if (value == null) {
return fallback;
}
if (typeof value === 'string') {
return value;
}
if (typeof value === 'object') {
const map = value;
const forLocale = map[locale];
if (typeof forLocale === 'string') {
return forLocale;
}
const first = Object.values(map).find((v)=>typeof v === 'string');
return first ?? fallback;
}
return String(value);
}
//# sourceMappingURL=resolveLocalized.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/i18n/resolveLocalized.ts"],"sourcesContent":["/**\n * Resolves a possibly-localized value to a string for the given locale.\n * Payload returns a localized field as a plain string (current locale) OR, with\n * locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles\n * both, with a safe fallback to the first available value — replacing the\n * hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,\n * rich text, form topics, …).\n *\n * import { resolveLocalized } from '@intecion/ipal-kit'\n * const name = resolveLocalized(item.label, locale) // '' if nothing\n * const city = resolveLocalized(company.city, locale, '—') // custom fallback\n */\nexport function resolveLocalized(value: unknown, locale: string, fallback = ''): string {\n if (value == null) {return fallback}\n if (typeof value === 'string') {return value}\n if (typeof value === 'object') {\n const map = value as Record<string, unknown>\n const forLocale = map[locale]\n if (typeof forLocale === 'string') {return forLocale}\n const first = Object.values(map).find((v) => typeof v === 'string')\n return (first) ?? fallback\n }\n return String(value)\n}\n"],"names":["resolveLocalized","value","locale","fallback","map","forLocale","first","Object","values","find","v","String"],"mappings":"AAAA;;;;;;;;;;;CAWC,GACD,OAAO,SAASA,iBAAiBC,KAAc,EAAEC,MAAc,EAAEC,WAAW,EAAE;IAC5E,IAAIF,SAAS,MAAM;QAAC,OAAOE;IAAQ;IACnC,IAAI,OAAOF,UAAU,UAAU;QAAC,OAAOA;IAAK;IAC5C,IAAI,OAAOA,UAAU,UAAU;QAC7B,MAAMG,MAAMH;QACZ,MAAMI,YAAYD,GAAG,CAACF,OAAO;QAC7B,IAAI,OAAOG,cAAc,UAAU;YAAC,OAAOA;QAAS;QACpD,MAAMC,QAAQC,OAAOC,MAAM,CAACJ,KAAKK,IAAI,CAAC,CAACC,IAAM,OAAOA,MAAM;QAC1D,OAAO,AAACJ,SAAUH;IACpB;IACA,OAAOQ,OAAOV;AAChB"}
+29
View File
@@ -0,0 +1,29 @@
type JsonLdSchema = Record<string, unknown>;
/**
* Renders one or more schema.org objects as a single JSON-LD @graph in a
* <script type="application/ld+json">. The plugin owns ONLY the wrapping and the
* safe serialization — NOT the schema contents. The project builds its own nodes
* (with the plugin's buildWebSiteJsonLd / buildOrganizationJsonLd /
* buildLocalBusinessJsonLd / buildSiteNavigationJsonLd helpers) and maps its own
* company data to the right @type.
*
* Why not a <GlobalJsonLd> that reads Company/Header: company data is a business
* domain that varies by country and industry (NIP/KRS in PL, ABN in AU, EIN in
* US; barAssociation for a law firm, licenceText for an HVAC business). A fixed
* model would be a leaky abstraction. So the project decides the @type and
* fields; the plugin just wraps and renders safely.
*
* // project — build nodes from YOUR data, choose the @type for YOUR market
* import { JsonLdGraph, buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'
* const website = buildWebSiteJsonLd({ name, url })
* const org = buildOrganizationJsonLd({ name, url, logo })
* const localBusiness = { '@type': 'HVACBusiness', taxID: company.abn, areaServed: company.serviceArea, ... }
* <JsonLdGraph schemas={[website, org, localBusiness]} />
*
* Replaces the ~140-line JsonLd.tsx (only the @graph wrapper + <script> was
* actually duplicated; the schema mapping stays in the project where it belongs).
*/
export declare function JsonLdGraph({ schemas }: {
schemas: Array<JsonLdSchema | null | undefined>;
}): import("react/jsx-runtime").JSX.Element | null;
export {};
+44
View File
@@ -0,0 +1,44 @@
import { jsx as _jsx } from "react/jsx-runtime";
/**
* Renders one or more schema.org objects as a single JSON-LD @graph in a
* <script type="application/ld+json">. The plugin owns ONLY the wrapping and the
* safe serialization — NOT the schema contents. The project builds its own nodes
* (with the plugin's buildWebSiteJsonLd / buildOrganizationJsonLd /
* buildLocalBusinessJsonLd / buildSiteNavigationJsonLd helpers) and maps its own
* company data to the right @type.
*
* Why not a <GlobalJsonLd> that reads Company/Header: company data is a business
* domain that varies by country and industry (NIP/KRS in PL, ABN in AU, EIN in
* US; barAssociation for a law firm, licenceText for an HVAC business). A fixed
* model would be a leaky abstraction. So the project decides the @type and
* fields; the plugin just wraps and renders safely.
*
* // project — build nodes from YOUR data, choose the @type for YOUR market
* import { JsonLdGraph, buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'
* const website = buildWebSiteJsonLd({ name, url })
* const org = buildOrganizationJsonLd({ name, url, logo })
* const localBusiness = { '@type': 'HVACBusiness', taxID: company.abn, areaServed: company.serviceArea, ... }
* <JsonLdGraph schemas={[website, org, localBusiness]} />
*
* Replaces the ~140-line JsonLd.tsx (only the @graph wrapper + <script> was
* actually duplicated; the schema mapping stays in the project where it belongs).
*/ export function JsonLdGraph({ schemas }) {
const graph = schemas.filter((s)=>Boolean(s));
if (graph.length === 0) {
return null;
}
const json = JSON.stringify({
'@context': 'https://schema.org',
'@graph': graph
});
return /*#__PURE__*/ _jsx("script", {
// Escape '<' to prevent the JSON from breaking out of the script tag
// (XSS hardening) — the only safety concern the plugin owns here.
dangerouslySetInnerHTML: {
__html: json.replace(/</g, '\\u003c')
},
type: "application/ld+json"
});
}
//# sourceMappingURL=JsonLdGraph.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/modules/seo/JsonLdGraph.tsx"],"sourcesContent":["type JsonLdSchema = Record<string, unknown>\n\n/**\n * Renders one or more schema.org objects as a single JSON-LD @graph in a\n * <script type=\"application/ld+json\">. The plugin owns ONLY the wrapping and the\n * safe serialization — NOT the schema contents. The project builds its own nodes\n * (with the plugin's buildWebSiteJsonLd / buildOrganizationJsonLd /\n * buildLocalBusinessJsonLd / buildSiteNavigationJsonLd helpers) and maps its own\n * company data to the right @type.\n *\n * Why not a <GlobalJsonLd> that reads Company/Header: company data is a business\n * domain that varies by country and industry (NIP/KRS in PL, ABN in AU, EIN in\n * US; barAssociation for a law firm, licenceText for an HVAC business). A fixed\n * model would be a leaky abstraction. So the project decides the @type and\n * fields; the plugin just wraps and renders safely.\n *\n * // project — build nodes from YOUR data, choose the @type for YOUR market\n * import { JsonLdGraph, buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'\n * const website = buildWebSiteJsonLd({ name, url })\n * const org = buildOrganizationJsonLd({ name, url, logo })\n * const localBusiness = { '@type': 'HVACBusiness', taxID: company.abn, areaServed: company.serviceArea, ... }\n * <JsonLdGraph schemas={[website, org, localBusiness]} />\n *\n * Replaces the ~140-line JsonLd.tsx (only the @graph wrapper + <script> was\n * actually duplicated; the schema mapping stays in the project where it belongs).\n */\nexport function JsonLdGraph({ schemas }: { schemas: Array<JsonLdSchema | null | undefined> }) {\n const graph = schemas.filter((s): s is JsonLdSchema => Boolean(s))\n if (graph.length === 0) {return null}\n\n const json = JSON.stringify({ '@context': 'https://schema.org', '@graph': graph })\n\n return (\n <script\n // Escape '<' to prevent the JSON from breaking out of the script tag\n // (XSS hardening) — the only safety concern the plugin owns here.\n dangerouslySetInnerHTML={{ __html: json.replace(/</g, '\\\\u003c') }}\n type=\"application/ld+json\"\n />\n )\n}\n"],"names":["JsonLdGraph","schemas","graph","filter","s","Boolean","length","json","JSON","stringify","script","dangerouslySetInnerHTML","__html","replace","type"],"mappings":";AAEA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,SAASA,YAAY,EAAEC,OAAO,EAAuD;IAC1F,MAAMC,QAAQD,QAAQE,MAAM,CAAC,CAACC,IAAyBC,QAAQD;IAC/D,IAAIF,MAAMI,MAAM,KAAK,GAAG;QAAC,OAAO;IAAI;IAEpC,MAAMC,OAAOC,KAAKC,SAAS,CAAC;QAAE,YAAY;QAAsB,UAAUP;IAAM;IAEhF,qBACE,KAACQ;QACC,qEAAqE;QACrE,kEAAkE;QAClEC,yBAAyB;YAAEC,QAAQL,KAAKM,OAAO,CAAC,MAAM;QAAW;QACjEC,MAAK;;AAGX"}
+9
View File
@@ -24,6 +24,15 @@ type Manifest = {
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
*
* NOTE on Docker/CI builds: the whole DB access is wrapped in try/catch, so a
* `next build` with no reachable database (the usual Coolify/Docker case) gets
* a minimal valid manifest instead of a crash — same contract as
* generateStaticParams and the sitemap handler. Projects should still mark the
* route dynamic so Next doesn't prerender it at build time:
*
* // app/manifest.ts
* export const dynamic = 'force-dynamic'
*/
export declare function createManifestHandler(opts: {
config: I18nConfig;
+32 -11
View File
@@ -9,22 +9,43 @@ import { getDefaultLocale } from '../i18n/index.js';
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
*
* NOTE on Docker/CI builds: the whole DB access is wrapped in try/catch, so a
* `next build` with no reachable database (the usual Coolify/Docker case) gets
* a minimal valid manifest instead of a crash — same contract as
* generateStaticParams and the sitemap handler. Projects should still mark the
* route dynamic so Next doesn't prerender it at build time:
*
* // app/manifest.ts
* export const dynamic = 'force-dynamic'
*/ export function createManifestHandler(opts) {
return async ()=>{
const defaultLocale = getDefaultLocale(opts.config);
const payload = await opts.getCachedPayload();
const settings = await payload.findGlobal({
slug: opts.settingsSlug ?? 'site-settings',
depth: 1,
locale: defaultLocale
}).catch(()=>null);
const start_url = `/${defaultLocale}`;
// Minimal, always-valid manifest. Used both when SiteSettings is empty and
// when the database is unreachable during a build.
const fallback = {
display: 'standalone',
icons: [],
start_url
};
let settings;
try {
// getCachedPayload() ITSELF throws when the DB can't be reached (e.g.
// `getaddrinfo ENOTFOUND` during `docker build`), BEFORE findGlobal runs
// — so the whole thing, not just the query, must sit inside try/catch.
const payload = await opts.getCachedPayload();
settings = await payload.findGlobal({
slug: opts.settingsSlug ?? 'site-settings',
depth: 1,
locale: defaultLocale
}).catch(()=>null);
} catch (err) {
console.warn('[ipal] createManifestHandler: database not reachable during build (Docker/CI) — returning minimal manifest; it fills in at runtime:', err);
return fallback;
}
if (!settings) {
return {
display: 'standalone',
icons: [],
start_url
};
return fallback;
}
const iconSource = settings.favicon ?? settings.logo;
const icons = [];
File diff suppressed because one or more lines are too long
+1
View File
@@ -25,6 +25,7 @@ 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';
+1
View File
@@ -20,6 +20,7 @@ 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 { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js';
export { buildSeoPlugin } from './seoPluginConfig.js';
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
{"version":3,"sources":["../../../src/modules/seo/index.ts"],"sourcesContent":["export { buildAutoFillMetaHook } from './autoFillMeta.js'\nexport type { AutoFillMapping } from './autoFillMeta.js'\nexport { buildArticleJsonLd } from './buildArticleJsonLd.js'\nexport { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'\nexport { buildFaqJsonLd } from './buildFaqJsonLd.js'\nexport { buildIconsMetadata } from './buildIconsMetadata.js'\nexport { buildLlmsTxt } from './buildLlmsTxt.js'\nexport { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'\nexport { createManifestHandler } from './buildManifest.js'\nexport { buildMetadata } from './buildMetadata.js'\nexport type { PageMetadata } from './buildMetadata.js'\nexport { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'\nexport { buildRobots } from './buildRobots.js'\nexport type { RobotsRules } from './buildRobots.js'\nexport { buildServiceJsonLd } from './buildServiceJsonLd.js'\nexport { buildSitemapEntries } from './buildSitemapEntries.js'\nexport type { SitemapEntry } from './buildSitemapEntries.js'\nexport { buildSitemapXml } from './buildSitemapXml.js'\nexport { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'\nexport { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'\nexport { composeTitle } from './composeTitle.js'\nexport type { TitleOrder } from './composeTitle.js'\nexport { createMetadataGenerator } from './createMetadataGenerator.js'\nexport { createPageMetadata } from './createPageMetadata.js'\nexport { buildHreflangAlternates } from './hreflang.js'\nexport { injectAutoFillMeta } from './injectAutoFillMeta.js'\nexport { injectSeoTabs } from './injectSeoTabs.js'\nexport { JsonLdGraph } from './JsonLdGraph.js'\nexport { readSiteMetaConfig } from './readSiteMetaConfig.js'\nexport type { SiteMetaConfig } from './readSiteMetaConfig.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'\nexport { buildSeoPlugin } from './seoPluginConfig.js'\nexport { slugsAcrossLocales } from './slugsAcrossLocales.js'\nexport type { SeoMeta, SeoOption } from './types.js'\nexport { validateFaviconField } from './validateFavicon.js'\n"],"names":["buildAutoFillMetaHook","buildArticleJsonLd","buildBreadcrumbJsonLd","buildFaqJsonLd","buildIconsMetadata","buildLlmsTxt","buildLocalBusinessJsonLd","createManifestHandler","buildMetadata","buildOrganizationJsonLd","buildRobots","buildServiceJsonLd","buildSitemapEntries","buildSitemapXml","buildSiteNavigationJsonLd","buildWebSiteJsonLd","composeTitle","createMetadataGenerator","createPageMetadata","buildHreflangAlternates","injectAutoFillMeta","injectSeoTabs","JsonLdGraph","readSiteMetaConfig","createLlmsTxtRoute","createSitemapRouteHandler","buildSeoPlugin","slugsAcrossLocales","validateFaviconField"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,oBAAmB;AAEzD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,qBAAqB,QAAQ,6BAA4B;AAClE,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,wBAAwB,QAAQ,gCAA+B;AACxE,SAASC,qBAAqB,QAAQ,qBAAoB;AAC1D,SAASC,aAAa,QAAQ,qBAAoB;AAElD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,WAAW,QAAQ,mBAAkB;AAE9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,mBAAmB,QAAQ,2BAA0B;AAE9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,yBAAyB,QAAQ,iCAAgC;AAC1E,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,uBAAuB,QAAQ,+BAA8B;AACtE,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,uBAAuB,QAAQ,gBAAe;AACvD,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,kBAAkB,EAAEC,yBAAyB,QAAQ,qBAAoB;AAClF,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,SAASC,oBAAoB,QAAQ,uBAAsB"}
+262
View File
@@ -0,0 +1,262 @@
<!--
SZABLON agents.md dla projektów na @intecion/ipal-kit.
UŻYCIE: skopiuj ten plik do ROOTA nowego projektu jako `agents.md` (albo
AGENTS.md). Agenci (Antigravity, Claude Code, Cursor) czytają go automatycznie.
NIE zostawiaj go w docs/ — musi być w katalogu głównym projektu.
Dostosuj tylko to, co oznaczone <!-- DOSTOSUJ -->; reszta to uniwersalne
reguły ekosystemu ipal-kit (nie zmieniaj bez powodu).
Źródło prawdy dla szczegółów: node_modules/@intecion/ipal-kit/docs/
-->
# Zasady i Standardy Projektowe — Payload CMS 3 + Next 16 + @intecion/ipal-kit
> **Projekt:** <!-- DOSTOSUJ: nazwa klienta, domena, rynek (PL/AU/US), branża -->
Niniejszy dokument stanowi bezwzględnie obowiązujące reguły pracy dla agenta (Antigravity) w niniejszym projekcie. Został sporządzony na podstawie dokumentacji w `/docs`. Każda zasada musi być ściśle przestrzegana, bez wyjątków i bez stosowania obejść/prowizorek.
---
## 1. ZASADA NADRZĘDNA: ipal-kit JEST OBOWIĄZKOWY
1. **Obowiązkowe użycie pluginu:**
- Każda funkcja dostarczana przez `@intecion/ipal-kit` (i18n, SEO, formularze, consent, email, slug, bezpieczeństwo, strony systemowe, storage R2, breadcrumbs, JSON-LD) **MUSI** być realizowana przez plugin.
- **NIGDY** nie twórz własnego kodu w projekcie dublującego możliwości pluginu.
2. **Sprawdzaj przed pisaniem:**
- Zanim napiszesz jakąkolwiek funkcję, helper czy komponent — sprawdź dokumentację w `node_modules/@intecion/ipal-kit/docs/` oraz definicje typów `.d.ts`. Jeśli funkcja istnieje w pluginie, **musisz** jej użyć.
3. **Gdy w pluginie czegoś brakuje:**
- **NIE** obchodź braku prowizorką ani własnym kodem w projekcie (to tworzy dług technologiczny i rozbieżności).
- **Zgłoś brak funkcji do rozbudowy pluginu**, zamiast łatać to lokalnie.
- Logika uniwersalna (przydatna w innych projektach) trafia do pluginu. W projekcie znajduje się **wyłącznie** specyfika danego klienta (jego bloki, wygląd, struktura danych).
4. **Gdy coś w pluginie nie działa:**
- **Zgłoś problem i błąd**, zamiast tworzyć ciche obejścia, prowizoryczne hooki czy hardkodowane patche.
---
## 2. KROK 0: INSTALACJA I DOSTĘP DO DOKUMENTACJI PLUGINU
1. **Utwórz `.npmrc` w katalogu projektu:**
```ini
legacy-peer-deps=true
@intecion:registry=https://git.intecion.net/api/packages/IntecionSoftware/npm/
```
*(Scoped override: tylko `@intecion/*` z Gitea, rejestr publiczny bez tokena).*
2. **Instalacja pluginu:**
```bash
pnpm add @intecion/ipal-kit
```
*(NIGDY nie instaluj z gita `git+https://...` — psuje React Client Manifest w Next).*
3. **Lokalizacja dokumentacji źródłowej:**
```bash
ls node_modules/@intecion/ipal-kit/docs/
```
Zawsze korzystaj z plików w `docs/` pluginu (`getting-started.md`, `seo.md`, `forms.md`, `email.md`, `storage.md`, `i18n.md`, `blocks.md`, `turnstile.md` itd.).
---
## 3. ABSOLUTNY ZAKAZ HARDKODOWANIA
### A. Treść i teksty:
- **ZAKAZ:** Tekst widoczny dla użytkownika wpisany w JSX, etykiety i komunikaty w kodzie, instrukcje `if (locale === 'pl')`, tablice z tekstami w kodzie.
- **WYMAGANE:** Każdy tekst pochodzi z pola `localized: true`, pobierany z panelu CMS.
- **Częsty błąd (ukryty hardkod w fallbacku):** `siteName || 'Nazwa Klienta'` lub `catch { return { name: 'Firma...' } }` to **niedopuszczalny hardkod**! Gdy brak danych z panelu/env: **pomiń pole** (np. `...(val ? { name: val } : {})`), nie wstawiaj danych klienta w fallbacku `||` ani w bloku `catch`.
### B. Obrazy i multimedia:
- **ZAKAZ:** `import logo from '@/assets/...'`, ścieżki `src="/images/..."`.
- **WYMAGANE:** Pole `type: 'upload', relationTo: 'media'`, renderowane z `media.url`. Do kolekcji `Media` obowiązkowo wepnij `normalizeFilenameHook`.
- **Preconnect:** Użyj `<MediaPreconnect />` z pluginu (czyta `R2_PUBLIC_URL` z env), nigdy sztywnego tagu `<link>` z domeną.
- **Favicon:** Użyj `buildIconsMetadata(settings.favicon)` z panelu (format PNG, nie ręczny SVG).
### C. Linki i routing:
- **ZAKAZ:** `href="/pl/kontakt"`, menu jako statyczna tablica w kodzie, oraz **sztywna mapa zlokalizowanych ścieżek** (`const localizedRoutes = {...}` — kardynalny antywzorzec).
- **WYMAGANE:** `getLocalizedSlugs` / `switchLocalePath` z bazy danych, `getSystemPagePath`, relacje `relationship -> pages` w panelu CMS.
### D. Konfiguracja i dane firmy:
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
### E. Renderer bloków, kolekcje, formularze (częste błędy):
- **Renderer rich text:** ZAWSZE `RenderRichText` z pluginu (`@intecion/ipal-kit/rsc`, wrapper nad oficjalnym konwerterem Lexical). NIGDY własny parser Lexical (switch po node.type, flagi node.format, dangerouslySetInnerHTML, hardkod `.pl`). Styl przez `converters`. Patrz richtext.md.
- **Renderer bloków:** ZAWSZE `RenderBlocks` z pluginu + mapa `registry`. NIGDY własny `switch (block.blockType)` — to gadatliwe, bez enhanceProps, rośnie liniowo. Mapa deklaratywna, silnik z pluginu.
- **MINIMUM kolekcji, nie maksimum:** Domyślnie tylko rdzeń (pages, media, settings, navigation, footer + globale). Kolekcję treści (blog/produkty) TYLKO gdy klient JAWNIE wymaga. NIGDY nie twórz: `users` (WBUDOWANE w Payload — nie duplikuj!), `daneFirmy`/`settings` jako kolekcje (to GLOBALE), FAQ/hero/features jako kolekcje (to BLOKI). Test przed stworzeniem: lista rekordów + własny URL + jawna potrzeba + Payload nie ma wbudowanego. Patrz `kolekcje-katalog.md`.
- **Formularze z buildera:** ZAWSZE formularz z buildera w panelu (kolekcja Forms) + `submitForm`. NIGDY własny hardkodowany formularz z polami w JSX — omija Turnstile, rate-limit, consent RODO, powiadomienia. Turnstile: `TurnstileProvider` (siteKey raz w layoutcie) + `useTurnstile()` w formularzu.
- **ZAKAZ:** `locale as 'pl' | 'en'`, zaszyty slug kolekcji, dane firmy, NIP, adres, telefon w kodzie.
- **WYMAGANE:** Jedno źródło prawdy `i18n.config.ts`, `locale as never`, dane firmy z globala (np. `siteSettings` / `CompanyInfo`), infrastruktura wyłącznie w `.env`.
---
## 4. ARCHITEKTURA I STRUKTURA PROJEKTU
### A. Next 16 + Payload 3:
- **NIGDY nie twórz `middleware.ts`.** W Next 16 stosuje się **WYŁĄCZNIE `proxy.ts`** (funkcja `proxy`). Jeśli plik `middleware.ts` istnieje — usuń go natychmiast.
- **Struktura katalogów:**
```
src/
app/
(frontend)/
styles.css # Tailwind + @source na plugin
[locale]/
layout.tsx # root layout bez sztywnego <head>
not-found.tsx # 404 (treść z panelu)
[[...slug]]/
page.tsx # render stron z bloków (podwójne nawiasy!)
(payload)/ # panel admina
manifest.ts # PWA z panelu
sitemap.ts # z lib/content + export const dynamic = 'force-dynamic'
robots.ts # z lib/content
blocks/
<NazwaBloku>/
config.ts # schemat pól bloku
Component.tsx # render komponentu
registry.ts # mapa blockType -> komponent
collections/
Pages.ts # layout typu blocks
Media.ts # upload + normalizeFilenameHook
globals/ # siteSettings, siteIntegrations, navigation, footer
lib/
content.ts # createContentHelpers — JEDNO źródło
payload.ts # helpery projektu (getSettings...)
i18n.config.ts # locale — jedno źródło
payload.config.ts
proxy.ts # routing locale (NIE middleware.ts)
```
### B. Przepływ danych i zależności:
- **Brak cykli importów:** Warstwa niższa (bloki) **NIE** może importować warstwy wyższej (`lib/*`). Dane zewnętrzne (np. klucze Turnstile) przekazuj przez `enhanceProps` w `page.tsx`.
- **Dostęp do Payloada:** Jedno źródło `getCachedPayload` w `lib/content.ts`.
- **Server Components (RSC) domyślnie:** Pobieranie danych po stronie serwera; `'use client'` stosuj wyłącznie dla komponentów z lokalnym stanem/interakcją. Chroń wrażliwe moduły przez `import 'server-only'`.
### C. Kluczowe wymagania SEO i Renderingu:
1. **Brak jawnego `<head>` w layoutcie:** Sztywny `<head>` wypycha metatagi Next.js do `<body>`. Pozwól Next.js zarządzać nagłówkiem. `<MediaPreconnect />` umieszczaj w `<body>` (React 19 automatycznie hoistuje tag link do head).
2. **Wymagane ISR:** `export const revalidate = 3600` w `page.tsx` stron (zapobiega race condition streamingu metadanych i zapewnia TTFB ~20ms).
3. **Wymagane `generateStaticParams`:** W `[[...slug]]/page.tsx` eksportuj `generateStaticParams` z `lib/content` (`export { generateStaticParams } from '@/lib/content'`). Gwarantuje synchroniczne generowanie metadanych w `<head>` dla robotów.
4. **`htmlLimitedBots`:** Skonfiguruj w `next.config.ts` zgodnie z `seo.md`.
---
## 5. STANDARDY KODU I TYPOWANIA (POZIOM SENIOR)
1. **Zero `any` i zero `@ts-ignore`:**
- Zawsze typuj precyzyjnie. Jeśli kształt danych z zewnątrz jest nieznany, użyj `unknown` + zawężenie (type guard).
- Wyjątek: wąskie rzutowanie `as unknown as Record<string, unknown>` przy udokumentowanych rozbieżnościach generatora Payload (np. pole zlokalizowane przy `locale: 'all'`).
2. **Typy generowane:** Importuj typy z `@/payload-types` (`pnpm generate:types`), nie twórz ręcznych duplikatów interfejsów.
3. **Generyki przy wywołaniu:** Stosuj np. `getSiteSettings<SiteSetting>(payload)`, a nie rzutowanie `as SiteSetting` na wyniku.
4. **`satisfies` dla konfiguracji:** Używaj `as const satisfies I18nConfig`.
5. **Obsługa błędów:** Nigdy nie połykaj błędów (`catch {}`). Loguj konkretny komunikat i zwracaj kontrolowany błąd. Stosuj guard clauses (płaski kod).
6. **Transakcje i hooki:** W hookach Payload zawsze przekazuj `req` do kolejnych operacji bazodanowych. Chroń hooki przed nieskończonymi pętlami za pomocą flagi w `context` (np. `context.skip`). Przy `payload.find` pamiętaj o `overrideAccess: false`, jeśli operacja ma respektować uprawnienia usera.
---
## 6. NAZEWNICTWO I KONWENCJE
- **Foldery bloków i pliki kolekcji:** PascalCase (`blocks/HeroSection/`, `collections/Pages.ts`).
- **Pliki bloku:** `config.ts` + `Component.tsx` w jednym folderze.
- **Slugi kolekcji:** camelCase, liczba mnoga (`pages`, `blogPosts`, `products`).
- **Slugi bloków:** camelCase (`hero`, `textSection`). Klucz w `registry.ts` musi być identyczny ze slugiem bloku.
- **Wspólne nazwy pól (obowiązkowe w każdym projekcie):**
- Nagłówek: `heading`
- Podtytuł: `subheading`
- Treść: `body` (textarea) lub `content` (richText)
- Obraz: `image` (upload -> media)
- Przycisk CTA: `ctaLabel` (text, localized)
- Cel CTA: `ctaTarget` (relationship -> pages)
- Link zewn.: `url` (text)
- Zgoda prawna: `consent` (checkbox)
---
**Globale Company/Header/Footer → PROJEKT, nie plugin.** Model danych firmy różni się per kraj (NIP/PL, ABN/AU, EIN/US) i branżę. NIE szukaj buildCompanyGlobal w pluginie — zdefiniuj własny src/globals/Company.ts. Schema.org: klocki pluginu (buildOrganizationJsonLd...) + JsonLdGraph, zmapuj SWOJE dane na @type (LegalService/PL, HVACBusiness/AU). Patrz seo.md.
## 6b. WYMAGANIA PRAWNE (COMPLIANCE)
Każda strona (PL/EU) MUSI mieć: polityka prywatności, polityka cookies, baner
zgody cookies, zgoda RODO w formularzach. Plugin dostarcza MECHANIZM:
- **Strony polityk** → System Pages (role: privacyPolicy, cookiePolicy, termsOfService), linkowane przez `getSystemPagePath`.
- **Baner cookies** → CookieBanner + CookieButton + ConsentProvider (analytics/marketing gated — NIE ładują się przed zgodą).
- **Zgoda RODO** → checkbox `consent` w formularzu (enforcement server-side w submitForm).
- **Strony noindex** → polityki/regulamin zaznacz `noindex` w panelu SEO (kanibalizacja fraz).
- **Ochrona:** hook `buildPreventDeleteSystemPage` blokuje usunięcie strony systemowej.
Granica: MY dostarczamy mechanizm, TREŚĆ prawną (tekst polityk) tworzy klient/prawnik.
**Widget dostępności (a11y)** — OPCJONALNY, NIE dodawaj domyślnie. Wymagany tylko
dla podmiotów publicznych / części e-commerce (European Accessibility Act). Dla
zwykłych stron komercyjnych to opcja — dodawaj GDY klient wymaga (AccessibilityProvider
+ AccessibilityWidget + CSS projektu). Patrz `accessibility.md`.
Patrz `wymagania-prawne.md`.
## 6c. HOOKI PLUGINU (automatyzacja)
Wpinaj w kolekcje gdzie dotyczy (patrz `hooks.md`):
- **buildRevalidateHook** (afterChange/afterDelete) — ISR odświeżany po zapisie (redaktor od razu widzi zmianę). `revalidatePath` wstrzykiwany z projektu.
- **trackSlugHistoryHook** (beforeChange) — zmiana slug → zapis starego → projekt robi 301 (stary URL nie daje 404).
- **setPublishedAtHook** — auto-data publikacji (blog).
- **normalizeFilenameHook** — czyste nazwy plików (Media, obowiązkowo).
- **buildPreventDeleteSystemPage** / **buildValidateUniqueRole** — ochrona stron systemowych.
## 6d. BEZPIECZEŃSTWO (nagłówki)
- **buildSecurityHeaders** w next.config — HSTS, COOP, nosniff, Referrer-Policy (z automatu, uniwersalne).
- **buildCsp** — generator CSP z twardymi regułami (base-uri, object-src, frame-ancestors). Flagi: turnstile, analytics, youtube, r2Url. Wdrażaj przez `report-only` → sprawdź konsolę → `enforce`.
- **2FA WYMUSZONE** — `ipalKit({ twoFactor: { issuer: 'Nazwa Firmy' } })` + `pnpm add @clocklimited/payload-2fa@3.0.0-beta.7`. Wymuszone dla WSZYSTKICH użytkowników (forceSetup), bez opcji wyłączenia per user. NIE ustawiaj `twoFactor: false` (chyba że klient wprost odmawia). Bez zależności = błąd buildu. Patrz security.md.
- **Ścieżka panelu** — `ipalKit({ adminRoute: '/its' })` ukrywa panel. WYMAGA przeniesienia folderu `app/(payload)/admin/` → `app/(payload)/its/`. To obscurity, nie security (2FA to prawdziwa ochrona).
- CSP zostaje w projekcie (domeny), ale skeleton z pluginu. NIE Trusted Types (psuje Turnstile/GA).
## 7. PODZIAŁ PRACY I RÓL
- **Antigravity (Agent):** Buduje architekturę, logikę, kolekcje, bloki, routing, edytowalność przez panel, integracje oraz dba o brak hardkodów.
- **Impeccable (osobne narzędzie):** Dopracowuje wygląd, system wizualny na bazie `PRODUCT.md` i `DESIGN.md`. Antigravity nie „dopieszcza" styli ad-hoc kosztem logiki i edytowalności.
- **Klient / Redaktor:** Samodzielnie zarządza każdą treścią z poziomu panelu CMS.
---
## 8. PROCEDURA RAPORTOWANIA DO PLUGINU
Jeśli w trakcie pracy:
1. Funkcja okaże się brakująca w `@intecion/ipal-kit`,
2. Wystąpi błąd wewnętrzny w bibliotece pluginu,
3. Pojawi się powtarzalna potrzeba biznesowa przydatna w wielu projektach,
**Należy natychmiast przygotować raport proponowanej zmiany/rozbudowy pluginu:**
- Dokładny opis problemu / brakującej funkcjonalności,
- Proponowany interfejs API / sygnatura funkcji lub konfiguracji,
- Uzasadnienie uniwersalności dla innych projektów.
**Nie wolno tworzyć cichej łaty w kodzie projektu.**
---
## 9. MAPA DOKUMENTACJI — gdzie szukać szczegółów
Ten plik to skondensowane reguły. Szczegóły w `node_modules/@intecion/ipal-kit/docs/`:
| Chcę... | Plik |
|---|---|
| Zbudować projekt od zera | `getting-started.md` |
| Strukturę, nazewnictwo, konwencje | `fundamenty-projektu.md` |
| Jakie kolekcje budować (minimum!) | `kolekcje-katalog.md` |
| SEO, metadane, sitemap, favicon, structured data, llms.txt | `seo.md` |
| Hooki (revalidate, slug history, ochrona) | `hooks.md` |
| Bezpieczeństwo, CSP, COOP | `security.md` |
| Formularze, Turnstile, submitForm | `forms.md`, `turnstile.md` |
| i18n, strona jednojęzyczna, ścieżki | `i18n.md` |
| Strony systemowe, routing | `pages.md` |
| Bloki, RenderBlocks | `blocks.md` |
| Media, R2, MediaPreconnect | `storage.md` |
| Email (SMTP/Graph) | `email.md` |
| Consent, cookies | `consent.md` |
| Deployment, ISR/SSG, Coolify | `deployment.md` |
| Wymagania prawne, compliance | `wymagania-prawne.md` |
| Filozofia CMS, edytowalność, Impeccable | `architektura-tresci.md` |
| Standardy kodu, antywzorce | `standardy-kodu.md` |
---
## 10. ZAPISZ REGUŁY PROJEKTU
Kluczowe ustalenia projektu (stack, decyzje, tryby stron) zapisz we własnym pliku
kontekstu (`agents.md` / `.agents/context/`), żeby nie gubić ich między sesjami.
Nie polegaj tylko na pamięci sesji.
+49 -42
View File
@@ -480,7 +480,7 @@ typu, itp.):
- dane z panelu (SiteSettings / pola strony) albo env
- nic zaszytego per klient (nazwa, kolor, adres, domena)
- jeśli to uniwersalne i powtarzalne → rozważ zgłoszenie do pluginu zamiast
ręcznie (patrz ANTIGRAVITY-ZASADY-AGENT.md A0)
ręcznie (patrz antigravity_zasady_agent.md A0)
## KRYTYCZNE: metadata w <head> dla Google
@@ -952,51 +952,17 @@ dla Google (crawlery ignorują dyrektywę).
const xml = buildSitemapXml(entries, { cssUrl: '/sitemap.css' })
```
### Starter CSS (public/sitemap.css)
### Gotowy CSS z pluginu
Plugin dostarcza gotowy plik — skopiuj do projektu:
Plugin dostarcza dopracowany `sitemap.css` (auto dark/light, kafelki, pigułki
hreflang, monospace URL). Skopiuj do projektu:
```bash
cp node_modules/@intecion/ipal-kit/dist/modules/seo/assets/sitemap.css public/sitemap.css
```
Albo skopiuj poniższy starter i dostosuj do designu. Selektory to
bezpośrednio nazwy tagów XML:
Dostosuj `--accent` i inne zmienne CSS do brandingu projektu. Selektory to nazwy
tagów XML (`urlset`, `url`, `loc`, `lastmod`, `link`). hreflang pokazuje się jako
pigułka przez `link::before { content: attr(hreflang) }`.
```css
/* public/sitemap.css */
urlset {
display: block;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #090d16; color: #f1f5f9;
padding: 2rem 1.5rem; max-width: 1200px; margin: 0 auto;
}
url { /* każdy adres jako kafelek */
display: block;
background: #111827; border: 1px solid #1e293b; border-radius: 8px;
padding: 1rem 1.25rem; margin-bottom: 0.75rem;
}
loc { /* adres URL */
display: block; font-size: 0.95rem; font-weight: 600;
color: #f97316; margin-bottom: 0.5rem; word-break: break-all;
}
lastmod, changefreq, priority {
display: inline-block; font-size: 0.8rem; color: #94a3b8; margin-right: 1.5rem;
}
lastmod::before { content: 'Ostatnia modyfikacja: '; color: #64748b; }
changefreq::before { content: 'Częstotliwość: '; color: #64748b; }
priority::before { content: 'Priorytet: '; color: #64748b; }
link { /* tagi hreflang */
display: inline-block; font-size: 0.75rem;
background: #1e293b; color: #38bdf8; border: 1px solid #334155;
padding: 0.15rem 0.45rem; border-radius: 4px; margin: 0.4rem 0.35rem 0 0;
}
```
Kluczowe: `display: block` na `<url>`/`<loc>` zamienia „ścianę tekstu" w kafelki.
Etykiety („Ostatnia modyfikacja:") przez `::before`. Dostosuj kolory do projektu.
**Ograniczenie:** `<loc>` to tag XML, nie `<a href>` — CSS nie zrobi z niego
klikalnego linku (niektóre przeglądarki autodetektują URL). Zysk to czytelność
i organizacja, nie klikalność. Dla sitemap (głównie dla robotów) to akceptowalne.
### WAŻNE — jeden sitemap, nie dwa
@@ -1005,4 +971,45 @@ Dwa sitemapy pod różnymi ścieżkami mylą crawlery. Wybierz jeden:
- **route.ts + buildSitemapXml** — czytelny XML w przeglądarce
- **sitemap.ts** (reeksport z lib/content) — mniej kodu, mniej czytelny w przeglądarce
Oba tak samo dobre dla Google — to kwestia czytelności dla człowieka, nie SEO.
Oba tak samo dobre dla Google — to kwestia czytelności dla człowieka, nie SEO.
## JsonLdGraph — opakowanie @graph (bez modelu firmy)
Plugin dostarcza klocki Schema.org (buildWebSiteJsonLd, buildOrganizationJsonLd,
buildLocalBusinessJsonLd, buildSiteNavigationJsonLd...) oraz `JsonLdGraph` —
komponent opakowujący węzły w `@graph` + bezpieczny `<script>`. Ale NIE narzuca
modelu danych firmy.
```tsx
import { JsonLdGraph, buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'
// Projekt buduje węzły ze SWOICH danych i wybiera @type dla SWOJEGO rynku
const website = buildWebSiteJsonLd({ name, url })
const org = buildOrganizationJsonLd({ name, url, logo })
const business = { '@type': 'HVACBusiness', taxID: company.abn, areaServed: company.serviceArea }
<JsonLdGraph schemas={[website, org, business]} />
```
### Granica: dane firmy → PROJEKT, nie plugin
Globale `Company`/`Header`/`Footer` definiuje PROJEKT, nie plugin. Bo model
danych firmy różni się per kraj i branża:
| Kraj | Pola rejestrowe |
|---|---|
| PL | NIP, KRS, REGON (+ barAssociation dla kancelarii, PWZ dla lekarza) |
| AU | ABN, entityName, licenceText, serviceArea |
| US | EIN, State |
| UK | Companies House, VAT ID |
Sztywny `buildCompanyGlobal()` w pluginie byłby **leaky abstraction** — australijski
projekt miałby martwe pole NIP i brakujący ABN. Dlatego:
- **Plugin:** klocki Schema (Organization, LocalBusiness, WebSite, SiteNavigation)
+ JsonLdGraph (opakowanie + bezpieczny render)
- **Projekt:** własny `src/globals/Company.ts` pod kraj/branżę + mapowanie swoich
danych na właściwy `@type` (LegalService w PL, HVACBusiness w AU)
To eliminuje JEDYNE realne powielenie (opakowanie @graph + script, ~20 linii),
zostawiając model danych projektowi (gdzie jego miejsce).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.6.0",
"version": "1.6.4",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
+20
View File
@@ -24,6 +24,26 @@ export {
} from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js'
export { useContactForm } from '../modules/forms/useContactForm.js'
export type {
ContactFormErrors,
ContactFormValues,
SubmitAction,
} from '../modules/forms/useContactForm.js'
export { useForm } from '../modules/forms/useForm.js'
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'
export {
buildValidator,
checked,
custom,
email,
isEmail,
maxLength,
minLength,
pattern,
required,
} from '../modules/forms/validators.js'
export type { Rule } from '../modules/forms/validators.js'
// Pure i18n path helpers — no server/RSC deps, safe to import in client
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
export {
+1
View File
@@ -14,4 +14,5 @@ export type {
} from '../modules/blocks/index.js'
export { RenderRichText } from '../modules/richtext/index.js'
export type { RenderRichTextProps } from '../modules/richtext/index.js'
export { JsonLdGraph } from '../modules/seo/index.js'
export { MediaPreconnect } from '../modules/storage/MediaPreconnect.js'
+17
View File
@@ -67,6 +67,22 @@ export type {
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 {
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'
export {
buildPreventDeleteSystemPage,
@@ -91,6 +107,7 @@ export {
export type { LocaleMiddlewareResult } from './modules/i18n/index.js'
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js'
export { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
export {
getNotificationTexts,
+18
View File
@@ -6,5 +6,23 @@ export type { RateLimitArgs } from './rateLimit.js'
export { submitForm } from './submitForm.js'
export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'
export { useContactForm } from './useContactForm.js'
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'
// Generic form engine (any field set) + the standard contact-form preset.
export { useForm } from './useForm.js'
export type { FormErrors, FormSubmitAction, Validator } from './useForm.js'
export { validateSubmission } from './validateSubmission.js'
export type { FormValidationResult } from './validateSubmission.js'
// Composable validation rules (pure — safe on server or client).
export {
buildValidator,
checked,
custom,
email,
isEmail,
maxLength,
minLength,
pattern,
required,
} from './validators.js'
export type { Rule } from './validators.js'
+91
View File
@@ -0,0 +1,91 @@
'use client'
import { useMemo } from 'react'
import { type FormSubmitAction, useForm } from './useForm.js'
import { buildValidator, checked, email, minLength, required } from './validators.js'
/**
* Field values of the STANDARD contact form. This is a preset shape — projects
* that need a different field set (or dynamic builder fields) should use
* `useForm` directly instead, where the shape is fully open.
*/
export type ContactFormValues = {
consent: boolean
email: string
message: string
name: string
phone: string
topic: string
}
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>
export type SubmitAction = FormSubmitAction<ContactFormValues>
type UseContactFormOptions = {
/** Generic error message shown when the action fails/throws. */
errorFallback?: string
initialTopic?: string
/** Override the per-field error message (shown via `errors.<field>`). */
messages?: Partial<Record<keyof ContactFormValues, string>>
/** Minimum message length. Default 10. */
minMessageLength?: number
/** Whether consent is required (project passes true when consentText shown). */
requireConsent?: boolean
/** Whether a topic must be chosen (project passes this when topics exist). */
requireTopic?: boolean
/** Require a Turnstile token before submit (when the widget is shown). */
requireTurnstile?: boolean
submitAction: SubmitAction
}
/**
* Zero-config preset over `useForm` for the everyday contact form: standard
* fields (name/email/phone/topic/message/consent) and standard rules, wired
* for you. Markup and styling stay 100% in the project — this only removes the
* duplicated logic.
*
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
*
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
*/
export function useContactForm(options: UseContactFormOptions) {
const {
errorFallback,
initialTopic = '',
messages,
minMessageLength = 10,
requireConsent = false,
requireTopic = false,
requireTurnstile = false,
submitAction,
} = options
const validate = useMemo(
() =>
buildValidator<ContactFormValues>({
name: [required(messages?.name)],
email: [required(messages?.email), email(messages?.email)],
...(requireTopic ? { topic: [required(messages?.topic)] } : {}),
message: [required(messages?.message), minLength(minMessageLength, messages?.message)],
...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),
}),
[requireTopic, requireConsent, minMessageLength, messages],
)
return useForm<ContactFormValues>({
errorFallback,
initialValues: {
name: '',
consent: false,
email: '',
message: '',
phone: '',
topic: initialTopic,
},
requireTurnstile,
submitAction,
validate,
})
}
+172
View File
@@ -0,0 +1,172 @@
'use client'
import { useState, useCallback, useRef, useMemo } from 'react'
/**
* Error map: a field key → its error message. A field is "in error" iff it has
* a key here, so `errors.email` is both the truthy flag (for a red border) AND
* the message (to display). Empty object = valid.
*/
export type FormErrors<T> = Partial<Record<keyof T, string>>
/**
* The project's server action that calls submitForm (server-only, holds the
* Turnstile secret). This hook is a client hook, so it can't call submitForm
* directly — the project injects its action. The result only needs `success`
* plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.
*/
export type FormSubmitAction<T> = (
values: T,
turnstileToken?: string,
) => Promise<{ success: boolean; message?: string }>
/** Turns the current values into an error map. Empty map = valid. */
export type Validator<T> = (values: T) => FormErrors<T>
type UseFormOptions<T extends Record<string, unknown>> = {
/** Defines the field set AND the reset state. Any shape you like. */
initialValues: T
submitAction: FormSubmitAction<T>
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
validate?: Validator<T>
/** Require a Turnstile token before submit (when the widget is shown). */
requireTurnstile?: boolean
/** Generic error message shown when the action fails/throws with no message. */
errorFallback?: string
/** Clear a field's error as soon as the user edits it. Default true. */
clearErrorOnChange?: boolean
}
/**
* Fully generic form engine: state, validation, Turnstile token, submit,
* success/error — WITHOUT any markup. The project owns 100% of the look AND
* the field set: there is no baked-in shape here. Replaces the identical
* ~150 lines of form plumbing copied into every project.
*
* The field set comes from `initialValues`; the rules come from `validate`
* (so dynamic/builder-driven forms just build both at runtime). For the
* everyday contact form use the `useContactForm` preset instead — it wires
* the standard fields and rules for you.
*
* const f = useForm({
* initialValues: { email: '', message: '' },
* submitAction, // your server action
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
* requireTurnstile: Boolean(siteKey),
* })
* <input value={f.values.email}
* onChange={(e) => f.setField('email', e.target.value)}
* className={f.errors.email ? 'border-red-500' : '…'} />
* <form onSubmit={f.handleSubmit}>…</form>
*/
export function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>) {
const {
initialValues,
submitAction,
validate,
requireTurnstile = false,
errorFallback = 'Something went wrong. Please try again.',
clearErrorOnChange = true,
} = options
// Freeze the initial snapshot so `reset` is stable even though callers pass a
// fresh object literal every render.
const initialRef = useRef(initialValues)
const [values, setValues] = useState<T>(initialRef.current)
const [errors, setErrors] = useState<FormErrors<T>>({})
const [isSubmitting, setIsSubmitting] = useState(false)
const [isSuccess, setIsSuccess] = useState(false)
const [errorMessage, setErrorMessage] = useState<string | null>(null)
const [turnstileToken, setTurnstileToken] = useState<string | null>(null)
const setField = useCallback(
<K extends keyof T>(key: K, value: T[K]) => {
setValues((prev) => ({ ...prev, [key]: value }))
if (clearErrorOnChange) {
setErrors((prev) => {
if (!prev[key]) return prev
const next = { ...prev }
delete next[key]
return next
})
}
},
[clearErrorOnChange],
)
// Validate against the LATEST values via a ref, so handleSubmit stays stable
// and never reads a stale snapshot.
const valuesRef = useRef(values)
valuesRef.current = values
const validateRef = useRef(validate)
validateRef.current = validate
const handleSubmit = useCallback(
async (e?: { preventDefault?: () => void }) => {
e?.preventDefault?.()
setErrorMessage(null)
const errs = validateRef.current ? validateRef.current(valuesRef.current) : {}
setErrors(errs)
if (Object.keys(errs).length > 0) return
if (requireTurnstile && !turnstileToken) {
setErrorMessage(errorFallback)
return
}
setIsSubmitting(true)
try {
const result = await submitAction(valuesRef.current, turnstileToken ?? undefined)
if (result.success) {
setIsSuccess(true)
setTurnstileToken(null)
} else {
setErrorMessage(result.message || errorFallback)
}
} catch (err) {
setErrorMessage(err instanceof Error ? err.message : errorFallback)
} finally {
setIsSubmitting(false)
}
},
[requireTurnstile, turnstileToken, submitAction, errorFallback],
)
const reset = useCallback(() => {
setValues(initialRef.current)
setErrors({})
setIsSuccess(false)
setErrorMessage(null)
setTurnstileToken(null)
}, [])
return useMemo(
() => ({
values,
errors,
isSubmitting,
isSuccess,
errorMessage,
turnstileToken,
setField,
setValues,
setErrors,
setTurnstileToken,
handleSubmit,
reset,
}),
[
values,
errors,
isSubmitting,
isSuccess,
errorMessage,
turnstileToken,
setField,
handleSubmit,
reset,
],
)
}
+100
View File
@@ -0,0 +1,100 @@
import type { FormErrors, Validator } from './useForm.js'
/**
* Composable validation rules + a builder that turns a per-field schema into a
* `Validator<T>`. These are the bits that actually repeat across projects
* (required / email / min-length / checkbox-must-be-true); the field SET and
* the MARKUP stay in the project.
*
* Pure functions, no 'use client' — usable both in the client `useForm` hook
* and server-side (e.g. re-validating inside a server action).
*
* const validate = buildValidator<MyValues>({
* email: [required(), email()],
* message: [required(), minLength(10)],
* consent: [checked()],
* })
*
* Dynamic / builder-driven forms build the schema at runtime:
*
* const schema = Object.fromEntries(
* fields.map((f) => [f.name, f.required ? [required()] : []]),
* )
* const validate = buildValidator(schema)
*/
/** 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
const EMAIL_RE = /^[^\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())
/** Non-empty string, non-null, and (for checkboxes) not `false`. */
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
return true
}
export const email =
(msg = 'invalid email'): Rule =>
(v) =>
isEmail(v) ? true : msg
export const minLength =
(n: number, msg?: string): Rule =>
(v) =>
typeof v === 'string' && v.trim().length >= n ? true : (msg ?? `min ${n} chars`)
export const maxLength =
(n: number, msg?: string): Rule =>
(v) =>
typeof v === 'string' && v.trim().length <= n ? true : (msg ?? `max ${n} chars`)
/** Checkbox must be ticked (true). */
export const checked =
(msg = 'required'): Rule =>
(v) =>
v === true ? true : msg
/** Value must match a regex (ignored when empty — pair with `required` to force). */
export const pattern =
(re: RegExp, msg = 'invalid format'): Rule =>
(v) =>
typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg
/** Escape hatch: any predicate → rule. */
export const custom =
(test: (value: unknown, values: Record<string, unknown>) => boolean, msg: string): Rule =>
(v, values) =>
test(v, values) ? true : msg
/**
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
* field wins. Fields with no rules (or an empty list) are skipped.
*/
export function buildValidator<T extends Record<string, unknown>>(
schema: Partial<Record<keyof T, Rule[]>>,
): Validator<T> {
return (values) => {
const errs: FormErrors<T> = {}
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
for (const rule of rules) {
const res = rule(all[key], all)
if (res !== true) {
errs[key as keyof T] = res
break
}
}
}
return errs
}
}
+1
View File
@@ -16,5 +16,6 @@ export { buildLocalizationConfig } from './localizationConfig.js'
export { buildLocalizedPath, switchLocalePath } from './localizedPath.js'
export type { LocalizedSlugs } from './localizedPath.js'
export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './negotiateLocale.js'
export { resolveLocalized } from './resolveLocalized.js'
export type { I18nConfig, LocaleDefinition } from './types.js'
export { validateI18nConfig } from './validation.js'
+24
View File
@@ -0,0 +1,24 @@
/**
* Resolves a possibly-localized value to a string for the given locale.
* Payload returns a localized field as a plain string (current locale) OR, with
* locale:'all' / unflattened docs, as a { pl: '…', en: '…' } map. This handles
* both, with a safe fallback to the first available value — replacing the
* hand-rolled `getSafeString` with `any` copied into every project (JSON-LD,
* rich text, form topics, …).
*
* import { resolveLocalized } from '@intecion/ipal-kit'
* const name = resolveLocalized(item.label, locale) // '' if nothing
* const city = resolveLocalized(company.city, locale, '—') // custom fallback
*/
export function resolveLocalized(value: unknown, locale: string, fallback = ''): string {
if (value == null) {return fallback}
if (typeof value === 'string') {return value}
if (typeof value === 'object') {
const map = value as Record<string, unknown>
const forLocale = map[locale]
if (typeof forLocale === 'string') {return forLocale}
const first = Object.values(map).find((v) => typeof v === 'string')
return (first) ?? fallback
}
return String(value)
}
+41
View File
@@ -0,0 +1,41 @@
type JsonLdSchema = Record<string, unknown>
/**
* Renders one or more schema.org objects as a single JSON-LD @graph in a
* <script type="application/ld+json">. The plugin owns ONLY the wrapping and the
* safe serialization — NOT the schema contents. The project builds its own nodes
* (with the plugin's buildWebSiteJsonLd / buildOrganizationJsonLd /
* buildLocalBusinessJsonLd / buildSiteNavigationJsonLd helpers) and maps its own
* company data to the right @type.
*
* Why not a <GlobalJsonLd> that reads Company/Header: company data is a business
* domain that varies by country and industry (NIP/KRS in PL, ABN in AU, EIN in
* US; barAssociation for a law firm, licenceText for an HVAC business). A fixed
* model would be a leaky abstraction. So the project decides the @type and
* fields; the plugin just wraps and renders safely.
*
* // project — build nodes from YOUR data, choose the @type for YOUR market
* import { JsonLdGraph, buildWebSiteJsonLd, buildOrganizationJsonLd } from '@intecion/ipal-kit'
* const website = buildWebSiteJsonLd({ name, url })
* const org = buildOrganizationJsonLd({ name, url, logo })
* const localBusiness = { '@type': 'HVACBusiness', taxID: company.abn, areaServed: company.serviceArea, ... }
* <JsonLdGraph schemas={[website, org, localBusiness]} />
*
* Replaces the ~140-line JsonLd.tsx (only the @graph wrapper + <script> was
* actually duplicated; the schema mapping stays in the project where it belongs).
*/
export function JsonLdGraph({ schemas }: { schemas: Array<JsonLdSchema | null | undefined> }) {
const graph = schemas.filter((s): s is JsonLdSchema => Boolean(s))
if (graph.length === 0) {return null}
const json = JSON.stringify({ '@context': 'https://schema.org', '@graph': graph })
return (
<script
// Escape '<' to prevent the JSON from breaking out of the script tag
// (XSS hardening) — the only safety concern the plugin owns here.
dangerouslySetInnerHTML={{ __html: json.replace(/</g, '\\u003c') }}
type="application/ld+json"
/>
)
}
+36 -10
View File
@@ -39,6 +39,15 @@ type SettingsShape = {
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
*
* NOTE on Docker/CI builds: the whole DB access is wrapped in try/catch, so a
* `next build` with no reachable database (the usual Coolify/Docker case) gets
* a minimal valid manifest instead of a crash — same contract as
* generateStaticParams and the sitemap handler. Projects should still mark the
* route dynamic so Next doesn't prerender it at build time:
*
* // app/manifest.ts
* export const dynamic = 'force-dynamic'
*/
export function createManifestHandler(opts: {
config: I18nConfig
@@ -47,18 +56,35 @@ export function createManifestHandler(opts: {
}): () => Promise<Manifest> {
return async () => {
const defaultLocale = getDefaultLocale(opts.config)
const payload = await opts.getCachedPayload()
const settings = (await payload
.findGlobal({
slug: (opts.settingsSlug ?? 'site-settings') as never,
depth: 1,
locale: defaultLocale as never,
})
.catch(() => null)) as null | SettingsShape
const start_url = `/${defaultLocale}`
// Minimal, always-valid manifest. Used both when SiteSettings is empty and
// when the database is unreachable during a build.
const fallback: Manifest = { display: 'standalone', icons: [], start_url }
let settings: null | SettingsShape
try {
// getCachedPayload() ITSELF throws when the DB can't be reached (e.g.
// `getaddrinfo ENOTFOUND` during `docker build`), BEFORE findGlobal runs
// — so the whole thing, not just the query, must sit inside try/catch.
const payload = await opts.getCachedPayload()
settings = (await payload
.findGlobal({
slug: (opts.settingsSlug ?? 'site-settings') as never,
depth: 1,
locale: defaultLocale as never,
})
.catch(() => null)) as null | SettingsShape
} catch (err) {
console.warn(
'[ipal] createManifestHandler: database not reachable during build (Docker/CI) — returning minimal manifest; it fills in at runtime:',
err,
)
return fallback
}
if (!settings) {
return { display: 'standalone', icons: [], start_url }
return fallback
}
const iconSource = settings.favicon ?? settings.logo
+1
View File
@@ -25,6 +25,7 @@ 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'