init commit for iPAL-kit plugin

This commit is contained in:
2026-07-18 20:30:23 +02:00
parent 10638127a9
commit 5733a9c8bf
119 changed files with 6892 additions and 411 deletions
+58
View File
@@ -0,0 +1,58 @@
import type { CollectionBeforeChangeHook } from 'payload'
/**
* Maps document fields to SEO meta fields for auto-fill.
* Defaults match the Payload website template (title → meta.title).
*/
export type AutoFillMapping = {
/** Document field used to fill meta.description when empty. */
description?: string
/** Document field used to fill meta.title when empty. Default: 'title'. */
title?: string
}
/**
* Reads a possibly-localized field value into a plain string.
* With localized fields at this hook stage the value is the active-locale
* string, so we just coerce defensively.
*/
function readString(value: unknown): string | undefined {
if (typeof value === 'string' && value.trim()) {return value.trim()}
return undefined
}
/**
* Builds a beforeChange hook that fills empty SEO meta fields from document
* content. Only fills when the meta field is blank — never overwrites what an
* editor typed. This runs server-side on every create/update, so editors get
* sensible meta without clicking "auto-generate".
*
* The plugin doesn't know the client's collection shape, so the field mapping
* is configurable; defaults follow the website template.
*/
export function buildAutoFillMetaHook(mapping: AutoFillMapping = {}): CollectionBeforeChangeHook {
const titleField = mapping.title ?? 'title'
const descriptionField = mapping.description
return ({ data }) => {
if (!data) {return data}
// plugin-seo stores meta as a group under `meta`
const meta = (data.meta as Record<string, unknown> | undefined) ?? {}
// Fill meta.title from the document title when empty
if (!readString(meta.title)) {
const sourceTitle = readString(data[titleField])
if (sourceTitle) {meta.title = sourceTitle}
}
// Fill meta.description from a configured field when empty
if (descriptionField && !readString(meta.description)) {
const sourceDescription = readString(data[descriptionField])
if (sourceDescription) {meta.description = sourceDescription}
}
data.meta = meta
return data
}
}
+122
View File
@@ -0,0 +1,122 @@
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import type { TitleOrder } from './composeTitle.js'
import type { SeoMeta } from './types.js'
import { buildLocalizedPath } from '../i18n/index.js'
import { composeTitle } from './composeTitle.js'
import { buildHreflangAlternates } from './hreflang.js'
/**
* Subset of Next.js `Metadata` this helper produces. Kept local so the plugin
* doesn't depend on `next` types; the shape is assignable to Next's Metadata.
*/
export type PageMetadata = {
alternates?: {
canonical?: string
languages?: Record<string, string>
}
description?: string
openGraph?: {
description?: string
images?: { url: string }[]
locale?: string
title: string
}
title: string
}
type BuildMetadataArgs = {
/** Absolute site origin, e.g. 'https://example.com'. */
baseUrl?: string
config: I18nConfig
/** Home slug that collapses to the locale root. Defaults to 'home'. */
homeSlug?: string
/** Resolved OG image URL (page image or site defaultShareImage). */
imageUrl?: null | string
/** Current locale being rendered. */
locale: string
/** SEO meta from the document (plugin-seo group). */
meta?: null | SeoMeta
/** Page title or site name first. Defaults to 'page-first'. */
order?: TitleOrder
/**
* Localized segment the document lives under (an archive page's slugs).
* Feeds both canonical and hreflang, so /pl/artykuly/moj-post and
* /en/articles/my-post point at each other correctly.
*/
prefix?: LocalizedSlugs
/**
* Query string appended to canonical and every hreflang, e.g. '?page=2'.
*
* A paginated listing must be canonical to itself — pointing page 2 at page 1
* tells Google the entries on it don't exist. Alternates carry the same page,
* since /pl/artykuly?page=2 corresponds to /en/articles?page=2.
*/
query?: string
/** Separator between page title and site name. Defaults to ' | '. */
separator?: string
/** Site name for title composition and OG. */
siteName?: null | string
/** slug per locale for this document — drives canonical + hreflang. */
slugs: LocalizedSlugs
}
/**
* Assembles a Next.js-compatible Metadata object from document SEO fields and
* site-level data. Locale-aware: canonical points at the current locale's
* path, and hreflang alternates cover every locale the document exists in.
*
* Designed for use inside Next.js `generateMetadata`. The caller resolves the
* pieces (meta group, site name, image URL, localized slugs) and passes them
* in — the plugin composes, it doesn't fetch.
*/
export function buildMetadata({
baseUrl,
config,
homeSlug = 'home',
imageUrl,
locale,
meta,
order,
prefix,
query,
separator,
siteName,
slugs,
}: BuildMetadataArgs): PageMetadata {
// titleOverride wins outright: an editor who filled it in wants that exact
// string in the tab, not a composition.
const override = meta?.titleOverride?.trim()
const title = override || composeTitle({ order, pageTitle: meta?.title, separator, siteName })
const description = meta?.description?.trim() || undefined
const origin = baseUrl?.replace(/\/$/, '') ?? ''
const suffix = query ?? ''
const currentPath = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs })
const canonical = currentPath ? `${origin}${currentPath}${suffix}` : undefined
const languages = buildHreflangAlternates({ baseUrl, config, homeSlug, prefix, slugs })
if (suffix) {
for (const code of Object.keys(languages)) {
languages[code] = `${languages[code]}${suffix}`
}
}
const images = imageUrl ? [{ url: imageUrl }] : undefined
return {
title,
...(description && { description }),
alternates: {
...(canonical && { canonical }),
...(Object.keys(languages).length > 0 && { languages }),
},
openGraph: {
title,
...(description && { description }),
...(images && { images }),
locale,
},
}
}
+39
View File
@@ -0,0 +1,39 @@
/** Which part comes first in a composed title. */
export type TitleOrder = 'page-first' | 'site-first'
type ComposeTitleArgs = {
/** Defaults to 'page-first' — the page title is what a visitor scans for. */
order?: TitleOrder
/** Page-specific title, e.g. 'About Us'. */
pageTitle?: null | string
/** Separator between page title and site name. Defaults to ' | '. */
separator?: string
/** Site name, e.g. 'Acme Inc'. */
siteName?: null | string
}
/**
* Composes a full document title from a page title and the site name.
*
* - both, page-first: "About Us | Acme Inc"
* - both, site-first: "Acme Inc | About Us"
* - page only: "About Us"
* - site only: "Acme Inc"
* - neither: ""
*
* Pure function — no dependency on Payload or request state.
*/
export function composeTitle({
order = 'page-first',
pageTitle,
separator = ' | ',
siteName,
}: ComposeTitleArgs): string {
const page = pageTitle?.trim()
const site = siteName?.trim()
if (page && site) {
return order === 'site-first' ? `${site}${separator}${page}` : `${page}${separator}${site}`
}
return page || site || ''
}
+105
View File
@@ -0,0 +1,105 @@
import type { BasePayload } from 'payload'
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import type { PageMetadata } from './buildMetadata.js'
import type { SeoMeta } from './types.js'
import { getLocalizedSlugs } from '../i18n/index.js'
import { buildMetadata } from './buildMetadata.js'
/**
* A document as needed for metadata: its SEO meta group and localized slug.
*/
type MetadataDocument = {
meta?: null | SeoMeta
slug?: null | Record<string, unknown>
}
type CreateMetadataGeneratorArgs = {
/** Absolute site origin, e.g. 'https://example.com'. */
baseUrl?: string
config: I18nConfig
/** Home slug that collapses to the locale root. Defaults to 'home'. */
homeSlug?: string
/**
* Resolves the document to build metadata for, given route params.
* The client supplies this (they own the collections and routing); it should
* fetch with `locale: 'all'` so the slug field is a locale→value map.
*/
resolveDocument: (args: {
locale: string
params: Record<string, string | string[]>
payload: BasePayload
}) => Promise<MetadataDocument | null>
/** Resolves the OG image URL for the document, if any. */
resolveImageUrl?: (args: {
doc: MetadataDocument
locale: string
payload: BasePayload
}) => Promise<null | string>
/** Resolves the site name (e.g. from SiteSettings). */
resolveSiteName?: (args: { locale: string; payload: BasePayload }) => Promise<null | string>
}
/**
* Builds a metadata generator, collapsing the usual generateMetadata
* boilerplate into a single wired-up function.
*
* The client provides resolvers (they own collections/routing); the plugin
* owns the assembly (title composition, canonical, hreflang, OG).
*
* The returned function takes `{ payload, params, locale }` — Next calls
* `generateMetadata({ params })` without those, and the plugin never calls
* getPayload itself, so the client wraps it in their route file:
*
* ```ts
* // app/(frontend)/[locale]/[[...slug]]/page.tsx
* const generate = createMetadataGenerator({
* config: i18nConfig,
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL,
* resolveDocument: async ({ payload, params, locale }) => { ... },
* })
*
* export async function generateMetadata({ params }) {
* const { locale, slug } = await params
* const payload = await getPayload({ config: await config })
* return generate({ payload, params: { slug: slug ?? [] }, locale })
* }
* ```
*
* `resolveDocument` should fetch with `locale: 'all'` so the slug field comes
* back as a locale→value map — that's what hreflang alternates are built from.
*/
export function createMetadataGenerator(args: CreateMetadataGeneratorArgs) {
const { baseUrl, config, homeSlug, resolveDocument, resolveImageUrl, resolveSiteName } = args
return async function generateMetadata(context: {
locale: string
params: Record<string, string | string[]>
payload: BasePayload
}): Promise<PageMetadata> {
const { locale, params, payload } = context
const doc = await resolveDocument({ locale, params, payload })
const slugs: LocalizedSlugs = doc?.slug
? getLocalizedSlugs({ config, slugField: doc.slug })
: {}
const [siteName, imageUrl] = await Promise.all([
resolveSiteName?.({ locale, payload }) ?? Promise.resolve(null),
doc && resolveImageUrl ? resolveImageUrl({ doc, locale, payload }) : Promise.resolve(null),
])
return buildMetadata({
baseUrl,
config,
homeSlug,
imageUrl,
locale,
meta: doc?.meta,
siteName,
slugs,
})
}
}
+198
View File
@@ -0,0 +1,198 @@
import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { PageMetadata } from './buildMetadata.js'
import type { TitleOrder } from './composeTitle.js'
import type { SeoMeta } from './types.js'
import { resolveRoute } from '../content/index.js'
import { getLocalizedSlugs } from '../i18n/index.js'
import { buildMetadata } from './buildMetadata.js'
type CreatePageMetadataArgs = {
/** Absolute site origin, e.g. 'https://example.com'. */
baseUrl?: string
/** Collection holding pages. Defaults to 'pages'. */
collection?: string
config: I18nConfig
/**
* Archive-backed collections, same value as the plugin option. Pass it and
* entry URLs (/pl/artykuly/moj-post) get correct canonical and hreflang;
* omit it and only pages are handled.
*/
content?: ContentOption
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
/** Field on SiteSettings holding the site name. Defaults to 'siteName'. */
siteNameField?: string
}
type PageMetadataContext = {
locale: string
/**
* Page number from ?page= on an archive listing. Pass it and page 2 gets a
* canonical to itself; leave it out and every page claims to be page 1.
*/
page?: number
payload: BasePayload
/** Route slug segments; empty/undefined means the locale root. */
slug?: string[]
}
type SettingsShape = {
[key: string]: unknown
homepage?: { id: number | string; slug?: unknown } | null | number | string
titleOrder?: null | TitleOrder
titleSeparator?: null | string
}
type DocShape = {
id: number | string
meta?: null | SeoMeta
/** A string when read in one locale, a locale→value map when read with 'all'. */
slug?: unknown
}
/** Reads a document again across locales — the slug map hreflang needs. */
async function slugsAcrossLocales(
payload: BasePayload,
collection: string,
id: number | string,
config: I18nConfig,
) {
const doc = (await payload.findByID({
id,
collection: collection as never,
depth: 0,
locale: 'all',
})) as DocShape
return doc.slug && typeof doc.slug === 'object'
? getLocalizedSlugs({ config, slugField: doc.slug as Record<string, unknown> })
: {}
}
/**
* Metadata for the page route, with every resolver already wired.
*
* `createMetadataGenerator` asks the client for resolvers because it can't know
* their collections. But for the plugin's own conventions it does know: pages
* live in one collection, the site name sits on SiteSettings, the OG image sits
* on the plugin-seo `meta` group, the home page is whatever System Pages points
* at, and — with `content` — entries live under their collection's archive page.
* Re-declaring all that in every project is copy-paste, so this resolves it.
*
* Reach for `createMetadataGenerator` instead when a route doesn't follow those
* conventions — custom image logic, a different global, hand-rolled paths.
*
* The plugin never calls getPayload, and Next calls generateMetadata without a
* payload, so the client keeps a small wrapper:
*
* ```ts
* const pageMetadata = createPageMetadata({ config: i18nConfig, baseUrl, content })
*
* export async function generateMetadata({ params }) {
* const { locale, slug } = await params
* return pageMetadata({ payload: await getPayload({ config }), locale, slug })
* }
* ```
*/
export function createPageMetadata(args: CreatePageMetadataArgs) {
const {
baseUrl,
collection = 'pages',
config,
content,
settingsSlug = 'site-settings',
siteNameField = 'siteName',
} = args
return async function pageMetadata({
slug,
locale,
page,
payload,
}: PageMetadataContext): Promise<PageMetadata> {
const settings = (await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: locale as never,
})) as SettingsShape
const siteName = (settings[siteNameField] as string | undefined) ?? null
// The panel stores the bare character ('|'); titles need it padded.
const separator = settings.titleSeparator ? ` ${settings.titleSeparator} ` : undefined
const order = settings.titleOrder ?? undefined
const homepage =
settings.homepage && typeof settings.homepage === 'object' ? settings.homepage : null
// The home page's slug collapses to the locale root (/pl, not /pl/homepage).
const homeSlug = typeof homepage?.slug === 'string' ? homepage.slug : undefined
const empty = () =>
buildMetadata({
baseUrl,
config,
homeSlug,
locale,
meta: null,
order,
separator,
siteName,
slugs: {},
})
const route = await resolveRoute({
content,
locale,
page,
pagesSlug: collection,
payload,
segments: slug,
settingsSlug,
})
// Unknown route (the page component will 404) — still return something
// coherent rather than throwing during metadata generation.
if (!route) {return empty()}
const doc = route.doc as DocShape
// An entry sits under its archive, so its URLs need that segment — and the
// segment differs per locale, since it's the archive page's own slug.
const prefix =
route.type === 'entry'
? await slugsAcrossLocales(payload, collection, (route.archive as DocShape).id, config)
: undefined
const docCollection = route.type === 'entry' ? route.collection : collection
const slugs = await slugsAcrossLocales(payload, docCollection, doc.id, config)
// Page 2 of a listing is its own URL, not a variant of page 1.
const query = route.type === 'archive' && route.page > 1 ? `?page=${route.page}` : undefined
// plugin-seo stores the OG image as an upload relationship.
const image = (doc.meta as { image?: unknown } | null | undefined)?.image
const imageUrl =
image && typeof image === 'object' && 'url' in image
? ((image as { url: string }).url ?? null)
: null
return buildMetadata({
baseUrl,
config,
homeSlug,
imageUrl,
locale,
meta: doc.meta,
order,
prefix,
query,
separator,
siteName,
slugs,
})
}
}
+55
View File
@@ -0,0 +1,55 @@
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import { buildLocalizedPath, getLocaleCodes } from '../i18n/index.js'
type BuildHreflangArgs = {
/** Absolute site origin, e.g. 'https://example.com'. Omit for relative paths. */
baseUrl?: string
config: I18nConfig
/** Home slug that collapses to the locale root. Defaults to 'home'. */
homeSlug?: string
/**
* Localized segment the document lives under (an archive page's slugs),
* e.g. { pl: 'artykuly', en: 'articles' }. Locales missing from the prefix
* are omitted — an entry with no archive in that language has no URL there.
*/
prefix?: LocalizedSlugs
/** slug per locale for the current document, e.g. { pl: 'o-nas', en: 'about' } */
slugs: LocalizedSlugs
}
/**
* Builds a map of locale → URL for hreflang alternate links, suitable for
* Next.js Metadata `alternates.languages`.
*
* Bridges SEO and i18n: for each configured locale that the document has a
* slug in, it produces the locale-aware path (via buildLocalizedPath),
* optionally prefixed with an absolute origin.
*
* @example
* buildHreflangAlternates({
* slugs: { pl: 'o-nas', en: 'about' },
* config,
* baseUrl: 'https://example.com',
* })
* // → { pl: 'https://example.com/pl/o-nas', en: 'https://example.com/en/about' }
*/
export function buildHreflangAlternates({
baseUrl,
config,
homeSlug = 'home',
prefix,
slugs,
}: BuildHreflangArgs): Record<string, string> {
const origin = baseUrl?.replace(/\/$/, '') ?? ''
const alternates: Record<string, string> = {}
for (const locale of getLocaleCodes(config)) {
const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs })
if (path) {
alternates[locale] = `${origin}${path}`
}
}
return alternates
}
+13
View File
@@ -0,0 +1,13 @@
export { buildAutoFillMetaHook } from './autoFillMeta.js'
export type { AutoFillMapping } from './autoFillMeta.js'
export { buildMetadata } from './buildMetadata.js'
export type { PageMetadata } from './buildMetadata.js'
export { composeTitle } from './composeTitle.js'
export type { TitleOrder } from './composeTitle.js'
export { createMetadataGenerator } from './createMetadataGenerator.js'
export { createPageMetadata } from './createPageMetadata.js'
export { buildHreflangAlternates } from './hreflang.js'
export { injectAutoFillMeta } from './injectAutoFillMeta.js'
export { injectSeoTabs } from './injectSeoTabs.js'
export { buildSeoPlugin } from './seoPluginConfig.js'
export type { SeoMeta, SeoOption } from './types.js'
+38
View File
@@ -0,0 +1,38 @@
import type { Config } from 'payload'
import type { SeoOption } from './types.js'
import { buildAutoFillMetaHook } from './autoFillMeta.js'
/**
* Injects the auto-fill meta hook into every SEO-enabled collection.
*
* Runs after @payloadcms/plugin-seo has added the meta group, appending a
* beforeChange hook that fills empty meta from document content. Existing
* hooks are preserved (plugin hook runs last, so editor input and other hooks
* win first).
*/
export function injectAutoFillMeta(config: Config, seo: SeoOption): Config {
// autoFill disabled explicitly — leave collections untouched
if (seo.autoFill === false) {
return config
}
const hook = buildAutoFillMetaHook(seo.autoFill)
return {
...config,
collections: (config.collections ?? []).map((collection) => {
if (!seo.collections.includes(collection.slug)) {
return collection
}
return {
...collection,
hooks: {
...collection.hooks,
beforeChange: [...(collection.hooks?.beforeChange ?? []), hook],
},
}
}),
}
}
+69
View File
@@ -0,0 +1,69 @@
import type { Config, Field, TabsField } from 'payload'
import type { SeoOption } from './types.js'
/**
* Wraps each SEO-enabled collection's fields into a tabbed UI: a "Content" tab
* holding the collection's own fields, and an "SEO" tab holding the `meta`
* group that @payloadcms/plugin-seo added.
*
* This replaces plugin-seo's own `tabbedUI`, which merges tabs by inspecting
* the first field and breaks when other plugins/fields (roles, slug) already
* sit in the collection — producing an empty SEO tab. Running this AFTER
* plugin-seo (so `meta` already exists) and after other field injections lets
* us build the tabs deterministically.
*
* If a collection's first field is already a tabs field, the SEO tab is
* appended to it instead of creating a new wrapper.
*/
export function injectSeoTabs(config: Config, seo: SeoOption): Config {
return {
...config,
collections: (config.collections ?? []).map((collection) => {
if (!seo.collections.includes(collection.slug)) {
return collection
}
const fields = collection.fields ?? []
// Separate the meta group (added by plugin-seo) from the rest.
const metaField = fields.find(
(f): f is { name: string } & Field => 'name' in f && f.name === 'meta',
)
const otherFields = fields.filter(
(f) => !('name' in f && f.name === 'meta'),
)
// Nothing to do if plugin-seo hasn't added meta (shouldn't happen).
if (!metaField) {return collection}
// If the collection already leads with a tabs field, append an SEO tab.
const firstField = otherFields[0]
if (firstField && firstField.type === 'tabs') {
const existingTabs = firstField
const withSeoTab: TabsField = {
...existingTabs,
tabs: [...existingTabs.tabs, { fields: [metaField], label: 'SEO' }],
}
return {
...collection,
fields: [withSeoTab, ...otherFields.slice(1)],
}
}
// Otherwise wrap everything: Content tab + SEO tab.
const tabs: TabsField = {
type: 'tabs',
tabs: [
{ fields: otherFields, label: collection.labels?.singular?.toString() || 'Content' },
{ fields: [metaField], label: 'SEO' },
],
}
return {
...collection,
fields: [tabs],
}
}),
}
}
+45
View File
@@ -0,0 +1,45 @@
import type { Field, Plugin } from 'payload'
import { seoPlugin } from '@payloadcms/plugin-seo'
import type { SeoOption } from './types.js'
type BuildSeoPluginArgs = {
seo: SeoOption
/** Upload collection slug for the meta image (typically 'media'). */
uploadsCollection?: string
}
/**
* Escape hatch from automatic title composition: whatever is typed here becomes
* the entire title — no site name, no separator. Useful on a home page, where
* composing would produce "Intecion Software | Intecion Software".
*/
const titleOverrideField: Field = {
name: 'titleOverride',
type: 'text',
admin: {
description:
'Use this exact text as the browser-tab title — no site name, no separator. Leave empty to compose the title automatically.',
},
localized: true,
}
/**
* Configures @payloadcms/plugin-seo from IPAL's SeoOption.
*
* Adds the `meta` field group (title, description, image) to the client's
* chosen collections. tabbedUI is intentionally NOT used — it merges tabs by
* inspecting the first field, which breaks when other plugins/fields (roles,
* slug) already sit in the collection, leaving an empty SEO tab. Instead the
* SEO UI fields are injected into a controlled tab by injectSeoTabs.
*/
export function buildSeoPlugin({ seo, uploadsCollection = 'media' }: BuildSeoPluginArgs): Plugin {
return seoPlugin({
collections: seo.collections,
fields: ({ defaultFields }) => [...defaultFields, titleOverrideField, ...(seo.fields ?? [])],
uploadsCollection,
...(seo.generateTitle && { generateTitle: seo.generateTitle }),
...(seo.generateDescription && { generateDescription: seo.generateDescription }),
})
}
+39
View File
@@ -0,0 +1,39 @@
import type { Field } from 'payload'
import type { AutoFillMapping } from './autoFillMeta.js'
/**
* SEO configuration.
*
* The plugin wires @payloadcms/plugin-seo into the client's config and adds
* locale-aware metadata helpers on top. Collections come from options because
* the plugin doesn't own the client's content collections (e.g. Pages).
*/
export type SeoOption = {
/**
* Auto-fill empty meta from document fields on save. Defaults to the website
* template mapping (title → meta.title). Set to false to disable.
*/
autoFill?: AutoFillMapping | false
/** Collection slugs that receive SEO meta fields, e.g. ['pages', 'posts']. */
collections: string[]
/** Extra fields appended to the SEO group in the admin. */
fields?: Field[]
/** Optional: customize how meta descriptions are generated. */
generateDescription?: (args: { doc: Record<string, unknown> }) => string
/** Optional: customize how meta titles are generated in the admin preview. */
generateTitle?: (args: { doc: Record<string, unknown> }) => string
}
/**
* Minimal shape of the SEO meta group as stored on a document by
* @payloadcms/plugin-seo. The client's generated types are richer; helpers
* depend only on this.
*/
export type SeoMeta = {
description?: null | string
image?: unknown
title?: null | string
/** When set, used as the whole title — no site name, no separator. */
titleOverride?: null | string
}