Gap fixes: top-level searchSettings, public shouldLoadGoogle, consent/stats collection overrides

- ipalKit({ searchSettings }): switches off / reshapes Site Settings → Search & AI
  without `seo`; read as options.searchSettings ?? options.seo?.searchSettings.
- shouldLoadGoogle moved to a pure module (analytics/shouldLoadGoogle.ts) and
  exported from @intecion/ipal-kit and /client.
- consentLog.collectionOverrides and stats.collectionOverrides (object merges
  access/admin/hooks key by key, function takes over), via the new exported
  applyCollectionOverride / CollectionOverride. The stats view and dashboard
  chart now follow the stats-visits read access, so overrides narrow them too.

All additive; defaults unchanged. Docs: AGENT.md, ipal-reference, consent,
stats, seo, analytics, ipal-setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 18:54:08 +02:00
co-authored by Claude Opus 5.5
parent 4911da7112
commit 5a07c42f76
22 changed files with 235 additions and 54 deletions
+2 -1
View File
@@ -3,9 +3,10 @@ export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '..
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js'
export type { AnalyticsProps } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js'
export { shouldLoadGoogle } from '../modules/analytics/shouldLoadGoogle.js'
/**
* Entry point: ipal-kit/client
*
+4 -1
View File
@@ -26,6 +26,7 @@ export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
export { shouldLoadGoogle } from './modules/analytics/shouldLoadGoogle.js'
// Shared section fields (header: eyebrow/heading/intro, settings: anchor/background).
export { buildSectionHeaderField, buildSectionSettingsField } from './modules/blocks/sectionFields.js'
export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './modules/blocks/sectionFields.js'
@@ -175,9 +176,9 @@ export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './module
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
@@ -225,6 +226,8 @@ export { robotsOptionsFrom, verificationFrom } from './modules/seo/index.js'
export type { AiBotRule, AiBotsPolicy, VerificationMetadata } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapIndexXml, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
export { applyCollectionOverride } from './modules/shared/collectionOverride.js'
export type { CollectionOverride } from './modules/shared/collectionOverride.js'
export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
+1 -18
View File
@@ -7,6 +7,7 @@ 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'
import { shouldLoadGoogle } from './shouldLoadGoogle.js'
declare global {
interface Window {
@@ -69,24 +70,6 @@ export type AnalyticsProps = {
deferTimeoutMs?: number
} & AnalyticsConfig
/**
* Whether the Google tag may load now. Pure, so the consent rule is testable
* without a DOM: 'basic' waits for an analytics or marketing grant, 'advanced'
* relies on the Consent Mode default and loads as soon as `ready`.
*/
export function shouldLoadGoogle({
consentMode,
ready,
state,
}: {
consentMode: 'advanced' | 'basic'
ready: boolean
state: { analytics?: boolean; marketing?: boolean }
}): boolean {
if (!ready) {return false}
return consentMode === 'advanced' || Boolean(state.analytics || state.marketing)
}
const INTERACTION_EVENTS = ['scroll', 'pointerdown', 'touchstart', 'keydown'] as const
/** True once third-party tags may load (immediately, or per `defer` rules). */
+23
View File
@@ -0,0 +1,23 @@
/**
* Pure consent gate for the Google tag — no React, no DOM, safe on the server
* and in the client bundle. <Analytics> uses it; export it to apply the same
* rule to your own Google-dependent code.
*/
/**
* Whether the Google tag may load now. Pure, so the consent rule is testable
* without a DOM: 'basic' waits for an analytics or marketing grant, 'advanced'
* relies on the Consent Mode default and loads as soon as `ready`.
*/
export function shouldLoadGoogle({
consentMode,
ready,
state,
}: {
consentMode: 'advanced' | 'basic'
ready: boolean
state: { analytics?: boolean; marketing?: boolean }
}): boolean {
if (!ready) {return false}
return consentMode === 'advanced' || Boolean(state.analytics || state.marketing)
}
+9
View File
@@ -1,5 +1,7 @@
import type { CollectionConfig, Endpoint, PayloadRequest } from 'payload'
import type { CollectionOverride } from '../shared/collectionOverride.js'
import { userMeetsRole } from '../access/predicates.js'
import { createDailyPurge } from '../shared/purge.js'
import { clientIp, consumeRateLimit } from '../shared/rateLimit.js'
@@ -20,6 +22,13 @@ import { CONSENT_CATEGORIES } from './categories.js'
export const CONSENT_LOG_SLUG = 'consent-records'
export type ConsentLogOptions = {
/**
* Change the `consent-records` collection: an object merges over it
* (`access` / `admin` / `hooks` key by key, your keys win), a function gets it
* and returns the one to use. E.g. narrow who reads the records in a project
* without roles: `{ access: { read: ({ req }) => req.user?.email === '[email protected]' } }`.
*/
collectionOverrides?: CollectionOverride
/** Days a record is kept. Default 1095 (3 years). */
retentionDays?: number
}
+32
View File
@@ -0,0 +1,32 @@
import type { CollectionConfig } from 'payload'
/**
* A project's change to a collection the plugin adds (consent records, stats):
* - an object is merged over the plugin's: `access`, `admin` and `hooks` key by
* key (your access rules win, your hooks run after the plugin's), anything
* else (labels, fields, …) replaces the plugin's value;
* - a function gets the plugin's collection and returns the one to use — full
* control. Keep the slug: the plugin's endpoints and views write and read it.
*
* Same rules as `globalOverrides`.
*/
export type CollectionOverride = ((collection: CollectionConfig) => CollectionConfig) | Partial<CollectionConfig>
type Hooks = NonNullable<CollectionConfig['hooks']>
/** Applies one CollectionOverride to a plugin collection. */
export function applyCollectionOverride(collection: CollectionConfig, override: CollectionOverride | undefined): CollectionConfig {
if (!override) {return collection}
if (typeof override === 'function') {return override(collection)}
const hooks: Record<string, unknown[]> = { ...(collection.hooks as Record<string, unknown[]>) }
for (const [key, list] of Object.entries(override.hooks ?? {})) {
hooks[key] = [...(hooks[key] ?? []), ...((list as unknown[]) ?? [])]
}
return {
...collection,
...override,
access: { ...collection.access, ...override.access },
admin: { ...collection.admin, ...override.admin },
hooks: hooks as Hooks,
}
}
+4 -4
View File
@@ -5,8 +5,8 @@ import { Gutter } from '@payloadcms/ui'
import type { StatsVisit } from '../collection.js'
import { userMeetsRole } from '../../access/predicates.js'
import { VISITOR_ID_PATTERN } from '../parse.js'
import { canReadStats } from './canReadStats.js'
import { loadRecentVisitors, loadStats, loadVisitor } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
@@ -77,7 +77,7 @@ function VisitorHistory({ base, timeZone, visitorId, visits }: { base: string; t
* Admin view at /admin/stats (ipalKit({ stats: true })): visits per day for the
* last 30 days, top pages, entry pages, referrers, devices, and — for visitors
* who accepted analytics cookies — a per-visitor history (?visitor=<id>).
* Admins only.
* For users the stats-visits collection lets read (admins by default).
*/
export async function StatsView(props: Props) {
const { adminRoute = '/admin', initPageResult, searchParams, timeZone = 'Europe/Warsaw' } = props
@@ -88,8 +88,8 @@ export async function StatsView(props: Props) {
const visitorId = visitorParam && VISITOR_ID_PATTERN.test(visitorParam) ? visitorParam : undefined
let content: React.ReactNode
if (!userMeetsRole(req, 'admin')) {
content = <p>Statistics are available to administrators only.</p>
if (!(await canReadStats(req.payload, req))) {
content = <p>You do not have access to the statistics.</p>
} else if (visitorId) {
content = <VisitorHistory base={base} timeZone={timeZone} visitorId={visitorId} visits={await loadVisitor(req.payload, visitorId)} />
} else {
+4 -3
View File
@@ -1,6 +1,6 @@
import type { Payload, PayloadRequest } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { canReadStats } from './canReadStats.js'
import { loadStats } from './loadStats.js'
import { STATS_CSS, VisitsChart } from './VisitsChart.js'
@@ -15,11 +15,12 @@ type Props = {
/**
* Dashboard card (admin.components.beforeDashboard): visits per day for the
* last 30 days with a link to the full view. Admins only; renders nothing on
* last 30 days with a link to the full view. For users the stats-visits
* collection lets read (admins by default); renders nothing on
* any error (DB not ready, collection missing).
*/
export async function StatsWidget({ adminRoute = '/admin', payload, req, timeZone = 'Europe/Warsaw', user }: Props) {
if (!payload || !userMeetsRole({ payload, user: req?.user ?? user }, 'admin')) {return null}
if (!payload || !(await canReadStats(payload, req, user))) {return null}
let stats
try {
stats = await loadStats(payload, { timeZone })
+19
View File
@@ -0,0 +1,19 @@
import type { Payload, PayloadRequest } from 'payload'
import { STATS_SLUG } from '../collection.js'
/**
* Whether the user may see the stats view and dashboard chart: the
* `stats-visits` collection's own `access.read` decides, so
* `stats.collectionOverrides` narrows the panel too. A `Where` result counts
* as allowed (the view shows totals, not single records).
*/
export async function canReadStats(payload: Payload, req: Partial<PayloadRequest> | undefined, user?: unknown): Promise<boolean> {
const read = payload.collections[STATS_SLUG as never]?.config.access?.read
if (!read) {return false}
try {
return Boolean(await read({ req: { ...req, payload, user: (req?.user ?? user) as never } as PayloadRequest }))
} catch {
return false
}
}
+9
View File
@@ -1,5 +1,7 @@
import type { CollectionConfig } from 'payload'
import type { CollectionOverride } from '../shared/collectionOverride.js'
import { userMeetsRole } from '../access/predicates.js'
/**
@@ -15,6 +17,13 @@ import { userMeetsRole } from '../access/predicates.js'
export const STATS_SLUG = 'stats-visits'
export type StatsOptions = {
/**
* Change the `stats-visits` collection: an object merges over it
* (`access` / `admin` / `hooks` key by key, your keys win), a function gets it
* and returns the one to use. Its `access.read` also decides who sees the
* dashboard chart and the stats view.
*/
collectionOverrides?: CollectionOverride
/** Show the 30-day chart on the admin dashboard. Default true. */
dashboard?: boolean
/** Days a visit is kept. Default 90 (the dashboard shows 30). */
+7 -9
View File
@@ -21,6 +21,7 @@ import { buildSystemPagesFields } from './modules/pages/index.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildIndexNowHook } from './modules/seo/indexNow.js'
import { searchSettingsFields } from './modules/seo/searchSettings.js'
import { applyCollectionOverride } from './modules/shared/collectionOverride.js'
import { buildStatsCollection, buildStatsEndpoint } from './modules/stats/index.js'
/**
@@ -277,19 +278,16 @@ export const ipalKit = (options: IpalOptions): Plugin => {
: []),
]
// Top-level option first (works without `seo`), then the older seo.searchSettings.
const searchSettings = options.searchSettings ?? options.seo?.searchSettings
const pluginGlobals = [
buildSiteSettings({
additionalFields: options.siteSettingsFields,
...(options.pages ? { constructionFields: buildConstructionFields(options.pages.slug) } : {}),
...(options.forms?.emailLayout ? { emailFields: emailSettingsFields } : {}),
...(options.seo?.searchSettings === false
...(searchSettings === false
? {}
: {
searchFields:
typeof options.seo?.searchSettings === 'function'
? options.seo.searchSettings(searchSettingsFields)
: searchSettingsFields,
}),
: { searchFields: typeof searchSettings === 'function' ? searchSettings(searchSettingsFields) : searchSettingsFields }),
systemPageFields,
}),
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
@@ -309,7 +307,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// --- consent log: proof of consent (opt-in) ---
if (options.consentLog) {
const logOptions = options.consentLog === true ? {} : options.consentLog
config.collections = [...(config.collections ?? []), buildConsentLogCollection()]
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildConsentLogCollection(), logOptions.collectionOverrides)]
config.endpoints = [...(config.endpoints ?? []), buildConsentLogEndpoint(logOptions)]
}
@@ -318,7 +316,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
const statsOptions = options.stats === true ? {} : options.stats
const adminRoute = options.adminRoute ?? '/admin'
const viewProps = { adminRoute, ...(statsOptions.timeZone ? { timeZone: statsOptions.timeZone } : {}) }
config.collections = [...(config.collections ?? []), buildStatsCollection()]
config.collections = [...(config.collections ?? []), applyCollectionOverride(buildStatsCollection(), statsOptions.collectionOverrides)]
config.endpoints = [...(config.endpoints ?? []), buildStatsEndpoint(statsOptions)]
config.admin = {
...(config.admin ?? {}),
+11 -2
View File
@@ -14,6 +14,7 @@ export type TotpPluginFactory = (options: {
}) => Plugin
import type { GlobalOverrides } from './globals/overrides.js'
import type { AccessOption } from './modules/access/types.js'
import type { ConsentLogOptions } from './modules/consent/consentLog.js'
import type { ContentOption } from './modules/content/types.js'
import type { FormsOption } from './modules/forms/types.js'
import type { RevalidatePathFn } from './modules/hooks/buildRevalidateHook.js'
@@ -50,9 +51,9 @@ export type IpalOptions = {
* Consent log (proof of consent, GDPR Art. 7(1)): adds the `consent-records`
* collection and POST /api/ipal/consent. Pass `<ConsentProvider logEndpoint="/api/ipal/consent">`.
* Stores a random id, choices, policy version and time — no personal data.
* `true` or `{ retentionDays }` (default 1095). Default off.
* `true` or `{ retentionDays, collectionOverrides }` (default 1095 days). Default off.
*/
consentLog?: { retentionDays?: number } | boolean
consentLog?: boolean | ConsentLogOptions
/**
* Collections whose entries live under an archive page — blog posts, case
@@ -112,6 +113,14 @@ export type IpalOptions = {
*/
revalidatePath?: RevalidatePathFn
/**
* Site Settings → "Search & AI" tab (verification codes, AI crawler policy,
* llms.txt intro). On by default; `false` removes it; a function gets the
* plugin's fields and returns the tab's fields. Works without `seo`; wins
* over `seo.searchSettings`.
*/
searchSettings?: ((defaults: Field[]) => Field[]) | false
/**
* SEO — adds meta fields to chosen collections (via @payloadcms/plugin-seo)
* and enables locale-aware metadata helpers.