diff --git a/dist/globals/SiteIntegrations/fields/analytics.d.ts b/dist/globals/SiteIntegrations/fields/analytics.d.ts index 518dfbd..2a725e8 100644 --- a/dist/globals/SiteIntegrations/fields/analytics.d.ts +++ b/dist/globals/SiteIntegrations/fields/analytics.d.ts @@ -1,6 +1,7 @@ import type { Field } from 'payload'; /** - * Analytics configuration — GA4 measurement ID and GTM container ID. - * IDs are public (exposed client-side), so no read restriction needed. + * Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no + * read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only + * after the matching consent category is granted (see modules/analytics). */ export declare const analyticsFields: Field[]; diff --git a/dist/globals/SiteIntegrations/fields/analytics.js b/dist/globals/SiteIntegrations/fields/analytics.js index 31e3543..eb39a18 100644 --- a/dist/globals/SiteIntegrations/fields/analytics.js +++ b/dist/globals/SiteIntegrations/fields/analytics.js @@ -1,12 +1,13 @@ /** - * Analytics configuration — GA4 measurement ID and GTM container ID. - * IDs are public (exposed client-side), so no read restriction needed. + * Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no + * read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only + * after the matching consent category is granted (see modules/analytics). */ export const analyticsFields = [ { name: 'ga4MeasurementId', type: 'text', admin: { - description: 'Google Analytics 4 Measurement ID.', + description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)', placeholder: 'G-XXXXXXXXXX' } }, @@ -14,9 +15,41 @@ name: 'gtmContainerId', type: 'text', admin: { - description: 'Google Tag Manager container ID.', + description: 'Google Tag Manager container ID. (Google — Consent Mode)', placeholder: 'GTM-XXXXXXX' } + }, + { + name: 'metaPixelId', + type: 'text', + admin: { + description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.', + placeholder: '1234567890123456' + } + }, + { + name: 'clarityProjectId', + type: 'text', + admin: { + description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.', + placeholder: 'abcdefghij' + } + }, + { + name: 'linkedInPartnerId', + type: 'text', + admin: { + description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.', + placeholder: '1234567' + } + }, + { + name: 'tiktokPixelId', + type: 'text', + admin: { + description: 'TikTok Pixel ID. Loads only after MARKETING consent.', + placeholder: 'CXXXXXXXXXXXXXXXXXXX' + } } ]; diff --git a/dist/globals/SiteIntegrations/fields/analytics.js.map b/dist/globals/SiteIntegrations/fields/analytics.js.map index 34eed37..291c1f1 100644 --- a/dist/globals/SiteIntegrations/fields/analytics.js.map +++ b/dist/globals/SiteIntegrations/fields/analytics.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/analytics.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Analytics configuration — GA4 measurement ID and GTM container ID.\n * IDs are public (exposed client-side), so no read restriction needed.\n */\nexport const analyticsFields: Field[] = [\n {\n name: 'ga4MeasurementId',\n type: 'text',\n admin: {\n description: 'Google Analytics 4 Measurement ID.',\n placeholder: 'G-XXXXXXXXXX',\n },\n },\n {\n name: 'gtmContainerId',\n type: 'text',\n admin: {\n description: 'Google Tag Manager container ID.',\n placeholder: 'GTM-XXXXXXX',\n },\n },\n]\n"],"names":["analyticsFields","name","type","admin","description","placeholder"],"mappings":"AAEA;;;CAGC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;CACD,CAAA"} \ No newline at end of file +{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/analytics.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no\n * read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only\n * after the matching consent category is granted (see modules/analytics).\n */\nexport const analyticsFields: Field[] = [\n {\n name: 'ga4MeasurementId',\n type: 'text',\n admin: {\n description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)',\n placeholder: 'G-XXXXXXXXXX',\n },\n },\n {\n name: 'gtmContainerId',\n type: 'text',\n admin: {\n description: 'Google Tag Manager container ID. (Google — Consent Mode)',\n placeholder: 'GTM-XXXXXXX',\n },\n },\n {\n name: 'metaPixelId',\n type: 'text',\n admin: {\n description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.',\n placeholder: '1234567890123456',\n },\n },\n {\n name: 'clarityProjectId',\n type: 'text',\n admin: {\n description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.',\n placeholder: 'abcdefghij',\n },\n },\n {\n name: 'linkedInPartnerId',\n type: 'text',\n admin: {\n description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.',\n placeholder: '1234567',\n },\n },\n {\n name: 'tiktokPixelId',\n type: 'text',\n admin: {\n description: 'TikTok Pixel ID. Loads only after MARKETING consent.',\n placeholder: 'CXXXXXXXXXXXXXXXXXXX',\n },\n },\n]\n"],"names":["analyticsFields","name","type","admin","description","placeholder"],"mappings":"AAEA;;;;CAIC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACbC,aAAa;QACf;IACF;CACD,CAAA"} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts index 12a59df..c3e3b9c 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -7,7 +7,7 @@ export { getAnalyticsConfig } from './modules/analytics/index.js'; export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent, } from './modules/consent/index.js'; export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'; export type { ContentCollectionOption, ContentOption, ResolvedRoute, } from './modules/content/index.js'; -export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js'; +export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent, } from './modules/content/index.js'; export type { ArchiveEntries } from './modules/content/index.js'; export type { SearchResult } from './modules/content/index.js'; export { graphAdapter } from './modules/email/graphAdapter.js'; diff --git a/dist/index.js b/dist/index.js index 4ebd7bb..5eb1923 100644 --- a/dist/index.js +++ b/dist/index.js @@ -2,7 +2,7 @@ export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSe export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'; export { getAnalyticsConfig } from './modules/analytics/index.js'; export { ACCEPT_ALL_CONSENT, CONSENT_CATEGORIES, CONSENT_COOKIE, CONSENT_MAX_AGE, CONSENT_VERSION, DEFAULT_CONSENT, getConsentTexts, parseConsent, REJECT_ALL_CONSENT, serializeConsent, setDefaultConsent, updateConsent } from './modules/consent/index.js'; -export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js'; +export { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js'; export { graphAdapter } from './modules/email/graphAdapter.js'; export { mailAdapter } from './modules/email/mailAdapter.js'; // Imported straight from the file, NOT from ./modules/email/index.js — that diff --git a/dist/index.js.map b/dist/index.js.map index 807a1e2..6f5a1c5 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type { AccessOption, Role } from './modules/access/index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport {\n A11Y_COOKIE,\n A11Y_DEFAULT,\n a11yAttributes,\n parseA11y,\n serializeA11y,\n} from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n DEFAULT_CONSENT,\n getConsentTexts,\n parseConsent,\n REJECT_ALL_CONSENT,\n serializeConsent,\n setDefaultConsent,\n updateConsent,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\nexport type {\n ContentCollectionOption,\n ContentOption,\n ResolvedRoute,\n} from './modules/content/index.js'\nexport {\n archiveFieldName,\n blocksToMarkdown,\n buildArchivePath,\n buildEntryPath,\n createMarkdownRenderer,\n createSearchRoute,\n getArchiveEntries,\n MARKDOWN_PREFIX,\n markdownHref,\n markdownResponse,\n parsePageParam,\n prefersMarkdown,\n resolveRedirect,\n resolveRoute,\n searchContent,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport type { SearchResult } from './modules/content/index.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\n// Boot-time environment validation (fail fast on misconfigured deploys).\nexport { assertEnv, ipalEnvRules } from './modules/env/index.js'\nexport type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'\n// Panel-managed form analytics (config-time field builder).\nexport { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'\nexport type {\n FormsCollectionOverrides,\n FormsFieldsOverride,\n FormsOption,\n} from './modules/forms/types.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'\n// Validation rules are pure — exported server-side too, for re-validating a\n// submission inside a server action. (useForm/useContactForm are client-only →\n// '@intecion/ipal-kit/client'.)\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'\nexport { createContentHelpers } from './modules/frontend/index.js'\n// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).\nexport { createHealthRoute } from './modules/health/index.js'\nexport {\n buildCrossLocaleFieldSync,\n buildPreventDeleteSystemPage,\n buildRevalidateHook,\n buildValidateUniqueRole,\n setPublishedAtHook,\n trackSlugHistoryHook,\n} from './modules/hooks/index.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { resolveLocalized } from './modules/i18n/index.js'\n// Read-only MCP server (Claude/agents connect to the site and query it).\nexport { createMcpRoute } from './modules/mcp/index.js'\nexport { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'\nexport {\n getNotificationTexts,\n NOTIFICATION_FALLBACK,\n resolveFormMessage,\n} from './modules/notifications/index.js'\nexport type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteIntegrations,\n getSiteSettings,\n SITE_INTEGRATIONS_SLUG,\n SITE_SETTINGS_SLUG,\n} from './modules/payload/index.js'\n// Lexical → Markdown (pure, no React) — for AI-readable output.\nexport { lexicalToMarkdown } from './modules/richtext/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\nexport { buildCsp } from './modules/security/index.js'\n\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'\nexport type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'\nexport { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'\nexport type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js'\nexport {\n AI_ASSISTANT_BOTS,\n AI_TRAINING_BOTS,\n buildAutoFillMetaHook,\n buildRobots,\n buildSitemapEntries,\n createMetadataGenerator,\n createPageMetadata,\n injectAutoFillMeta,\n} from './modules/seo/index.js'\nexport {\n createLlmsTxtRoute,\n createManifestHandler,\n createSitemapRouteHandler,\n} from './modules/seo/index.js'\nexport {\n buildIconsMetadata,\n buildOrganizationJsonLd,\n validateFaviconField,\n} from './modules/seo/index.js'\nexport { buildNoindexField } from './modules/seo/index.js'\nexport { buildSpeakableJsonLd } from './modules/seo/index.js'\nexport { buildSummaryField } from './modules/seo/index.js'\nexport {\n buildBreadcrumbJsonLd,\n buildSiteNavigationJsonLd,\n buildWebSiteJsonLd,\n} from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport {\n buildFaqJsonLd,\n buildLocalBusinessJsonLd,\n buildServiceJsonLd,\n} from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapXml } from './modules/seo/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\n"],"names":["adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y","getAnalyticsConfig","ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","DEFAULT_CONSENT","getConsentTexts","parseConsent","REJECT_ALL_CONSENT","serializeConsent","setDefaultConsent","updateConsent","archiveFieldName","blocksToMarkdown","buildArchivePath","buildEntryPath","createMarkdownRenderer","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","markdownResponse","parsePageParam","prefersMarkdown","resolveRedirect","resolveRoute","searchContent","graphAdapter","mailAdapter","panelSmtpAdapter","assertEnv","ipalEnvRules","buildFormAnalyticsFields","buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","createContentHelpers","createHealthRoute","buildCrossLocaleFieldSync","buildPreventDeleteSystemPage","buildRevalidateHook","buildValidateUniqueRole","setPublishedAtHook","trackSlugHistoryHook","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","resolveLocalized","createMcpRoute","normalizeFilename","normalizeFilenameHook","getNotificationTexts","NOTIFICATION_FALLBACK","resolveFormMessage","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","getGlobal","getSiteIntegrations","getSiteSettings","SITE_INTEGRATIONS_SLUG","SITE_SETTINGS_SLUG","lexicalToMarkdown","buildSecurityHeaders","buildCsp","buildHreflangAlternates","buildMetadata","composeTitle","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildAutoFillMetaHook","buildRobots","buildSitemapEntries","createMetadataGenerator","createPageMetadata","injectAutoFillMeta","createLlmsTxtRoute","createManifestHandler","createSitemapRouteHandler","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","buildSpeakableJsonLd","buildSummaryField","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildWebSiteJsonLd","buildFaqJsonLd","buildLocalBusinessJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapXml","buildSlugField","toSlug","buildR2Storage","ipalKit"],"mappings":"AACA,SACEA,SAAS,EACTC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,EACbC,cAAc,EACdC,OAAO,EACPC,QAAQ,EACRC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,QACT,4BAA2B;AAClC,SACEC,WAAW,EACXC,YAAY,EACZC,cAAc,EACdC,SAAS,EACTC,aAAa,QACR,mCAAkC;AAGzC,SAASC,kBAAkB,QAAQ,+BAA8B;AACjE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,QACR,6BAA4B;AAOnC,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,gBAAgB,EAChBC,cAAc,EACdC,sBAAsB,EACtBC,iBAAiB,EACjBC,iBAAiB,EACjBC,eAAe,EACfC,YAAY,EACZC,gBAAgB,EAChBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,aAAa,QACR,6BAA4B;AAGnC,SAASC,YAAY,QAAQ,kCAAiC;AAE9D,SAASC,WAAW,QAAQ,iCAAgC;AAE5D,4EAA4E;AAC5E,gFAAgF;AAChF,gFAAgF;AAChF,SAASC,gBAAgB,QAAQ,sCAAqC;AAEtE,yEAAyE;AACzE,SAASC,SAAS,EAAEC,YAAY,QAAQ,yBAAwB;AAEhE,4DAA4D;AAC5D,SAASC,wBAAwB,QAAQ,yCAAwC;AACjF,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,8BAA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qB,EACrBC,WAAW,EACXC,mBAAmB,EACnBC,uBAAuB,EACvBC,kBAAkB,EAClBC,kBAAkB,QACb,yBAAwB;AAC/B,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,yBAAyB,QACpB,yBAAwB;AAC/B,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,oBAAoB,QACf,yBAAwB;AAC/B,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,kBAAkB,QACb,yBAAwB;AAC/B,qFAAqF;AACrF,SACEC,cAAc,EACdC,wBAAwB,EACxBC,kBAAkB,QACb,yBAAwB;AAC/B,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,cAAc,EAAEC,MAAM,QAAQ,0BAAyB;AAChE,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,OAAO,QAAQ,cAAa"} \ No newline at end of file +{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export type { AccessOption, Role } from './modules/access/index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport {\n A11Y_COOKIE,\n A11Y_DEFAULT,\n a11yAttributes,\n parseA11y,\n serializeA11y,\n} from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n DEFAULT_CONSENT,\n getConsentTexts,\n parseConsent,\n REJECT_ALL_CONSENT,\n serializeConsent,\n setDefaultConsent,\n updateConsent,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\nexport type {\n ContentCollectionOption,\n ContentOption,\n ResolvedRoute,\n} from './modules/content/index.js'\nexport {\n archiveFieldName,\n blocksToMarkdown,\n buildArchivePath,\n buildEntryPath,\n createMarkdownRenderer,\n createSearchRoute,\n getArchiveEntries,\n MARKDOWN_PREFIX,\n markdownHref,\n markdownResponse,\n parsePageParam,\n prefersMarkdown,\n resolveNotFoundPage,\n resolveRedirect,\n resolveRoute,\n searchContent,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport type { SearchResult } from './modules/content/index.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\n// Boot-time environment validation (fail fast on misconfigured deploys).\nexport { assertEnv, ipalEnvRules } from './modules/env/index.js'\nexport type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'\n// Panel-managed form analytics (config-time field builder).\nexport { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'\nexport type {\n FormsCollectionOverrides,\n FormsFieldsOverride,\n FormsOption,\n} from './modules/forms/types.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'\n// Validation rules are pure — exported server-side too, for re-validating a\n// submission inside a server action. (useForm/useContactForm are client-only →\n// '@intecion/ipal-kit/client'.)\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'\nexport { createContentHelpers } from './modules/frontend/index.js'\n// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).\nexport { createHealthRoute } from './modules/health/index.js'\nexport {\n buildCrossLocaleFieldSync,\n buildPreventDeleteSystemPage,\n buildRevalidateHook,\n buildValidateUniqueRole,\n setPublishedAtHook,\n trackSlugHistoryHook,\n} from './modules/hooks/index.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { resolveLocalized } from './modules/i18n/index.js'\n// Read-only MCP server (Claude/agents connect to the site and query it).\nexport { createMcpRoute } from './modules/mcp/index.js'\nexport { normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'\nexport {\n getNotificationTexts,\n NOTIFICATION_FALLBACK,\n resolveFormMessage,\n} from './modules/notifications/index.js'\nexport type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteIntegrations,\n getSiteSettings,\n SITE_INTEGRATIONS_SLUG,\n SITE_SETTINGS_SLUG,\n} from './modules/payload/index.js'\n// Lexical → Markdown (pure, no React) — for AI-readable output.\nexport { lexicalToMarkdown } from './modules/richtext/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\nexport { buildCsp } from './modules/security/index.js'\n\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'\nexport type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'\nexport { buildHreflangAlternates, buildMetadata, composeTitle } from './modules/seo/index.js'\nexport type { AutoFillMapping, RobotsRules, SitemapEntry } from './modules/seo/index.js'\nexport {\n AI_ASSISTANT_BOTS,\n AI_TRAINING_BOTS,\n buildAutoFillMetaHook,\n buildRobots,\n buildSitemapEntries,\n createMetadataGenerator,\n createPageMetadata,\n injectAutoFillMeta,\n} from './modules/seo/index.js'\nexport {\n createLlmsTxtRoute,\n createManifestHandler,\n createSitemapRouteHandler,\n} from './modules/seo/index.js'\nexport {\n buildIconsMetadata,\n buildOrganizationJsonLd,\n validateFaviconField,\n} from './modules/seo/index.js'\nexport { buildNoindexField } from './modules/seo/index.js'\nexport { buildSpeakableJsonLd } from './modules/seo/index.js'\nexport { buildSummaryField } from './modules/seo/index.js'\nexport {\n buildBreadcrumbJsonLd,\n buildSiteNavigationJsonLd,\n buildWebSiteJsonLd,\n} from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport {\n buildFaqJsonLd,\n buildLocalBusinessJsonLd,\n buildServiceJsonLd,\n} from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapXml } from './modules/seo/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\n"],"names":["adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y","getAnalyticsConfig","ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","DEFAULT_CONSENT","getConsentTexts","parseConsent","REJECT_ALL_CONSENT","serializeConsent","setDefaultConsent","updateConsent","archiveFieldName","blocksToMarkdown","buildArchivePath","buildEntryPath","createMarkdownRenderer","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","markdownResponse","parsePageParam","prefersMarkdown","resolveNotFoundPage","resolveRedirect","resolveRoute","searchContent","graphAdapter","mailAdapter","panelSmtpAdapter","assertEnv","ipalEnvRules","buildFormAnalyticsFields","buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","createContentHelpers","createHealthRoute","buildCrossLocaleFieldSync","buildPreventDeleteSystemPage","buildRevalidateHook","buildValidateUniqueRole","setPublishedAtHook","trackSlugHistoryHook","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","resolveLocalized","createMcpRoute","normalizeFilename","normalizeFilenameHook","getNotificationTexts","NOTIFICATION_FALLBACK","resolveFormMessage","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","getGlobal","getSiteIntegrations","getSiteSettings","SITE_INTEGRATIONS_SLUG","SITE_SETTINGS_SLUG","lexicalToMarkdown","buildSecurityHeaders","buildCsp","buildHreflangAlternates","buildMetadata","composeTitle","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildAutoFillMetaHook","buildRobots","buildSitemapEntries","createMetadataGenerator","createPageMetadata","injectAutoFillMeta","createLlmsTxtRoute","createManifestHandler","createSitemapRouteHandler","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","buildSpeakableJsonLd","buildSummaryField","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildWebSiteJsonLd","buildFaqJsonLd","buildLocalBusinessJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapXml","buildSlugField","toSlug","buildR2Storage","ipalKit"],"mappings":"AACA,SACEA,SAAS,EACTC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,EACbC,cAAc,EACdC,OAAO,EACPC,QAAQ,EACRC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,QACT,4BAA2B;AAClC,SACEC,WAAW,EACXC,YAAY,EACZC,cAAc,EACdC,SAAS,EACTC,aAAa,QACR,mCAAkC;AAGzC,SAASC,kBAAkB,QAAQ,+BAA8B;AACjE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,QACR,6BAA4B;AAOnC,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,gBAAgB,EAChBC,cAAc,EACdC,sBAAsB,EACtBC,iBAAiB,EACjBC,iBAAiB,EACjBC,eAAe,EACfC,YAAY,EACZC,gBAAgB,EAChBC,cAAc,EACdC,eAAe,EACfC,mBAAmB,EACnBC,eAAe,EACfC,YAAY,EACZC,aAAa,QACR,6BAA4B;AAGnC,SAASC,YAAY,QAAQ,kCAAiC;AAE9D,SAASC,WAAW,QAAQ,iCAAgC;AAE5D,4EAA4E;AAC5E,gFAAgF;AAChF,gFAAgF;AAChF,SAASC,gBAAgB,QAAQ,sCAAq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SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SAASC,QAAQ,QAAQ,8BAA6B;AAKtD,SAASC,uBAAuB,EAAEC,aAAa,EAAEC,YAAY,QAAQ,yBAAwB;AAE7F,SACEC,iBAAiB,EACjBC,gBAAgB,EAChBC,qBAAqB,EACrBC,WAAW,EACXC,mBAAmB,EACnBC,uBAAuB,EACvBC,kBAAkB,EAClBC,kBAAkB,QACb,yBAAwB;AAC/B,SACEC,kBAAkB,EAClBC,qBAAqB,EACrBC,yBAAyB,QACpB,yBAAwB;AAC/B,SACEC,kBAAkB,EAClBC,uBAAuB,EACvBC,oBAAoB,QACf,yBAAwB;AAC/B,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SACEC,qBAAqB,EACrBC,yBAAyB,EACzBC,kBAAkB,QACb,yBAAwB;AAC/B,qFAAqF;AACrF,SACEC,cAAc,EACdC,wBAAwB,EACxBC,kBAAkB,QACb,yBAAwB;AAC/B,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,eAAe,QAAQ,yBAAwB;AACxD,SAASC,cAAc,EAAEC,MAAM,QAAQ,0BAAyB;AAChE,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,OAAO,QAAQ,cAAa"} \ No newline at end of file diff --git a/dist/modules/analytics/Analytics.d.ts b/dist/modules/analytics/Analytics.d.ts index 4a2fd87..4924bb5 100644 --- a/dist/modules/analytics/Analytics.d.ts +++ b/dist/modules/analytics/Analytics.d.ts @@ -5,15 +5,18 @@ declare global { } } /** - * Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag. + * Loads every configured analytics / marketing tag, each respecting consent: * - * Consent Mode is initialised to the visitor's stored consent BEFORE the tag - * loads (via setDefaultConsent from the consent module), so tags respect the - * choice from the first hit; useConsent sends an update the moment the visitor - * decides. IDs are public and come from SiteIntegrations, passed in as props - * (the client project reads them server-side). + * - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's + * stored choice is set as the default BEFORE the tag loads, and useConsent + * pushes an update the moment they decide. GTM wins if both IDs are set. + * - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have + * no Consent Mode, so they load ONLY after the matching category is granted + * (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to + * the consent banner: accept → the tag loads immediately, no reload. * - * Renders nothing — it only injects the scripts. Mount once, high in the tree - * (e.g. root layout), inside ConsentProvider. + * All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed + * in as props. Renders nothing. Mount once, high in the tree, INSIDE + * (required — it reads live consent state). */ -export declare function Analytics({ ga4MeasurementId, gtmContainerId }: AnalyticsConfig): null; +export declare function Analytics(props: AnalyticsConfig): null; diff --git a/dist/modules/analytics/Analytics.js b/dist/modules/analytics/Analytics.js index f3eef21..0b7a710 100644 --- a/dist/modules/analytics/Analytics.js +++ b/dist/modules/analytics/Analytics.js @@ -1,7 +1,9 @@ 'use client'; import { useEffect } from 'react'; +import { useConsentContext } from '../consent/client.js'; import { gtag } from '../consent/googleConsent.js'; import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js'; +import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'; const GTM_SCRIPT = (id)=>`https://www.googletagmanager.com/gtm.js?id=${id}`; const GA4_SCRIPT = (id)=>`https://www.googletagmanager.com/gtag/js?id=${id}`; /** Reads the current consent state from cookie, or defaults if none. */ function readConsent() { @@ -21,24 +23,29 @@ function injectScript(src) { document.head.appendChild(s); } /** - * Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag. + * Loads every configured analytics / marketing tag, each respecting consent: * - * Consent Mode is initialised to the visitor's stored consent BEFORE the tag - * loads (via setDefaultConsent from the consent module), so tags respect the - * choice from the first hit; useConsent sends an update the moment the visitor - * decides. IDs are public and come from SiteIntegrations, passed in as props - * (the client project reads them server-side). + * - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's + * stored choice is set as the default BEFORE the tag loads, and useConsent + * pushes an update the moment they decide. GTM wins if both IDs are set. + * - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have + * no Consent Mode, so they load ONLY after the matching category is granted + * (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to + * the consent banner: accept → the tag loads immediately, no reload. * - * Renders nothing — it only injects the scripts. Mount once, high in the tree - * (e.g. root layout), inside ConsentProvider. - */ export function Analytics({ ga4MeasurementId, gtmContainerId }) { + * All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed + * in as props. Renders nothing. Mount once, high in the tree, INSIDE + * (required — it reads live consent state). + */ export function Analytics(props) { + const { clarityProjectId, ga4MeasurementId, gtmContainerId, linkedInPartnerId, metaPixelId, tiktokPixelId } = props; + // Live consent state — drives the non-Google pixels. + const { state } = useConsentContext(); + // --- Google: load once, Consent Mode handles gating --- useEffect(()=>{ if (!ga4MeasurementId && !gtmContainerId) { return; } - // 1. Consent Mode default = the visitor's stored choice, before tags load. setDefaultConsent(readConsent()); - // 2. Load the tag. if (gtmContainerId) { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ @@ -48,8 +55,6 @@ function injectScript(src) { injectScript(GTM_SCRIPT(gtmContainerId)); } else if (ga4MeasurementId) { injectScript(GA4_SCRIPT(ga4MeasurementId)); - // Uses the shared gtag (pushes `arguments`, as Google's tags expect); - // real gtag.js wires itself up once the script loads. gtag('js', new Date()); gtag('config', ga4MeasurementId); } @@ -57,6 +62,32 @@ function injectScript(src) { ga4MeasurementId, gtmContainerId ]); + // --- Non-Google: load each when its consent category is granted --- + // The loaders are idempotent, so re-running on state changes is safe; a tag + // loads the first time its category flips to true and never doubles up. + useEffect(()=>{ + if (state.marketing) { + if (metaPixelId) { + loadMetaPixel(metaPixelId); + } + if (linkedInPartnerId) { + loadLinkedIn(linkedInPartnerId); + } + if (tiktokPixelId) { + loadTikTok(tiktokPixelId); + } + } + if (state.analytics && clarityProjectId) { + loadClarity(clarityProjectId); + } + }, [ + state.marketing, + state.analytics, + metaPixelId, + linkedInPartnerId, + tiktokPixelId, + clarityProjectId + ]); return null; } diff --git a/dist/modules/analytics/Analytics.js.map b/dist/modules/analytics/Analytics.js.map index 7fa6bc1..f4b9aaf 100644 --- a/dist/modules/analytics/Analytics.js.map +++ b/dist/modules/analytics/Analytics.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/analytics/Analytics.tsx"],"sourcesContent":["'use client'\nimport { useEffect } from 'react'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { gtag } from '../consent/googleConsent.js'\nimport { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js'\n\ndeclare global {\n interface Window {\n dataLayer?: unknown[]\n }\n}\n\nconst GTM_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtm.js?id=${id}`\nconst GA4_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtag/js?id=${id}`\n\n/** Reads the current consent state from cookie, or defaults if none. */\nfunction readConsent() {\n if (typeof document === 'undefined') {return DEFAULT_CONSENT}\n const raw = document.cookie\n .split('; ')\n .find((c) => c.startsWith(`${CONSENT_COOKIE}=`))\n ?.split('=')[1]\n return parseConsent(raw) ?? DEFAULT_CONSENT\n}\n\nfunction injectScript(src: string) {\n if (document.querySelector(`script[src=\"${src}\"]`)) {return}\n const s = document.createElement('script')\n s.src = src\n s.async = true\n document.head.appendChild(s)\n}\n\n/**\n * Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag.\n *\n * Consent Mode is initialised to the visitor's stored consent BEFORE the tag\n * loads (via setDefaultConsent from the consent module), so tags respect the\n * choice from the first hit; useConsent sends an update the moment the visitor\n * decides. IDs are public and come from SiteIntegrations, passed in as props\n * (the client project reads them server-side).\n *\n * Renders nothing — it only injects the scripts. Mount once, high in the tree\n * (e.g. root layout), inside ConsentProvider.\n */\nexport function Analytics({ ga4MeasurementId, gtmContainerId }: AnalyticsConfig) {\n useEffect(() => {\n if (!ga4MeasurementId && !gtmContainerId) {return}\n\n // 1. Consent Mode default = the visitor's stored choice, before tags load.\n setDefaultConsent(readConsent())\n\n // 2. Load the tag.\n if (gtmContainerId) {\n window.dataLayer = window.dataLayer || []\n window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })\n injectScript(GTM_SCRIPT(gtmContainerId))\n } else if (ga4MeasurementId) {\n injectScript(GA4_SCRIPT(ga4MeasurementId))\n // Uses the shared gtag (pushes `arguments`, as Google's tags expect);\n // real gtag.js wires itself up once the script loads.\n gtag('js', new Date())\n gtag('config', ga4MeasurementId)\n }\n }, [ga4MeasurementId, gtmContainerId])\n\n return null\n}\n"],"names":["useEffect","gtag","CONSENT_COOKIE","DEFAULT_CONSENT","parseConsent","setDefaultConsent","GTM_SCRIPT","id","GA4_SCRIPT","readConsent","document","raw","cookie","split","find","c","startsWith","injectScript","src","querySelector","s","createElement","async","head","appendChild","Analytics","ga4MeasurementId","gtmContainerId","window","dataLayer","push","event","Date","now"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,QAAO;AAIjC,SAASC,IAAI,QAAQ,8BAA6B;AAClD,SAASC,cAAc,EAAEC,eAAe,EAAEC,YAAY,EAAEC,iBAAiB,QAAS,sBAAqB;AAQvG,MAAMC,aAAa,CAACC,KAAe,CAAC,2CAA2C,EAAEA,IAAI;AACrF,MAAMC,aAAa,CAACD,KAAe,CAAC,4CAA4C,EAAEA,IAAI;AAEtF,sEAAsE,GACtE,SAASE;IACP,IAAI,OAAOC,aAAa,aAAa;QAAC,OAAOP;IAAe;IAC5D,MAAMQ,MAAMD,SAASE,MAAM,CACxBC,KAAK,CAAC,MACNC,IAAI,CAAC,CAACC,IAAMA,EAAEC,UAAU,CAAC,GAAGd,eAAe,CAAC,CAAC,IAC5CW,MAAM,IAAI,CAAC,EAAE;IACjB,OAAOT,aAAaO,QAAQR;AAC9B;AAEA,SAASc,aAAaC,GAAW;IAC/B,IAAIR,SAASS,aAAa,CAAC,CAAC,YAAY,EAAED,IAAI,EAAE,CAAC,GAAG;QAAC;IAAM;IAC3D,MAAME,IAAIV,SAASW,aAAa,CAAC;IACjCD,EAAEF,GAAG,GAAGA;IACRE,EAAEE,KAAK,GAAG;IACVZ,SAASa,IAAI,CAACC,WAAW,CAACJ;AAC5B;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASK,UAAU,EAAEC,gBAAgB,EAAEC,cAAc,EAAmB;IAC7E3B,UAAU;QACR,IAAI,CAAC0B,oBAAoB,CAACC,gBAAgB;YAAC;QAAM;QAEjD,2EAA2E;QAC3EtB,kBAAkBI;QAElB,mBAAmB;QACnB,IAAIkB,gBAAgB;YAClBC,OAAOC,SAAS,GAAGD,OAAOC,SAAS,IAAI,EAAE;YACzCD,OAAOC,SAAS,CAACC,IAAI,CAAC;gBAAEC,OAAO;gBAAU,aAAaC,KAAKC,GAAG;YAAG;YACjEhB,aAAaX,WAAWqB;QAC1B,OAAO,IAAID,kBAAkB;YAC3BT,aAAaT,WAAWkB;YACxB,sEAAsE;YACtE,sDAAsD;YACtDzB,KAAK,MAAM,IAAI+B;YACf/B,KAAK,UAAUyB;QACjB;IACF,GAAG;QAACA;QAAkBC;KAAe;IAErC,OAAO;AACT"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/analytics/Analytics.tsx"],"sourcesContent":["'use client'\nimport { useEffect } from 'react'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { useConsentContext } from '../consent/client.js'\nimport { gtag } from '../consent/googleConsent.js'\nimport { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js'\nimport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'\n\ndeclare global {\n interface Window {\n dataLayer?: unknown[]\n }\n}\n\nconst GTM_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtm.js?id=${id}`\nconst GA4_SCRIPT = (id: string) => `https://www.googletagmanager.com/gtag/js?id=${id}`\n\n/** Reads the current consent state from cookie, or defaults if none. */\nfunction readConsent() {\n if (typeof document === 'undefined') {return DEFAULT_CONSENT}\n const raw = document.cookie\n .split('; ')\n .find((c) => c.startsWith(`${CONSENT_COOKIE}=`))\n ?.split('=')[1]\n return parseConsent(raw) ?? DEFAULT_CONSENT\n}\n\nfunction injectScript(src: string) {\n if (document.querySelector(`script[src=\"${src}\"]`)) {return}\n const s = document.createElement('script')\n s.src = src\n s.async = true\n document.head.appendChild(s)\n}\n\n/**\n * Loads every configured analytics / marketing tag, each respecting consent:\n *\n * - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's\n * stored choice is set as the default BEFORE the tag loads, and useConsent\n * pushes an update the moment they decide. GTM wins if both IDs are set.\n * - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have\n * no Consent Mode, so they load ONLY after the matching category is granted\n * (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to\n * the consent banner: accept → the tag loads immediately, no reload.\n *\n * All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed\n * in as props. Renders nothing. Mount once, high in the tree, INSIDE\n * (required — it reads live consent state).\n */\nexport function Analytics(props: AnalyticsConfig) {\n const {\n clarityProjectId,\n ga4MeasurementId,\n gtmContainerId,\n linkedInPartnerId,\n metaPixelId,\n tiktokPixelId,\n } = props\n\n // Live consent state — drives the non-Google pixels.\n const { state } = useConsentContext()\n\n // --- Google: load once, Consent Mode handles gating ---\n useEffect(() => {\n if (!ga4MeasurementId && !gtmContainerId) {return}\n setDefaultConsent(readConsent())\n if (gtmContainerId) {\n window.dataLayer = window.dataLayer || []\n window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() })\n injectScript(GTM_SCRIPT(gtmContainerId))\n } else if (ga4MeasurementId) {\n injectScript(GA4_SCRIPT(ga4MeasurementId))\n gtag('js', new Date())\n gtag('config', ga4MeasurementId)\n }\n }, [ga4MeasurementId, gtmContainerId])\n\n // --- Non-Google: load each when its consent category is granted ---\n // The loaders are idempotent, so re-running on state changes is safe; a tag\n // loads the first time its category flips to true and never doubles up.\n useEffect(() => {\n if (state.marketing) {\n if (metaPixelId) {loadMetaPixel(metaPixelId)}\n if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)}\n if (tiktokPixelId) {loadTikTok(tiktokPixelId)}\n }\n if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)}\n }, [\n state.marketing,\n state.analytics,\n metaPixelId,\n linkedInPartnerId,\n tiktokPixelId,\n clarityProjectId,\n ])\n\n return null\n}\n"],"names":["useEffect","useConsentContext","gtag","CONSENT_COOKIE","DEFAULT_CONSENT","parseConsent","setDefaultConsent","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","GTM_SCRIPT","id","GA4_SCRIPT","readConsent","document","raw","cookie","split","find","c","startsWith","injectScript","src","querySelector","s","createElement","async","head","appendChild","Analytics","props","clarityProjectId","ga4MeasurementId","gtmContainerId","linkedInPartnerId","metaPixelId","tiktokPixelId","state","window","dataLayer","push","event","Date","now","marketing","analytics"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,QAAO;AAIjC,SAASC,iBAAiB,QAAQ,uBAAsB;AACxD,SAASC,IAAI,QAAQ,8BAA6B;AAClD,SAASC,cAAc,EAAEC,eAAe,EAAEC,YAAY,EAAEC,iBAAiB,QAAS,sBAAqB;AACvG,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,cAAa;AAQlF,MAAMC,aAAa,CAACC,KAAe,CAAC,2CAA2C,EAAEA,IAAI;AACrF,MAAMC,aAAa,CAACD,KAAe,CAAC,4CAA4C,EAAEA,IAAI;AAEtF,sEAAsE,GACtE,SAASE;IACP,IAAI,OAAOC,aAAa,aAAa;QAAC,OAAOX;IAAe;IAC5D,MAAMY,MAAMD,S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BAAC3B,aAAa2B;YAAkB;YACvD,IAAIE,eAAe;gBAAC3B,WAAW2B;YAAc;QAC/C;QACA,IAAIC,MAAMQ,SAAS,IAAId,kBAAkB;YAACzB,YAAYyB;QAAiB;IACzE,GAAG;QACDM,MAAMO,SAAS;QACfP,MAAMQ,SAAS;QACfV;QACAD;QACAE;QACAL;KACD;IAED,OAAO;AACT"} \ No newline at end of file diff --git a/dist/modules/analytics/client.d.ts b/dist/modules/analytics/client.d.ts index 9c9534a..4fc2620 100644 --- a/dist/modules/analytics/client.d.ts +++ b/dist/modules/analytics/client.d.ts @@ -1,2 +1,3 @@ export { Analytics } from './Analytics.js'; +export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'; export { pushDataLayer } from './pushDataLayer.js'; diff --git a/dist/modules/analytics/client.js b/dist/modules/analytics/client.js index 292610a..af834e2 100644 --- a/dist/modules/analytics/client.js +++ b/dist/modules/analytics/client.js @@ -1,5 +1,8 @@ 'use client'; export { Analytics } from './Analytics.js'; +// Low-level pixel loaders — exported for manual conversion events if a project +// needs them (Analytics loads them automatically, consent-gated). +export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'; export { pushDataLayer } from './pushDataLayer.js'; //# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/dist/modules/analytics/client.js.map b/dist/modules/analytics/client.js.map index 42b6d7d..5b7bb7c 100644 --- a/dist/modules/analytics/client.js.map +++ b/dist/modules/analytics/client.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,aAAa,QAAQ,qBAAoB"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/analytics/client.ts"],"sourcesContent":["'use client'\nexport { Analytics } from './Analytics.js'\n// Low-level pixel loaders — exported for manual conversion events if a project\n// needs them (Analytics loads them automatically, consent-gated).\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js'\nexport { pushDataLayer } from './pushDataLayer.js'\n"],"names":["Analytics","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","pushDataLayer"],"mappings":"AAAA;AACA,SAASA,SAAS,QAAQ,iBAAgB;AAC1C,+EAA+E;AAC/E,kEAAkE;AAClE,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,cAAa;AAClF,SAASC,aAAa,QAAQ,qBAAoB"} \ No newline at end of file diff --git a/dist/modules/analytics/getAnalyticsConfig.d.ts b/dist/modules/analytics/getAnalyticsConfig.d.ts index 16252a2..54e4400 100644 --- a/dist/modules/analytics/getAnalyticsConfig.d.ts +++ b/dist/modules/analytics/getAnalyticsConfig.d.ts @@ -1,9 +1,8 @@ import type { BasePayload } from 'payload'; import type { AnalyticsConfig } from './types.js'; /** - * Reads the public analytics IDs from SiteIntegrations, server-side. - * - * Returns only the two public IDs (GA4 / GTM) — safe to pass to the client + * Reads the public analytics / marketing tag IDs from SiteIntegrations, + * server-side. All are public (exposed client-side), so safe to pass to the * component. Does NOT expose any secret from SiteIntegrations. */ export declare function getAnalyticsConfig(payload: BasePayload): Promise; diff --git a/dist/modules/analytics/getAnalyticsConfig.js b/dist/modules/analytics/getAnalyticsConfig.js index 2b6cfd0..87f9b57 100644 --- a/dist/modules/analytics/getAnalyticsConfig.js +++ b/dist/modules/analytics/getAnalyticsConfig.js @@ -1,14 +1,17 @@ import { getSiteIntegrations } from '../payload/index.js'; /** - * Reads the public analytics IDs from SiteIntegrations, server-side. - * - * Returns only the two public IDs (GA4 / GTM) — safe to pass to the client + * Reads the public analytics / marketing tag IDs from SiteIntegrations, + * server-side. All are public (exposed client-side), so safe to pass to the * component. Does NOT expose any secret from SiteIntegrations. */ export async function getAnalyticsConfig(payload) { const integrations = await getSiteIntegrations(payload); return { + clarityProjectId: integrations.clarityProjectId ?? null, ga4MeasurementId: integrations.ga4MeasurementId ?? null, - gtmContainerId: integrations.gtmContainerId ?? null + gtmContainerId: integrations.gtmContainerId ?? null, + linkedInPartnerId: integrations.linkedInPartnerId ?? null, + metaPixelId: integrations.metaPixelId ?? null, + tiktokPixelId: integrations.tiktokPixelId ?? null }; } diff --git a/dist/modules/analytics/getAnalyticsConfig.js.map b/dist/modules/analytics/getAnalyticsConfig.js.map index 493a328..633fca3 100644 --- a/dist/modules/analytics/getAnalyticsConfig.js.map +++ b/dist/modules/analytics/getAnalyticsConfig.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/analytics/getAnalyticsConfig.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { getSiteIntegrations } from '../payload/index.js'\n\n/**\n * Reads the public analytics IDs from SiteIntegrations, server-side.\n *\n * Returns only the two public IDs (GA4 / GTM) — safe to pass to the client\n * component. Does NOT expose any secret from SiteIntegrations.\n */\nexport async function getAnalyticsConfig(payload: BasePayload): Promise {\n const integrations = await getSiteIntegrations(payload)\n return {\n ga4MeasurementId: integrations.ga4MeasurementId ?? null,\n gtmContainerId: integrations.gtmContainerId ?? null,\n }\n}\n"],"names":["getSiteIntegrations","getAnalyticsConfig","payload","integrations","ga4MeasurementId","gtmContainerId"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,sBAAqB;AAEzD;;;;;CAKC,GACD,OAAO,eAAeC,mBAAmBC,OAAoB;IAC3D,MAAMC,eAAe,MAAMH,oBAAqCE;IAChE,OAAO;QACLE,kBAAkBD,aAAaC,gBAAgB,IAAI;QACnDC,gBAAgBF,aAAaE,cAAc,IAAI;IACjD;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/analytics/getAnalyticsConfig.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { AnalyticsConfig } from './types.js'\n\nimport { getSiteIntegrations } from '../payload/index.js'\n\n/**\n * Reads the public analytics / marketing tag IDs from SiteIntegrations,\n * server-side. All are public (exposed client-side), so safe to pass to the\n * component. Does NOT expose any secret from SiteIntegrations.\n */\nexport async function getAnalyticsConfig(payload: BasePayload): Promise {\n const integrations = await getSiteIntegrations(payload)\n return {\n clarityProjectId: integrations.clarityProjectId ?? null,\n ga4MeasurementId: integrations.ga4MeasurementId ?? null,\n gtmContainerId: integrations.gtmContainerId ?? null,\n linkedInPartnerId: integrations.linkedInPartnerId ?? null,\n metaPixelId: integrations.metaPixelId ?? null,\n tiktokPixelId: integrations.tiktokPixelId ?? null,\n }\n}\n"],"names":["getSiteIntegrations","getAnalyticsConfig","payload","integrations","clarityProjectId","ga4MeasurementId","gtmContainerId","linkedInPartnerId","metaPixelId","tiktokPixelId"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,sBAAqB;AAEzD;;;;CAIC,GACD,OAAO,eAAeC,mBAAmBC,OAAoB;IAC3D,MAAMC,eAAe,MAAMH,oBAAqCE;IAChE,OAAO;QACLE,kBAAkBD,aAAaC,gBAAgB,IAAI;QACnDC,kBAAkBF,aAAaE,gBAAgB,IAAI;QACnDC,gBAAgBH,aAAaG,cAAc,IAAI;QAC/CC,mBAAmBJ,aAAaI,iBAAiB,IAAI;QACrDC,aAAaL,aAAaK,WAAW,IAAI;QACzCC,eAAeN,aAAaM,aAAa,IAAI;IAC/C;AACF"} \ No newline at end of file diff --git a/dist/modules/analytics/pixels.d.ts b/dist/modules/analytics/pixels.d.ts new file mode 100644 index 0000000..c12a0ac --- /dev/null +++ b/dist/modules/analytics/pixels.d.ts @@ -0,0 +1,21 @@ +/** + * Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards + * against double-init) and loads the vendor's own script + bootstrap. + * + * These are the one place `any` is unavoidable: vendor SDK bootstraps attach + * untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained + * here; nothing else in the kit uses `any`. + * + * CONSENT: these vendors have no Google Consent Mode — the caller (Analytics) + * loads each ONLY after the matching consent category is granted: + * Meta Pixel / LinkedIn / TikTok → marketing + * Microsoft Clarity → analytics + */ +/** Meta (Facebook) Pixel — fires PageView on load. */ +export declare function loadMetaPixel(id: string): void; +/** Microsoft Clarity — heatmaps / session recordings (analytics category). */ +export declare function loadClarity(id: string): void; +/** LinkedIn Insight Tag (marketing). */ +export declare function loadLinkedIn(partnerId: string): void; +/** TikTok Pixel (marketing) — fires page view on load. */ +export declare function loadTikTok(id: string): void; diff --git a/dist/modules/analytics/pixels.js b/dist/modules/analytics/pixels.js new file mode 100644 index 0000000..ab777ca --- /dev/null +++ b/dist/modules/analytics/pixels.js @@ -0,0 +1,134 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ /** + * Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards + * against double-init) and loads the vendor's own script + bootstrap. + * + * These are the one place `any` is unavoidable: vendor SDK bootstraps attach + * untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained + * here; nothing else in the kit uses `any`. + * + * CONSENT: these vendors have no Google Consent Mode — the caller (Analytics) + * loads each ONLY after the matching consent category is granted: + * Meta Pixel / LinkedIn / TikTok → marketing + * Microsoft Clarity → analytics + */ /** Meta (Facebook) Pixel — fires PageView on load. */ export function loadMetaPixel(id) { + if (typeof window === 'undefined') { + return; + } + const w = window; + if (w.fbq) { + return; + } + const n = w.fbq = function(...args) { + if (n.callMethod) { + n.callMethod.apply(n, args); + } else { + n.queue.push(args); + } + }; + if (!w._fbq) { + w._fbq = n; + } + n.push = n; + n.loaded = true; + n.version = '2.0'; + n.queue = []; + const s = document.createElement('script'); + s.async = true; + s.src = 'https://connect.facebook.net/en_US/fbevents.js'; + document.head.appendChild(s); + w.fbq('init', id); + w.fbq('track', 'PageView'); +} +/** Microsoft Clarity — heatmaps / session recordings (analytics category). */ export function loadClarity(id) { + if (typeof window === 'undefined') { + return; + } + const w = window; + if (w.clarity) { + return; + } + w.clarity = function(...a) { + ; + (w.clarity.q = w.clarity.q || []).push(a); + }; + const s = document.createElement('script'); + s.async = true; + s.src = `https://www.clarity.ms/tag/${id}`; + document.head.appendChild(s); +} +/** LinkedIn Insight Tag (marketing). */ export function loadLinkedIn(partnerId) { + if (typeof window === 'undefined') { + return; + } + const w = window; + w._linkedin_partner_id = partnerId; + w._linkedin_data_partner_ids = w._linkedin_data_partner_ids || []; + if (w._linkedin_data_partner_ids.includes(partnerId)) { + if (document.getElementById('ipal-linkedin-insight')) { + return; + } + } else { + w._linkedin_data_partner_ids.push(partnerId); + } + if (document.getElementById('ipal-linkedin-insight')) { + return; + } + const s = document.createElement('script'); + s.async = true; + s.id = 'ipal-linkedin-insight'; + s.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js'; + document.head.appendChild(s); +} +/** TikTok Pixel (marketing) — fires page view on load. */ export function loadTikTok(id) { + if (typeof window === 'undefined') { + return; + } + const w = window; + if (w.ttq) { + return; + } + w.TiktokAnalyticsObject = 'ttq'; + const ttq = w.ttq = []; + ttq.methods = [ + 'page', + 'track', + 'identify', + 'instances', + 'debug', + 'on', + 'off', + 'once', + 'ready', + 'alias', + 'group', + 'enableCookie', + 'disableCookie' + ]; + ttq.setAndDefer = function(t, e) { + t[e] = function(...args) { + t.push([ + e, + ...args + ]); + }; + }; + for (const m of ttq.methods){ + ttq.setAndDefer(ttq, m); + } + ttq.load = function(e) { + const url = 'https://analytics.tiktok.com/i18n/pixel/events.js'; + ttq._i = ttq._i || {}; + ttq._i[e] = []; + ttq._i[e]._u = url; + ttq._t = ttq._t || {}; + ttq._t[e] = Number(new Date()); + const s = document.createElement('script'); + s.async = true; + s.src = `${url}?sdkid=${e}&lib=ttq`; + document.head.appendChild(s); + }; + ttq.load(id); + ttq.page(); +} + +//# sourceMappingURL=pixels.js.map \ No newline at end of file diff --git a/dist/modules/analytics/pixels.js.map b/dist/modules/analytics/pixels.js.map new file mode 100644 index 0000000..436a9a9 --- /dev/null +++ b/dist/modules/analytics/pixels.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/analytics/pixels.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards\n * against double-init) and loads the vendor's own script + bootstrap.\n *\n * These are the one place `any` is unavoidable: vendor SDK bootstraps attach\n * untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained\n * here; nothing else in the kit uses `any`.\n *\n * CONSENT: these vendors have no Google Consent Mode — the caller (Analytics)\n * loads each ONLY after the matching consent category is granted:\n * Meta Pixel / LinkedIn / TikTok → marketing\n * Microsoft Clarity → analytics\n */\n\ntype Win = Record & typeof window\n\n/** Meta (Facebook) Pixel — fires PageView on load. */\nexport function loadMetaPixel(id: string): void {\n if (typeof window === 'undefined') {return}\n const w = window as Win\n if (w.fbq) {return}\n const n: any = (w.fbq = function (...args: unknown[]) {\n if (n.callMethod) {\n n.callMethod.apply(n, args)\n } else {\n n.queue.push(args)\n }\n })\n if (!w._fbq) {w._fbq = n}\n n.push = n\n n.loaded = true\n n.version = '2.0'\n n.queue = []\n const s = document.createElement('script')\n s.async = true\n s.src = 'https://connect.facebook.net/en_US/fbevents.js'\n document.head.appendChild(s)\n w.fbq('init', id)\n w.fbq('track', 'PageView')\n}\n\n/** Microsoft Clarity — heatmaps / session recordings (analytics category). */\nexport function loadClarity(id: string): void {\n if (typeof window === 'undefined') {return}\n const w = window as Win\n if (w.clarity) {return}\n w.clarity = function (...a: unknown[]) {\n ;(w.clarity.q = w.clarity.q || []).push(a)\n }\n const s = document.createElement('script')\n s.async = true\n s.src = `https://www.clarity.ms/tag/${id}`\n document.head.appendChild(s)\n}\n\n/** LinkedIn Insight Tag (marketing). */\nexport function loadLinkedIn(partnerId: string): void {\n if (typeof window === 'undefined') {return}\n const w = window as Win\n w._linkedin_partner_id = partnerId\n w._linkedin_data_partner_ids = w._linkedin_data_partner_ids || []\n if (w._linkedin_data_partner_ids.includes(partnerId)) {\n if (document.getElementById('ipal-linkedin-insight')) {return}\n } else {\n w._linkedin_data_partner_ids.push(partnerId)\n }\n if (document.getElementById('ipal-linkedin-insight')) {return}\n const s = document.createElement('script')\n s.async = true\n s.id = 'ipal-linkedin-insight'\n s.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js'\n document.head.appendChild(s)\n}\n\n/** TikTok Pixel (marketing) — fires page view on load. */\nexport function loadTikTok(id: string): void {\n if (typeof window === 'undefined') {return}\n const w = window as Win\n if (w.ttq) {return}\n w.TiktokAnalyticsObject = 'ttq'\n const ttq: any = (w.ttq = [])\n ttq.methods = [\n 'page',\n 'track',\n 'identify',\n 'instances',\n 'debug',\n 'on',\n 'off',\n 'once',\n 'ready',\n 'alias',\n 'group',\n 'enableCookie',\n 'disableCookie',\n ]\n ttq.setAndDefer = function (t: any, e: string) {\n t[e] = function (...args: unknown[]) {\n t.push([e, ...args])\n }\n }\n for (const m of ttq.methods) {ttq.setAndDefer(ttq, m)}\n ttq.load = function (e: string) {\n const url = 'https://analytics.tiktok.com/i18n/pixel/events.js'\n ttq._i = ttq._i || {}\n ttq._i[e] = []\n ttq._i[e]._u = url\n ttq._t = ttq._t || {}\n ttq._t[e] = Number(new Date())\n const s = document.createElement('script')\n s.async = true\n s.src = `${url}?sdkid=${e}&lib=ttq`\n document.head.appendChild(s)\n }\n ttq.load(id)\n ttq.page()\n}\n"],"names":["loadMetaPixel","id","window","w","fbq","n","args","callMethod","apply","queue","push","_fbq","loaded","version","s","document","createElement","async","src","head","appendChild","loadClarity","clarity","a","q","loadLinkedIn","partnerId","_linkedin_partner_id","_linkedin_data_partner_ids","includes","getElementById","loadTikTok","ttq","TiktokAnalyticsObject","methods","setAndDefer","t","e","m","load","url","_i","_u","_t","Number","Date","page"],"mappings":"AAAA,qDAAqD,GACrD;;;;;;;;;;;;CAYC,GAID,oDAAoD,GACpD,OAAO,SAASA,cAAcC,EAAU;IACtC,IAAI,OAAOC,WAAW,aAAa;QAAC;IAAM;IAC1C,MAAMC,IAAID;IACV,IAAIC,EAAEC,GAAG,EAAE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AGF;QACfR,IAAIW,EAAE,GAAGX,IAAIW,EAAE,IAAI,CAAC;QACpBX,IAAIW,EAAE,CAACN,EAAE,GAAGO,OAAO,IAAIC;QACvB,MAAM/B,IAAIC,SAASC,aAAa,CAAC;QACjCF,EAAEG,KAAK,GAAG;QACVH,EAAEI,GAAG,GAAG,GAAGsB,IAAI,OAAO,EAAEH,EAAE,QAAQ,CAAC;QACnCtB,SAASI,IAAI,CAACC,WAAW,CAACN;IAC5B;IACAkB,IAAIO,IAAI,CAACtC;IACT+B,IAAIc,IAAI;AACV"} \ No newline at end of file diff --git a/dist/modules/analytics/types.d.ts b/dist/modules/analytics/types.d.ts index ac35fff..9d979dc 100644 --- a/dist/modules/analytics/types.d.ts +++ b/dist/modules/analytics/types.d.ts @@ -1,9 +1,19 @@ /** - * Analytics IDs, read from SiteIntegrations (public — safe on the client). + * Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe + * on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only + * after the matching consent category is granted (see Analytics). */ export type AnalyticsConfig = { - /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */ + /** Microsoft Clarity project ID. (analytics consent) */ + clarityProjectId?: null | string; + /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */ ga4MeasurementId?: null | string; - /** GTM Container ID, e.g. 'GTM-XXXXXXX'. */ + /** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */ gtmContainerId?: null | string; + /** LinkedIn Insight Tag partner ID. (marketing consent) */ + linkedInPartnerId?: null | string; + /** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */ + metaPixelId?: null | string; + /** TikTok Pixel ID. (marketing consent) */ + tiktokPixelId?: null | string; }; diff --git a/dist/modules/analytics/types.js b/dist/modules/analytics/types.js index 93dfc2e..9ed2828 100644 --- a/dist/modules/analytics/types.js +++ b/dist/modules/analytics/types.js @@ -1,5 +1,7 @@ /** - * Analytics IDs, read from SiteIntegrations (public — safe on the client). + * Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe + * on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only + * after the matching consent category is granted (see Analytics). */ export { }; //# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/modules/analytics/types.js.map b/dist/modules/analytics/types.js.map index 95b37d4..b5c9893 100644 --- a/dist/modules/analytics/types.js.map +++ b/dist/modules/analytics/types.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/analytics/types.ts"],"sourcesContent":["/**\n * Analytics IDs, read from SiteIntegrations (public — safe on the client).\n */\nexport type AnalyticsConfig = {\n /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */\n ga4MeasurementId?: null | string\n /** GTM Container ID, e.g. 'GTM-XXXXXXX'. */\n gtmContainerId?: null | string\n}\n"],"names":[],"mappings":"AAAA;;CAEC,GACD,WAKC"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/analytics/types.ts"],"sourcesContent":["/**\n * Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe\n * on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only\n * after the matching consent category is granted (see Analytics).\n */\nexport type AnalyticsConfig = {\n /** Microsoft Clarity project ID. (analytics consent) */\n clarityProjectId?: null | string\n /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */\n ga4MeasurementId?: null | string\n /** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */\n gtmContainerId?: null | string\n /** LinkedIn Insight Tag partner ID. (marketing consent) */\n linkedInPartnerId?: null | string\n /** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */\n metaPixelId?: null | string\n /** TikTok Pixel ID. (marketing consent) */\n tiktokPixelId?: null | string\n}\n"],"names":[],"mappings":"AAAA;;;;CAIC,GACD,WAaC"} \ No newline at end of file diff --git a/dist/modules/content/index.d.ts b/dist/modules/content/index.d.ts index 564819b..feb141d 100644 --- a/dist/modules/content/index.d.ts +++ b/dist/modules/content/index.d.ts @@ -6,6 +6,7 @@ export { getArchiveEntries } from './getArchiveEntries.js'; export type { ArchiveEntries } from './getArchiveEntries.js'; export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'; export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'; +export { resolveNotFoundPage } from './resolveNotFoundPage.js'; export { resolveRedirect } from './resolveRedirect.js'; export { resolveRoute } from './resolveRoute.js'; export type { ResolvedRoute } from './resolveRoute.js'; diff --git a/dist/modules/content/index.js b/dist/modules/content/index.js index 5362f45..2dbd75a 100644 --- a/dist/modules/content/index.js +++ b/dist/modules/content/index.js @@ -5,6 +5,7 @@ export { createSearchRoute } from './createSearchRoute.js'; export { getArchiveEntries } from './getArchiveEntries.js'; export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'; export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'; +export { resolveNotFoundPage } from './resolveNotFoundPage.js'; export { resolveRedirect } from './resolveRedirect.js'; export { resolveRoute } from './resolveRoute.js'; export { searchContent } from './searchContent.js'; diff --git a/dist/modules/content/index.js.map b/dist/modules/content/index.js.map index cb7c89d..b4d3883 100644 --- a/dist/modules/content/index.js.map +++ b/dist/modules/content/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/content/index.ts"],"sourcesContent":["export { buildArchiveFields } from './archiveFields.js'\nexport { blocksToMarkdown } from './blocksToMarkdown.js'\nexport { createMarkdownRenderer, markdownResponse } from './createMarkdownRenderer.js'\nexport { createSearchRoute } from './createSearchRoute.js'\nexport { getArchiveEntries } from './getArchiveEntries.js'\nexport type { ArchiveEntries } from './getArchiveEntries.js'\nexport { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js'\nexport { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js'\nexport { resolveNotFoundPage } from './resolveNotFoundPage.js'\nexport { resolveRedirect } from './resolveRedirect.js'\nexport { resolveRoute } from './resolveRoute.js'\nexport type { ResolvedRoute } from './resolveRoute.js'\nexport { searchContent } from './searchContent.js'\nexport type { SearchResult } from './searchContent.js'\nexport type { ContentCollectionOption, ContentOption } from './types.js'\nexport { archiveFieldName } from './types.js'\n"],"names":["buildArchiveFields","blocksToMarkdown","createMarkdownRenderer","markdownResponse","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","prefersMarkdown","buildArchivePath","buildEntryPath","parsePageParam","resolveNotFoundPage","resolveRedirect","resolveRoute","searchContent","archiveFieldName"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,qBAAoB;AACvD,SAASC,gBAAgB,QAAQ,wBAAuB;AACxD,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,8BAA6B;AACtF,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,iBAAiB,QAAQ,yBAAwB;AAE1D,SAASC,eAAe,EAAEC,YAAY,EAAEC,eAAe,QAAQ,2BAA0B;AACzF,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,cAAc,QAAQ,aAAY;AAC7E,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,YAAY,QAAQ,oBAAmB;AAEhD,SAASC,aAAa,QAAQ,qBAAoB;AAGlD,SAASC,gBAAgB,QAAQ,aAAY"} \ No newline at end of file diff --git a/dist/modules/content/resolveNotFoundPage.d.ts b/dist/modules/content/resolveNotFoundPage.d.ts new file mode 100644 index 0000000..c271ef3 --- /dev/null +++ b/dist/modules/content/resolveNotFoundPage.d.ts @@ -0,0 +1,23 @@ +import type { BasePayload } from 'payload'; +type ResolveNotFoundPageArgs = { + locale: string; + /** Client's Pages collection slug. Defaults to 'pages'. */ + pagesSlug?: string; + payload: BasePayload; + /** SiteSettings global slug. Defaults to 'site-settings'. */ + settingsSlug?: string; +}; +/** + * Returns the page the editor assigned as **404 (Not Found)** in System Pages, + * fully populated (depth 2, same shape as resolveRoute's pages), or null when + * the role is unassigned. + * + * Used by the project's `not-found.tsx`. The editor decides what a 404 looks + * like: a dedicated "Not found" page, or simply the homepage. Null means + * "render the project's built-in fallback view". + * + * Never throws — a missing DB (container build prerendering not-found) or a + * deleted page just yields null, so the 404 view can't crash the build. + */ +export declare function resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug, }: ResolveNotFoundPageArgs): Promise>; +export {}; diff --git a/dist/modules/content/resolveNotFoundPage.js b/dist/modules/content/resolveNotFoundPage.js new file mode 100644 index 0000000..322db23 --- /dev/null +++ b/dist/modules/content/resolveNotFoundPage.js @@ -0,0 +1,37 @@ +/** + * Returns the page the editor assigned as **404 (Not Found)** in System Pages, + * fully populated (depth 2, same shape as resolveRoute's pages), or null when + * the role is unassigned. + * + * Used by the project's `not-found.tsx`. The editor decides what a 404 looks + * like: a dedicated "Not found" page, or simply the homepage. Null means + * "render the project's built-in fallback view". + * + * Never throws — a missing DB (container build prerendering not-found) or a + * deleted page just yields null, so the 404 view can't crash the build. + */ export async function resolveNotFoundPage({ locale, pagesSlug = 'pages', payload, settingsSlug = 'site-settings' }) { + try { + const settings = await payload.findGlobal({ + slug: settingsSlug, + depth: 0, + locale: locale + }); + const rel = settings.notFound; + const id = typeof rel === 'string' || typeof rel === 'number' ? rel : rel && typeof rel === 'object' ? rel.id : undefined; + if (id === undefined) { + return null; + } + const doc = await payload.findByID({ + id, + collection: pagesSlug, + depth: 2, + locale: locale + }); + return doc ?? null; + } catch (error) { + console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error); + return null; + } +} + +//# sourceMappingURL=resolveNotFoundPage.js.map \ No newline at end of file diff --git a/dist/modules/content/resolveNotFoundPage.js.map b/dist/modules/content/resolveNotFoundPage.js.map new file mode 100644 index 0000000..60a3b29 --- /dev/null +++ b/dist/modules/content/resolveNotFoundPage.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/content/resolveNotFoundPage.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\ntype ResolveNotFoundPageArgs = {\n locale: string\n /** Client's Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Returns the page the editor assigned as **404 (Not Found)** in System Pages,\n * fully populated (depth 2, same shape as resolveRoute's pages), or null when\n * the role is unassigned.\n *\n * Used by the project's `not-found.tsx`. The editor decides what a 404 looks\n * like: a dedicated \"Not found\" page, or simply the homepage. Null means\n * \"render the project's built-in fallback view\".\n *\n * Never throws — a missing DB (container build prerendering not-found) or a\n * deleted page just yields null, so the 404 view can't crash the build.\n */\nexport async function resolveNotFoundPage({\n locale,\n pagesSlug = 'pages',\n payload,\n settingsSlug = 'site-settings',\n}: ResolveNotFoundPageArgs): Promise> {\n try {\n const settings = (await payload.findGlobal({\n slug: settingsSlug as never,\n depth: 0,\n locale: locale as never,\n })) as Record\n\n const rel = settings.notFound\n const id =\n typeof rel === 'string' || typeof rel === 'number'\n ? rel\n : rel && typeof rel === 'object'\n ? (rel as { id?: number | string }).id\n : undefined\n if (id === undefined) {return null}\n\n const doc = await payload.findByID({\n id,\n collection: pagesSlug as never,\n depth: 2,\n locale: locale as never,\n })\n return (doc as null | Record) ?? null\n } catch (error) {\n console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error)\n return null\n }\n}\n"],"names":["resolveNotFoundPage","locale","pagesSlug","payload","settingsSlug","settings","findGlobal","slug","depth","rel","notFound","id","undefined","doc","findByID","collection","error","console","warn"],"mappings":"AAWA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeA,oBAAoB,EACxCC,MAAM,EACNC,YAAY,OAAO,EACnBC,OAAO,EACPC,eAAe,eAAe,EACN;IACxB,IAAI;QACF,MAAMC,WAAY,MAAMF,QAAQG,UAAU,CAAC;YACzCC,MAAMH;YACNI,OAAO;YACPP,QAAQA;QACV;QAEA,MAAMQ,MAAMJ,SAASK,QAAQ;QAC7B,MAAMC,KACJ,OAAOF,QAAQ,YAAY,OAAOA,QAAQ,WACtCA,MACAA,OAAO,OAAOA,QAAQ,WACpB,AAACA,IAAiCE,EAAE,GACpCC;QACR,IAAID,OAAOC,WAAW;YAAC,OAAO;QAAI;QAElC,MAAMC,MAAM,MAAMV,QAAQW,QAAQ,CAAC;YACjCH;YACAI,YAAYb;YACZM,OAAO;YACPP,QAAQA;QACV;QACA,OAAO,AAACY,OAA0C;IACpD,EAAE,OAAOG,OAAO;QACdC,QAAQC,IAAI,CAAC,kEAAkEF;QAC/E,OAAO;IACT;AACF"} \ No newline at end of file diff --git a/dist/modules/content/resolveRoute.js b/dist/modules/content/resolveRoute.js index 8fedc0e..4926433 100644 --- a/dist/modules/content/resolveRoute.js +++ b/dist/modules/content/resolveRoute.js @@ -114,6 +114,20 @@ import { archiveFieldName } from './types.js'; if (!doc) { return null; } + // The page assigned as 404 in System Pages must not be reachable as a normal + // 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat + // it as not found, so the route calls notFound() and not-found.tsx renders + // that same page with a real 404 status. (If 404 = homepage, the homepage is + // served from the root branch above and never reaches here by its own slug + // in a way that matters — but guard anyway so we never hide the homepage.) + const notFound = settings.notFound; + const homepage = settings.homepage; + const notFoundId = notFound && typeof notFound === 'object' ? notFound.id : notFound; + const homepageId = homepage && typeof homepage === 'object' ? homepage.id : homepage; + const docId = doc.id; + if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) { + return null; + } return { type: 'page', doc: doc diff --git a/dist/modules/content/resolveRoute.js.map b/dist/modules/content/resolveRoute.js.map index b0a7f5b..153c09a 100644 --- a/dist/modules/content/resolveRoute.js.map +++ b/dist/modules/content/resolveRoute.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/content/resolveRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from './types.js'\n\nimport { archiveFieldName } from './types.js'\n\ntype ArchivePage = { id: number | string; slug?: unknown }\n\nexport type ResolvedRoute =\n /** Locale root — the page assigned as Homepage in System Pages. */\n | {\n /** The archive page this entry lives under — its slug is the URL prefix. */\n archive: Record\n collection: string\n doc: Record\n type: 'entry'\n }\n /** An ordinary page. */\n | {\n collection: string\n doc: Record\n /** 1-based, from ?page=. */\n page: number\n perPage: number\n type: 'archive'\n }\n /** A collection's archive page, e.g. /pl/artykuly. */\n | { doc: Record; type: 'home' }\n /** A single entry, e.g. /pl/artykuly/moj-post. */\n | { doc: Record; type: 'page' }\n\ntype ResolveRouteArgs = {\n content?: ContentOption\n locale: string\n /** Page number from the query string (?page=2). Defaults to 1. */\n page?: number\n /** Client's Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** Route segments after the locale, e.g. ['artykuly', 'moj-post']. */\n segments?: string[]\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Works out what a URL points at: the home page, an ordinary page, a\n * collection's archive, or a single entry.\n *\n * Routing only. An archive result says which collection to list and on which\n * page, but doesn't fetch the entries — that's `getArchiveEntries`, called by\n * whoever actually needs them. Keeping the two apart means listing changes\n * (sorting, filtering, pagination) never touch routing rules, and metadata\n * generation doesn't pay for a query it would discard.\n *\n * The trick is that archive prefixes aren't configured anywhere — they're the\n * slug of whichever page an editor assigned as that collection's archive. So\n * /pl/artykuly and /en/articles come from one assignment, and renaming the page\n * moves the whole section.\n *\n * Resolution order matters: a first segment matching an archive's slug wins\n * over an ordinary page of the same name, because an archive *is* a page and\n * would otherwise shadow its own entries.\n *\n * Depth beyond {archive}/{entry} isn't supported — categories in the path would\n * make canonical and hreflang ambiguous (the same entry reachable under several\n * URLs).\n */\nexport async function resolveRoute({\n content,\n locale,\n page = 1,\n pagesSlug = 'pages',\n payload,\n segments,\n settingsSlug = 'site-settings',\n}: ResolveRouteArgs): Promise {\n const settings = (await payload.findGlobal({\n slug: settingsSlug,\n depth: 1,\n locale: locale as never,\n })) as Record\n\n // Locale root → Homepage from System Pages.\n // settings.homepage is a shallow relation (depth: 1 above) — it identifies\n // WHICH page is the homepage, but its nested block relations (e.g. Hero\n // images) aren't populated. Re-fetch that page from the pages collection at\n // the same depth as every other page, so the frontend gets one consistent\n // shape. Uses pagesSlug/locale from args — no hard-coded collection or locale.\n if (!segments?.length) {\n const homepage = settings.homepage\n if (!homepage || typeof homepage !== 'object') {\n return null\n }\n\n const homepageId = (homepage as { id: number | string }).id\n const doc = await payload.findByID({\n id: homepageId,\n collection: pagesSlug,\n depth: 2,\n locale: locale as never,\n })\n\n return doc ? { type: 'home', doc: doc as Record } : null\n }\n\n const [first, ...rest] = segments\n\n // Does the first segment name an archive page?\n for (const collection of content?.collections ?? []) {\n const archive = settings[archiveFieldName(collection.slug)]\n if (!archive || typeof archive !== 'object') {continue}\n\n const archiveDoc = archive as ArchivePage\n if (archiveDoc.slug !== first) {continue}\n\n // /pl/artykuly → the archive page itself.\n if (rest.length === 0) {\n return {\n type: 'archive',\n collection: collection.slug,\n doc: archiveDoc as Record,\n page,\n perPage: collection.perPage ?? 10,\n }\n }\n\n // /pl/artykuly/moj-post → an entry.\n if (rest.length === 1) {\n const found = await payload.find({\n collection: collection.slug as never,\n depth: 2,\n limit: 1,\n locale: locale as never,\n where: { slug: { equals: rest[0] } },\n })\n const entry = found.docs[0]\n if (!entry) {return null}\n\n return {\n type: 'entry',\n archive: archiveDoc as Record,\n collection: collection.slug,\n doc: entry as Record,\n }\n }\n\n // Deeper than {archive}/{entry}.\n return null\n }\n\n // An ordinary page. Joined, so nested slugs ('a/b') keep working.\n const found = await payload.find({\n collection: pagesSlug as never,\n depth: 2,\n limit: 1,\n locale: locale as never,\n where: { slug: { equals: segments.join('/') } },\n })\n const doc = found.docs[0]\n if (!doc) {return null}\n\n return { type: 'page', doc: doc as Record }\n}\n"],"names":["archiveFieldName","resolveRoute","content","locale","page","pagesSlug","payload","segments","settingsSlug","settings","findGlobal","slug","depth","length","homepage","homepageId","id","doc","findByID","collection","type","first","rest","collections","archive","archiveDoc","perPage","found","find","limit","where","equals","entry","docs","join"],"mappings":"AAIA,SAASA,gBAAg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KT,MAAM,KAAK,GAAG;YACrB,MAAMc,QAAQ,MAAMrB,QAAQsB,IAAI,CAAC;gBAC/BT,YAAYA,WAAWR,IAAI;gBAC3BC,OAAO;gBACPiB,OAAO;gBACP1B,QAAQA;gBACR2B,OAAO;oBAAEnB,MAAM;wBAAEoB,QAAQT,IAAI,CAAC,EAAE;oBAAC;gBAAE;YACrC;YACA,MAAMU,QAAQL,MAAMM,IAAI,CAAC,EAAE;YAC3B,IAAI,CAACD,OAAO;gBAAC,OAAO;YAAI;YAExB,OAAO;gBACLZ,MAAM;gBACNI,SAASC;gBACTN,YAAYA,WAAWR,IAAI;gBAC3BM,KAAKe;YACP;QACF;QAEA,iCAAiC;QACjC,OAAO;IACT;IAEA,kEAAkE;IAClE,MAAML,QAAQ,MAAMrB,QAAQsB,IAAI,CAAC;QAC/BT,YAAYd;QACZO,OAAO;QACPiB,OAAO;QACP1B,QAAQA;QACR2B,OAAO;YAAEnB,MAAM;gBAAEoB,QAAQxB,SAAS2B,IAAI,CAAC;YAAK;QAAE;IAChD;IACA,MAAMjB,MAAMU,MAAMM,IAAI,CAAC,EAAE;IACzB,IAAI,CAAChB,KAAK;QAAC,OAAO;IAAI;IAEtB,OAAO;QAAEG,MAAM;QAAQH,KAAKA;IAA+B;AAC7D"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/content/resolveRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\nimport type { ContentOption } from './types.js'\n\nimport { archiveFieldName } from './types.js'\n\ntype ArchivePage = { id: number | string; slug?: unknown }\n\nexport type ResolvedRoute =\n /** Locale root — the page assigned as Homepage in System Pages. */\n | {\n /** The archive page this entry lives under — its slug is the URL prefix. */\n archive: Record\n collection: string\n doc: Record\n type: 'entry'\n }\n /** An ordinary page. */\n | {\n collection: string\n doc: Record\n /** 1-based, from ?page=. */\n page: number\n perPage: number\n type: 'archive'\n }\n /** A collection's archive page, e.g. /pl/artykuly. */\n | { doc: Record; type: 'home' }\n /** A single entry, e.g. /pl/artykuly/moj-post. */\n | { doc: Record; type: 'page' }\n\ntype ResolveRouteArgs = {\n content?: ContentOption\n locale: string\n /** Page number from the query string (?page=2). Defaults to 1. */\n page?: number\n /** Client's Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n payload: BasePayload\n /** Route segments after the locale, e.g. ['artykuly', 'moj-post']. */\n segments?: string[]\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Works out what a URL points at: the home page, an ordinary page, a\n * collection's archive, or a single entry.\n *\n * Routing only. An archive result says which collection to list and on which\n * page, but doesn't fetch the entries — that's `getArchiveEntries`, called by\n * whoever actually needs them. Keeping the two apart means listing changes\n * (sorting, filtering, pagination) never touch routing rules, and metadata\n * generation doesn't pay for a query it would discard.\n *\n * The trick is that archive prefixes aren't configured anywhere — they're the\n * slug of whichever page an editor assigned as that collection's archive. So\n * /pl/artykuly and /en/articles come from one assignment, and renaming the page\n * moves the whole section.\n *\n * Resolution order matters: a first segment matching an archive's slug wins\n * over an ordinary page of the same name, because an archive *is* a page and\n * would otherwise shadow its own entries.\n *\n * Depth beyond {archive}/{entry} isn't supported — categories in the path would\n * make canonical and hreflang ambiguous (the same entry reachable under several\n * URLs).\n */\nexport async function resolveRoute({\n content,\n locale,\n page = 1,\n pagesSlug = 'pages',\n payload,\n segments,\n settingsSlug = 'site-settings',\n}: ResolveRouteArgs): Promise {\n const settings = (await payload.findGlobal({\n slug: settingsSlug,\n depth: 1,\n locale: locale as never,\n })) as Record\n\n // Locale root → Homepage from System Pages.\n // settings.homepage is a shallow relation (depth: 1 above) — it identifies\n // WHICH page is the homepage, but its nested block relations (e.g. Hero\n // images) aren't populated. Re-fetch that page from the pages collection at\n // the same depth as every other page, so the frontend gets one consistent\n // shape. Uses pagesSlug/locale from args — no hard-coded collection or locale.\n if (!segments?.length) {\n const homepage = settings.homepage\n if (!homepage || typeof homepage !== 'object') {\n return null\n }\n\n const homepageId = (homepage as { id: number | string }).id\n const doc = await payload.findByID({\n id: homepageId,\n collection: pagesSlug,\n depth: 2,\n locale: locale as never,\n })\n\n return doc ? { type: 'home', doc: doc as Record } : null\n }\n\n const [first, ...rest] = segments\n\n // Does the first segment name an archive page?\n for (const collection of content?.collections ?? []) {\n const archive = settings[archiveFieldName(collection.slug)]\n if (!archive || typeof archive !== 'object') {continue}\n\n const archiveDoc = archive as ArchivePage\n if (archiveDoc.slug !== first) {continue}\n\n // /pl/artykuly → the archive page itself.\n if (rest.length === 0) {\n return {\n type: 'archive',\n collection: collection.slug,\n doc: archiveDoc as Record,\n page,\n perPage: collection.perPage ?? 10,\n }\n }\n\n // /pl/artykuly/moj-post → an entry.\n if (rest.length === 1) {\n const found = await payload.find({\n collection: collection.slug as never,\n depth: 2,\n limit: 1,\n locale: locale as never,\n where: { slug: { equals: rest[0] } },\n })\n const entry = found.docs[0]\n if (!entry) {return null}\n\n return {\n type: 'entry',\n archive: archiveDoc as Record,\n collection: collection.slug,\n doc: entry as Record,\n }\n }\n\n // Deeper than {archive}/{entry}.\n return null\n }\n\n // An ordinary page. Joined, so nested slugs ('a/b') keep working.\n const found = await payload.find({\n collection: pagesSlug as never,\n depth: 2,\n limit: 1,\n locale: locale as never,\n where: { slug: { equals: segments.join('/') } },\n })\n const doc = found.docs[0]\n if (!doc) {return null}\n\n // The page assigned as 404 in System Pages must not be reachable as a normal\n // 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat\n // it as not found, so the route calls notFound() and not-found.tsx renders\n // that same page with a real 404 status. (If 404 = homepage, the homepage is\n // served from the root branch above and never reaches here by its own slug\n // in a way that matters — but guard anyway so we never hide the homepage.)\n const notFound = settings.notFound\n const homepage = settings.homepage\n const notFoundId =\n notFound && typeof notFound === 'object' ? (notFound as { id?: unknown }).id : notFound\n const homepageId =\n homepage && typeof homepage === 'object' ? (homepage as { id?: unknown }).id : homepage\n const docId = (doc as { id?: unknown }).id\n if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) {\n return null\n }\n\n return { type: 'page', doc: doc as Record }\n}\n"],"names":["archiveFieldName","resolveRoute","content","locale","page","pagesSlug","payload","segments","settingsSlug","settings","findGlobal","slug","depth","length","homepage","homepageId","id","doc","findByID","collection","type","first","rest","collections","archive","archiveDoc","perPage","found","find","limit","where","equals","entry","docs","join","notFound","notFoundId","docId"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,aAAY;AAyC7C;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,eAAeC,aAAa,EACjCC,OAAO,EACPC,MAAM,EACNC,OAAO,CAAC,EACRC,YAAY,OAAO,EACnBC,OAAO,EACPC,QAAQ,EACRC,eAAe,eAAe,EACb;IACjB,MAAMC,WAAY,MAAMH,QAAQI,UAAU,CAAC;QACzCC,MAAMH;QACNI,OAAO;QACPT,QAAQA;IACV;IAEA,4CAA4C;IAC5C,2EAA2E;IAC3E,wEAAwE;IACxE,4EAA4E;IAC5E,0EAA0E;IAC1E,+EAA+E;IAC/E,IAAI,CAACI,UAAUM,QAAQ;QACrB,MAAMC,WAAWL,SAASK,QAAQ;QAClC,IAAI,CAACA,YAAY,OAAOA,aAAa,UAAU;YAC7C,OAAO;QACT;QAEA,MAAMC,aAAa,AAACD,SAAqCE,EAAE;QAC3D,MAAMC,MAAM,MAAMX,QAAQY,QAAQ,CAAC;YACjCF,IAAID;YACJI,YAAYd;YACZO,OAAO;YACPT,QAAQA;QACV;QAEA,OAAOc,MAAM;YAAEG,MAAM;YAAQH,KAAKA;QAA+B,IAAI;IACvE;IAEA,MAAM,CAACI,OAAO,GAAGC,KAAK,GAAGf;IAEzB,+CAA+C;IAC/C,KAAK,MAAMY,cAAcjB,SAASqB,eAAe,EAAE,CAAE;QACnD,MAAMC,UAAUf,QAAQ,CAACT,iBAAiBmB,WAAWR,IAAI,EAAE;QAC3D,IAAI,CAACa,WAAW,OAAOA,YAAY,UAAU;YAAC;QAAQ;QAEtD,MAAMC,aAAaD;QACnB,IAAIC,WAAWd,IAAI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,aACJD,YAAY,OAAOA,aAAa,WAAW,AAACA,SAA8BE,EAAE,GAAGF;IACjF,MAAMuB,QAAQ,AAACpB,IAAyBD,EAAE;IAC1C,IAAIoB,cAAc,QAAQA,eAAeC,SAASD,eAAerB,YAAY;QAC3E,OAAO;IACT;IAEA,OAAO;QAAEK,MAAM;QAAQH,KAAKA;IAA+B;AAC7D"} \ No newline at end of file diff --git a/dist/modules/frontend/createContentHelpers.d.ts b/dist/modules/frontend/createContentHelpers.d.ts index 0a8aee9..cb6234a 100644 --- a/dist/modules/frontend/createContentHelpers.d.ts +++ b/dist/modules/frontend/createContentHelpers.d.ts @@ -62,6 +62,7 @@ export declare function createContentHelpers({ baseUrl, config, content, i18n, p getCachedPayload: () => Promise; getConfiguredLocales: () => Promise; getEntries: (collection: string, locale: string, page: number, perPage: number) => Promise; + getNotFoundPage: (locale: string) => Promise | null>; getSettings: (locale: string) => Promise; resolveRoute: (locale: string, segments: string[] | undefined, page: number) => Promise; robots: () => RobotsRules; diff --git a/dist/modules/frontend/createContentHelpers.js b/dist/modules/frontend/createContentHelpers.js index ad23f9f..979fa56 100644 --- a/dist/modules/frontend/createContentHelpers.js +++ b/dist/modules/frontend/createContentHelpers.js @@ -1,6 +1,6 @@ import { getPayload } from 'payload'; import { cache } from 'react'; -import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'; +import { getArchiveEntries, resolveNotFoundPage, resolveRoute as resolveRouteRaw } from '../content/index.js'; import { buildRobots, buildSitemapEntries } from '../seo/index.js'; /** * Bundles the per-request data helpers a frontend needs — the same cached @@ -56,6 +56,24 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js'; settingsSlug }); }); + /** + * The page assigned as 404 in System Pages (or null → built-in fallback). + * For app/not-found.tsx; never throws. Locale comes from the x-locale header + * set by createProxy (not-found.tsx receives no params). + */ const getNotFoundPage = cache(async (locale)=>{ + try { + const payload = await getCachedPayload(); + return await resolveNotFoundPage({ + locale, + pagesSlug, + payload, + settingsSlug + }); + } catch { + return null // DB unreachable (container build) — fallback view + ; + } + }); /** One page of a collection's entries, for an archive listing. */ const getEntries = cache(async (collection, locale, page, perPage)=>{ const payload = await getCachedPayload(); return getArchiveEntries({ @@ -154,6 +172,8 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js'; locale: 'all' }).catch(()=>null); const homeId = settings?.homepage?.id; + // The assigned 404 page renders via not-found.tsx, never as its own URL. + const notFoundId = settings?.notFound?.id !== undefined && settings.notFound.id !== homeId ? settings.notFound.id : undefined; const EXCLUDED = new Set([ '404', '500', @@ -177,6 +197,9 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js'; if (raw._status && raw._status !== 'published') { continue; } + if (notFoundId !== undefined && raw.id === notFoundId) { + continue; + } // NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex // page (privacy, cookies, terms) still needs to render — users reach it // from the footer and crawlers read its . Pre-render @@ -230,6 +253,7 @@ import { buildRobots, buildSitemapEntries } from '../seo/index.js'; getCachedPayload, getConfiguredLocales, getEntries, + getNotFoundPage, getSettings, resolveRoute, robots, diff --git a/dist/modules/frontend/createContentHelpers.js.map b/dist/modules/frontend/createContentHelpers.js.map index 032e034..ccec158 100644 --- a/dist/modules/frontend/createContentHelpers.js.map +++ b/dist/modules/frontend/createContentHelpers.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/frontend/createContentHelpers.ts"],"sourcesContent":["import type { BasePayload, SanitizedConfig } from 'payload'\n\nimport { getPayload } from 'payload'\nimport { cache } from 'react'\n\nimport type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { RobotsRules, SitemapEntry } from '../seo/index.js'\n\nimport { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'\nimport { buildRobots, buildSitemapEntries } from '../seo/index.js'\n\ntype CreateContentHelpersArgs = {\n /**\n * Absolute site origin for sitemap/robots URLs. Falls back to\n * NEXT_PUBLIC_SERVER_URL, then to a relative origin (which most crawlers\n * reject, so set one in production).\n */\n baseUrl?: string\n /**\n * The client's payload config promise (the default export of payload.config).\n * Passed in because the plugin never imports the client's config directly.\n */\n config: Promise | SanitizedConfig\n /** Archive-backed collections, same value as the plugin option. */\n content?: ContentOption\n /**\n * i18n config. Required only if you want the ready-made `sitemap` / `robots`\n * handlers — they need the locale list to emit hreflang.\n */\n i18n?: I18nConfig\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Bundles the per-request data helpers a frontend needs — the same cached\n * wrappers every project was writing by hand (getPayload, settings, locale\n * list, route resolution, archive entries).\n *\n * Everything is wrapped in React `cache()`, so within one request a value is\n * fetched once no matter how many times it's asked for — which matters because\n * Next runs generateMetadata and the page component separately, and both hit\n * these. Crucially the Payload instance is cached *here*, once, so every helper\n * shares it; that's why this is a factory and not loose functions importing a\n * shared module.\n *\n * ```ts\n * // src/lib/content.ts\n * import { createContentHelpers } from 'ipal-kit'\n * import config from '@/payload.config'\n * import { contentConfig } from '@/content.config'\n *\n * export const { getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries } =\n * createContentHelpers({ config, content: contentConfig })\n * ```\n *\n * `resolveRoute` and `getEntries` are separate on purpose: routing decides what\n * a URL is, fetching gets the listing. Metadata generation needs the first and\n * not the second, and a page component composes them in two obvious lines.\n */\nexport function createContentHelpers({\n baseUrl,\n config,\n content,\n i18n,\n pagesSlug = 'pages',\n settingsSlug = 'site-settings',\n}: CreateContentHelpersArgs) {\n const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''\n const getCachedPayload = cache(async (): Promise =>\n getPayload({ config: await config }),\n )\n\n const getConfiguredLocales = cache(async (): Promise => {\n const c = await config\n return c.localization ? c.localization.locales.map((l) => l.code) : []\n })\n\n const getSettings = cache(async (locale: string) => {\n const payload = await getCachedPayload()\n return payload.findGlobal({ slug: settingsSlug as never, depth: 2, locale: locale as never })\n })\n\n /** What does this URL point at? Routing only — no listing data. */\n const resolveRoute = cache(\n async (\n locale: string,\n segments: string[] | undefined,\n page: number,\n ): Promise => {\n const payload = await getCachedPayload()\n return resolveRouteRaw({ content, locale, page, pagesSlug, payload, segments, settingsSlug })\n },\n )\n\n /** One page of a collection's entries, for an archive listing. */\n const getEntries = cache(\n async (\n collection: string,\n locale: string,\n page: number,\n perPage: number,\n ): Promise => {\n const payload = await getCachedPayload()\n return getArchiveEntries({ collection, locale, page, payload, perPage })\n },\n )\n\n /**\n * Ready-made handler for Next's `app/sitemap.ts` — every page and entry with\n * per-URL hreflang and lastmod. Re-export it directly:\n *\n * ```ts\n * // app/sitemap.ts\n * export { sitemap as default } from '@/lib/content'\n * export const dynamic = 'force-dynamic' // generate at runtime, not build\n * ```\n *\n * IMPORTANT — container deploys (Coolify/Docker/Railway/CI): Next treats\n * sitemap.ts as STATIC by default and prerenders it during `next build`, which\n * calls into Payload → the database. The build container usually has no access\n * to the internal Docker network, so the DB connection fails (ENOTFOUND) and\n * the build dies. Two defenses:\n * 1. `export const dynamic = 'force-dynamic'` in app/sitemap.ts — skips build\n * prerender, generates at runtime when the DB is reachable (recommended).\n * 2. This handler also catches DB errors and returns [] so that even without\n * (1) the build won't crash — it just ships an empty sitemap until the\n * next runtime regeneration. (1) is still preferred; (2) is a safety net.\n */\n const sitemap = cache(async (): Promise => {\n if (!i18n) {\n throw new Error('[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.')\n }\n try {\n return await buildSitemapEntries({\n baseUrl: origin,\n config: i18n,\n content,\n pagesSlug,\n payload: await getCachedPayload(),\n settingsSlug,\n })\n } catch (error) {\n // DB unreachable (typically a container build with no DB network) — return\n // an empty sitemap instead of failing the build. Runtime regeneration will\n // produce the real one once the DB is reachable. See dynamic='force-dynamic'.\n console.warn(\n '[ipal] sitemap: could not reach the database, returning empty entries ' +\n \"(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to \" +\n 'generate at runtime and avoid build-time DB access):',\n error,\n )\n return []\n }\n })\n\n /**\n * Ready-made handler for Next's `app/robots.ts`. Re-export directly:\n *\n * ```ts\n * // app/robots.ts\n * export { robots as default } from '@/lib/content'\n * ```\n */\n const robots = (): RobotsRules => buildRobots({ baseUrl: origin })\n\n /**\n * Next.js generateStaticParams for the [[...slug]] route (or\n * [locale]/[[...slug]]). Returns every routable page as a params object, so\n * Next PRE-RENDERS them as static (SSG) instead of dynamic.\n *\n * Why this matters beyond convenience: an optional catch-all with no\n * generateStaticParams is treated as a DYNAMIC route (ƒ), which streams\n * metadata into (crawlers miss it). Providing generateStaticParams\n * compiles routes as SSG (●) — the is synchronous and complete. This is\n * the strongest fix for the metadata-in-head problem (stronger than ISR alone).\n *\n * Handles automatically:\n * - pages collection + content collections (with their archive prefix)\n * - excludes the homepage (maps to { slug: [] } — the root)\n * - excludes drafts and 404/500/system slugs\n * - KEEPS noindex pages (they must still render — noindex controls indexing,\n * not existence; skipping them would force dynamic rendering)\n * - localized slugs (string or per-locale map) both handled\n * - single-locale → { slug }[]; multi-locale → { locale, slug }[]\n *\n * Wire it in the project:\n * // app/(frontend)/[[...slug]]/page.tsx (or [locale]/[[...slug]])\n * export { generateStaticParams } from '@/lib/content'\n */\n const generateStaticParams = async (): Promise<\n Array<{ locale: string; slug: string[] } | { slug: string[] }>\n > => {\n try {\n const payload = await getCachedPayload()\n const locales = i18n ? i18n.locales.map((l) => l.code) : [undefined]\n const singleLocale = !i18n || i18n.locales.length === 1\n\n // Home slug per locale, to exclude the homepage (it's the root, slug []).\n const settings = (await payload\n .findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })\n .catch(() => null)) as { homepage?: { id?: number | string; slug?: unknown } } | null\n const homeId = settings?.homepage?.id\n\n const EXCLUDED = new Set(['404', '500', 'error', 'not-found'])\n const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []\n\n for (const locale of locales) {\n // NO where:{_status} filter — collections without drafts enabled don't\n // register the _status field, and querying it throws\n // \"path cannot be queried: _status\". We filter drafts in memory below,\n // which is safe for every collection (with or without drafts).\n const result = await payload.find({\n collection: pagesSlug as never,\n depth: 0,\n limit: 1000,\n locale: (locale ?? 'all') as never,\n })\n\n for (const raw of result.docs as Array<{\n _status?: string\n id: number | string\n meta?: { noindex?: boolean } | null\n slug?: unknown\n }>) {\n // Draft filter in memory (safe whether or not the collection has drafts).\n if (raw._status && raw._status !== 'published') {continue}\n\n // NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex\n // page (privacy, cookies, terms) still needs to render — users reach it\n // from the footer and crawlers read its . Pre-render\n // it as SSG so it's fast and its is complete; noindex controls\n // INDEXING, not whether the page exists. Skipping it would force dynamic\n // rendering (the very streaming problem we're avoiding).\n\n if (homeId && raw.id === homeId) {\n // Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.\n const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }\n if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}\n continue\n }\n\n // Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when\n // read with locale:'all' or left unflattened. Handle both, or localized\n // pages get silently dropped.\n const rawSlug = raw.slug\n const slug =\n typeof rawSlug === 'string'\n ? rawSlug\n : rawSlug && typeof rawSlug === 'object'\n ? (((rawSlug as Record)[locale ?? ''] as string | undefined) ??\n (Object.values(rawSlug as Record)[0] as string | undefined))\n : undefined\n\n if (!slug || EXCLUDED.has(slug)) {continue}\n\n // Multi-level slugs ('atrakcje/telefon') → array segments.\n const segments = String(slug).split('/').filter(Boolean)\n params.push(\n singleLocale ? { slug: segments } : { slug: segments, locale: locale as string },\n )\n }\n }\n\n return params\n } catch (err) {\n // DB unreachable — typically a container build (Docker/Coolify/CI) with no\n // database network. Return [] so the build doesn't crash: Next falls back\n // to on-demand rendering for the routes, which fill in once the DB is\n // reachable at runtime. Without this every project would need its own\n // try/catch here. (Same graceful-degradation as the sitemap handler.)\n console.warn(\n '[ipal] generateStaticParams: database not reachable during build ' +\n '(Docker/CI) — returning empty params; routes render on-demand at runtime:',\n err,\n )\n return []\n }\n }\n\n return {\n generateStaticParams,\n getCachedPayload,\n getConfiguredLocales,\n getEntries,\n getSettings,\n resolveRoute,\n robots,\n sitemap,\n }\n}\n"],"names":["getPayload","cache","getArchiveEntries","resolveRoute","resolveRouteRaw","buildRobots","buildSitemapEntries","createContentHelpers","baseUrl","config","content","i18n","pagesSlug","settingsSlug","origin","process","env","NEXT_PUBLIC_SERVER_URL","getCachedPayload","getConfiguredLocales","c","localization","locales","map","l","code","getSettings","locale","payload","findGlobal","slug","depth","segments","page","getEntries","collection","perPage","sitemap","Error","error","console","warn","robots","generateStaticParams","undefined","singleLocale","length","settings","catch","homeId","homepage","id","EXCLUDED","Set","params","result","find","limit","raw","docs","_status","empty","some","p","JSON","stringify","push","rawSlug","Object","values","has","String","split","filter","Boolean","err"],"mappings":"AAEA,SAASA,UAAU,QAAQ,UAAS;AACpC,SAASC,KAAK,QAAQ,QAAO;AAM7B,SAASC,iBAAiB,EAAEC,gBAAgBC,eAAe,QAAQ,sBAAqB;AACxF,SAASC,WAAW,EAAEC,mBAAmB,QAAQ,kBAAiB;AA2BlE;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,SAASC,qBAAqB,EACnCC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,IAAI,EACJC,YAAY,OAAO,EACnBC,eAAe,eAAe,EACL;IACzB,MAAMC,SAASN,WAAWO,QAAQC,GAAG,CAACC,sBAAsB,IAAI;IAChE,MAAMC,mBAAmBjB,MAAM,UAC7BD,WAAW;YAAES,QAAQ,MAAMA;QAAO;IAGpC,MAAMU,uBAAuBlB,MAAM;QACjC,MAAMmB,IAAI,MAAMX;QAChB,OAAOW,EAAEC,YAAY,GAAGD,EAAEC,YAAY,CAACC,OAAO,CAACC,GAAG,CAAC,CAACC,IAAMA,EAAEC,IAAI,IAAI,EAAE;IACxE;IAEA,MAAMC,cAAczB,MAAM,O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,OAAOC,MAAM,CAACF,QAAmC,CAAC,EAAE,GACrDvB;oBAER,IAAI,CAACd,QAAQsB,SAASkB,GAAG,CAACxC,OAAO;wBAAC;oBAAQ;oBAE1C,2DAA2D;oBAC3D,MAAME,WAAWuC,OAAOzC,MAAM0C,KAAK,CAAC,KAAKC,MAAM,CAACC;oBAChDpB,OAAOY,IAAI,CACTrB,eAAe;wBAAEf,MAAME;oBAAS,IAAI;wBAAEF,MAAME;wBAAUL,QAAQA;oBAAiB;gBAEnF;YACF;YAEA,OAAO2B;QACT,EAAE,OAAOqB,KAAK;YACZ,2EAA2E;YAC3E,0EAA0E;YAC1E,sEAAsE;YACtE,sEAAsE;YACtE,sEAAsE;YACtEnC,QAAQC,IAAI,CACV,sEACE,6EACFkC;YAEF,OAAO,EAAE;QACX;IACF;IAEA,OAAO;QACLhC;QACAzB;QACAC;QACAe;QACAR;QACAvB;QACAuC;QACAL;IACF;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/frontend/createContentHelpers.ts"],"sourcesContent":["import type { BasePayload, SanitizedConfig } from 'payload'\n\nimport { getPayload } from 'payload'\nimport { cache } from 'react'\n\nimport type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'\nimport type { I18nConfig } from '../i18n/index.js'\nimport type { RobotsRules, SitemapEntry } from '../seo/index.js'\n\nimport {\n getArchiveEntries,\n resolveNotFoundPage,\n resolveRoute as resolveRouteRaw,\n} from '../content/index.js'\nimport { buildRobots, buildSitemapEntries } from '../seo/index.js'\n\ntype CreateContentHelpersArgs = {\n /**\n * Absolute site origin for sitemap/robots URLs. Falls back to\n * NEXT_PUBLIC_SERVER_URL, then to a relative origin (which most crawlers\n * reject, so set one in production).\n */\n baseUrl?: string\n /**\n * The client's payload config promise (the default export of payload.config).\n * Passed in because the plugin never imports the client's config directly.\n */\n config: Promise | SanitizedConfig\n /** Archive-backed collections, same value as the plugin option. */\n content?: ContentOption\n /**\n * i18n config. Required only if you want the ready-made `sitemap` / `robots`\n * handlers — they need the locale list to emit hreflang.\n */\n i18n?: I18nConfig\n /** Pages collection slug. Defaults to 'pages'. */\n pagesSlug?: string\n /** SiteSettings global slug. Defaults to 'site-settings'. */\n settingsSlug?: string\n}\n\n/**\n * Bundles the per-request data helpers a frontend needs — the same cached\n * wrappers every project was writing by hand (getPayload, settings, locale\n * list, route resolution, archive entries).\n *\n * Everything is wrapped in React `cache()`, so within one request a value is\n * fetched once no matter how many times it's asked for — which matters because\n * Next runs generateMetadata and the page component separately, and both hit\n * these. Crucially the Payload instance is cached *here*, once, so every helper\n * shares it; that's why this is a factory and not loose functions importing a\n * shared module.\n *\n * ```ts\n * // src/lib/content.ts\n * import { createContentHelpers } from 'ipal-kit'\n * import config from '@/payload.config'\n * import { contentConfig } from '@/content.config'\n *\n * export const { getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries } =\n * createContentHelpers({ config, content: contentConfig })\n * ```\n *\n * `resolveRoute` and `getEntries` are separate on purpose: routing decides what\n * a URL is, fetching gets the listing. Metadata generation needs the first and\n * not the second, and a page component composes them in two obvious lines.\n */\nexport function createContentHelpers({\n baseUrl,\n config,\n content,\n i18n,\n pagesSlug = 'pages',\n settingsSlug = 'site-settings',\n}: CreateContentHelpersArgs) {\n const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''\n const getCachedPayload = cache(async (): Promise =>\n getPayload({ config: await config }),\n )\n\n const getConfiguredLocales = cache(async (): Promise => {\n const c = await config\n return c.localization ? c.localization.locales.map((l) => l.code) : []\n })\n\n const getSettings = cache(async (locale: string) => {\n const payload = await getCachedPayload()\n return payload.findGlobal({ slug: settingsSlug as never, depth: 2, locale: locale as never })\n })\n\n /** What does this URL point at? Routing only — no listing data. */\n const resolveRoute = cache(\n async (\n locale: string,\n segments: string[] | undefined,\n page: number,\n ): Promise => {\n const payload = await getCachedPayload()\n return resolveRouteRaw({ content, locale, page, pagesSlug, payload, segments, settingsSlug })\n },\n )\n\n /**\n * The page assigned as 404 in System Pages (or null → built-in fallback).\n * For app/not-found.tsx; never throws. Locale comes from the x-locale header\n * set by createProxy (not-found.tsx receives no params).\n */\n const getNotFoundPage = cache(async (locale: string) => {\n try {\n const payload = await getCachedPayload()\n return await resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug })\n } catch {\n return null // DB unreachable (container build) — fallback view\n }\n })\n\n /** One page of a collection's entries, for an archive listing. */\n const getEntries = cache(\n async (\n collection: string,\n locale: string,\n page: number,\n perPage: number,\n ): Promise => {\n const payload = await getCachedPayload()\n return getArchiveEntries({ collection, locale, page, payload, perPage })\n },\n )\n\n /**\n * Ready-made handler for Next's `app/sitemap.ts` — every page and entry with\n * per-URL hreflang and lastmod. Re-export it directly:\n *\n * ```ts\n * // app/sitemap.ts\n * export { sitemap as default } from '@/lib/content'\n * export const dynamic = 'force-dynamic' // generate at runtime, not build\n * ```\n *\n * IMPORTANT — container deploys (Coolify/Docker/Railway/CI): Next treats\n * sitemap.ts as STATIC by default and prerenders it during `next build`, which\n * calls into Payload → the database. The build container usually has no access\n * to the internal Docker network, so the DB connection fails (ENOTFOUND) and\n * the build dies. Two defenses:\n * 1. `export const dynamic = 'force-dynamic'` in app/sitemap.ts — skips build\n * prerender, generates at runtime when the DB is reachable (recommended).\n * 2. This handler also catches DB errors and returns [] so that even without\n * (1) the build won't crash — it just ships an empty sitemap until the\n * next runtime regeneration. (1) is still preferred; (2) is a safety net.\n */\n const sitemap = cache(async (): Promise => {\n if (!i18n) {\n throw new Error('[ipal] createContentHelpers: pass `i18n` to use the sitemap handler.')\n }\n try {\n return await buildSitemapEntries({\n baseUrl: origin,\n config: i18n,\n content,\n pagesSlug,\n payload: await getCachedPayload(),\n settingsSlug,\n })\n } catch (error) {\n // DB unreachable (typically a container build with no DB network) — return\n // an empty sitemap instead of failing the build. Runtime regeneration will\n // produce the real one once the DB is reachable. See dynamic='force-dynamic'.\n console.warn(\n '[ipal] sitemap: could not reach the database, returning empty entries ' +\n \"(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to \" +\n 'generate at runtime and avoid build-time DB access):',\n error,\n )\n return []\n }\n })\n\n /**\n * Ready-made handler for Next's `app/robots.ts`. Re-export directly:\n *\n * ```ts\n * // app/robots.ts\n * export { robots as default } from '@/lib/content'\n * ```\n */\n const robots = (): RobotsRules => buildRobots({ baseUrl: origin })\n\n /**\n * Next.js generateStaticParams for the [[...slug]] route (or\n * [locale]/[[...slug]]). Returns every routable page as a params object, so\n * Next PRE-RENDERS them as static (SSG) instead of dynamic.\n *\n * Why this matters beyond convenience: an optional catch-all with no\n * generateStaticParams is treated as a DYNAMIC route (ƒ), which streams\n * metadata into (crawlers miss it). Providing generateStaticParams\n * compiles routes as SSG (●) — the is synchronous and complete. This is\n * the strongest fix for the metadata-in-head problem (stronger than ISR alone).\n *\n * Handles automatically:\n * - pages collection + content collections (with their archive prefix)\n * - excludes the homepage (maps to { slug: [] } — the root)\n * - excludes drafts and 404/500/system slugs\n * - KEEPS noindex pages (they must still render — noindex controls indexing,\n * not existence; skipping them would force dynamic rendering)\n * - localized slugs (string or per-locale map) both handled\n * - single-locale → { slug }[]; multi-locale → { locale, slug }[]\n *\n * Wire it in the project:\n * // app/(frontend)/[[...slug]]/page.tsx (or [locale]/[[...slug]])\n * export { generateStaticParams } from '@/lib/content'\n */\n const generateStaticParams = async (): Promise<\n Array<{ locale: string; slug: string[] } | { slug: string[] }>\n > => {\n try {\n const payload = await getCachedPayload()\n const locales = i18n ? i18n.locales.map((l) => l.code) : [undefined]\n const singleLocale = !i18n || i18n.locales.length === 1\n\n // Home slug per locale, to exclude the homepage (it's the root, slug []).\n const settings = (await payload\n .findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never })\n .catch(() => null)) as {\n homepage?: { id?: number | string; slug?: unknown }\n notFound?: { id?: number | string } | null\n } | null\n const homeId = settings?.homepage?.id\n // The assigned 404 page renders via not-found.tsx, never as its own URL.\n const notFoundId =\n settings?.notFound?.id !== undefined && settings.notFound.id !== homeId\n ? settings.notFound.id\n : undefined\n\n const EXCLUDED = new Set(['404', '500', 'error', 'not-found'])\n const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = []\n\n for (const locale of locales) {\n // NO where:{_status} filter — collections without drafts enabled don't\n // register the _status field, and querying it throws\n // \"path cannot be queried: _status\". We filter drafts in memory below,\n // which is safe for every collection (with or without drafts).\n const result = await payload.find({\n collection: pagesSlug as never,\n depth: 0,\n limit: 1000,\n locale: (locale ?? 'all') as never,\n })\n\n for (const raw of result.docs as Array<{\n _status?: string\n id: number | string\n meta?: { noindex?: boolean } | null\n slug?: unknown\n }>) {\n // Draft filter in memory (safe whether or not the collection has drafts).\n if (raw._status && raw._status !== 'published') {continue}\n if (notFoundId !== undefined && raw.id === notFoundId) {continue}\n\n // NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex\n // page (privacy, cookies, terms) still needs to render — users reach it\n // from the footer and crawlers read its . Pre-render\n // it as SSG so it's fast and its is complete; noindex controls\n // INDEXING, not whether the page exists. Skipping it would force dynamic\n // rendering (the very streaming problem we're avoiding).\n\n if (homeId && raw.id === homeId) {\n // Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.\n const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }\n if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}\n continue\n }\n\n // Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when\n // read with locale:'all' or left unflattened. Handle both, or localized\n // pages get silently dropped.\n const rawSlug = raw.slug\n const slug =\n typeof rawSlug === 'string'\n ? rawSlug\n : rawSlug && typeof rawSlug === 'object'\n ? (((rawSlug as Record)[locale ?? ''] as string | undefined) ??\n (Object.values(rawSlug as Record)[0] as string | undefined))\n : undefined\n\n if (!slug || EXCLUDED.has(slug)) {continue}\n\n // Multi-level slugs ('atrakcje/telefon') → array segments.\n const segments = String(slug).split('/').filter(Boolean)\n params.push(\n singleLocale ? { slug: segments } : { slug: segments, locale: locale as string },\n )\n }\n }\n\n return params\n } catch (err) {\n // DB unreachable — typically a container build (Docker/Coolify/CI) with no\n // database network. Return [] so the build doesn't crash: Next falls back\n // to on-demand rendering for the routes, which fill in once the DB is\n // reachable at runtime. Without this every project would need its own\n // try/catch here. (Same graceful-degradation as the sitemap handler.)\n console.warn(\n '[ipal] generateStaticParams: database not reachable during build ' +\n '(Docker/CI) — returning empty params; routes render on-demand at runtime:',\n err,\n )\n return []\n }\n }\n\n return {\n generateStaticParams,\n getCachedPayload,\n getConfiguredLocales,\n getEntries,\n getNotFoundPage,\n getSettings,\n resolveRoute,\n robots,\n sitemap,\n }\n}\n"],"names":["getPayload","cache","getArchiveEntries","resolveNotFoundPage","resolveRoute","resolveRouteRaw","buildRobots","buildSitemapEntries","createContentHelpers","baseUrl","config","content","i18n","pagesSlug","settingsSlug","origin","process","env","NEXT_PUBLIC_SERVER_URL","getCachedPayload","getConfiguredLocales","c","localization","locales","map","l","code","getSettings","locale","payload","findGlobal","slug","depth","segments","page","getNotFoundPage","getEntries","collection","perPage","sitemap","Error","error","console","warn","robots","generateStaticParams","undefined","singleLocale","length","settings","catch","homeId","homepage","id","notFoundId","notFound","EXCLUDED","Set","params","result","find","limit","raw","docs","_status","empty","some","p","JSON","stringify","push","rawSlug","Object","values","has","String","split","filter","Boolean","err"],"mappings":"AAEA,SAASA,UAAU,QAAQ,UAAS;AACpC,SAASC,KAAK,QAAQ,QAAO;AAM7B,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,gBAAgBC,eAAe,QAC1B,sBAAqB;AAC5B,SAASC,WAAW,EAAEC,mBAAmB,QAAQ,kBAAiB;AA2BlE;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,SAASC,qBAAqB,EACnCC,OAAO,EACPC,MAAM,EACNC,OAAO,EACPC,IAAI,EACJC,YAAY,OAAO,EACnBC,eAAe,eAAe,EACL;IACzB,MAAMC,SAASN,WAAWO,QAAQC,GAAG,CAACC,sBAAsB,IAAI;IAChE,MAAMC,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QACAgB;QACAD;QACAR;QACAvB;QACAwC;QACAL;IACF;AACF"} \ No newline at end of file diff --git a/dist/modules/pages/systemPagesFields.js b/dist/modules/pages/systemPagesFields.js index 4426845..cefaf27 100644 --- a/dist/modules/pages/systemPagesFields.js +++ b/dist/modules/pages/systemPagesFields.js @@ -2,12 +2,14 @@ import { ALL_SYSTEM_PAGE_ROLES } from './types.js'; /** Admin-facing labels per role. */ const ROLE_LABELS = { cookiePolicy: 'Cookie Policy', homepage: 'Homepage', + notFound: '404 (Not Found)', privacyPolicy: 'Privacy Policy', termsOfService: 'Terms of Service' }; /** Admin descriptions per role. */ const ROLE_DESCRIPTIONS = { cookiePolicy: 'Page linked from the cookie consent banner.', homepage: 'Page served at the locale root (e.g. /pl, /en).', + notFound: 'Page shown for unknown URLs (404). Pick a dedicated "Not found" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.', privacyPolicy: 'Page linked as the privacy policy.', termsOfService: 'Page linked as the terms of service / site regulations.' }; diff --git a/dist/modules/pages/systemPagesFields.js.map b/dist/modules/pages/systemPagesFields.js.map index da8e72b..12fd1b3 100644 --- a/dist/modules/pages/systemPagesFields.js.map +++ b/dist/modules/pages/systemPagesFields.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/pages/systemPagesFields.ts"],"sourcesContent":["import type { Field, RelationshipField } from 'payload'\n\nimport type { PagesOption, SystemPageRole } from './types.js'\n\nimport { ALL_SYSTEM_PAGE_ROLES } from './types.js'\n\n/** Admin-facing labels per role. */\nconst ROLE_LABELS: Record = {\n cookiePolicy: 'Cookie Policy',\n homepage: 'Homepage',\n privacyPolicy: 'Privacy Policy',\n termsOfService: 'Terms of Service',\n}\n\n/** Admin descriptions per role. */\nconst ROLE_DESCRIPTIONS: Record = {\n cookiePolicy: 'Page linked from the cookie consent banner.',\n homepage: 'Page served at the locale root (e.g. /pl, /en).',\n privacyPolicy: 'Page linked as the privacy policy.',\n termsOfService: 'Page linked as the terms of service / site regulations.',\n}\n\n/**\n * Builds one relationship field per configured system-page role.\n *\n * Each field points at the client's Pages collection (via the provided slug)\n * and holds a single document reference. The referenced document's slug is\n * localized, so the same assignment resolves to /pl/strona-glowna and\n * /en/home at runtime — role assignment is locale-agnostic, path resolution\n * is locale-aware (see getSystemPagePath).\n */\nexport function buildSystemPagesFields(pages: PagesOption): Field[] {\n const roles = pages.roles?.length ? pages.roles : [...ALL_SYSTEM_PAGE_ROLES]\n\n return roles.map((role): RelationshipField => ({\n name: role,\n type: 'relationship',\n admin: {\n description: ROLE_DESCRIPTIONS[role],\n },\n label: ROLE_LABELS[role],\n maxDepth: 1,\n relationTo: pages.slug,\n }))\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES","ROLE_LABELS","cookiePolicy","homepage","privacyPolicy","termsOfService","ROLE_DESCRIPTIONS","buildSystemPagesFields","pages","roles","length","map","role","name","type","admin","description","label","maxDepth","relationTo","slug"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,aAAY;AAElD,kCAAkC,GAClC,MAAMC,cAA8C;IAClDC,cAAc;IACdC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA,iCAAiC,GACjC,MAAMC,oBAAoD;IACxDJ,cAAc;IACdC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,uBAAuBC,KAAkB;IACvD,MAAMC,QAAQD,MAAMC,KAAK,EAAEC,SAASF,MAAMC,KAAK,GAAG;WAAIT;KAAsB;IAE5E,OAAOS,MAAME,GAAG,CAAC,CAACC,OAA6B,CAAA;YAC7CC,MAAMD;YACNE,MAAM;YACNC,OAAO;gBACLC,aAAaV,iBAAiB,CAACM,KAAK;YACtC;YACAK,OAAOhB,WAAW,CAACW,KAAK;YACxBM,UAAU;YACVC,YAAYX,MAAMY,IAAI;QACxB,CAAA;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/pages/systemPagesFields.ts"],"sourcesContent":["import type { Field, RelationshipField } from 'payload'\n\nimport type { PagesOption, SystemPageRole } from './types.js'\n\nimport { ALL_SYSTEM_PAGE_ROLES } from './types.js'\n\n/** Admin-facing labels per role. */\nconst ROLE_LABELS: Record = {\n cookiePolicy: 'Cookie Policy',\n homepage: 'Homepage',\n notFound: '404 (Not Found)',\n privacyPolicy: 'Privacy Policy',\n termsOfService: 'Terms of Service',\n}\n\n/** Admin descriptions per role. */\nconst ROLE_DESCRIPTIONS: Record = {\n cookiePolicy: 'Page linked from the cookie consent banner.',\n homepage: 'Page served at the locale root (e.g. /pl, /en).',\n notFound:\n 'Page shown for unknown URLs (404). Pick a dedicated \"Not found\" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.',\n privacyPolicy: 'Page linked as the privacy policy.',\n termsOfService: 'Page linked as the terms of service / site regulations.',\n}\n\n/**\n * Builds one relationship field per configured system-page role.\n *\n * Each field points at the client's Pages collection (via the provided slug)\n * and holds a single document reference. The referenced document's slug is\n * localized, so the same assignment resolves to /pl/strona-glowna and\n * /en/home at runtime — role assignment is locale-agnostic, path resolution\n * is locale-aware (see getSystemPagePath).\n */\nexport function buildSystemPagesFields(pages: PagesOption): Field[] {\n const roles = pages.roles?.length ? pages.roles : [...ALL_SYSTEM_PAGE_ROLES]\n\n return roles.map((role): RelationshipField => ({\n name: role,\n type: 'relationship',\n admin: {\n description: ROLE_DESCRIPTIONS[role],\n },\n label: ROLE_LABELS[role],\n maxDepth: 1,\n relationTo: pages.slug,\n }))\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES","ROLE_LABELS","cookiePolicy","homepage","notFound","privacyPolicy","termsOfService","ROLE_DESCRIPTIONS","buildSystemPagesFields","pages","roles","length","map","role","name","type","admin","description","label","maxDepth","relationTo","slug"],"mappings":"AAIA,SAASA,qBAAqB,QAAQ,aAAY;AAElD,kCAAkC,GAClC,MAAMC,cAA8C;IAClDC,cAAc;IACdC,UAAU;IACVC,UAAU;IACVC,eAAe;IACfC,gBAAgB;AAClB;AAEA,iCAAiC,GACjC,MAAMC,oBAAoD;IACxDL,cAAc;IACdC,UAAU;IACVC,UACE;IACFC,eAAe;IACfC,gBAAgB;AAClB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,uBAAuBC,KAAkB;IACvD,MAAMC,QAAQD,MAAMC,KAAK,EAAEC,SAASF,MAAMC,KAAK,GAAG;WAAIV;KAAsB;IAE5E,OAAOU,MAAME,GAAG,CAAC,CAACC,OAA6B,CAAA;YAC7CC,MAAMD;YACNE,MAAM;YACNC,OAAO;gBACLC,aAAaV,iBAAiB,CAACM,KAAK;YACtC;YACAK,OAAOjB,WAAW,CAACY,KAAK;YACxBM,UAAU;YACVC,YAAYX,MAAMY,IAAI;QACxB,CAAA;AACF"} \ No newline at end of file diff --git a/dist/modules/pages/types.d.ts b/dist/modules/pages/types.d.ts index fe3ed3f..bd4c2b2 100644 --- a/dist/modules/pages/types.d.ts +++ b/dist/modules/pages/types.d.ts @@ -2,7 +2,7 @@ * Built-in "system page" roles — documents from the client's Pages * collection that the site references by function rather than by slug. */ -export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService'; +export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService'; /** * All system roles in a stable order (used when no subset is configured). */ diff --git a/dist/modules/pages/types.js b/dist/modules/pages/types.js index cd81089..7545d31 100644 --- a/dist/modules/pages/types.js +++ b/dist/modules/pages/types.js @@ -5,6 +5,7 @@ * All system roles in a stable order (used when no subset is configured). */ export const ALL_SYSTEM_PAGE_ROLES = [ 'homepage', + 'notFound', 'privacyPolicy', 'cookiePolicy', 'termsOfService' diff --git a/dist/modules/pages/types.js.map b/dist/modules/pages/types.js.map index 9011940..f664cb2 100644 --- a/dist/modules/pages/types.js.map +++ b/dist/modules/pages/types.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/pages/types.ts"],"sourcesContent":["/**\n * Built-in \"system page\" roles — documents from the client's Pages\n * collection that the site references by function rather than by slug.\n */\nexport type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService'\n\n/**\n * All system roles in a stable order (used when no subset is configured).\n */\nexport const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [\n 'homepage',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n]\n\n/**\n * Plugin option enabling system-page assignments in SiteSettings.\n *\n * The plugin doesn't own the Pages collection — the client creates it in\n * their own project. This option hands the plugin the collection's slug so\n * it can build relationship fields pointing at it. No hardcoding: the slug\n * always comes from the client.\n */\nexport type PagesOption = {\n /**\n * Which system roles to expose as assignable fields.\n * Defaults to all roles when omitted.\n */\n roles?: SystemPageRole[]\n /** Slug of the client's Pages collection, e.g. 'pages'. */\n slug: string\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES"],"mappings":"AAAA;;;CAGC,GAGD;;CAEC,GACD,OAAO,MAAMA,wBAAmD;IAC9D;IACA;IACA;IACA;CACD,CAAA"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/pages/types.ts"],"sourcesContent":["/**\n * Built-in \"system page\" roles — documents from the client's Pages\n * collection that the site references by function rather than by slug.\n */\nexport type SystemPageRole =\n 'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService'\n\n/**\n * All system roles in a stable order (used when no subset is configured).\n */\nexport const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [\n 'homepage',\n 'notFound',\n 'privacyPolicy',\n 'cookiePolicy',\n 'termsOfService',\n]\n\n/**\n * Plugin option enabling system-page assignments in SiteSettings.\n *\n * The plugin doesn't own the Pages collection — the client creates it in\n * their own project. This option hands the plugin the collection's slug so\n * it can build relationship fields pointing at it. No hardcoding: the slug\n * always comes from the client.\n */\nexport type PagesOption = {\n /**\n * Which system roles to expose as assignable fields.\n * Defaults to all roles when omitted.\n */\n roles?: SystemPageRole[]\n /** Slug of the client's Pages collection, e.g. 'pages'. */\n slug: string\n}\n"],"names":["ALL_SYSTEM_PAGE_ROLES"],"mappings":"AAAA;;;CAGC,GAID;;CAEC,GACD,OAAO,MAAMA,wBAAmD;IAC9D;IACA;IACA;IACA;IACA;CACD,CAAA"} \ No newline at end of file diff --git a/docs/analytics.md b/docs/analytics.md index 1b421f7..9667d00 100644 --- a/docs/analytics.md +++ b/docs/analytics.md @@ -1,22 +1,58 @@ # analytics -Ładuje GA4 albo Google Tag Manager, spięte z modułem consent: Consent Mode -dostaje decyzję odwiedzającego, zanim tag się załaduje, i aktualizację w -momencie kliknięcia w banerze. +Ładuje tagi analityczne i marketingowe wpisane w panelu, każdy zgodnie ze +zgodą z modułu consent: + +- **Google (GA4 / GTM)** — przez Consent Mode v2: tag ładuje się od razu, ale + dostaje decyzję odwiedzającego, zanim cokolwiek zmierzy. +- **Pozostałe (Meta Pixel, Microsoft Clarity, LinkedIn Insight, TikTok Pixel)** — + nie mają Consent Mode, więc ładują się **dopiero po zgodzie** na właściwą + kategorię. Reagują na żywo: klik „Akceptuj” → tag startuje bez przeładowania. ## Config Brak opcji w `payload.config` — plugin czyta ID z globala **Site Integrations** (Settings → Site Integrations): -- **GA4 Measurement ID** — `G-XXXXXXXXXX` -- **GTM Container ID** — `GTM-XXXXXXX` +| Pole | Format | Kategoria zgody | +|---|---|---| +| GA4 Measurement ID | `G-XXXXXXXXXX` | Consent Mode (analytics_storage) | +| GTM Container ID | `GTM-XXXXXXX` | Consent Mode (wszystkie sygnały) | +| Meta Pixel ID | `1234567890123456` | **marketing** | +| Microsoft Clarity Project ID | `abcdefghij` | **analytics** | +| LinkedIn Partner ID | `1234567` | **marketing** | +| TikTok Pixel ID | `CXXXXXXXXXXXXXXXXXXX` | **marketing** | -Gdy ustawione są oba, wygrywa GTM. Gdy żadne — komponent nie robi nic. +GA4 + GTM ustawione jednocześnie → wygrywa GTM. Puste pole = tag się nie ładuje. -To jedyne pola z Site Integrations, które trafiają na klienta — są publiczne -(widać je w źródle każdej strony z GA). `getAnalyticsConfig` czyta wyłącznie je, -więc sekrety (Turnstile, SMTP) nie mają jak wyciec. +Wszystkie te ID są publiczne (widać je w źródle strony). `getAnalyticsConfig` +czyta wyłącznie je, więc sekrety (Turnstile, SMTP) nie mają jak wyciec. + +### Pixel w panelu czy w GTM? + +**Jedno albo drugie, nigdy oba** — inaczej każde zdarzenie liczy się +podwójnie. Zasada: + +- Klient bez GTM / prosta strona → wpisz Pixel ID w panelu (najprościej, + zgoda obsłużona automatycznie). +- Klient ma agencję/marketera, który zarządza tagami w GTM → zostaw pole Pixel + puste, Pixel konfiguruje się w GTM z warunkiem `ad_storage` (patrz + [gtm-meta-pixel.md](./gtm-meta-pixel.md)). + +### Zdarzenia konwersji (non-Google) + +`Analytics` wysyła tylko `PageView`. Konwersje (np. Lead po formularzu) wołasz +sam — globale istnieją dopiero po zgodzie, więc zawsze ze strażnikiem: + +```ts +window.fbq?.('track', 'Lead') // Meta +window.ttq?.track('SubmitForm') // TikTok +window.lintrk?.('track', { conversion_id: 123 }) // LinkedIn +``` + +Niskopoziomowe loadery (`loadMetaPixel`, `loadClarity`, `loadLinkedIn`, +`loadTikTok`) są eksportowane z `/client`, ale normalnie nie są potrzebne — +NIE wołaj ich z pominięciem zgody. ## Front @@ -41,7 +77,8 @@ export default async function LocaleLayout({ children, params }) { ``` `Analytics` nie renderuje nic — wstrzykuje skrypty. Zamontuj raz, wysoko w -drzewie. +drzewie. **Musi być wewnątrz `ConsentProvider`** (od 1.8.0 czyta stan zgody na +żywo — poza providerem rzuci błąd kontekstu). ## Jak działa Consent Mode @@ -68,6 +105,11 @@ W konsoli: `window.dataLayer` — powinien zawierać `Arguments(3)` z `consent` Ciasteczko `_ga` pojawia się dopiero po zgodzie na analytics — to jest sedno Consent Mode. +Pixele non-Google: przed zgodą w Network **nie może** być żądań do +`connect.facebook.net`, `clarity.ms`, `snap.licdn.com`, `analytics.tiktok.com`. +Po kliknięciu zgody pojawiają się od razu. Meta Pixel Helper (rozszerzenie +Chrome) powinien pokazać `PageView` dopiero po akceptacji marketingu. + ## Zdarzenia do GTM — pushDataLayer Do wypchnięcia własnego zdarzenia (np. `form_submit` pod tag Lead w GTM) jest diff --git a/docs/pages.md b/docs/pages.md index 947b2e5..6afefb6 100644 --- a/docs/pages.md +++ b/docs/pages.md @@ -1,7 +1,7 @@ # pages -System pages: centralne przypisanie ról (homepage / privacyPolicy / -cookiePolicy) do dokumentów z klienckiej kolekcji Pages, w SiteSettings. +System pages: centralne przypisanie ról (homepage / notFound / privacyPolicy / +cookiePolicy / termsOfService) do dokumentów z klienckiej kolekcji Pages, w SiteSettings. Front rozwiązuje rolę na ścieżkę locale-aware. ## Config (payload.config.ts) @@ -51,9 +51,55 @@ stopce / bannerze cookies bierzesz z `getSystemPagePath({ role: privacyPolicy }) ```ts import { ALL_SYSTEM_PAGE_ROLES } from '@intecion/ipal-kit' -// ['homepage', 'privacyPolicy', 'cookiePolicy'] +// ['homepage', 'notFound', 'privacyPolicy', 'cookiePolicy', 'termsOfService'] ``` +## Strona 404 — wybierana w panelu (od 1.8.0) + +Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera: + +- dedykowaną stronę „Nie znaleziono” (np. slug `strona-nie-znaleziona`), **albo** +- stronę główną (część klientów tak woli), **albo** +- nic → projekt pokazuje wbudowany fallback z `not-found.tsx`. + +Projekt (`app/(frontend)/[locale]/not-found.tsx`) — gotowy przykład w +`frontend/[locale]/not-found.tsx`: + +```tsx +import { headers } from 'next/headers' +import { getNotFoundPage } from '@/lib/content' // z createContentHelpers + +export default async function NotFound() { + const locale = (await headers()).get('x-locale') ?? i18nConfig.defaultLocale + const page = await getNotFoundPage(locale) // null → fallback + if (page?.layout?.length) return + return +} +``` + +`not-found.tsx` nie dostaje `params` — locale bierzemy z nagłówka `x-locale`, +który ustawia proxy z `createProxy`. Status HTTP zostaje **404** (renderuje go +Next po `notFound()`), treść jest z panelu. + +Co plugin robi automatycznie z przypisaną stroną 404: + +| Miejsce | Zachowanie | +|---|---| +| `resolveRoute` | bezpośrednie wejście na `/pl/strona-nie-znaleziona` → `null` → `notFound()` → prawdziwy 404 (bez soft-404 / duplikatu z kodem 200) | +| sitemap | wykluczona po ID (slug może być dowolny) | +| `generateStaticParams` | pominięta (nie jest osobnym URL-em) | +| `getNotFoundPage` / `resolveNotFoundPage` | nigdy nie rzuca — brak bazy w buildzie = fallback | + +Gdy 404 = strona główna, nic z powyższego nie ukrywa strony głównej — dalej +działa pod `/{locale}` i jest w sitemapie; dodatkowo jej treść pokazuje się pod +nieznanymi URL-ami (z kodem 404). + +Bez `createContentHelpers`: `resolveNotFoundPage({ payload, locale })` z +`@intecion/ipal-kit`. + +Wskazówka: zaznacz na dedykowanej stronie 404 **noindex** — wtedy wypada też z +llms.txt i wyszukiwarki. + ## KRYTYCZNE: generateStaticParams dla [[...slug]] (SEO + head) Trasa `[[...slug]]` (opcjonalny catch-all) BEZ `generateStaticParams` jest przez diff --git a/src/globals/SiteIntegrations/fields/analytics.ts b/src/globals/SiteIntegrations/fields/analytics.ts index bebcf9d..ca29481 100644 --- a/src/globals/SiteIntegrations/fields/analytics.ts +++ b/src/globals/SiteIntegrations/fields/analytics.ts @@ -1,15 +1,16 @@ import type { Field } from 'payload' /** - * Analytics configuration — GA4 measurement ID and GTM container ID. - * IDs are public (exposed client-side), so no read restriction needed. + * Analytics / marketing tag IDs. All are PUBLIC (exposed client-side), so no + * read restriction. Google tags (GA4/GTM) use Consent Mode; the rest load only + * after the matching consent category is granted (see modules/analytics). */ export const analyticsFields: Field[] = [ { name: 'ga4MeasurementId', type: 'text', admin: { - description: 'Google Analytics 4 Measurement ID.', + description: 'Google Analytics 4 Measurement ID. (Google — Consent Mode)', placeholder: 'G-XXXXXXXXXX', }, }, @@ -17,8 +18,40 @@ export const analyticsFields: Field[] = [ name: 'gtmContainerId', type: 'text', admin: { - description: 'Google Tag Manager container ID.', + description: 'Google Tag Manager container ID. (Google — Consent Mode)', placeholder: 'GTM-XXXXXXX', }, }, + { + name: 'metaPixelId', + type: 'text', + admin: { + description: 'Meta (Facebook) Pixel ID. Loads only after MARKETING consent.', + placeholder: '1234567890123456', + }, + }, + { + name: 'clarityProjectId', + type: 'text', + admin: { + description: 'Microsoft Clarity project ID (heatmaps). Loads only after ANALYTICS consent.', + placeholder: 'abcdefghij', + }, + }, + { + name: 'linkedInPartnerId', + type: 'text', + admin: { + description: 'LinkedIn Insight Tag partner ID. Loads only after MARKETING consent.', + placeholder: '1234567', + }, + }, + { + name: 'tiktokPixelId', + type: 'text', + admin: { + description: 'TikTok Pixel ID. Loads only after MARKETING consent.', + placeholder: 'CXXXXXXXXXXXXXXXXXXX', + }, + }, ] diff --git a/src/index.ts b/src/index.ts index fbb6480..e124052 100644 --- a/src/index.ts +++ b/src/index.ts @@ -56,6 +56,7 @@ export { markdownResponse, parsePageParam, prefersMarkdown, + resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent, diff --git a/src/modules/analytics/Analytics.tsx b/src/modules/analytics/Analytics.tsx index 0664a53..8f866d9 100644 --- a/src/modules/analytics/Analytics.tsx +++ b/src/modules/analytics/Analytics.tsx @@ -3,8 +3,10 @@ import { useEffect } from 'react' import type { AnalyticsConfig } from './types.js' +import { useConsentContext } from '../consent/client.js' import { gtag } from '../consent/googleConsent.js' import { CONSENT_COOKIE, DEFAULT_CONSENT, parseConsent, setDefaultConsent } from '../consent/index.js' +import { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js' declare global { interface Window { @@ -34,37 +36,66 @@ function injectScript(src: string) { } /** - * Loads Google Analytics — GTM if a container ID is set, otherwise GA4 gtag. + * Loads every configured analytics / marketing tag, each respecting consent: * - * Consent Mode is initialised to the visitor's stored consent BEFORE the tag - * loads (via setDefaultConsent from the consent module), so tags respect the - * choice from the first hit; useConsent sends an update the moment the visitor - * decides. IDs are public and come from SiteIntegrations, passed in as props - * (the client project reads them server-side). + * - **Google (GA4 / GTM)** — loaded immediately with Consent Mode: the visitor's + * stored choice is set as the default BEFORE the tag loads, and useConsent + * pushes an update the moment they decide. GTM wins if both IDs are set. + * - **Non-Google (Meta Pixel, Clarity, LinkedIn, TikTok)** — these vendors have + * no Consent Mode, so they load ONLY after the matching category is granted + * (marketing for Pixel/LinkedIn/TikTok, analytics for Clarity). Reacts live to + * the consent banner: accept → the tag loads immediately, no reload. * - * Renders nothing — it only injects the scripts. Mount once, high in the tree - * (e.g. root layout), inside ConsentProvider. + * All IDs are public and come from SiteIntegrations (getAnalyticsConfig), passed + * in as props. Renders nothing. Mount once, high in the tree, INSIDE + * (required — it reads live consent state). */ -export function Analytics({ ga4MeasurementId, gtmContainerId }: AnalyticsConfig) { +export function Analytics(props: AnalyticsConfig) { + const { + clarityProjectId, + ga4MeasurementId, + gtmContainerId, + linkedInPartnerId, + metaPixelId, + tiktokPixelId, + } = props + + // Live consent state — drives the non-Google pixels. + const { state } = useConsentContext() + + // --- Google: load once, Consent Mode handles gating --- useEffect(() => { if (!ga4MeasurementId && !gtmContainerId) {return} - - // 1. Consent Mode default = the visitor's stored choice, before tags load. setDefaultConsent(readConsent()) - - // 2. Load the tag. if (gtmContainerId) { window.dataLayer = window.dataLayer || [] window.dataLayer.push({ event: 'gtm.js', 'gtm.start': Date.now() }) injectScript(GTM_SCRIPT(gtmContainerId)) } else if (ga4MeasurementId) { injectScript(GA4_SCRIPT(ga4MeasurementId)) - // Uses the shared gtag (pushes `arguments`, as Google's tags expect); - // real gtag.js wires itself up once the script loads. gtag('js', new Date()) gtag('config', ga4MeasurementId) } }, [ga4MeasurementId, gtmContainerId]) + // --- Non-Google: load each when its consent category is granted --- + // The loaders are idempotent, so re-running on state changes is safe; a tag + // loads the first time its category flips to true and never doubles up. + useEffect(() => { + if (state.marketing) { + if (metaPixelId) {loadMetaPixel(metaPixelId)} + if (linkedInPartnerId) {loadLinkedIn(linkedInPartnerId)} + if (tiktokPixelId) {loadTikTok(tiktokPixelId)} + } + if (state.analytics && clarityProjectId) {loadClarity(clarityProjectId)} + }, [ + state.marketing, + state.analytics, + metaPixelId, + linkedInPartnerId, + tiktokPixelId, + clarityProjectId, + ]) + return null } diff --git a/src/modules/analytics/client.ts b/src/modules/analytics/client.ts index f082b0e..b57e5ff 100644 --- a/src/modules/analytics/client.ts +++ b/src/modules/analytics/client.ts @@ -1,3 +1,6 @@ 'use client' export { Analytics } from './Analytics.js' +// Low-level pixel loaders — exported for manual conversion events if a project +// needs them (Analytics loads them automatically, consent-gated). +export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from './pixels.js' export { pushDataLayer } from './pushDataLayer.js' diff --git a/src/modules/analytics/getAnalyticsConfig.ts b/src/modules/analytics/getAnalyticsConfig.ts index d7256fc..d7773d5 100644 --- a/src/modules/analytics/getAnalyticsConfig.ts +++ b/src/modules/analytics/getAnalyticsConfig.ts @@ -5,15 +5,18 @@ import type { AnalyticsConfig } from './types.js' import { getSiteIntegrations } from '../payload/index.js' /** - * Reads the public analytics IDs from SiteIntegrations, server-side. - * - * Returns only the two public IDs (GA4 / GTM) — safe to pass to the client + * Reads the public analytics / marketing tag IDs from SiteIntegrations, + * server-side. All are public (exposed client-side), so safe to pass to the * component. Does NOT expose any secret from SiteIntegrations. */ export async function getAnalyticsConfig(payload: BasePayload): Promise { const integrations = await getSiteIntegrations(payload) return { + clarityProjectId: integrations.clarityProjectId ?? null, ga4MeasurementId: integrations.ga4MeasurementId ?? null, gtmContainerId: integrations.gtmContainerId ?? null, + linkedInPartnerId: integrations.linkedInPartnerId ?? null, + metaPixelId: integrations.metaPixelId ?? null, + tiktokPixelId: integrations.tiktokPixelId ?? null, } } diff --git a/src/modules/analytics/pixels.ts b/src/modules/analytics/pixels.ts new file mode 100644 index 0000000..ea40de0 --- /dev/null +++ b/src/modules/analytics/pixels.ts @@ -0,0 +1,118 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/** + * Loaders for non-Google marketing/analytics pixels. Each is idempotent (guards + * against double-init) and loads the vendor's own script + bootstrap. + * + * These are the one place `any` is unavoidable: vendor SDK bootstraps attach + * untyped globals (fbq, clarity, lintrk, ttq) to `window`. Casts are contained + * here; nothing else in the kit uses `any`. + * + * CONSENT: these vendors have no Google Consent Mode — the caller (Analytics) + * loads each ONLY after the matching consent category is granted: + * Meta Pixel / LinkedIn / TikTok → marketing + * Microsoft Clarity → analytics + */ + +type Win = Record & typeof window + +/** Meta (Facebook) Pixel — fires PageView on load. */ +export function loadMetaPixel(id: string): void { + if (typeof window === 'undefined') {return} + const w = window as Win + if (w.fbq) {return} + const n: any = (w.fbq = function (...args: unknown[]) { + if (n.callMethod) { + n.callMethod.apply(n, args) + } else { + n.queue.push(args) + } + }) + if (!w._fbq) {w._fbq = n} + n.push = n + n.loaded = true + n.version = '2.0' + n.queue = [] + const s = document.createElement('script') + s.async = true + s.src = 'https://connect.facebook.net/en_US/fbevents.js' + document.head.appendChild(s) + w.fbq('init', id) + w.fbq('track', 'PageView') +} + +/** Microsoft Clarity — heatmaps / session recordings (analytics category). */ +export function loadClarity(id: string): void { + if (typeof window === 'undefined') {return} + const w = window as Win + if (w.clarity) {return} + w.clarity = function (...a: unknown[]) { + ;(w.clarity.q = w.clarity.q || []).push(a) + } + const s = document.createElement('script') + s.async = true + s.src = `https://www.clarity.ms/tag/${id}` + document.head.appendChild(s) +} + +/** LinkedIn Insight Tag (marketing). */ +export function loadLinkedIn(partnerId: string): void { + if (typeof window === 'undefined') {return} + const w = window as Win + w._linkedin_partner_id = partnerId + w._linkedin_data_partner_ids = w._linkedin_data_partner_ids || [] + if (w._linkedin_data_partner_ids.includes(partnerId)) { + if (document.getElementById('ipal-linkedin-insight')) {return} + } else { + w._linkedin_data_partner_ids.push(partnerId) + } + if (document.getElementById('ipal-linkedin-insight')) {return} + const s = document.createElement('script') + s.async = true + s.id = 'ipal-linkedin-insight' + s.src = 'https://snap.licdn.com/li.lms-analytics/insight.min.js' + document.head.appendChild(s) +} + +/** TikTok Pixel (marketing) — fires page view on load. */ +export function loadTikTok(id: string): void { + if (typeof window === 'undefined') {return} + const w = window as Win + if (w.ttq) {return} + w.TiktokAnalyticsObject = 'ttq' + const ttq: any = (w.ttq = []) + ttq.methods = [ + 'page', + 'track', + 'identify', + 'instances', + 'debug', + 'on', + 'off', + 'once', + 'ready', + 'alias', + 'group', + 'enableCookie', + 'disableCookie', + ] + ttq.setAndDefer = function (t: any, e: string) { + t[e] = function (...args: unknown[]) { + t.push([e, ...args]) + } + } + for (const m of ttq.methods) {ttq.setAndDefer(ttq, m)} + ttq.load = function (e: string) { + const url = 'https://analytics.tiktok.com/i18n/pixel/events.js' + ttq._i = ttq._i || {} + ttq._i[e] = [] + ttq._i[e]._u = url + ttq._t = ttq._t || {} + ttq._t[e] = Number(new Date()) + const s = document.createElement('script') + s.async = true + s.src = `${url}?sdkid=${e}&lib=ttq` + document.head.appendChild(s) + } + ttq.load(id) + ttq.page() +} diff --git a/src/modules/analytics/types.ts b/src/modules/analytics/types.ts index 0c08fbe..378aa48 100644 --- a/src/modules/analytics/types.ts +++ b/src/modules/analytics/types.ts @@ -1,9 +1,19 @@ /** - * Analytics IDs, read from SiteIntegrations (public — safe on the client). + * Analytics / marketing tag IDs, read from SiteIntegrations (all public — safe + * on the client). Google tags (GA4/GTM) use Consent Mode; the rest load only + * after the matching consent category is granted (see Analytics). */ export type AnalyticsConfig = { - /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. */ + /** Microsoft Clarity project ID. (analytics consent) */ + clarityProjectId?: null | string + /** GA4 Measurement ID, e.g. 'G-XXXXXXXXXX'. (Google — Consent Mode) */ ga4MeasurementId?: null | string - /** GTM Container ID, e.g. 'GTM-XXXXXXX'. */ + /** GTM Container ID, e.g. 'GTM-XXXXXXX'. (Google — Consent Mode) */ gtmContainerId?: null | string + /** LinkedIn Insight Tag partner ID. (marketing consent) */ + linkedInPartnerId?: null | string + /** Meta (Facebook) Pixel ID, ~15–16 digits. (marketing consent) */ + metaPixelId?: null | string + /** TikTok Pixel ID. (marketing consent) */ + tiktokPixelId?: null | string } diff --git a/src/modules/content/index.ts b/src/modules/content/index.ts index 15cf0f4..24fb88b 100644 --- a/src/modules/content/index.ts +++ b/src/modules/content/index.ts @@ -6,6 +6,7 @@ export { getArchiveEntries } from './getArchiveEntries.js' export type { ArchiveEntries } from './getArchiveEntries.js' export { MARKDOWN_PREFIX, markdownHref, prefersMarkdown } from './markdownNegotiation.js' export { buildArchivePath, buildEntryPath, parsePageParam } from './paths.js' +export { resolveNotFoundPage } from './resolveNotFoundPage.js' export { resolveRedirect } from './resolveRedirect.js' export { resolveRoute } from './resolveRoute.js' export type { ResolvedRoute } from './resolveRoute.js' diff --git a/src/modules/content/resolveNotFoundPage.ts b/src/modules/content/resolveNotFoundPage.ts new file mode 100644 index 0000000..88b4a3c --- /dev/null +++ b/src/modules/content/resolveNotFoundPage.ts @@ -0,0 +1,57 @@ +import type { BasePayload } from 'payload' + +type ResolveNotFoundPageArgs = { + locale: string + /** Client's Pages collection slug. Defaults to 'pages'. */ + pagesSlug?: string + payload: BasePayload + /** SiteSettings global slug. Defaults to 'site-settings'. */ + settingsSlug?: string +} + +/** + * Returns the page the editor assigned as **404 (Not Found)** in System Pages, + * fully populated (depth 2, same shape as resolveRoute's pages), or null when + * the role is unassigned. + * + * Used by the project's `not-found.tsx`. The editor decides what a 404 looks + * like: a dedicated "Not found" page, or simply the homepage. Null means + * "render the project's built-in fallback view". + * + * Never throws — a missing DB (container build prerendering not-found) or a + * deleted page just yields null, so the 404 view can't crash the build. + */ +export async function resolveNotFoundPage({ + locale, + pagesSlug = 'pages', + payload, + settingsSlug = 'site-settings', +}: ResolveNotFoundPageArgs): Promise> { + try { + const settings = (await payload.findGlobal({ + slug: settingsSlug as never, + depth: 0, + locale: locale as never, + })) as Record + + const rel = settings.notFound + const id = + typeof rel === 'string' || typeof rel === 'number' + ? rel + : rel && typeof rel === 'object' + ? (rel as { id?: number | string }).id + : undefined + if (id === undefined) {return null} + + const doc = await payload.findByID({ + id, + collection: pagesSlug as never, + depth: 2, + locale: locale as never, + }) + return (doc as null | Record) ?? null + } catch (error) { + console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error) + return null + } +} diff --git a/src/modules/content/resolveRoute.ts b/src/modules/content/resolveRoute.ts index 46c24bc..e5cf3e7 100644 --- a/src/modules/content/resolveRoute.ts +++ b/src/modules/content/resolveRoute.ts @@ -160,5 +160,22 @@ export async function resolveRoute({ const doc = found.docs[0] if (!doc) {return null} + // The page assigned as 404 in System Pages must not be reachable as a normal + // 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat + // it as not found, so the route calls notFound() and not-found.tsx renders + // that same page with a real 404 status. (If 404 = homepage, the homepage is + // served from the root branch above and never reaches here by its own slug + // in a way that matters — but guard anyway so we never hide the homepage.) + const notFound = settings.notFound + const homepage = settings.homepage + const notFoundId = + notFound && typeof notFound === 'object' ? (notFound as { id?: unknown }).id : notFound + const homepageId = + homepage && typeof homepage === 'object' ? (homepage as { id?: unknown }).id : homepage + const docId = (doc as { id?: unknown }).id + if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) { + return null + } + return { type: 'page', doc: doc as Record } } diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 4a9779a..763671f 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -7,7 +7,11 @@ import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/in import type { I18nConfig } from '../i18n/index.js' import type { RobotsRules, SitemapEntry } from '../seo/index.js' -import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js' +import { + getArchiveEntries, + resolveNotFoundPage, + resolveRoute as resolveRouteRaw, +} from '../content/index.js' import { buildRobots, buildSitemapEntries } from '../seo/index.js' type CreateContentHelpersArgs = { @@ -96,6 +100,20 @@ export function createContentHelpers({ }, ) + /** + * The page assigned as 404 in System Pages (or null → built-in fallback). + * For app/not-found.tsx; never throws. Locale comes from the x-locale header + * set by createProxy (not-found.tsx receives no params). + */ + const getNotFoundPage = cache(async (locale: string) => { + try { + const payload = await getCachedPayload() + return await resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug }) + } catch { + return null // DB unreachable (container build) — fallback view + } + }) + /** One page of a collection's entries, for an archive listing. */ const getEntries = cache( async ( @@ -202,8 +220,16 @@ export function createContentHelpers({ // Home slug per locale, to exclude the homepage (it's the root, slug []). const settings = (await payload .findGlobal({ slug: settingsSlug as never, depth: 1, locale: 'all' as never }) - .catch(() => null)) as { homepage?: { id?: number | string; slug?: unknown } } | null + .catch(() => null)) as { + homepage?: { id?: number | string; slug?: unknown } + notFound?: { id?: number | string } | null + } | null const homeId = settings?.homepage?.id + // The assigned 404 page renders via not-found.tsx, never as its own URL. + const notFoundId = + settings?.notFound?.id !== undefined && settings.notFound.id !== homeId + ? settings.notFound.id + : undefined const EXCLUDED = new Set(['404', '500', 'error', 'not-found']) const params: Array<{ locale: string; slug: string[] } | { slug: string[] }> = [] @@ -228,6 +254,7 @@ export function createContentHelpers({ }>) { // Draft filter in memory (safe whether or not the collection has drafts). if (raw._status && raw._status !== 'published') {continue} + if (notFoundId !== undefined && raw.id === notFoundId) {continue} // NOTE: unlike the sitemap, we do NOT skip meta.noindex here. A noindex // page (privacy, cookies, terms) still needs to render — users reach it @@ -286,6 +313,7 @@ export function createContentHelpers({ getCachedPayload, getConfiguredLocales, getEntries, + getNotFoundPage, getSettings, resolveRoute, robots, diff --git a/src/modules/pages/systemPagesFields.ts b/src/modules/pages/systemPagesFields.ts index e95678e..87c1bc9 100644 --- a/src/modules/pages/systemPagesFields.ts +++ b/src/modules/pages/systemPagesFields.ts @@ -8,6 +8,7 @@ import { ALL_SYSTEM_PAGE_ROLES } from './types.js' const ROLE_LABELS: Record = { cookiePolicy: 'Cookie Policy', homepage: 'Homepage', + notFound: '404 (Not Found)', privacyPolicy: 'Privacy Policy', termsOfService: 'Terms of Service', } @@ -16,6 +17,8 @@ const ROLE_LABELS: Record = { const ROLE_DESCRIPTIONS: Record = { cookiePolicy: 'Page linked from the cookie consent banner.', homepage: 'Page served at the locale root (e.g. /pl, /en).', + notFound: + 'Page shown for unknown URLs (404). Pick a dedicated "Not found" page, or reuse the homepage. If left empty, the project falls back to its built-in not-found view.', privacyPolicy: 'Page linked as the privacy policy.', termsOfService: 'Page linked as the terms of service / site regulations.', } diff --git a/src/modules/pages/types.ts b/src/modules/pages/types.ts index a4d5563..a023577 100644 --- a/src/modules/pages/types.ts +++ b/src/modules/pages/types.ts @@ -2,13 +2,15 @@ * Built-in "system page" roles — documents from the client's Pages * collection that the site references by function rather than by slug. */ -export type SystemPageRole = 'cookiePolicy' | 'homepage' | 'privacyPolicy' | 'termsOfService' +export type SystemPageRole = + 'cookiePolicy' | 'homepage' | 'notFound' | 'privacyPolicy' | 'termsOfService' /** * All system roles in a stable order (used when no subset is configured). */ export const ALL_SYSTEM_PAGE_ROLES: readonly SystemPageRole[] = [ 'homepage', + 'notFound', 'privacyPolicy', 'cookiePolicy', 'termsOfService',