Files
ipal-kit/src/modules/seo/buildMetadata.ts
T
Radosław SmolińskiandClaude Opus 5.5 0d8d906653 Comments: tab name Search engines, credit text, generateStaticParams scope
Comments and the ipal-kit usage line only (adds ipal-doctor); no behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 00:01:19 +01:00

231 lines
8.6 KiB
TypeScript

import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import type { TitleOrder } from './composeTitle.js'
import type { VerificationMetadata } from './searchSettings.js'
import type { SeoMeta } from './types.js'
import { buildLocalizedPath } from '../i18n/index.js'
import { composeTitle } from './composeTitle.js'
import { buildHreflangAlternates } from './hreflang.js'
import { isSiteNoindex } from './siteNoindex.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.
*/
/** Share image with its size and alt — lets X/LinkedIn/Facebook render the card without guessing. */
export type OgImage = { alt?: string; height?: number; url: string; width?: number }
export type PageMetadata = {
alternates?: {
canonical?: string
languages?: Record<string, string>
/** Alternate representations by MIME type, e.g. { 'text/markdown': '/md/pl/o-nas' }. */
types?: Record<string, string>
}
description?: string
openGraph?: {
description?: string
images?: OgImage[]
locale?: string
/** Article entries: ISO dates (og:article:published_time / modified_time). */
modifiedTime?: string
publishedTime?: string
/** Site/brand name for the OG card. */
siteName?: string
title: string
/** 'website' | 'article' etc. Defaults to 'website'. */
type?: string
/** Canonical URL of this page. */
url?: string
}
/**
* robots directives. Indexed pages get generous snippet/preview limits by
* default (Google shows richer results); noindex pages get index:false.
*/
robots?: {
follow: boolean
index: boolean
/** 'none' | 'standard' | 'large' — image preview size in results. */
'max-image-preview'?: 'large' | 'none' | 'standard'
/** Max text snippet length; -1 = no limit. Next maps to max-snippet. */
'max-snippet'?: number
/** Max video preview seconds; -1 = no limit. */
'max-video-preview'?: number
}
title: string
/** X (Twitter) card — large image when there is one. */
twitter?: {
card: 'summary' | 'summary_large_image'
description?: string
images?: string[]
title: string
}
/** Search console ownership tags (google-site-verification, msvalidate.01, yandex-verification). */
verification?: VerificationMetadata
}
type BuildMetadataArgs = {
/**
* Article dates for archive entries (blog posts…): og:type becomes 'article'
* with published/modified times — a freshness signal for search and AI.
*/
article?: { modifiedTime?: null | string; publishedTime?: null | string }
/** Absolute site origin, e.g. 'https://example.com'. */
baseUrl?: string
config: I18nConfig
/** Home slug that collapses to the locale root. Defaults to 'home'. */
homeSlug?: Record<string, string> | string
/** Resolved OG image with size/alt (wins over imageUrl). */
image?: null | OgImage
/** 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
/**
* Top-level noindex flag (buildNoindexField). Checked alongside meta.noindex:
* plugin-seo's meta group doesn't declare noindex, so a mirror into
* meta.noindex is stripped on save — the top-level field is the one that
* persists. Either being true emits robots index:false.
*/
noindex?: boolean | null
/** Page title or site name first. Defaults to 'page-first'. */
order?: TitleOrder
/**
* The document's own title (e.g. page.title = 'Sprzątanie biur'). Used as the
* page-title source when meta.title is empty — the browser tab and search
* result should show the page name, not go blank, when an editor didn't fill
* the SEO title. Priority: titleOverride > meta.title > pageTitle.
*/
pageTitle?: null | string
/**
* 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
/**
* Global fallback description (from SiteSettings.siteDescription). Used when a
* page has no meta.description — better than emitting no description at all
* (Google would then scrape random on-page text for the snippet).
*/
siteDescription?: null | string
/** Site name for title composition and OG. */
siteName?: null | string
/** slug per locale for this document — drives canonical + hreflang. */
slugs: LocalizedSlugs
/** Site Settings → Search engines verification codes; rendered as <meta> tags by Next. */
verification?: VerificationMetadata
}
/**
* 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({
article,
baseUrl,
config,
homeSlug = 'home',
image,
imageUrl,
locale,
meta,
noindex,
order,
pageTitle,
prefix,
query,
separator,
siteDescription,
siteName,
slugs,
verification,
}: BuildMetadataArgs): PageMetadata {
// Title source priority: titleOverride (exact, wins outright) > meta.title
// (SEO title an editor set) > pageTitle (the document's own name). This means
// a page with no SEO title still shows its name (e.g. 'Sprzątanie biur')
// composed with the site name, instead of just the site name or a blank.
const override = meta?.titleOverride?.trim()
const resolvedPageTitle = meta?.title?.trim() || pageTitle?.trim() || undefined
const title =
override || composeTitle({ order, pageTitle: resolvedPageTitle, separator, siteName })
const description = meta?.description?.trim() || siteDescription?.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 ogImage: null | OgImage = image?.url ? image : imageUrl ? { url: imageUrl } : null
const images = ogImage ? [ogImage] : undefined
const isArticle = Boolean(article?.publishedTime || article?.modifiedTime)
return {
title,
...(description && { description }),
alternates: {
...(canonical && { canonical }),
...(Object.keys(languages).length > 0 && { languages }),
},
openGraph: {
title,
...(description && { description }),
...(images && { images }),
type: isArticle ? 'article' : 'website',
locale,
...(siteName ? { siteName } : {}),
...(canonical ? { url: canonical } : {}),
...(article?.publishedTime ? { publishedTime: article.publishedTime } : {}),
...(article?.modifiedTime ? { modifiedTime: article.modifiedTime } : {}),
},
twitter: {
card: ogImage ? 'summary_large_image' : 'summary',
title,
...(description && { description }),
...(ogImage ? { images: [ogImage.url] } : {}),
},
...(verification ? { verification } : {}),
// robots: noindex pages are excluded (follow keeps link authority). Indexed
// pages get generous snippet/preview limits so Google can show rich results
// (long snippets, large image previews, full video previews).
...(isSiteNoindex()
? { robots: { follow: false, index: false } }
: noindex || meta?.noindex
? { robots: { follow: true, index: false } }
: {
robots: {
follow: true,
index: true,
'max-image-preview': 'large' as const,
'max-snippet': -1,
'max-video-preview': -1,
},
}),
}
}