scripts/starter-gate.mjs (node_modules/@intecion/ipal-kit), dev/tsconfig.json (the 'ipal-kit' path alias), test/starter.test.ts (the lockfile must not contain 'ipal-kit'); two JSDoc import lines. Found by pnpm starter:gate. Co-Authored-By: Claude Fable 5.2 <[email protected]>
924 lines
41 KiB
TypeScript
924 lines
41 KiB
TypeScript
import type { BasePayload, SanitizedConfig } from 'payload'
|
||
|
||
import { getPayload } from 'payload'
|
||
import { cache } from 'react'
|
||
|
||
import type { AnalyticsConfig } from '../analytics/types.js'
|
||
import type { ConsentTexts } from '../consent/texts.js'
|
||
import type { ConstructionMode } from '../construction/types.js'
|
||
import type { PathVisibility } from '../construction/visibility.js'
|
||
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
|
||
import type { I18nConfig } from '../i18n/index.js'
|
||
import type { LightboxTexts } from '../lightbox/types.js'
|
||
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
|
||
import type { CreateMcpRouteArgs } from '../mcp/createMcpRoute.js'
|
||
import type { FormNotificationTexts } from '../notifications/types.js'
|
||
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapRouteOptions, SitemapStyleOptions } from '../seo/index.js'
|
||
|
||
import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js'
|
||
import { getConsentTexts } from '../consent/getConsentTexts.js'
|
||
import { isPathAllowed, isPathVisibleIn } from '../construction/logic.js'
|
||
import { pathOf } from '../construction/visibility.js'
|
||
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
|
||
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
|
||
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
|
||
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
|
||
import { archiveFieldName } from '../content/types.js'
|
||
import { createHealthRoute } from '../health/createHealthRoute.js'
|
||
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js'
|
||
import { createMcpRoute } from '../mcp/createMcpRoute.js'
|
||
import { getNotificationTexts } from '../notifications/getNotificationTexts.js'
|
||
import { buildOrganizationJsonLd, sameAsUrls } from '../seo/buildOrganizationJsonLd.js'
|
||
import { buildWebPageJsonLd } from '../seo/buildWebPageJsonLd.js'
|
||
import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
|
||
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
|
||
import { createIndexNowKeyRoute } from '../seo/indexNow.js'
|
||
import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
|
||
import { robotsOptionsFrom } from '../seo/searchSettings.js'
|
||
import { type ThemeConfig, themeConfigFrom } from '../theme/theme.js'
|
||
import { getTurnstileConfig } from '../turnstile/config.js'
|
||
|
||
type CreateContentHelpersArgs = {
|
||
/**
|
||
* Absolute site origin for sitemap/robots URLs. Falls back to
|
||
* NEXT_PUBLIC_SERVER_URL, then to a relative origin (which most crawlers
|
||
* reject, so set one in production).
|
||
*/
|
||
baseUrl?: string
|
||
/**
|
||
* The client's payload config promise (the default export of payload.config).
|
||
* Passed in because the plugin never imports the client's config directly.
|
||
*/
|
||
config: Promise<SanitizedConfig> | SanitizedConfig
|
||
/** Archive-backed collections, same value as the plugin option. */
|
||
content?: ContentOption
|
||
/**
|
||
* i18n config. Required only if you want the ready-made `sitemap` / `robots`
|
||
* handlers — they need the locale list to emit hreflang.
|
||
*/
|
||
i18n?: I18nConfig
|
||
/** Markdown route (`markdownRoute`): per-block overrides, frontmatter, layout field. */
|
||
markdown?: { frontmatter?: boolean; isPathVisible?: PathVisibility; layoutField?: string; overrides?: Record<string, (block: Record<string, unknown>) => string> }
|
||
/**
|
||
* Advertise each page's Markdown version from generatePageMetadata:
|
||
* `<link rel="alternate" type="text/markdown" href="/md/pl/o-nas">` (GEO —
|
||
* agents find the clean version without guessing). `true` uses the '/md'
|
||
* prefix, a string sets another one. Needs the matching Markdown route
|
||
* (content.md). Indexable pages only.
|
||
*/
|
||
markdownAlternate?: boolean | string
|
||
/** MCP route (`mcpRoute`): server name/version, rate limit, batch size. */
|
||
mcp?: Pick<CreateMcpRouteArgs, 'clientIp' | 'isPathVisible' | 'maxBatch' | 'rateLimit' | 'serverName' | 'serverVersion'>
|
||
/** Defaults for getPageJsonLd — each call can override them. */
|
||
pageJsonLd?: PageJsonLdOptions
|
||
/** Pages collection slug. Defaults to 'pages'. */
|
||
pagesSlug?: string
|
||
/** Collections checked for an old slug before a 404 (`resolvePageRedirect`). Default pages. */
|
||
redirectCollections?: { historyField?: string; slug: string; slugField?: string }[]
|
||
/**
|
||
* Options for the ready-made `robots` handler, e.g.
|
||
* `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or
|
||
* `{ adminRoute: false }` when the admin path is hidden (iapl adminRoute).
|
||
*/
|
||
robots?: RobotsOptions
|
||
/**
|
||
* Depth of the Site Settings read behind getSettings / getSiteShell. Default
|
||
* 1 (relations as documents, their relations as ids). Raise it only if your
|
||
* layout reads deeper — every request pays for it.
|
||
*/
|
||
settingsDepth?: number
|
||
/** SiteSettings global slug. Defaults to 'site-settings'. */
|
||
settingsSlug?: string
|
||
/**
|
||
* Site-wide JSON-LD for `getSiteShell` (layout). Default: WebSite + Organization
|
||
* from Site Settings (siteName, logo, sameAs) — skipped when the name or the
|
||
* origin is missing, never a fallback name. A function replaces it (e.g.
|
||
* LocalBusiness from the Company global); `false` = none.
|
||
*/
|
||
siteJsonLd?: ((ctx: { baseUrl: string; locale: string; settings: Record<string, unknown> }) => Promise<Record<string, unknown>[]> | Record<string, unknown>[]) | false
|
||
/**
|
||
* Last word on the sitemap: gets the plugin's entries (after the construction
|
||
* filter) and returns the list to publish — add URLs from your own routes,
|
||
* drop or reorder some, set priority. Used by `sitemap` and `sitemapRoute`.
|
||
*/
|
||
sitemapEntries?: (entries: SitemapEntry[]) => Promise<SitemapEntry[]> | SitemapEntry[]
|
||
/** Image URLs of a document for the sitemap (Google Images). Default: its SEO share image. */
|
||
sitemapImages?: (doc: Record<string, unknown>) => (null | string | undefined)[]
|
||
/**
|
||
* `sitemapRoute` behaviour: `maxUrls` (split into an index, default 10 000),
|
||
* `cacheControl` (string or false), `memoSeconds` (default 300, 0 = off).
|
||
*/
|
||
sitemapOptions?: Pick<SitemapRouteOptions, 'cacheControl' | 'maxUrls' | 'memoSeconds'>
|
||
/**
|
||
* Browser look of `sitemapRoute` (/sitemap.xml). Default: built-in style,
|
||
* header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML.
|
||
*/
|
||
sitemapStyle?: false | SitemapStyleOptions
|
||
/** Field with the AI summary (buildSummaryField) — llms.txt and MCP prefer it. */
|
||
summaryField?: string
|
||
/**
|
||
* While Site Settings → Under construction is on, the sitemap and llms.txt
|
||
* list only the pages still open. Default true; false lists everything.
|
||
*/
|
||
underConstructionSeo?: boolean
|
||
}
|
||
|
||
/** What an entry's own JSON-LD builder gets (PageJsonLdOptions.entries). */
|
||
export type EntryJsonLdContext = {
|
||
/** Archive page of the entry (title, slug). */
|
||
archive: Record<string, unknown>
|
||
/** Meta description (SEO tab or the site's description). */
|
||
description?: string
|
||
doc: Record<string, unknown>
|
||
/** Absolute share-image URL. */
|
||
image?: string
|
||
locale: string
|
||
siteName?: string
|
||
/** Absolute canonical URL of the entry. */
|
||
url: string
|
||
}
|
||
|
||
export type PageJsonLdOptions = {
|
||
/** BreadcrumbList (home › archive › page) from the real route. Default true. */
|
||
breadcrumbs?: boolean
|
||
/**
|
||
* The main node per content collection, instead of the article (`entryType`):
|
||
* `{ products: (ctx) => buildProductJsonLd({…}), categories: (ctx) => buildWebPageJsonLd({ type: 'CollectionPage', … }) }`.
|
||
* Return null to emit no main node. Breadcrumbs and FAQ still follow.
|
||
*/
|
||
entries?: Record<string, (ctx: EntryJsonLdContext) => null | Record<string, unknown>>
|
||
/** schema.org type of archive entries. Default 'BlogPosting'. */
|
||
entryType?: 'Article' | 'BlogPosting' | 'NewsArticle'
|
||
/**
|
||
* Q&A visible on this page (e.g. from its FAQ block) → FAQPage. The project
|
||
* knows its block shape, so it maps it: `(doc) => doc.layout…map(i => ({ question, answer }))`.
|
||
*/
|
||
faq?: (doc: Record<string, unknown>) => { answer: string; question: string }[]
|
||
/** schema.org type of ordinary pages, per document (e.g. 'ContactPage'). Default 'WebPage'. */
|
||
pageType?: (doc: Record<string, unknown>) => string | undefined
|
||
}
|
||
|
||
/**
|
||
* Bundles the per-request data helpers a frontend needs — the same cached
|
||
* wrappers every project was writing by hand (getPayload, settings, locale
|
||
* list, route resolution, archive entries).
|
||
*
|
||
* Everything is wrapped in React `cache()`, so within one request a value is
|
||
* fetched once no matter how many times it's asked for — which matters because
|
||
* Next runs generateMetadata and the page component separately, and both hit
|
||
* these. Crucially the Payload instance is cached *here*, once, so every helper
|
||
* shares it; that's why this is a factory and not loose functions importing a
|
||
* shared module.
|
||
*
|
||
* ```ts
|
||
* // src/lib/content.ts
|
||
* import { createContentHelpers } from '@intecion/ipal-kit'
|
||
* import config from '@/payload.config'
|
||
* import { contentConfig } from '@/content.config'
|
||
*
|
||
* export const { getCachedPayload, getSettings, getConfiguredLocales, resolveRoute, getEntries } =
|
||
* createContentHelpers({ config, content: contentConfig })
|
||
* ```
|
||
*
|
||
* `resolveRoute` and `getEntries` are separate on purpose: routing decides what
|
||
* a URL is, fetching gets the listing. Metadata generation needs the first and
|
||
* not the second, and a page component composes them in two obvious lines.
|
||
*/
|
||
export function createContentHelpers({
|
||
baseUrl,
|
||
config,
|
||
content,
|
||
i18n,
|
||
markdown: markdownOptions,
|
||
markdownAlternate,
|
||
mcp: mcpOptions,
|
||
pageJsonLd: pageJsonLdDefaults,
|
||
pagesSlug = 'pages',
|
||
redirectCollections,
|
||
robots: robotsOptions,
|
||
settingsDepth = 1,
|
||
settingsSlug = 'site-settings',
|
||
siteJsonLd,
|
||
sitemapEntries: transformSitemap,
|
||
sitemapImages,
|
||
sitemapOptions,
|
||
sitemapStyle,
|
||
summaryField,
|
||
underConstructionSeo = true,
|
||
}: CreateContentHelpersArgs) {
|
||
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
|
||
const getCachedPayload = cache(
|
||
async (): Promise<BasePayload> => getPayload({ config: await config }),
|
||
)
|
||
|
||
const getConfiguredLocales = cache(async (): Promise<string[]> => {
|
||
const c = await config
|
||
return c.localization ? c.localization.locales.map((l) => l.code) : []
|
||
})
|
||
|
||
/**
|
||
* SiteSettings for a locale — ONE query per locale per request, shared by the
|
||
* layout, generatePageMetadata, resolveRoute and anything else that asks.
|
||
*
|
||
* Depth 1: logos and assigned pages arrive as documents (slug, title), but
|
||
* not THEIR relations. Depth 2 pulled every assigned page's blocks and media
|
||
* (homepage, archives, system pages) into every request; resolveRoute
|
||
* re-fetches the one page it actually renders.
|
||
*/
|
||
const getSettings = cache(async (locale: string) => {
|
||
const payload = await getCachedPayload()
|
||
return payload.findGlobal({ slug: settingsSlug as never, depth: settingsDepth, locale: locale as never })
|
||
})
|
||
|
||
/** What does this URL point at? Routing only — no listing data. */
|
||
const resolveRoute = cache(
|
||
async (
|
||
locale: string,
|
||
segments: string[] | undefined,
|
||
page: number,
|
||
): Promise<null | ResolvedRoute> => {
|
||
const payload = await getCachedPayload()
|
||
const settings = (await getSettings(locale)) as Record<string, unknown>
|
||
return resolveRouteRaw({
|
||
content,
|
||
locale,
|
||
page,
|
||
pagesSlug,
|
||
payload,
|
||
segments,
|
||
settings,
|
||
settingsSlug,
|
||
})
|
||
},
|
||
)
|
||
|
||
/**
|
||
* generateMetadata for the catch-all page, sharing the request cache with
|
||
* the page component: the same settings read and the same resolveRoute call
|
||
* (React cache spans generateMetadata and the page within one request), so
|
||
* metadata costs no extra route/settings queries.
|
||
*
|
||
* export async function generateMetadata({ params }) {
|
||
* const { locale, slug } = await params
|
||
* return generatePageMetadata(locale, slug)
|
||
* }
|
||
*/
|
||
let pageMetadata: ReturnType<typeof createPageMetadata> | undefined
|
||
const generatePageMetadata = async (
|
||
locale: string,
|
||
segments: string[] | undefined,
|
||
page = 1,
|
||
): Promise<PageMetadata> => {
|
||
if (!i18n) {
|
||
throw new Error('[iapl] createContentHelpers: pass `i18n` to use generatePageMetadata.')
|
||
}
|
||
pageMetadata ??= createPageMetadata({
|
||
baseUrl: origin || undefined,
|
||
collection: pagesSlug,
|
||
config: i18n,
|
||
content,
|
||
loaders: {
|
||
getSettings: async (l) => (await getSettings(l)) as Record<string, unknown>,
|
||
resolveRoute,
|
||
},
|
||
settingsSlug,
|
||
})
|
||
const meta = await pageMetadata({ slug: segments, locale, page, payload: await getCachedPayload() })
|
||
const canonical = meta.alternates?.canonical
|
||
if (!markdownAlternate || !canonical || meta.robots?.index === false) {return meta}
|
||
const prefix = typeof markdownAlternate === 'string' ? markdownAlternate : MARKDOWN_PREFIX
|
||
const pathname = new URL(canonical, 'http://localhost').pathname
|
||
return {
|
||
...meta,
|
||
alternates: { ...meta.alternates, types: { ...meta.alternates?.types, 'text/markdown': markdownHref(pathname, prefix) } },
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Per-page structured data — WebPage (BlogPosting for archive entries) with
|
||
* language and dates, BreadcrumbList from the actual route, FAQPage when the
|
||
* project maps its FAQ block. Built from the same cached route and metadata
|
||
* as the page, so it can't disagree with canonical/title. Returns plain nodes
|
||
* — render them with <JsonLdGraph schemas={…}> next to the layout's
|
||
* WebSite/Organization, add your own, or drop any.
|
||
*
|
||
* // [[...slug]]/page.tsx
|
||
* <JsonLdGraph schemas={await getPageJsonLd(locale, slug)} />
|
||
*/
|
||
const getPageJsonLd = async (
|
||
locale: string,
|
||
segments: string[] | undefined,
|
||
options: PageJsonLdOptions = {},
|
||
): Promise<Record<string, unknown>[]> => {
|
||
const opts = { ...pageJsonLdDefaults, ...options }
|
||
const [meta, route, settings] = await Promise.all([
|
||
generatePageMetadata(locale, segments),
|
||
resolveRoute(locale, segments ?? [], 1),
|
||
getSettings(locale) as Promise<Record<string, unknown>>,
|
||
])
|
||
const url = meta.alternates?.canonical
|
||
if (!route || !url || meta.robots?.index === false) {return []}
|
||
|
||
const doc = route.doc
|
||
const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined)
|
||
const name = str(doc.title) ?? meta.title
|
||
const siteName = str(settings?.siteName)
|
||
const root = new URL(url)
|
||
const singleLocale = (i18n?.locales.length ?? 0) === 1
|
||
const homeUrl = `${root.origin}${singleLocale ? '' : `/${locale}`}`
|
||
const image = meta.openGraph?.images?.[0]?.url
|
||
const nodes: (null | Record<string, unknown>)[] = []
|
||
|
||
const entryNode = route.type === 'entry' ? opts.entries?.[route.collection] : undefined
|
||
if (route.type === 'entry' && entryNode) {
|
||
nodes.push(entryNode({ archive: route.archive, description: meta.description, doc, image, locale, siteName, url }))
|
||
} else if (route.type === 'entry') {
|
||
nodes.push(
|
||
buildArticleJsonLd({
|
||
type: opts.entryType ?? 'BlogPosting',
|
||
dateModified: str(doc.updatedAt),
|
||
datePublished: str(doc.publishedAt) ?? str(doc.createdAt),
|
||
description: meta.description,
|
||
headline: name,
|
||
image: image ? { url: image } : undefined,
|
||
publisherName: siteName,
|
||
url,
|
||
}),
|
||
)
|
||
} else {
|
||
nodes.push(
|
||
buildWebPageJsonLd({
|
||
name,
|
||
type: route.type === 'archive' ? 'CollectionPage' : (opts.pageType?.(doc) ?? 'WebPage'),
|
||
dateModified: str(doc.updatedAt),
|
||
description: meta.description,
|
||
image,
|
||
inLanguage: locale,
|
||
url,
|
||
websiteUrl: homeUrl,
|
||
}),
|
||
)
|
||
}
|
||
|
||
if (opts.breadcrumbs !== false && route.type !== 'home') {
|
||
const homepage = settings?.homepage as Record<string, unknown> | undefined
|
||
const crumbs = [{ name: str(homepage?.title) ?? siteName ?? root.host, url: homeUrl }]
|
||
if (route.type === 'entry') {
|
||
const archiveName = str(route.archive.title)
|
||
if (archiveName) {crumbs.push({ name: archiveName, url: url.replace(/\/[^/]+$/, '') })}
|
||
}
|
||
crumbs.push({ name, url })
|
||
nodes.push(buildBreadcrumbJsonLd(crumbs))
|
||
}
|
||
|
||
const faq = opts.faq?.(doc)?.filter((i) => i.question?.trim() && i.answer?.trim())
|
||
if (faq?.length) {nodes.push(buildFaqJsonLd(faq))}
|
||
|
||
// JsonLdGraph adds the @context once for the whole @graph.
|
||
return nodes
|
||
.filter((n): n is Record<string, unknown> => Boolean(n))
|
||
.map(({ '@context': _context, ...node }) => node)
|
||
}
|
||
|
||
/** ID of the page assigned as 404 — the relation isn't localized, so one read serves every locale. */
|
||
const getNotFoundPageId = cache(async (): Promise<null | number | string> => {
|
||
const payload = await getCachedPayload()
|
||
const settings = (await payload.findGlobal({
|
||
slug: settingsSlug as never,
|
||
depth: 0,
|
||
})) as { notFound?: unknown }
|
||
const rel = settings.notFound
|
||
if (typeof rel === 'string' || typeof rel === 'number') {return rel}
|
||
if (rel && typeof rel === 'object') {
|
||
const id = (rel as { id?: unknown }).id
|
||
if (typeof id === 'string' || typeof id === 'number') {return id}
|
||
}
|
||
return null
|
||
})
|
||
|
||
/**
|
||
* The page assigned as 404 in System Pages (or null → built-in fallback).
|
||
* For app/not-found.tsx; never throws. not-found.tsx receives no params and
|
||
* must NOT read headers() (breaks SSG/ISR) — call this for every configured
|
||
* locale and let <LocaleView> (client) pick the one from the URL. See pages.md.
|
||
*/
|
||
const getNotFoundPage = cache(async (locale: string) => {
|
||
try {
|
||
const id = await getNotFoundPageId()
|
||
if (id === null) {return null}
|
||
const payload = await getCachedPayload()
|
||
const doc = await payload.findByID({
|
||
id,
|
||
collection: pagesSlug as never,
|
||
depth: 2,
|
||
locale: locale as never,
|
||
})
|
||
return (doc as null | Record<string, unknown>) ?? null
|
||
} catch {
|
||
return null // DB unreachable (container build) or page deleted — fallback view
|
||
}
|
||
})
|
||
|
||
/** One page of a collection's entries, for an archive listing. */
|
||
const getEntries = cache(
|
||
async (
|
||
collection: string,
|
||
locale: string,
|
||
page: number,
|
||
perPage: number,
|
||
): Promise<ArchiveEntries> => {
|
||
const payload = await getCachedPayload()
|
||
return getArchiveEntries({ collection, locale, page, payload, perPage })
|
||
},
|
||
)
|
||
|
||
/**
|
||
* Ready-made handler for Next's `app/sitemap.ts` — every page and entry with
|
||
* per-URL hreflang and lastmod. Re-export it directly:
|
||
*
|
||
* ```ts
|
||
* // app/sitemap.ts
|
||
* export { sitemap as default } from '@/lib/content'
|
||
* export const dynamic = 'force-dynamic' // generate at runtime, not build
|
||
* ```
|
||
*
|
||
* IMPORTANT — container deploys (Coolify/Docker/Railway/CI): Next treats
|
||
* sitemap.ts as STATIC by default and prerenders it during `next build`, which
|
||
* calls into Payload → the database. The build container usually has no access
|
||
* to the internal Docker network, so the DB connection fails (ENOTFOUND) and
|
||
* the build dies. Two defenses:
|
||
* 1. `export const dynamic = 'force-dynamic'` in app/sitemap.ts — skips build
|
||
* prerender, generates at runtime when the DB is reachable (recommended).
|
||
* 2. This handler also catches DB errors and returns [] so that even without
|
||
* (1) the build won't crash — it just ships an empty sitemap until the
|
||
* next runtime regeneration. (1) is still preferred; (2) is a safety net.
|
||
*/
|
||
const sitemap = cache(async (): Promise<SitemapEntry[]> => {
|
||
if (!i18n) {
|
||
throw new Error(
|
||
'[iapl] createContentHelpers: pass `i18n` to use the sitemap handler.',
|
||
)
|
||
}
|
||
try {
|
||
const entries = await buildSitemapEntries({
|
||
baseUrl: origin,
|
||
config: i18n,
|
||
content,
|
||
images: sitemapImages,
|
||
pagesSlug,
|
||
payload: await getCachedPayload(),
|
||
settingsSlug,
|
||
})
|
||
// Under construction: list only the pages visitors can still open — the
|
||
// rest redirect to the homepage notice, which crawlers would index.
|
||
// Same check as isPathVisibleIn(mode, pathOf(url)) (security-perf branch), with the
|
||
// mode read once for the whole list.
|
||
const open = await constructionPaths()
|
||
const visible = open ? entries.filter((e) => isPathAllowed(pathOf(e.url), open)) : entries
|
||
return transformSitemap ? await transformSitemap(visible) : visible
|
||
} catch (error) {
|
||
// At runtime a failure is an error (the sitemap route answers 503, so
|
||
// crawlers retry) — an empty sitemap would read as "no pages".
|
||
if (process.env.NEXT_PHASE !== 'phase-production-build') {throw error}
|
||
// DB unreachable during `next build` (container with no DB network) —
|
||
// return an empty sitemap instead of failing the build. Runtime regeneration
|
||
// produces the real one. See dynamic='force-dynamic'.
|
||
console.warn(
|
||
'[iapl] sitemap: could not reach the database, returning empty entries ' +
|
||
"(add `export const dynamic = 'force-dynamic'` to app/sitemap.ts to " +
|
||
'generate at runtime and avoid build-time DB access):',
|
||
error,
|
||
)
|
||
return []
|
||
}
|
||
})
|
||
|
||
/**
|
||
* Ready-made handler for Next's `app/robots.ts`. Re-export directly:
|
||
*
|
||
* ```ts
|
||
* // app/robots.ts
|
||
* export { robots as default } from '@/lib/content'
|
||
* ```
|
||
*/
|
||
const robots = (): RobotsRules => buildRobots({ ...robotsOptions, baseUrl: origin })
|
||
|
||
/**
|
||
* `robots` plus what editors set in Site Settings → Search engines (AI bot policy
|
||
* and per-bot exceptions), read per request. Use it instead of `robots` to
|
||
* let the panel manage AI crawlers:
|
||
*
|
||
* ```ts
|
||
* // app/robots.ts
|
||
* export { getRobots as default } from '@/lib/content'
|
||
* export const dynamic = 'force-dynamic'
|
||
* ```
|
||
*
|
||
* Database unreachable → the options from code, as `robots` returns.
|
||
*/
|
||
const getRobots = async (): Promise<RobotsRules> => {
|
||
let fromPanel: ReturnType<typeof robotsOptionsFrom> = {}
|
||
try {
|
||
const payload = await getCachedPayload()
|
||
fromPanel = robotsOptionsFrom(
|
||
(await payload.findGlobal({ slug: settingsSlug as never, depth: 0 })) as Record<string, unknown>,
|
||
)
|
||
} catch {
|
||
// keep the code options
|
||
}
|
||
return buildRobots({
|
||
...robotsOptions,
|
||
...fromPanel,
|
||
aiBotRules: [...(robotsOptions?.aiBotRules ?? []), ...(fromPanel.aiBotRules ?? [])],
|
||
baseUrl: origin,
|
||
})
|
||
}
|
||
|
||
/**
|
||
* Next.js generateStaticParams for the [[...slug]] route (or
|
||
* [locale]/[[...slug]]). Returns every routable page as a params object, so
|
||
* Next PRE-RENDERS them as static (SSG) instead of dynamic.
|
||
*
|
||
* Why this matters beyond convenience: an optional catch-all with no
|
||
* generateStaticParams is treated as a DYNAMIC route (ƒ), which streams
|
||
* metadata into <body> (crawlers miss it). Providing generateStaticParams
|
||
* compiles routes as SSG (●) — the <head> is synchronous and complete. This is
|
||
* the strongest fix for the metadata-in-head problem (stronger than ISR alone).
|
||
*
|
||
* Handles automatically:
|
||
* - the pages collection only (content-collection entries render on first request)
|
||
* - the homepage as the root ({ slug: [] })
|
||
* - excludes drafts and 404/500/system slugs
|
||
* - KEEPS noindex pages (they must still render — noindex controls indexing,
|
||
* not existence; skipping them would force dynamic rendering)
|
||
* - localized slugs (string or per-locale map) both handled
|
||
* - single-locale → { slug }[]; multi-locale → { locale, slug }[]
|
||
*
|
||
* Wire it in the project:
|
||
* // app/(frontend)/[[...slug]]/page.tsx (or [locale]/[[...slug]])
|
||
* export { generateStaticParams } from '@/lib/content'
|
||
*/
|
||
const generateStaticParams = async (): Promise<
|
||
Array<{ locale: string; slug: string[] } | { slug: string[] }>
|
||
> => {
|
||
try {
|
||
const payload = await getCachedPayload()
|
||
const locales = i18n ? i18n.locales.map((l) => l.code) : [undefined]
|
||
const singleLocale = !i18n || i18n.locales.length === 1
|
||
|
||
// 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 }
|
||
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[] }> = []
|
||
|
||
for (const locale of locales) {
|
||
// NO where:{_status} filter — collections without drafts enabled don't
|
||
// register the _status field, and querying it throws
|
||
// "path cannot be queried: _status". We filter drafts in memory below,
|
||
// which is safe for every collection (with or without drafts).
|
||
const result = await payload.find({
|
||
collection: pagesSlug as never,
|
||
depth: 0,
|
||
limit: 1000,
|
||
locale: (locale ?? 'all') as never,
|
||
})
|
||
|
||
for (const raw of result.docs as Array<{
|
||
_status?: string
|
||
id: number | string
|
||
meta?: { noindex?: boolean } | null
|
||
slug?: unknown
|
||
}>) {
|
||
// 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
|
||
// from the footer and crawlers read its <meta robots=noindex>. Pre-render
|
||
// it as SSG so it's fast and its <head> is complete; noindex controls
|
||
// INDEXING, not whether the page exists. Skipping it would force dynamic
|
||
// rendering (the very streaming problem we're avoiding).
|
||
|
||
if (homeId && raw.id === homeId) {
|
||
// Homepage → root. Emit an empty-slug param so '/' (or '/pl') builds.
|
||
const empty = singleLocale ? { slug: [] } : { slug: [], locale: locale as string }
|
||
if (!params.some((p) => JSON.stringify(p) === JSON.stringify(empty))) {params.push(empty)}
|
||
continue
|
||
}
|
||
|
||
// Slug may be a plain string OR a localized map ({ pl: 'kontakt' }) when
|
||
// read with locale:'all' or left unflattened. Handle both, or localized
|
||
// pages get silently dropped.
|
||
const rawSlug = raw.slug
|
||
const slug =
|
||
typeof rawSlug === 'string'
|
||
? rawSlug
|
||
: rawSlug && typeof rawSlug === 'object'
|
||
? ((rawSlug as Record<string, unknown>)[locale ?? ''] as string | undefined) ??
|
||
(Object.values(rawSlug as Record<string, unknown>)[0] as string | undefined)
|
||
: undefined
|
||
|
||
if (!slug || EXCLUDED.has(slug)) {continue}
|
||
|
||
// Multi-level slugs ('atrakcje/telefon') → array segments.
|
||
const segments = String(slug).split('/').filter(Boolean)
|
||
params.push(singleLocale ? { slug: segments } : { slug: segments, locale: locale as string })
|
||
}
|
||
}
|
||
|
||
return params
|
||
} catch (err) {
|
||
// DB unreachable — typically a container build (Docker/Coolify/CI) with no
|
||
// database network. Return [] so the build doesn't crash: Next falls back
|
||
// to on-demand rendering for the routes, which fill in once the DB is
|
||
// reachable at runtime. Without this every project would need its own
|
||
// try/catch here. (Same graceful-degradation as the sitemap handler.)
|
||
console.warn(
|
||
'[iapl] generateStaticParams: database not reachable during build ' +
|
||
'(Docker/CI) — returning empty params; routes render on-demand at runtime:',
|
||
err,
|
||
)
|
||
return []
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Route handler for app/sitemap.xml/route.ts — XML for crawlers, styled for
|
||
* people (`?style` serves the CSS from the plugin; nothing in /public):
|
||
*
|
||
* export { sitemapRoute as GET } from '@/lib/content'
|
||
* export const dynamic = 'force-dynamic'
|
||
*/
|
||
const sitemapRoute = createSitemapRouteHandler(sitemap, { ...sitemapOptions, style: sitemapStyle ?? {} })
|
||
|
||
const needI18n = (what: string): I18nConfig => {
|
||
if (!i18n) {throw new Error(`[iapl] createContentHelpers: pass \`i18n\` to use ${what}.`)}
|
||
return i18n
|
||
}
|
||
|
||
// ── Links & navigation ────────────────────────────────────────────────────
|
||
/** Homepage slug in this locale (SiteSettings.homepage) — links to it collapse to /{locale}. */
|
||
const getHomeSlug = async (locale: string) => homeSlugFrom(await getSettings(locale))
|
||
|
||
/** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */
|
||
const getLinkOptions = async (locale: string): Promise<ResolveLinkHrefOptions> => {
|
||
const settings = await getSettings(locale)
|
||
const homeSlug = homeSlugFrom(settings)
|
||
// Archive page per content collection → links to entries (categories, products…) resolve too.
|
||
const archives = Object.fromEntries(
|
||
(content?.collections ?? []).flatMap(({ slug }) => {
|
||
const archive = (settings as Record<string, unknown>)[archiveFieldName(slug)]
|
||
const archiveSlug = archive && typeof archive === 'object' ? (archive as { slug?: unknown }).slug : undefined
|
||
return typeof archiveSlug === 'string' && archiveSlug ? [[slug, archiveSlug]] : []
|
||
}),
|
||
)
|
||
return {
|
||
config: needI18n('getLinkOptions'),
|
||
locale,
|
||
pagesSlug,
|
||
...(homeSlug ? { homeSlug } : {}),
|
||
...(Object.keys(archives).length ? { archives } : {}),
|
||
}
|
||
}
|
||
|
||
/**
|
||
* A panel link → `{ href, label, internal, newTab, targetProps, appearance }`
|
||
* or null. The project's CMSLink only picks the element and the classes.
|
||
*/
|
||
const resolveLink = async (link: LinkValue | null | undefined, locale: string): Promise<null | ResolvedLink> =>
|
||
resolveLinkRaw(link, await getLinkOptions(locale))
|
||
|
||
/** Menu items of a Header/Footer global → serializable NavItem[] (pass to a client MobileNav as is). */
|
||
const resolveNav = async (items: unknown, locale: string, options: { childrenField?: string; linkField?: string } = {}): Promise<NavItem[]> =>
|
||
resolveNavRaw(items, { ...(await getLinkOptions(locale)), ...options })
|
||
|
||
/**
|
||
* Legal links for the footer from Site Settings → System Pages — href and label
|
||
* (the page title) in this locale. Default roles: privacy policy, cookie policy, terms.
|
||
*/
|
||
const getSystemLinks = async (locale: string, roles?: readonly string[]): Promise<SystemLink[]> =>
|
||
resolveSystemLinks(await getSettings(locale), { ...(await getLinkOptions(locale)), ...(roles ? { roles } : {}) })
|
||
|
||
/** Old slug → its new URL (308), for the catch-all page before notFound(). */
|
||
const resolvePageRedirect = async (locale: string, segments: string[] | undefined): Promise<null | string> =>
|
||
resolveRedirectRaw({
|
||
collections: redirectCollections,
|
||
config: needI18n('resolvePageRedirect'),
|
||
homeSlug: await getHomeSlug(locale),
|
||
locale,
|
||
payload: await getCachedPayload(),
|
||
segments,
|
||
})
|
||
|
||
/**
|
||
* Site Settings → Under construction, for this locale: whether it's on, the
|
||
* paths still reachable (homepage + chosen pages, in every language), the
|
||
* homepage to redirect to and the notice texts. createPageRoute (with
|
||
* `redirect`) and <ConstructionNotice> (/client) use it.
|
||
*/
|
||
const getConstructionMode = cache(async (locale: string): Promise<ConstructionMode> => {
|
||
const settings = (await getSettings(locale)) as null | Record<string, unknown>
|
||
const options = await getLinkOptions(locale)
|
||
const rootOf = (code: string) => (options.config.locales.length > 1 ? `/${code}` : '/')
|
||
const homePath = resolveLinkRaw({ type: 'internal', page: settings?.homepage }, options)?.href ?? rootOf(locale)
|
||
const construction = (settings?.construction ?? {}) as { buttonLabel?: unknown; enabled?: unknown; message?: unknown; title?: unknown }
|
||
if (construction.enabled !== true) {return { allowedPaths: [], enabled: false, homePath, locale, texts: {} }}
|
||
|
||
const configured = await getConfiguredLocales()
|
||
const paths = await Promise.all(
|
||
(configured.length ? configured : [locale]).map(async (code) => {
|
||
const localized = (await getSettings(code)) as null | Record<string, unknown>
|
||
const linkOptions = await getLinkOptions(code)
|
||
const allowed = (localized?.construction as { allowedPages?: unknown } | undefined)?.allowedPages
|
||
const pages = [localized?.homepage, ...(Array.isArray(allowed) ? allowed : [])]
|
||
return [rootOf(code), ...pages.map((page) => resolveLinkRaw({ type: 'internal', page }, linkOptions)?.href)]
|
||
}),
|
||
)
|
||
const text = (value: unknown) => (typeof value === 'string' && value.trim() ? value.trim() : undefined)
|
||
const texts = { button: text(construction.buttonLabel), message: text(construction.message), title: text(construction.title) }
|
||
return {
|
||
allowedPaths: [...new Set(paths.flat().filter((path): path is string => typeof path === 'string'))],
|
||
enabled: true,
|
||
homePath,
|
||
locale,
|
||
texts: Object.fromEntries(Object.entries(texts).filter(([, value]) => value)),
|
||
}
|
||
})
|
||
|
||
/**
|
||
* Is this page path public right now? False for pages construction mode
|
||
* hides. The Markdown and MCP routes use it; pass it to createSearchRoute.
|
||
*
|
||
* Lists call it once per result (Promise.all). React `cache` doesn't dedupe
|
||
* in route handlers, so concurrent calls share ONE in-flight mode read per
|
||
* locale — a list of 200 pages costs one Site Settings read, not 200. The
|
||
* entry is dropped once it settles, so the next request reads fresh.
|
||
*/
|
||
const inflightMode = new Map<string, Promise<ConstructionMode>>()
|
||
const isPathVisible: PathVisibility = async (path, locale) => {
|
||
let mode = inflightMode.get(locale)
|
||
if (!mode) {
|
||
mode = getConstructionMode(locale).finally(() => inflightMode.delete(locale))
|
||
inflightMode.set(locale, mode)
|
||
}
|
||
return isPathVisibleIn(await mode, path)
|
||
}
|
||
|
||
/**
|
||
* While Site Settings → Under construction is on: the paths still open (every
|
||
* language), which the sitemap and llms.txt list instead of everything.
|
||
* null when the site is open or the setting can't be read. Same rule as
|
||
* `isPathVisible`, but resolved ONCE per list: the sitemap may hold tens of
|
||
* thousands of URLs, and in a route handler React `cache` doesn't dedupe a
|
||
* per-URL settings read.
|
||
*/
|
||
const constructionPaths = async (): Promise<null | string[]> => {
|
||
if (!i18n || !underConstructionSeo) {return null}
|
||
try {
|
||
const mode = await getConstructionMode(i18n.defaultLocale)
|
||
return mode.enabled ? mode.allowedPaths : null
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
|
||
// ── Layout ────────────────────────────────────────────────────────────────
|
||
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
|
||
const getNotifications = cache(async (locale: string) => getNotificationTexts({ locale, payload: await getCachedPayload() }))
|
||
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> => (await getNotifications(locale)).form)
|
||
|
||
/**
|
||
* Everything the [locale] layout reads, in one cached call: consent texts,
|
||
* analytics IDs, Turnstile site key, site JSON-LD, form and lightbox texts and Site
|
||
* Settings. Feed it to <SiteProviders> (/rsc) — or use the pieces yourself.
|
||
*/
|
||
const getSiteShell = cache(async (locale: string): Promise<SiteShell> => {
|
||
const payload = await getCachedPayload()
|
||
const [consent, analytics, turnstile, settings, notifications] = await Promise.all([
|
||
getConsentTexts({ config: needI18n('getSiteShell'), locale, payload, settingsSlug }),
|
||
getAnalyticsConfig(payload),
|
||
getTurnstileConfig(payload),
|
||
getSettings(locale) as Promise<Record<string, unknown>>,
|
||
getNotifications(locale),
|
||
])
|
||
let jsonLd: Record<string, unknown>[] = []
|
||
if (typeof siteJsonLd === 'function') {
|
||
jsonLd = await siteJsonLd({ baseUrl: origin, locale, settings: settings ?? {} })
|
||
} else if (siteJsonLd !== false) {
|
||
const name = typeof settings?.siteName === 'string' && settings.siteName.trim() ? settings.siteName.trim() : undefined
|
||
if (name && origin) {
|
||
jsonLd = [
|
||
buildWebSiteJsonLd({ name, url: origin }),
|
||
buildOrganizationJsonLd({ name, logo: settings.logo as never, sameAs: sameAsUrls(settings), url: origin }),
|
||
]
|
||
}
|
||
}
|
||
return {
|
||
analytics,
|
||
consent,
|
||
formTexts: notifications.form,
|
||
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
|
||
lightboxTexts: notifications.lightbox,
|
||
settings: settings ?? {},
|
||
theme: themeConfigFrom(settings, (payload.config.custom as { ipal?: { themeStorageKey?: string } } | undefined)?.ipal?.themeStorageKey),
|
||
turnstileSiteKey: turnstile.siteKey,
|
||
}
|
||
})
|
||
|
||
// ── Ready route handlers (one line per route file) ────────────────────────
|
||
// Created on first request, so a project that doesn't use one pays nothing
|
||
// and a missing option only fails the route that needs it.
|
||
const lazy = <T>(make: () => T) => {
|
||
let value: T | undefined
|
||
return () => (value ??= make())
|
||
}
|
||
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
|
||
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, getIncludedPaths: constructionPaths, pagesSlug, settingsSlug, summaryField }))
|
||
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, isPathVisible, settingsSlug, ...markdownOptions }))
|
||
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, isPathVisible, settingsSlug, summaryField, ...mcpOptions }))
|
||
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
|
||
const indexNowKey = lazy(() => createIndexNowKeyRoute({ getCachedPayload }))
|
||
const manifestHandler = lazy(() => createManifestHandler({ config: needI18n('manifest'), getCachedPayload, settingsSlug }))
|
||
|
||
/** app/llms.txt/route.ts: `export { llmsRoute as GET } from '@/lib/content'` */
|
||
const llmsRoute = () => llms()()
|
||
/** app/llms-full.txt/route.ts: `export { llmsFullRoute as GET } from '@/lib/content'` */
|
||
const llmsFullRoute = () => llmsFull()()
|
||
/** app/md/[locale]/[[...slug]]/route.ts (single language: app/md/[[...slug]]/route.ts): `export { markdownRoute as GET } from '@/lib/content'` */
|
||
const markdownRoute = (req: Request, ctx: { params: Promise<{ locale?: string; slug?: string[] }> }) => md().GET(req, ctx)
|
||
/** app/api/mcp/route.ts: `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` */
|
||
const mcpGET = () => mcp().GET()
|
||
const mcpPOST = (req: Request) => mcp().POST(req)
|
||
/** app/api/health/route.ts: `export { healthRoute as GET } from '@/lib/content'` */
|
||
const healthRoute = () => health()()
|
||
/** app/indexnow-key.txt/route.ts: `export { indexNowKeyRoute as GET } from '@/lib/content'` */
|
||
const indexNowKeyRoute = () => indexNowKey()()
|
||
/** app/manifest.ts: `export { manifest as default } from '@/lib/content'` */
|
||
const manifest = () => manifestHandler()()
|
||
|
||
return {
|
||
generatePageMetadata,
|
||
generateStaticParams,
|
||
getCachedPayload,
|
||
getConfiguredLocales,
|
||
getConstructionMode,
|
||
getEntries,
|
||
getFormTexts,
|
||
getHomeSlug,
|
||
getLinkOptions,
|
||
getNotFoundPage,
|
||
getPageJsonLd,
|
||
getRobots,
|
||
getSettings,
|
||
getSiteShell,
|
||
getSystemLinks,
|
||
healthRoute,
|
||
i18n,
|
||
indexNowKeyRoute,
|
||
isPathVisible,
|
||
llmsFullRoute,
|
||
llmsRoute,
|
||
manifest,
|
||
markdownRoute,
|
||
mcpGET,
|
||
mcpPOST,
|
||
resolveLink,
|
||
resolveNav,
|
||
resolvePageRedirect,
|
||
resolveRoute,
|
||
robots,
|
||
sitemap,
|
||
sitemapRoute,
|
||
}
|
||
}
|
||
|
||
/** What the layout needs — getSiteShell(locale). Plain data, safe to pass to client components. */
|
||
export type SiteShell = {
|
||
analytics: AnalyticsConfig
|
||
consent: ConsentTexts
|
||
formTexts: FormNotificationTexts
|
||
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
|
||
jsonLd: Record<string, unknown>[]
|
||
/** Notifications → Lightbox (English fallbacks without iapl `lightbox`) — <SiteProviders lightbox> reads it. */
|
||
lightboxTexts?: LightboxTexts
|
||
settings: Record<string, unknown>
|
||
/** Site Settings → Theme, for <ThemeScript> / <SiteProviders theme> and <ThemeSwitcher label>. */
|
||
theme: ThemeConfig
|
||
turnstileSiteKey: null | string
|
||
}
|
||
|
||
export type ContentHelpers = ReturnType<typeof createContentHelpers>
|