import type { Config, Payload } from 'payload' import type { AdminText } from '../admin-i18n/index.js' /** * Admin panel for link previews and search engines: what Slack, * Messenger and similar show for a pasted /admin link, and noindex for robots. * * Payload builds every admin page's metadata from `config.admin.meta` on each * request, so the plugin * - sets static defaults at config time (robots, preview image and icon * pointing at the plugin's own endpoints), and * - fills the site-dependent parts (title suffix, description, siteName) * from SiteSettings on start and after every Site settings save. * Next may load the config more than once per process (dev recompiles, route * bundles), so the site name lives in a process-wide store and the meta reads * it through getters: `openGraph` keeps its object reference through Payload's * sanitize, so its getters run on every request; the top-level `titleSuffix` * and `description` are read when a config is loaded, and the live config is * updated in place as well. * A key the project set in its own `admin.meta` is never touched. */ /** Who supports the technology: named in the credit, the description and the preview image. */ export type AgencyOption = { name: string; url: string } export const DEFAULT_AGENCY: AgencyOption = { name: 'Intecion.com', url: 'https://intecion.com' } export type AdminMetaOptions = { /** Description for link previews; `{site}` and `{agency}` are replaced. `false` = Payload's own. */ description?: AdminText | false | string /** Favicon of the panel from SiteSettings (`/api/ipal/admin-icon`). `false` = Payload's own. */ icons?: boolean /** Preview image: generated from the site's logo (`/api/ipal/admin-og`), your own URL, or `false` = Payload's own. */ image?: false | string /** Language of the description and suffix. Default: the site's default locale when it is `pl`, else `en`. */ language?: 'en' | 'pl' /** Robots meta. Default noindex, nofollow. `false` = none. */ robots?: { follow?: boolean; index?: boolean } | false /** Browser-tab suffix; `{site}` is replaced. Default "— {site} | Panel". `false` = none. */ titleSuffix?: false | string } export const ADMIN_META_TEXTS = { en: { description: 'Administration panel of {site}. Built on Payload CMS, technology support: {agency}.', descriptionNoAgency: 'Administration panel of {site}. Built on Payload CMS.', imageLine: 'Technology support: {agency}', imageTitle: 'Administration panel', titleSuffix: '— {site} | Panel', titleSuffixNoSite: '| Panel', }, pl: { description: 'Panel administracyjny witryny {site}. Zbudowany na Payload CMS, wsparcie technologiczne: {agency}.', descriptionNoAgency: 'Panel administracyjny witryny {site}. Zbudowany na Payload CMS.', imageLine: 'Wsparcie technologiczne: {agency}', imageTitle: 'Panel administracyjny', titleSuffix: '— {site} | Panel', titleSuffixNoSite: '| Panel', }, } type Store = { site?: string } const STORE_KEY = Symbol.for('ipal.adminMeta') /** Process-wide: the site name the meta getters read. */ export const adminMetaStore = (): Store => { const g = globalThis as unknown as Record return (g[STORE_KEY] ??= {}) } export const ADMIN_OG_PATH = '/ipal/admin-og' export const ADMIN_ICON_PATH = '/ipal/admin-icon' type Meta = NonNullable['meta']> const fill = (template: string, site: string, agency: AgencyOption | false) => template.replaceAll('{site}', site).replaceAll('{agency}', agency ? agency.name : '').trim() export type ResolvedAdminMeta = { agency: AgencyOption | false language: 'en' | 'pl' options: AdminMetaOptions /** Keys the project set itself in admin.meta — never overwritten. */ own: { description: boolean; icons: boolean; images: boolean; robots: boolean; siteName: boolean; titleSuffix: boolean } } /** Static defaults at config time. Returns the new meta and what the runtime sync may fill. */ export function buildAdminMeta({ agency, apiRoute = '/api', defaultLocale, meta = {}, options = {}, }: { agency: AgencyOption | false apiRoute?: string defaultLocale?: string meta?: Meta options?: AdminMetaOptions }): { meta: Meta; resolved: ResolvedAdminMeta } { const og = (meta.openGraph ?? {}) as Record const own = { description: meta.description !== undefined || og.description !== undefined, icons: meta.icons !== undefined, images: og.images !== undefined, robots: meta.robots !== undefined, siteName: og.siteName !== undefined, titleSuffix: meta.titleSuffix !== undefined, } const language = options.language ?? (defaultLocale?.toLowerCase().startsWith('pl') ? 'pl' : 'en') const api = apiRoute.replace(/\/$/, '') const next: Meta = { ...meta } const openGraph: Record = { ...og } const resolved: ResolvedAdminMeta = { agency, language, options, own } const current = () => { const site = adminMetaStore().site return site ? adminMetaForSite(site, resolved) : null } const getter = (target: object, key: string, read: () => unknown) => Object.defineProperty(target, key, { configurable: true, enumerable: true, get: read }) if (!own.titleSuffix && options.titleSuffix !== false) { getter(next, 'titleSuffix', () => current()?.titleSuffix ?? ADMIN_META_TEXTS[language].titleSuffixNoSite) } if (!own.description && options.description !== false) { getter(next, 'description', () => current()?.description) getter(openGraph, 'description', () => current()?.description) } if (!own.siteName) {getter(openGraph, 'siteName', () => current()?.siteName)} if (!own.robots && options.robots !== false) { next.robots = { follow: false, index: false, ...(options.robots ?? {}) } as Meta['robots'] } if (!own.images && options.image !== false) { openGraph.images = [{ height: 630, url: options.image ?? `${api}${ADMIN_OG_PATH}`, width: 1200 }] } if (!own.icons && options.icons !== false) { next.icons = [{ rel: 'icon', url: `${api}${ADMIN_ICON_PATH}` }] as Meta['icons'] } if (Object.keys(openGraph).length) {next.openGraph = openGraph as Meta['openGraph']} return { meta: next, resolved } } /** Site-dependent parts of the meta for a given site name. */ export function adminMetaForSite(site: string, { agency, language, options }: ResolvedAdminMeta) { const texts = ADMIN_META_TEXTS[language] const description = options.description === false ? undefined : fill( typeof options.description === 'string' ? options.description : options.description ? options.description[language] : agency ? texts.description : texts.descriptionNoAgency, site, agency, ) const titleSuffix = options.titleSuffix === false ? undefined : fill(options.titleSuffix ?? texts.titleSuffix, site, agency) return { description, siteName: site, titleSuffix } } /** * Writes the site-dependent parts into the live config Payload reads for every * admin page. Never throws; skips keys the project set itself. */ export async function syncAdminMeta( payload: Payload, resolved: ResolvedAdminMeta, { nameField = 'siteName', settingsSlug = 'site-settings' }: { nameField?: string; settingsSlug?: string } = {}, ): Promise { // A hook called without a Payload instance (tests, scripts) has nothing to read or write. if (!payload) {return} try { const locale = payload.config.localization ? payload.config.localization.defaultLocale : undefined const settings = (await payload.findGlobal({ slug: settingsSlug as never, depth: 0, ...(locale ? { locale: locale as never } : {}) })) as Record const raw = settings[nameField] const site = typeof raw === 'string' ? raw.trim() : '' if (!site) {return} adminMetaStore().site = site // The live config was sanitized before this ran: its top-level values are plain copies. const { description, titleSuffix } = adminMetaForSite(site, resolved) const meta = payload.config.admin.meta as (Meta & Record) | undefined if (!meta) {return} if (!resolved.own.description && resolved.options.description !== false && description) {meta.description = description} if (!resolved.own.titleSuffix && resolved.options.titleSuffix !== false && titleSuffix) {meta.titleSuffix = titleSuffix} } catch (error) { payload?.logger?.warn({ err: error, msg: '[ipal] admin meta: could not read Site settings; Payload defaults stay.' }) } }